code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
/**
* 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+'"> </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('×');
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})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\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})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/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">×</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('×');
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 |
/*
moo.fx pack, effects extensions for moo.fx.
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE
for more info visit (http://moofx.mad4milk.net).
Friday, April 14, 2006
v 1.2.4
*/
//smooth scroll
fx.Scroll = Class.create();
fx.Scroll.prototype = Object.extend(new fx.Base(), {
initialize: function(options) {
this.setOptions(options);
},
scrollTo: function(el){
var dest = Position.cumulativeOffset($(el))[1];
var client = window.innerHeight || document.documentElement.clientHeight;
var full = document.documentElement.scrollHeight;
var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
if (dest+client > full) this.custom(top, dest - client + (full-dest));
else this.custom(top, dest);
},
increase: function(){
window.scrollTo(0, this.now);
}
});
//text size modify, now works with pixels too.
fx.Text = Class.create();
fx.Text.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.setOptions(options);
if (!this.options.unit) this.options.unit = "em";
},
increase: function() {
this.el.style.fontSize = this.now + this.options.unit;
}
});
//composition effect: widht/height/opacity
fx.Combo = Class.create();
fx.Combo.prototype = {
setOptions: function(options) {
this.options = {
opacity: true,
height: true,
width: false
}
Object.extend(this.options, options || {});
},
initialize: function(el, options) {
this.el = $(el);
this.setOptions(options);
if (this.options.opacity) {
this.o = new fx.Opacity(el, options);
options.onComplete = null;
}
if (this.options.height) {
this.h = new fx.Height(el, options);
options.onComplete = null;
}
if (this.options.width) this.w = new fx.Width(el, options);
},
toggle: function() { this.checkExec('toggle'); },
hide: function(){ this.checkExec('hide'); },
clearTimer: function(){ this.checkExec('clearTimer'); },
checkExec: function(func){
if (this.o) this.o[func]();
if (this.h) this.h[func]();
if (this.w) this.w[func]();
},
//only if width+height
resizeTo: function(hto, wto) {
if (this.h && this.w) {
this.h.custom(this.el.offsetHeight, this.el.offsetHeight + hto);
this.w.custom(this.el.offsetWidth, this.el.offsetWidth + wto);
}
},
customSize: function(hto, wto) {
if (this.h && this.w) {
this.h.custom(this.el.offsetHeight, hto);
this.w.custom(this.el.offsetWidth, wto);
}
}
}
fx.Accordion = Class.create();
fx.Accordion.prototype = {
setOptions: function(options) {
this.options = {
delay: 100,
opacity: false
}
Object.extend(this.options, options || {});
},
initialize: function(togglers, elements, options) {
this.elements = elements;
this.setOptions(options);
var options = options || '';
this.fxa = [];
if (options && options.onComplete) options.onFinish = options.onComplete;
elements.each(function(el, i){
options.onComplete = function(){
if (el.offsetHeight > 0) el.style.height = '1%';
if (options.onFinish) options.onFinish(el);
}
this.fxa[i] = new fx.Combo(el, options);
this.fxa[i].hide();
}.bind(this));
togglers.each(function(tog, i){
if (typeof tog.onclick == 'function') var exClick = tog.onclick;
tog.onclick = function(){
if (exClick) exClick();
this.showThisHideOpen(elements[i]);
}.bind(this);
}.bind(this));
},
showThisHideOpen: function(toShow){
this.elements.each(function(el, j){
if (el.offsetHeight > 0 && el != toShow) this.clearAndToggle(el, j);
if (el == toShow && toShow.offsetHeight == 0) setTimeout(function(){this.clearAndToggle(toShow, j);}.bind(this), this.options.delay);
}.bind(this));
},
clearAndToggle: function(el, i){
this.fxa[i].clearTimer();
this.fxa[i].toggle();
}
}
var Remember = new Object();
Remember = function(){};
Remember.prototype = {
initialize: function(el, options){
this.el = $(el);
this.days = 365;
this.options = options;
this.effect();
var cookie = this.readCookie();
if (cookie) {
this.fx.now = cookie;
this.fx.increase();
}
},
//cookie functions based on code by Peter-Paul Koch
setCookie: function(value) {
var date = new Date();
date.setTime(date.getTime()+(this.days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = this.el+this.el.id+this.prefix+"="+value+expires+"; path=/";
},
readCookie: function() {
var nameEQ = this.el+this.el.id+this.prefix + "=";
var ca = document.cookie.split(';');
for(var i=0;c=ca[i];i++) {
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return false;
},
custom: function(from, to){
if (this.fx.now != to) {
this.setCookie(to);
this.fx.custom(from, to);
}
}
}
fx.RememberHeight = Class.create();
fx.RememberHeight.prototype = Object.extend(new Remember(), {
effect: function(){
this.fx = new fx.Height(this.el, this.options);
this.prefix = 'height';
},
toggle: function(){
if (this.el.offsetHeight == 0) this.setCookie(this.el.scrollHeight);
else this.setCookie(0);
this.fx.toggle();
},
resize: function(to){
this.setCookie(this.el.offsetHeight+to);
this.fx.custom(this.el.offsetHeight,this.el.offsetHeight+to);
},
hide: function(){
if (!this.readCookie()) {
this.fx.hide();
}
}
});
fx.RememberText = Class.create();
fx.RememberText.prototype = Object.extend(new Remember(), {
effect: function(){
this.fx = new fx.Text(this.el, this.options);
this.prefix = 'text';
}
});
//useful for-replacement
Array.prototype.iterate = function(func){
for(var i=0;i<this.length;i++) func(this[i], i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;
//Easing Equations (c) 2003 Robert Penner, all rights reserved.
//This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html.
//expo
fx.expoIn = function(pos){
return Math.pow(2, 10 * (pos - 1));
}
fx.expoOut = function(pos){
return (-Math.pow(2, -10 * pos) + 1);
}
//quad
fx.quadIn = function(pos){
return Math.pow(pos, 2);
}
fx.quadOut = function(pos){
return -(pos)*(pos-2);
}
//circ
fx.circOut = function(pos){
return Math.sqrt(1 - Math.pow(pos-1,2));
}
fx.circIn = function(pos){
return -(Math.sqrt(1 - Math.pow(pos, 2)) - 1);
}
//back
fx.backIn = function(pos){
return (pos)*pos*((2.7)*pos - 1.7);
}
fx.backOut = function(pos){
return ((pos-1)*(pos-1)*((2.7)*(pos-1) + 1.7) + 1);
}
//sine
fx.sineOut = function(pos){
return Math.sin(pos * (Math.PI/2));
}
fx.sineIn = function(pos){
return -Math.cos(pos * (Math.PI/2)) + 1;
}
fx.sineInOut = function(pos){
return -(Math.cos(Math.PI*pos) - 1)/2;
} | JavaScript |
/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
Sunday, March 05, 2006
v 1.2.3
*/
var fx = new Object();
//base
fx.Base = function(){};
fx.Base.prototype = {
setOptions: function(options) {
this.options = {
duration: 500,
onComplete: '',
transition: fx.sinoidal
}
Object.extend(this.options, options || {});
},
step: function() {
var time = (new Date).getTime();
if (time >= this.options.duration+this.startTime) {
this.now = this.to;
clearInterval (this.timer);
this.timer = null;
if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
}
else {
var Tpos = (time - this.startTime) / (this.options.duration);
this.now = this.options.transition(Tpos) * (this.to-this.from) + this.from;
}
this.increase();
},
custom: function(from, to) {
if (this.timer != null) return;
this.from = from;
this.to = to;
this.startTime = (new Date).getTime();
this.timer = setInterval (this.step.bind(this), 13);
},
hide: function() {
this.now = 0;
this.increase();
},
clearTimer: function() {
clearInterval(this.timer);
this.timer = null;
}
}
//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.el.style.overflow = "hidden";
this.iniWidth = this.el.offsetWidth;
this.iniHeight = this.el.offsetHeight;
this.setOptions(options);
}
});
fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {
increase: function() {
this.el.style.height = this.now + "px";
},
toggle: function() {
if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
else this.custom(0, this.el.scrollHeight);
}
});
fx.Width = Class.create();
Object.extend(Object.extend(fx.Width.prototype, fx.Layout.prototype), {
increase: function() {
this.el.style.width = this.now + "px";
},
toggle: function(){
if (this.el.offsetWidth > 0) this.custom(this.el.offsetWidth, 0);
else this.custom(0, this.iniWidth);
}
});
//fader
fx.Opacity = Class.create();
fx.Opacity.prototype = Object.extend(new fx.Base(), {
initialize: function(el, options) {
this.el = $(el);
this.now = 1;
this.increase();
this.setOptions(options);
},
increase: function() {
if (this.now == 1 && (/Firefox/.test(navigator.userAgent))) this.now = 0.9999;
this.setOpacity(this.now);
},
setOpacity: function(opacity) {
if (opacity == 0 && this.el.style.visibility != "hidden") this.el.style.visibility = "hidden";
else if (this.el.style.visibility != "visible") this.el.style.visibility = "visible";
if (window.ActiveXObject) this.el.style.filter = "alpha(opacity=" + opacity*100 + ")";
this.el.style.opacity = opacity;
},
toggle: function() {
if (this.now > 0) this.custom(1, 0);
else this.custom(0, 1);
}
});
//transitions
fx.sinoidal = function(pos){
return ((-Math.cos(pos*Math.PI)/2) + 0.5);
//this transition is from script.aculo.us
}
fx.linear = function(pos){
return pos;
}
fx.cubic = function(pos){
return Math.pow(pos, 3);
}
fx.circ = function(pos){
return Math.sqrt(pos);
} | JavaScript |
//** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
var featuredcontentslider={
enablepersist: false, //persist to last content viewed when returning to page?
settingcaches: {}, //object to cache "setting" object of each script instance
buildcontentdivs:function(setting){
var alldivs=document.getElementById(setting.id).getElementsByTagName("div")
for (var i=0; i<alldivs.length; i++){
if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv"
setting.contentdivs.push(alldivs[i])
alldivs[i].style.display="none" //collapse all content DIVs to begin with
}
}
},
buildpaginate:function(setting){
this.buildcontentdivs(setting)
var sliderdiv=document.getElementById(setting.id)
var pdiv=document.getElementById("paginate-"+setting.id)
var toc=setting.toc
var pdivlinks=pdiv.getElementsByTagName("a")
var toclinkscount=0 //var to keep track of actual # of toc links
for (var i=0; i<pdivlinks.length; i++){
if (this.css(pdivlinks[i], "toc", "check")){
if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents)
pdivlinks[i].style.display="none" //hide this toc link
continue
}
pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link
pdivlinks[i][setting.revealtype]=function(){
featuredcontentslider.turnpage(setting, this.getAttribute("rel"))
return false
}
setting.toclinks.push(pdivlinks[i])
}
else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next"
pdivlinks[i].onclick=function(){
featuredcontentslider.turnpage(setting, this.className)
return false
}
}
}
this.turnpage(setting, setting.currentpage, true)
if (setting.autorotate[0]){ //if auto rotate enabled
pdiv[setting.revealtype]=function(){
featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
}
sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on
featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id])
}
setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation
this.autorotate(setting)
}
},
urlparamselect:function(fcsid){
var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL
return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
},
turnpage:function(setting, thepage, autocall){
var currentpage=setting.currentpage //current page # before change
var totalpages=setting.contentdivs.length
var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage)
turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust
if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly
return
setting.currentpage=turntopage
// setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex
this.cleartimer(setting, window["fcsfade"+setting.id])
setting.cacheprevpage=setting.prevpage
if (setting.enablefade[0]==true){
setting.curopacity=0
this.fadeup(setting)
}
if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete)
setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
setting.onChange(setting.prevpage, setting.currentpage)
}
setting.contentdivs[turntopage-1].style.visibility="visible"
setting.contentdivs[turntopage-1].style.display="block"
if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
this.css(setting.toclinks[setting.prevpage-1], "selected", "remove")
if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted)
this.css(setting.toclinks[turntopage-1], "selected", "add")
setting.prevpage=turntopage
if (this.enablepersist)
this.setCookie("fcspersist"+setting.id, turntopage)
},
setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between)
var targetobject=setting.contentdivs[setting.currentpage-1]
if (targetobject.filters && targetobject.filters[0]){ //IE syntax
if (typeof targetobject.filters[0].opacity=="number") //IE6
targetobject.filters[0].opacity=value*100
else //IE 5.5
targetobject.style.filter="alpha(opacity="+value*100+")"
}
else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax
targetobject.style.MozOpacity=value
else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax
targetobject.style.opacity=value
setting.curopacity=value
},
fadeup:function(setting){
if (setting.curopacity<1){
this.setopacity(setting, setting.curopacity+setting.enablefade[1])
window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50)
}
else{ //when fade is complete
if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run)
setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block")
setting.onChange(setting.cacheprevpage, setting.currentpage)
}
},
cleartimer:function(setting, timervar){
if (typeof timervar!="undefined"){
clearTimeout(timervar)
clearInterval(timervar)
if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div
setting.contentdivs[setting.cacheprevpage-1].style.display="none"
}
}
},
css:function(el, targetclass, action){
var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig")
if (action=="check")
return needle.test(el.className)
else if (action=="remove")
el.className=el.className.replace(needle, "")
else if (action=="add")
el.className+=" "+targetclass
},
autorotate:function(setting){
window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1])
},
getCookie:function(Name){
var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
if (document.cookie.match(re)) //if cookie found
return document.cookie.match(re)[0].split("=")[1] //return its value
return null
},
setCookie:function(name, value){
document.cookie = name+"="+value
},
init:function(setting){
var persistedpage=this.getCookie("fcspersist"+setting.id) || 1
var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index
this.settingcaches[setting.id]=setting //cache "setting" object
setting.contentdivs=[]
setting.toclinks=[]
// setting.topzindex=0
setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1)
setting.prevpage=setting.currentpage
setting.revealtype="on"+(setting.revealtype || "click")
setting.curopacity=0
setting.onChange=setting.onChange || function(){}
if (setting.contentsource[0]=="inline")
this.buildpaginate(setting)
}
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
(function()
{
// IE6 doens't handle absolute positioning properly (it is always in quirks
// mode). This function fixes the sizes and positions of many elements that
// compose the skin (this is skin specific).
var fixSizes = window.DoResizeFixes = function()
{
var fckDlg = window.document.body ;
for ( var i = 0 ; i < fckDlg.childNodes.length ; i++ )
{
var child = fckDlg.childNodes[i] ;
switch ( child.className )
{
case 'contents' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 ) ; // -left -right
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 ) ; // -bottom -top
break ;
case 'blocker' :
case 'cover' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 + 4 ) ; // -left -right + 4
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 + 4 ) ; // -bottom -top + 4
break ;
case 'tr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
break ;
case 'tc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 16 - 16 ) ;
break ;
case 'ml' :
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'mr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'bl' :
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'br' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'bc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 30 - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
}
}
}
var closeButtonOver = function()
{
this.style.backgroundPosition = '-16px -687px' ;
} ;
var closeButtonOut = function()
{
this.style.backgroundPosition = '-16px -651px' ;
} ;
var fixCloseButton = function()
{
var closeButton = document.getElementById ( 'closeButton' ) ;
closeButton.onmouseover = closeButtonOver ;
closeButton.onmouseout = closeButtonOut ;
}
var onLoad = function()
{
fixSizes() ;
fixCloseButton() ;
window.attachEvent( 'onresize', fixSizes ) ;
window.detachEvent( 'onload', onLoad ) ;
}
window.attachEvent( 'onload', onLoad ) ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
(function()
{
// IE6 doens't handle absolute positioning properly (it is always in quirks
// mode). This function fixes the sizes and positions of many elements that
// compose the skin (this is skin specific).
var fixSizes = window.DoResizeFixes = function()
{
var fckDlg = window.document.body ;
for ( var i = 0 ; i < fckDlg.childNodes.length ; i++ )
{
var child = fckDlg.childNodes[i] ;
switch ( child.className )
{
case 'contents' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 ) ; // -left -right
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 ) ; // -bottom -top
break ;
case 'blocker' :
case 'cover' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 + 4 ) ; // -left -right + 4
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 + 4 ) ; // -bottom -top + 4
break ;
case 'tr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
break ;
case 'tc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 16 - 16 ) ;
break ;
case 'ml' :
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'mr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'bl' :
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'br' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'bc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 30 - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
}
}
}
var closeButtonOver = function()
{
this.style.backgroundPosition = '-16px -687px' ;
} ;
var closeButtonOut = function()
{
this.style.backgroundPosition = '-16px -651px' ;
} ;
var fixCloseButton = function()
{
var closeButton = document.getElementById ( 'closeButton' ) ;
closeButton.onmouseover = closeButtonOver ;
closeButton.onmouseout = closeButtonOut ;
}
var onLoad = function()
{
fixSizes() ;
fixCloseButton() ;
window.attachEvent( 'onresize', fixSizes ) ;
window.detachEvent( 'onload', onLoad ) ;
}
window.attachEvent( 'onload', onLoad ) ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
(function()
{
// IE6 doens't handle absolute positioning properly (it is always in quirks
// mode). This function fixes the sizes and positions of many elements that
// compose the skin (this is skin specific).
var fixSizes = window.DoResizeFixes = function()
{
var fckDlg = window.document.body ;
for ( var i = 0 ; i < fckDlg.childNodes.length ; i++ )
{
var child = fckDlg.childNodes[i] ;
switch ( child.className )
{
case 'contents' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 ) ; // -left -right
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 ) ; // -bottom -top
break ;
case 'blocker' :
case 'cover' :
child.style.width = Math.max( 0, fckDlg.offsetWidth - 16 - 16 + 4 ) ; // -left -right + 4
child.style.height = Math.max( 0, fckDlg.clientHeight - 20 - 2 + 4 ) ; // -bottom -top + 4
break ;
case 'tr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
break ;
case 'tc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 16 - 16 ) ;
break ;
case 'ml' :
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'mr' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 16 ) ;
child.style.height = Math.max( 0, fckDlg.clientHeight - 16 - 51 ) ;
break ;
case 'bl' :
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'br' :
child.style.left = Math.max( 0, fckDlg.clientWidth - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
case 'bc' :
child.style.width = Math.max( 0, fckDlg.clientWidth - 30 - 30 ) ;
child.style.top = Math.max( 0, fckDlg.clientHeight - 51 ) ;
break ;
}
}
}
var closeButtonOver = function()
{
this.style.backgroundPosition = '-16px -687px' ;
} ;
var closeButtonOut = function()
{
this.style.backgroundPosition = '-16px -651px' ;
} ;
var fixCloseButton = function()
{
var closeButton = document.getElementById ( 'closeButton' ) ;
closeButton.onmouseover = closeButtonOver ;
closeButton.onmouseout = closeButtonOut ;
}
var onLoad = function()
{
fixSizes() ;
fixCloseButton() ;
window.attachEvent( 'onresize', fixSizes ) ;
window.detachEvent( 'onload', onLoad ) ;
}
window.attachEvent( 'onload', onLoad ) ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Compatibility code for Adobe AIR.
*/
if ( FCKBrowserInfo.IsAIR )
{
var FCKAdobeAIR = (function()
{
/*
* ### Private functions.
*/
var getDocumentHead = function( doc )
{
var head ;
var heads = doc.getElementsByTagName( 'head' ) ;
if( heads && heads[0] )
head = heads[0] ;
else
{
head = doc.createElement( 'head' ) ;
doc.documentElement.insertBefore( head, doc.documentElement.firstChild ) ;
}
return head ;
} ;
/*
* ### Public interface.
*/
return {
FCKeditorAPI_Evaluate : function( parentWindow, script )
{
// TODO : This one doesn't work always. The parent window will
// point to an anonymous function in this window. If this
// window is destroyied the parent window will be pointing to
// an invalid reference.
// Evaluate the script in this window.
eval( script ) ;
// Point the FCKeditorAPI property of the parent window to the
// local reference.
parentWindow.FCKeditorAPI = window.FCKeditorAPI ;
},
EditingArea_Start : function( doc, html )
{
// Get the HTML for the <head>.
var headInnerHtml = html.match( /<head>([\s\S]*)<\/head>/i )[1] ;
if ( headInnerHtml && headInnerHtml.length > 0 )
{
// Inject the <head> HTML inside a <div>.
// Do that before getDocumentHead because WebKit moves
// <link css> elements to the <head> at this point.
var div = doc.createElement( 'div' ) ;
div.innerHTML = headInnerHtml ;
// Move the <div> nodes to <head>.
FCKDomTools.MoveChildren( div, getDocumentHead( doc ) ) ;
}
doc.body.innerHTML = html.match( /<body>([\s\S]*)<\/body>/i )[1] ;
//prevent clicking on hyperlinks and navigating away
doc.addEventListener('click', function( ev )
{
ev.preventDefault() ;
ev.stopPropagation() ;
}, true ) ;
},
Panel_Contructor : function( doc, baseLocation )
{
var head = getDocumentHead( doc ) ;
// Set the <base> href.
head.appendChild( doc.createElement('base') ).href = baseLocation ;
doc.body.style.margin = '0px' ;
doc.body.style.padding = '0px' ;
},
ToolbarSet_GetOutElement : function( win, outMatch )
{
var toolbarTarget = win.parent ;
var targetWindowParts = outMatch[1].split( '.' ) ;
while ( targetWindowParts.length > 0 )
{
var part = targetWindowParts.shift() ;
if ( part.length > 0 )
toolbarTarget = toolbarTarget[ part ] ;
}
toolbarTarget = toolbarTarget.document.getElementById( outMatch[2] ) ;
},
ToolbarSet_InitOutFrame : function( doc )
{
var head = getDocumentHead( doc ) ;
head.appendChild( doc.createElement('base') ).href = window.document.location ;
var targetWindow = doc.defaultView;
targetWindow.adjust = function()
{
targetWindow.frameElement.height = doc.body.scrollHeight;
} ;
targetWindow.onresize = targetWindow.adjust ;
targetWindow.setTimeout( targetWindow.adjust, 0 ) ;
doc.body.style.overflow = 'hidden';
doc.body.innerHTML = document.getElementById( 'xToolbarSpace' ).innerHTML ;
}
} ;
})();
/*
* ### Overrides
*/
( function()
{
// Save references for override reuse.
var _Original_FCKPanel_Window_OnFocus = FCKPanel_Window_OnFocus ;
var _Original_FCKPanel_Window_OnBlur = FCKPanel_Window_OnBlur ;
var _Original_FCK_StartEditor = FCK.StartEditor ;
FCKPanel_Window_OnFocus = function( e, panel )
{
// Call the original implementation.
_Original_FCKPanel_Window_OnFocus.call( this, e, panel ) ;
if ( panel._focusTimer )
clearTimeout( panel._focusTimer ) ;
}
FCKPanel_Window_OnBlur = function( e, panel )
{
// Delay the execution of the original function.
panel._focusTimer = FCKTools.SetTimeout( _Original_FCKPanel_Window_OnBlur, 100, this, [ e, panel ] ) ;
}
FCK.StartEditor = function()
{
// Force pointing to the CSS files instead of using the inline CSS cached styles.
window.FCK_InternalCSS = FCKConfig.BasePath + 'css/fck_internal.css' ;
window.FCK_ShowTableBordersCSS = FCKConfig.BasePath + 'css/fck_showtableborders_gecko.css' ;
_Original_FCK_StartEditor.apply( this, arguments ) ;
}
})();
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Contains the DTD mapping for XHTML 1.0 Strict.
* This file was automatically generated from the file: xhtml10-strict.dtd
*/
FCK.DTD = (function()
{
var X = FCKTools.Merge ;
var H,I,J,K,C,L,M,A,B,D,E,G,N,F ;
A = {ins:1, del:1, script:1} ;
B = {hr:1, ul:1, div:1, blockquote:1, noscript:1, table:1, address:1, pre:1, p:1, h5:1, dl:1, h4:1, ol:1, h6:1, h1:1, h3:1, h2:1} ;
C = X({fieldset:1}, B) ;
D = X({sub:1, bdo:1, 'var':1, sup:1, br:1, kbd:1, map:1, samp:1, b:1, acronym:1, '#':1, abbr:1, code:1, i:1, cite:1, tt:1, strong:1, q:1, em:1, big:1, small:1, span:1, dfn:1}, A) ;
E = X({img:1, object:1}, D) ;
F = {input:1, button:1, textarea:1, select:1, label:1} ;
G = X({a:1}, F) ;
H = {img:1, noscript:1, br:1, kbd:1, button:1, h5:1, h4:1, samp:1, h6:1, ol:1, h1:1, h3:1, h2:1, form:1, select:1, '#':1, ins:1, abbr:1, label:1, code:1, table:1, script:1, cite:1, input:1, strong:1, textarea:1, big:1, small:1, span:1, hr:1, sub:1, bdo:1, 'var':1, div:1, object:1, sup:1, map:1, dl:1, del:1, fieldset:1, ul:1, b:1, acronym:1, a:1, blockquote:1, i:1, address:1, tt:1, q:1, pre:1, p:1, em:1, dfn:1} ;
I = X({form:1, fieldset:1}, B, E, G) ;
J = {tr:1} ;
K = {'#':1} ;
L = X(E, G) ;
M = {li:1} ;
N = X({form:1}, A, C) ;
return {
col: {},
tr: {td:1, th:1},
img: {},
colgroup: {col:1},
noscript: N,
td: I,
br: {},
th: I,
kbd: L,
button: X(B, E),
h5: L,
h4: L,
samp: L,
h6: L,
ol: M,
h1: L,
h3: L,
option: K,
h2: L,
form: X(A, C),
select: {optgroup:1, option:1},
ins: I,
abbr: L,
label: L,
code: L,
table: {thead:1, col:1, tbody:1, tr:1, colgroup:1, caption:1, tfoot:1},
script: K,
tfoot: J,
cite: L,
li: I,
input: {},
strong: L,
textarea: K,
big: L,
small: L,
span: L,
dt: L,
hr: {},
sub: L,
optgroup: {option:1},
bdo: L,
param: {},
'var': L,
div: I,
object: X({param:1}, H),
sup: L,
dd: I,
area: {},
map: X({form:1, area:1}, A, C),
dl: {dt:1, dd:1},
del: I,
fieldset: X({legend:1}, H),
thead: J,
ul: M,
acronym: L,
b: L,
a: X({img:1, object:1}, D, F),
blockquote: N,
caption: L,
i: L,
tbody: J,
address: L,
tt: L,
legend: L,
q: L,
pre: X({a:1}, D, F),
p: L,
em: L,
dfn: L
} ;
})() ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Contains the DTD mapping for XHTML 1.0 Transitional.
* This file was automatically generated from the file: xhtml10-transitional.dtd
*/
FCK.DTD = (function()
{
var X = FCKTools.Merge ;
var A,L,J,M,N,O,D,H,P,K,Q,F,G,C,B,E,I ;
A = {isindex:1, fieldset:1} ;
B = {input:1, button:1, select:1, textarea:1, label:1} ;
C = X({a:1}, B) ;
D = X({iframe:1}, C) ;
E = {hr:1, ul:1, menu:1, div:1, blockquote:1, noscript:1, table:1, center:1, address:1, dir:1, pre:1, h5:1, dl:1, h4:1, noframes:1, h6:1, ol:1, h1:1, h3:1, h2:1} ;
F = {ins:1, del:1, script:1} ;
G = X({b:1, acronym:1, bdo:1, 'var':1, '#':1, abbr:1, code:1, br:1, i:1, cite:1, kbd:1, u:1, strike:1, s:1, tt:1, strong:1, q:1, samp:1, em:1, dfn:1, span:1}, F) ;
H = X({sub:1, img:1, object:1, sup:1, basefont:1, map:1, applet:1, font:1, big:1, small:1}, G) ;
I = X({p:1}, H) ;
J = X({iframe:1}, H, B) ;
K = {img:1, noscript:1, br:1, kbd:1, center:1, button:1, basefont:1, h5:1, h4:1, samp:1, h6:1, ol:1, h1:1, h3:1, h2:1, form:1, font:1, '#':1, select:1, menu:1, ins:1, abbr:1, label:1, code:1, table:1, script:1, cite:1, input:1, iframe:1, strong:1, textarea:1, noframes:1, big:1, small:1, span:1, hr:1, sub:1, bdo:1, 'var':1, div:1, object:1, sup:1, strike:1, dir:1, map:1, dl:1, applet:1, del:1, isindex:1, fieldset:1, ul:1, b:1, acronym:1, a:1, blockquote:1, i:1, u:1, s:1, tt:1, address:1, q:1, pre:1, p:1, em:1, dfn:1} ;
L = X({a:1}, J) ;
M = {tr:1} ;
N = {'#':1} ;
O = X({param:1}, K) ;
P = X({form:1}, A, D, E, I) ;
Q = {li:1} ;
return {
col: {},
tr: {td:1, th:1},
img: {},
colgroup: {col:1},
noscript: P,
td: P,
br: {},
th: P,
center: P,
kbd: L,
button: X(I, E),
basefont: {},
h5: L,
h4: L,
samp: L,
h6: L,
ol: Q,
h1: L,
h3: L,
option: N,
h2: L,
form: X(A, D, E, I),
select: {optgroup:1, option:1},
font: J, // Changed from L to J (see (1))
ins: P,
menu: Q,
abbr: L,
label: L,
table: {thead:1, col:1, tbody:1, tr:1, colgroup:1, caption:1, tfoot:1},
code: L,
script: N,
tfoot: M,
cite: L,
li: P,
input: {},
iframe: P,
strong: J, // Changed from L to J (see (1))
textarea: N,
noframes: P,
big: J, // Changed from L to J (see (1))
small: J, // Changed from L to J (see (1))
span: J, // Changed from L to J (see (1))
hr: {},
dt: L,
sub: J, // Changed from L to J (see (1))
optgroup: {option:1},
param: {},
bdo: L,
'var': J, // Changed from L to J (see (1))
div: P,
object: O,
sup: J, // Changed from L to J (see (1))
dd: P,
strike: J, // Changed from L to J (see (1))
area: {},
dir: Q,
map: X({area:1, form:1, p:1}, A, F, E),
applet: O,
dl: {dt:1, dd:1},
del: P,
isindex: {},
fieldset: X({legend:1}, K),
thead: M,
ul: Q,
acronym: L,
b: J, // Changed from L to J (see (1))
a: J,
blockquote: P,
caption: L,
i: J, // Changed from L to J (see (1))
u: J, // Changed from L to J (see (1))
tbody: M,
s: L,
address: X(D, I),
tt: J, // Changed from L to J (see (1))
legend: L,
q: L,
pre: X(G, C),
p: L,
em: J, // Changed from L to J (see (1))
dfn: L
} ;
})() ;
/*
Notes:
(1) According to the DTD, many elements, like <b> accept <a> elements
inside of them. But, to produce better output results, we have manually
changed the map to avoid breaking the links on pieces, having
"<b>this is a </b><a><b>link</b> test</a>", instead of
"<b>this is a <a>link</a></b><a> test</a>".
*/
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Chinese Simplified language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "折叠工具栏",
ToolbarExpand : "展开工具栏",
// Toolbar Items and Context Menu
Save : "保存",
NewPage : "新建",
Preview : "预览",
Cut : "剪切",
Copy : "复制",
Paste : "粘贴",
PasteText : "粘贴为无格式文本",
PasteWord : "从 MS Word 粘贴",
Print : "打印",
SelectAll : "全选",
RemoveFormat : "清除格式",
InsertLinkLbl : "超链接",
InsertLink : "插入/编辑超链接",
RemoveLink : "取消超链接",
VisitLink : "打开超链接",
Anchor : "插入/编辑锚点链接",
AnchorDelete : "清除锚点链接",
InsertImageLbl : "图象",
InsertImage : "插入/编辑图象",
InsertFlashLbl : "Flash",
InsertFlash : "插入/编辑 Flash",
InsertTableLbl : "表格",
InsertTable : "插入/编辑表格",
InsertLineLbl : "水平线",
InsertLine : "插入水平线",
InsertSpecialCharLbl: "特殊符号",
InsertSpecialChar : "插入特殊符号",
InsertSmileyLbl : "表情符",
InsertSmiley : "插入表情图标",
About : "关于 FCKeditor",
Bold : "加粗",
Italic : "倾斜",
Underline : "下划线",
StrikeThrough : "删除线",
Subscript : "下标",
Superscript : "上标",
LeftJustify : "左对齐",
CenterJustify : "居中对齐",
RightJustify : "右对齐",
BlockJustify : "两端对齐",
DecreaseIndent : "减少缩进量",
IncreaseIndent : "增加缩进量",
Blockquote : "块引用",
CreateDiv : "新增 Div 标籤",
EditDiv : "更改 Div 标籤",
DeleteDiv : "删除 Div 标籤",
Undo : "撤消",
Redo : "重做",
NumberedListLbl : "编号列表",
NumberedList : "插入/删除编号列表",
BulletedListLbl : "项目列表",
BulletedList : "插入/删除项目列表",
ShowTableBorders : "显示表格边框",
ShowDetails : "显示详细资料",
Style : "样式",
FontFormat : "格式",
Font : "字体",
FontSize : "大小",
TextColor : "文本颜色",
BGColor : "背景颜色",
Source : "源代码",
Find : "查找",
Replace : "替换",
SpellCheck : "拼写检查",
UniversalKeyboard : "软键盘",
PageBreakLbl : "分页符",
PageBreak : "插入分页符",
Form : "表单",
Checkbox : "复选框",
RadioButton : "单选按钮",
TextField : "单行文本",
Textarea : "多行文本",
HiddenField : "隐藏域",
Button : "按钮",
SelectionField : "列表/菜单",
ImageButton : "图像域",
FitWindow : "全屏编辑",
ShowBlocks : "显示区块",
// Context Menu
EditLink : "编辑超链接",
CellCM : "单元格",
RowCM : "行",
ColumnCM : "列",
InsertRowAfter : "下插入行",
InsertRowBefore : "上插入行",
DeleteRows : "删除行",
InsertColumnAfter : "右插入列",
InsertColumnBefore : "左插入列",
DeleteColumns : "删除列",
InsertCellAfter : "右插入单元格",
InsertCellBefore : "左插入单元格",
DeleteCells : "删除单元格",
MergeCells : "合并单元格",
MergeRight : "右合并单元格",
MergeDown : "下合并单元格",
HorizontalSplitCell : "橫拆分单元格",
VerticalSplitCell : "縱拆分单元格",
TableDelete : "删除表格",
CellProperties : "单元格属性",
TableProperties : "表格属性",
ImageProperties : "图象属性",
FlashProperties : "Flash 属性",
AnchorProp : "锚点链接属性",
ButtonProp : "按钮属性",
CheckboxProp : "复选框属性",
HiddenFieldProp : "隐藏域属性",
RadioButtonProp : "单选按钮属性",
ImageButtonProp : "图像域属性",
TextFieldProp : "单行文本属性",
SelectionFieldProp : "菜单/列表属性",
TextareaProp : "多行文本属性",
FormProp : "表单属性",
FontFormats : "普通;已编排格式;地址;标题 1;标题 2;标题 3;标题 4;标题 5;标题 6;段落(DIV)",
// Alerts and Messages
ProcessingXHTML : "正在处理 XHTML,请稍等...",
Done : "完成",
PasteWordConfirm : "您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?",
NotCompatiblePaste : "该命令需要 Internet Explorer 5.5 或更高版本的支持,是否按常规粘贴进行?",
UnknownToolbarItem : "未知工具栏项目 \"%1\"",
UnknownCommand : "未知命令名称 \"%1\"",
NotImplemented : "命令无法执行",
UnknownToolbarSet : "工具栏设置 \"%1\" 不存在",
NoActiveX : "浏览器安全设置限制了本编辑器的某些功能。您必须启用安全设置中的“运行 ActiveX 控件和插件”,否则将出现某些错误并缺少功能。",
BrowseServerBlocked : "无法打开资源浏览器,请确认是否启用了禁止弹出窗口。",
DialogBlocked : "无法打开对话框窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。",
VisitLinkBlocked : "无法打开新窗口,请确认是否启用了禁止弹出窗口或网页对话框(IE)。",
// Dialogs
DlgBtnOK : "确定",
DlgBtnCancel : "取消",
DlgBtnClose : "关闭",
DlgBtnBrowseServer : "浏览服务器",
DlgAdvancedTag : "高级",
DlgOpOther : "<其它>",
DlgInfoTab : "信息",
DlgAlertUrl : "请插入 URL",
// General Dialogs Labels
DlgGenNotSet : "<没有设置>",
DlgGenId : "ID",
DlgGenLangDir : "语言方向",
DlgGenLangDirLtr : "从左到右 (LTR)",
DlgGenLangDirRtl : "从右到左 (RTL)",
DlgGenLangCode : "语言代码",
DlgGenAccessKey : "访问键",
DlgGenName : "名称",
DlgGenTabIndex : "Tab 键次序",
DlgGenLongDescr : "详细说明地址",
DlgGenClass : "样式类名称",
DlgGenTitle : "标题",
DlgGenContType : "内容类型",
DlgGenLinkCharset : "字符编码",
DlgGenStyle : "行内样式",
// Image Dialog
DlgImgTitle : "图象属性",
DlgImgInfoTab : "图象",
DlgImgBtnUpload : "发送到服务器上",
DlgImgURL : "源文件",
DlgImgUpload : "上传",
DlgImgAlt : "替换文本",
DlgImgWidth : "宽度",
DlgImgHeight : "高度",
DlgImgLockRatio : "锁定比例",
DlgBtnResetSize : "恢复尺寸",
DlgImgBorder : "边框大小",
DlgImgHSpace : "水平间距",
DlgImgVSpace : "垂直间距",
DlgImgAlign : "对齐方式",
DlgImgAlignLeft : "左对齐",
DlgImgAlignAbsBottom: "绝对底边",
DlgImgAlignAbsMiddle: "绝对居中",
DlgImgAlignBaseline : "基线",
DlgImgAlignBottom : "底边",
DlgImgAlignMiddle : "居中",
DlgImgAlignRight : "右对齐",
DlgImgAlignTextTop : "文本上方",
DlgImgAlignTop : "顶端",
DlgImgPreview : "预览",
DlgImgAlertUrl : "请输入图象地址",
DlgImgLinkTab : "链接",
// Flash Dialog
DlgFlashTitle : "Flash 属性",
DlgFlashChkPlay : "自动播放",
DlgFlashChkLoop : "循环",
DlgFlashChkMenu : "启用 Flash 菜单",
DlgFlashScale : "缩放",
DlgFlashScaleAll : "全部显示",
DlgFlashScaleNoBorder : "无边框",
DlgFlashScaleFit : "严格匹配",
// Link Dialog
DlgLnkWindowTitle : "超链接",
DlgLnkInfoTab : "超链接信息",
DlgLnkTargetTab : "目标",
DlgLnkType : "超链接类型",
DlgLnkTypeURL : "超链接",
DlgLnkTypeAnchor : "页内锚点链接",
DlgLnkTypeEMail : "电子邮件",
DlgLnkProto : "协议",
DlgLnkProtoOther : "<其它>",
DlgLnkURL : "地址",
DlgLnkAnchorSel : "选择一个锚点",
DlgLnkAnchorByName : "按锚点名称",
DlgLnkAnchorById : "按锚点 ID",
DlgLnkNoAnchors : "(此文档没有可用的锚点)",
DlgLnkEMail : "地址",
DlgLnkEMailSubject : "主题",
DlgLnkEMailBody : "内容",
DlgLnkUpload : "上传",
DlgLnkBtnUpload : "发送到服务器上",
DlgLnkTarget : "目标",
DlgLnkTargetFrame : "<框架>",
DlgLnkTargetPopup : "<弹出窗口>",
DlgLnkTargetBlank : "新窗口 (_blank)",
DlgLnkTargetParent : "父窗口 (_parent)",
DlgLnkTargetSelf : "本窗口 (_self)",
DlgLnkTargetTop : "整页 (_top)",
DlgLnkTargetFrameName : "目标框架名称",
DlgLnkPopWinName : "弹出窗口名称",
DlgLnkPopWinFeat : "弹出窗口属性",
DlgLnkPopResize : "调整大小",
DlgLnkPopLocation : "地址栏",
DlgLnkPopMenu : "菜单栏",
DlgLnkPopScroll : "滚动条",
DlgLnkPopStatus : "状态栏",
DlgLnkPopToolbar : "工具栏",
DlgLnkPopFullScrn : "全屏 (IE)",
DlgLnkPopDependent : "依附 (NS)",
DlgLnkPopWidth : "宽",
DlgLnkPopHeight : "高",
DlgLnkPopLeft : "左",
DlgLnkPopTop : "右",
DlnLnkMsgNoUrl : "请输入超链接地址",
DlnLnkMsgNoEMail : "请输入电子邮件地址",
DlnLnkMsgNoAnchor : "请选择一个锚点",
DlnLnkMsgInvPopName : "弹出窗口名称必须以字母开头,并且不能含有空格。",
// Color Dialog
DlgColorTitle : "选择颜色",
DlgColorBtnClear : "清除",
DlgColorHighlight : "预览",
DlgColorSelected : "选择",
// Smiley Dialog
DlgSmileyTitle : "插入表情图标",
// Special Character Dialog
DlgSpecialCharTitle : "选择特殊符号",
// Table Dialog
DlgTableTitle : "表格属性",
DlgTableRows : "行数",
DlgTableColumns : "列数",
DlgTableBorder : "边框",
DlgTableAlign : "对齐",
DlgTableAlignNotSet : "<没有设置>",
DlgTableAlignLeft : "左对齐",
DlgTableAlignCenter : "居中",
DlgTableAlignRight : "右对齐",
DlgTableWidth : "宽度",
DlgTableWidthPx : "像素",
DlgTableWidthPc : "百分比",
DlgTableHeight : "高度",
DlgTableCellSpace : "间距",
DlgTableCellPad : "边距",
DlgTableCaption : "标题",
DlgTableSummary : "摘要",
// Table Cell Dialog
DlgCellTitle : "单元格属性",
DlgCellWidth : "宽度",
DlgCellWidthPx : "像素",
DlgCellWidthPc : "百分比",
DlgCellHeight : "高度",
DlgCellWordWrap : "自动换行",
DlgCellWordWrapNotSet : "<没有设置>",
DlgCellWordWrapYes : "是",
DlgCellWordWrapNo : "否",
DlgCellHorAlign : "水平对齐",
DlgCellHorAlignNotSet : "<没有设置>",
DlgCellHorAlignLeft : "左对齐",
DlgCellHorAlignCenter : "居中",
DlgCellHorAlignRight: "右对齐",
DlgCellVerAlign : "垂直对齐",
DlgCellVerAlignNotSet : "<没有设置>",
DlgCellVerAlignTop : "顶端",
DlgCellVerAlignMiddle : "居中",
DlgCellVerAlignBottom : "底部",
DlgCellVerAlignBaseline : "基线",
DlgCellRowSpan : "纵跨行数",
DlgCellCollSpan : "横跨列数",
DlgCellBackColor : "背景颜色",
DlgCellBorderColor : "边框颜色",
DlgCellBtnSelect : "选择...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "查找和替换",
// Find Dialog
DlgFindTitle : "查找",
DlgFindFindBtn : "查找",
DlgFindNotFoundMsg : "指定文本没有找到。",
// Replace Dialog
DlgReplaceTitle : "替换",
DlgReplaceFindLbl : "查找:",
DlgReplaceReplaceLbl : "替换:",
DlgReplaceCaseChk : "区分大小写",
DlgReplaceReplaceBtn : "替换",
DlgReplaceReplAllBtn : "全部替换",
DlgReplaceWordChk : "全字匹配",
// Paste Operations / Dialog
PasteErrorCut : "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成。",
PasteErrorCopy : "您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl+C)来完成。",
PasteAsText : "粘贴为无格式文本",
PasteFromWord : "从 MS Word 粘贴",
DlgPasteMsg2 : "请使用键盘快捷键(<STRONG>Ctrl+V</STRONG>)把内容粘贴到下面的方框里,再按 <STRONG>确定</STRONG>。",
DlgPasteSec : "因为你的浏览器的安全设置原因,本编辑器不能直接访问你的剪贴板内容,你需要在本窗口重新粘贴一次。",
DlgPasteIgnoreFont : "忽略 Font 标签",
DlgPasteRemoveStyles : "清理 CSS 样式",
// Color Picker
ColorAutomatic : "自动",
ColorMoreColors : "其它颜色...",
// Document Properties
DocProps : "页面属性",
// Anchor Dialog
DlgAnchorTitle : "命名锚点",
DlgAnchorName : "锚点名称",
DlgAnchorErrorName : "请输入锚点名称",
// Speller Pages Dialog
DlgSpellNotInDic : "没有在字典里",
DlgSpellChangeTo : "更改为",
DlgSpellBtnIgnore : "忽略",
DlgSpellBtnIgnoreAll : "全部忽略",
DlgSpellBtnReplace : "替换",
DlgSpellBtnReplaceAll : "全部替换",
DlgSpellBtnUndo : "撤消",
DlgSpellNoSuggestions : "- 没有建议 -",
DlgSpellProgress : "正在进行拼写检查...",
DlgSpellNoMispell : "拼写检查完成:没有发现拼写错误",
DlgSpellNoChanges : "拼写检查完成:没有更改任何单词",
DlgSpellOneChange : "拼写检查完成:更改了一个单词",
DlgSpellManyChanges : "拼写检查完成:更改了 %1 个单词",
IeSpellDownload : "拼写检查插件还没安装,你是否想现在就下载?",
// Button Dialog
DlgButtonText : "标签(值)",
DlgButtonType : "类型",
DlgButtonTypeBtn : "按钮",
DlgButtonTypeSbm : "提交",
DlgButtonTypeRst : "重设",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "名称",
DlgCheckboxValue : "选定值",
DlgCheckboxSelected : "已勾选",
// Form Dialog
DlgFormName : "名称",
DlgFormAction : "动作",
DlgFormMethod : "方法",
// Select Field Dialog
DlgSelectName : "名称",
DlgSelectValue : "选定",
DlgSelectSize : "高度",
DlgSelectLines : "行",
DlgSelectChkMulti : "允许多选",
DlgSelectOpAvail : "列表值",
DlgSelectOpText : "标签",
DlgSelectOpValue : "值",
DlgSelectBtnAdd : "新增",
DlgSelectBtnModify : "修改",
DlgSelectBtnUp : "上移",
DlgSelectBtnDown : "下移",
DlgSelectBtnSetValue : "设为初始化时选定",
DlgSelectBtnDelete : "删除",
// Textarea Dialog
DlgTextareaName : "名称",
DlgTextareaCols : "字符宽度",
DlgTextareaRows : "行数",
// Text Field Dialog
DlgTextName : "名称",
DlgTextValue : "初始值",
DlgTextCharWidth : "字符宽度",
DlgTextMaxChars : "最多字符数",
DlgTextType : "类型",
DlgTextTypeText : "文本",
DlgTextTypePass : "密码",
// Hidden Field Dialog
DlgHiddenName : "名称",
DlgHiddenValue : "初始值",
// Bulleted List Dialog
BulletedListProp : "项目列表属性",
NumberedListProp : "编号列表属性",
DlgLstStart : "开始序号",
DlgLstType : "列表类型",
DlgLstTypeCircle : "圆圈",
DlgLstTypeDisc : "圆点",
DlgLstTypeSquare : "方块",
DlgLstTypeNumbers : "数字 (1, 2, 3)",
DlgLstTypeLCase : "小写字母 (a, b, c)",
DlgLstTypeUCase : "大写字母 (A, B, C)",
DlgLstTypeSRoman : "小写罗马数字 (i, ii, iii)",
DlgLstTypeLRoman : "大写罗马数字 (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "常规",
DlgDocBackTab : "背景",
DlgDocColorsTab : "颜色和边距",
DlgDocMetaTab : "Meta 数据",
DlgDocPageTitle : "页面标题",
DlgDocLangDir : "语言方向",
DlgDocLangDirLTR : "从左到右 (LTR)",
DlgDocLangDirRTL : "从右到左 (RTL)",
DlgDocLangCode : "语言代码",
DlgDocCharSet : "字符编码",
DlgDocCharSetCE : "中欧",
DlgDocCharSetCT : "繁体中文 (Big5)",
DlgDocCharSetCR : "西里尔文",
DlgDocCharSetGR : "希腊文",
DlgDocCharSetJP : "日文",
DlgDocCharSetKR : "韩文",
DlgDocCharSetTR : "土耳其文",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "西欧",
DlgDocCharSetOther : "其它字符编码",
DlgDocDocType : "文档类型",
DlgDocDocTypeOther : "其它文档类型",
DlgDocIncXHTML : "包含 XHTML 声明",
DlgDocBgColor : "背景颜色",
DlgDocBgImage : "背景图像",
DlgDocBgNoScroll : "不滚动背景图像",
DlgDocCText : "文本",
DlgDocCLink : "超链接",
DlgDocCVisited : "已访问的超链接",
DlgDocCActive : "活动超链接",
DlgDocMargins : "页面边距",
DlgDocMaTop : "上",
DlgDocMaLeft : "左",
DlgDocMaRight : "右",
DlgDocMaBottom : "下",
DlgDocMeIndex : "页面索引关键字 (用半角逗号[,]分隔)",
DlgDocMeDescr : "页面说明",
DlgDocMeAuthor : "作者",
DlgDocMeCopy : "版权",
DlgDocPreview : "预览",
// Templates Dialog
Templates : "模板",
DlgTemplatesTitle : "内容模板",
DlgTemplatesSelMsg : "请选择编辑器内容模板<br>(当前内容将会被清除替换):",
DlgTemplatesLoading : "正在加载模板列表,请稍等...",
DlgTemplatesNoTpl : "(没有模板)",
DlgTemplatesReplace : "替换当前内容",
// About Dialog
DlgAboutAboutTab : "关于",
DlgAboutBrowserInfoTab : "浏览器信息",
DlgAboutLicenseTab : "许可证",
DlgAboutVersion : "版本",
DlgAboutInfo : "要获得更多信息请访问 ",
// Div Dialog
DlgDivGeneralTab : "常规",
DlgDivAdvancedTab : "高级",
DlgDivStyle : "样式",
DlgDivInlineStyle : "CSS 样式",
insertCodeBtn : "插入代码"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* English language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "Collapse Toolbar",
ToolbarExpand : "Expand Toolbar",
// Toolbar Items and Context Menu
Save : "Save",
NewPage : "New Page",
Preview : "Preview",
Cut : "Cut",
Copy : "Copy",
Paste : "Paste",
PasteText : "Paste as plain text",
PasteWord : "Paste from Word",
Print : "Print",
SelectAll : "Select All",
RemoveFormat : "Remove Format",
InsertLinkLbl : "Link",
InsertLink : "Insert/Edit Link",
RemoveLink : "Remove Link",
VisitLink : "Open Link",
Anchor : "Insert/Edit Anchor",
AnchorDelete : "Remove Anchor",
InsertImageLbl : "Image",
InsertImage : "Insert/Edit Image",
InsertFlashLbl : "Flash",
InsertFlash : "Insert/Edit Flash",
InsertTableLbl : "Table",
InsertTable : "Insert/Edit Table",
InsertLineLbl : "Line",
InsertLine : "Insert Horizontal Line",
InsertSpecialCharLbl: "Special Character",
InsertSpecialChar : "Insert Special Character",
InsertSmileyLbl : "Smiley",
InsertSmiley : "Insert Smiley",
About : "About FCKeditor",
Bold : "Bold",
Italic : "Italic",
Underline : "Underline",
StrikeThrough : "Strike Through",
Subscript : "Subscript",
Superscript : "Superscript",
LeftJustify : "Left Justify",
CenterJustify : "Center Justify",
RightJustify : "Right Justify",
BlockJustify : "Block Justify",
DecreaseIndent : "Decrease Indent",
IncreaseIndent : "Increase Indent",
Blockquote : "Blockquote",
CreateDiv : "Create Div Container",
EditDiv : "Edit Div Container",
DeleteDiv : "Remove Div Container",
Undo : "Undo",
Redo : "Redo",
NumberedListLbl : "Numbered List",
NumberedList : "Insert/Remove Numbered List",
BulletedListLbl : "Bulleted List",
BulletedList : "Insert/Remove Bulleted List",
ShowTableBorders : "Show Table Borders",
ShowDetails : "Show Details",
Style : "Style",
FontFormat : "Format",
Font : "Font",
FontSize : "Size",
TextColor : "Text Color",
BGColor : "Background Color",
Source : "Source",
Find : "Find",
Replace : "Replace",
SpellCheck : "Check Spelling",
UniversalKeyboard : "Universal Keyboard",
PageBreakLbl : "Page Break",
PageBreak : "Insert Page Break",
Form : "Form",
Checkbox : "Checkbox",
RadioButton : "Radio Button",
TextField : "Text Field",
Textarea : "Textarea",
HiddenField : "Hidden Field",
Button : "Button",
SelectionField : "Selection Field",
ImageButton : "Image Button",
FitWindow : "Maximize the editor size",
ShowBlocks : "Show Blocks",
// Context Menu
EditLink : "Edit Link",
CellCM : "Cell",
RowCM : "Row",
ColumnCM : "Column",
InsertRowAfter : "Insert Row After",
InsertRowBefore : "Insert Row Before",
DeleteRows : "Delete Rows",
InsertColumnAfter : "Insert Column After",
InsertColumnBefore : "Insert Column Before",
DeleteColumns : "Delete Columns",
InsertCellAfter : "Insert Cell After",
InsertCellBefore : "Insert Cell Before",
DeleteCells : "Delete Cells",
MergeCells : "Merge Cells",
MergeRight : "Merge Right",
MergeDown : "Merge Down",
HorizontalSplitCell : "Split Cell Horizontally",
VerticalSplitCell : "Split Cell Vertically",
TableDelete : "Delete Table",
CellProperties : "Cell Properties",
TableProperties : "Table Properties",
ImageProperties : "Image Properties",
FlashProperties : "Flash Properties",
AnchorProp : "Anchor Properties",
ButtonProp : "Button Properties",
CheckboxProp : "Checkbox Properties",
HiddenFieldProp : "Hidden Field Properties",
RadioButtonProp : "Radio Button Properties",
ImageButtonProp : "Image Button Properties",
TextFieldProp : "Text Field Properties",
SelectionFieldProp : "Selection Field Properties",
TextareaProp : "Textarea Properties",
FormProp : "Form Properties",
FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)",
// Alerts and Messages
ProcessingXHTML : "Processing XHTML. Please wait...",
Done : "Done",
PasteWordConfirm : "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?",
NotCompatiblePaste : "This command is available for Internet Explorer version 5.5 or more. Do you want to paste without cleaning?",
UnknownToolbarItem : "Unknown toolbar item \"%1\"",
UnknownCommand : "Unknown command name \"%1\"",
NotImplemented : "Command not implemented",
UnknownToolbarSet : "Toolbar set \"%1\" doesn't exist",
NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.",
BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.",
DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.",
VisitLinkBlocked : "It was not possible to open a new window. Make sure all popup blockers are disabled.",
// Dialogs
DlgBtnOK : "OK",
DlgBtnCancel : "Cancel",
DlgBtnClose : "Close",
DlgBtnBrowseServer : "Browse Server",
DlgAdvancedTag : "Advanced",
DlgOpOther : "<Other>",
DlgInfoTab : "Info",
DlgAlertUrl : "Please insert the URL",
// General Dialogs Labels
DlgGenNotSet : "<not set>",
DlgGenId : "Id",
DlgGenLangDir : "Language Direction",
DlgGenLangDirLtr : "Left to Right (LTR)",
DlgGenLangDirRtl : "Right to Left (RTL)",
DlgGenLangCode : "Language Code",
DlgGenAccessKey : "Access Key",
DlgGenName : "Name",
DlgGenTabIndex : "Tab Index",
DlgGenLongDescr : "Long Description URL",
DlgGenClass : "Stylesheet Classes",
DlgGenTitle : "Advisory Title",
DlgGenContType : "Advisory Content Type",
DlgGenLinkCharset : "Linked Resource Charset",
DlgGenStyle : "Style",
// Image Dialog
DlgImgTitle : "Image Properties",
DlgImgInfoTab : "Image Info",
DlgImgBtnUpload : "Send it to the Server",
DlgImgURL : "URL",
DlgImgUpload : "Upload",
DlgImgAlt : "Alternative Text",
DlgImgWidth : "Width",
DlgImgHeight : "Height",
DlgImgLockRatio : "Lock Ratio",
DlgBtnResetSize : "Reset Size",
DlgImgBorder : "Border",
DlgImgHSpace : "HSpace",
DlgImgVSpace : "VSpace",
DlgImgAlign : "Align",
DlgImgAlignLeft : "Left",
DlgImgAlignAbsBottom: "Abs Bottom",
DlgImgAlignAbsMiddle: "Abs Middle",
DlgImgAlignBaseline : "Baseline",
DlgImgAlignBottom : "Bottom",
DlgImgAlignMiddle : "Middle",
DlgImgAlignRight : "Right",
DlgImgAlignTextTop : "Text Top",
DlgImgAlignTop : "Top",
DlgImgPreview : "Preview",
DlgImgAlertUrl : "Please type the image URL",
DlgImgLinkTab : "Link",
// Flash Dialog
DlgFlashTitle : "Flash Properties",
DlgFlashChkPlay : "Auto Play",
DlgFlashChkLoop : "Loop",
DlgFlashChkMenu : "Enable Flash Menu",
DlgFlashScale : "Scale",
DlgFlashScaleAll : "Show all",
DlgFlashScaleNoBorder : "No Border",
DlgFlashScaleFit : "Exact Fit",
// Link Dialog
DlgLnkWindowTitle : "Link",
DlgLnkInfoTab : "Link Info",
DlgLnkTargetTab : "Target",
DlgLnkType : "Link Type",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Link to anchor in the text",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protocol",
DlgLnkProtoOther : "<other>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "Select an Anchor",
DlgLnkAnchorByName : "By Anchor Name",
DlgLnkAnchorById : "By Element Id",
DlgLnkNoAnchors : "(No anchors available in the document)",
DlgLnkEMail : "E-Mail Address",
DlgLnkEMailSubject : "Message Subject",
DlgLnkEMailBody : "Message Body",
DlgLnkUpload : "Upload",
DlgLnkBtnUpload : "Send it to the Server",
DlgLnkTarget : "Target",
DlgLnkTargetFrame : "<frame>",
DlgLnkTargetPopup : "<popup window>",
DlgLnkTargetBlank : "New Window (_blank)",
DlgLnkTargetParent : "Parent Window (_parent)",
DlgLnkTargetSelf : "Same Window (_self)",
DlgLnkTargetTop : "Topmost Window (_top)",
DlgLnkTargetFrameName : "Target Frame Name",
DlgLnkPopWinName : "Popup Window Name",
DlgLnkPopWinFeat : "Popup Window Features",
DlgLnkPopResize : "Resizable",
DlgLnkPopLocation : "Location Bar",
DlgLnkPopMenu : "Menu Bar",
DlgLnkPopScroll : "Scroll Bars",
DlgLnkPopStatus : "Status Bar",
DlgLnkPopToolbar : "Toolbar",
DlgLnkPopFullScrn : "Full Screen (IE)",
DlgLnkPopDependent : "Dependent (Netscape)",
DlgLnkPopWidth : "Width",
DlgLnkPopHeight : "Height",
DlgLnkPopLeft : "Left Position",
DlgLnkPopTop : "Top Position",
DlnLnkMsgNoUrl : "Please type the link URL",
DlnLnkMsgNoEMail : "Please type the e-mail address",
DlnLnkMsgNoAnchor : "Please select an anchor",
DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces",
// Color Dialog
DlgColorTitle : "Select Color",
DlgColorBtnClear : "Clear",
DlgColorHighlight : "Highlight",
DlgColorSelected : "Selected",
// Smiley Dialog
DlgSmileyTitle : "Insert a Smiley",
// Special Character Dialog
DlgSpecialCharTitle : "Select Special Character",
// Table Dialog
DlgTableTitle : "Table Properties",
DlgTableRows : "Rows",
DlgTableColumns : "Columns",
DlgTableBorder : "Border size",
DlgTableAlign : "Alignment",
DlgTableAlignNotSet : "<Not set>",
DlgTableAlignLeft : "Left",
DlgTableAlignCenter : "Center",
DlgTableAlignRight : "Right",
DlgTableWidth : "Width",
DlgTableWidthPx : "pixels",
DlgTableWidthPc : "percent",
DlgTableHeight : "Height",
DlgTableCellSpace : "Cell spacing",
DlgTableCellPad : "Cell padding",
DlgTableCaption : "Caption",
DlgTableSummary : "Summary",
// Table Cell Dialog
DlgCellTitle : "Cell Properties",
DlgCellWidth : "Width",
DlgCellWidthPx : "pixels",
DlgCellWidthPc : "percent",
DlgCellHeight : "Height",
DlgCellWordWrap : "Word Wrap",
DlgCellWordWrapNotSet : "<Not set>",
DlgCellWordWrapYes : "Yes",
DlgCellWordWrapNo : "No",
DlgCellHorAlign : "Horizontal Alignment",
DlgCellHorAlignNotSet : "<Not set>",
DlgCellHorAlignLeft : "Left",
DlgCellHorAlignCenter : "Center",
DlgCellHorAlignRight: "Right",
DlgCellVerAlign : "Vertical Alignment",
DlgCellVerAlignNotSet : "<Not set>",
DlgCellVerAlignTop : "Top",
DlgCellVerAlignMiddle : "Middle",
DlgCellVerAlignBottom : "Bottom",
DlgCellVerAlignBaseline : "Baseline",
DlgCellRowSpan : "Rows Span",
DlgCellCollSpan : "Columns Span",
DlgCellBackColor : "Background Color",
DlgCellBorderColor : "Border Color",
DlgCellBtnSelect : "Select...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "Find and Replace",
// Find Dialog
DlgFindTitle : "Find",
DlgFindFindBtn : "Find",
DlgFindNotFoundMsg : "The specified text was not found.",
// Replace Dialog
DlgReplaceTitle : "Replace",
DlgReplaceFindLbl : "Find what:",
DlgReplaceReplaceLbl : "Replace with:",
DlgReplaceCaseChk : "Match case",
DlgReplaceReplaceBtn : "Replace",
DlgReplaceReplAllBtn : "Replace All",
DlgReplaceWordChk : "Match whole word",
// Paste Operations / Dialog
PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).",
PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).",
PasteAsText : "Paste as Plain Text",
PasteFromWord : "Paste from Word",
DlgPasteMsg2 : "Please paste inside the following box using the keyboard (<strong>Ctrl+V</strong>) and hit <strong>OK</strong>.",
DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.",
DlgPasteIgnoreFont : "Ignore Font Face definitions",
DlgPasteRemoveStyles : "Remove Styles definitions",
// Color Picker
ColorAutomatic : "Automatic",
ColorMoreColors : "More Colors...",
// Document Properties
DocProps : "Document Properties",
// Anchor Dialog
DlgAnchorTitle : "Anchor Properties",
DlgAnchorName : "Anchor Name",
DlgAnchorErrorName : "Please type the anchor name",
// Speller Pages Dialog
DlgSpellNotInDic : "Not in dictionary",
DlgSpellChangeTo : "Change to",
DlgSpellBtnIgnore : "Ignore",
DlgSpellBtnIgnoreAll : "Ignore All",
DlgSpellBtnReplace : "Replace",
DlgSpellBtnReplaceAll : "Replace All",
DlgSpellBtnUndo : "Undo",
DlgSpellNoSuggestions : "- No suggestions -",
DlgSpellProgress : "Spell check in progress...",
DlgSpellNoMispell : "Spell check complete: No misspellings found",
DlgSpellNoChanges : "Spell check complete: No words changed",
DlgSpellOneChange : "Spell check complete: One word changed",
DlgSpellManyChanges : "Spell check complete: %1 words changed",
IeSpellDownload : "Spell checker not installed. Do you want to download it now?",
// Button Dialog
DlgButtonText : "Text (Value)",
DlgButtonType : "Type",
DlgButtonTypeBtn : "Button",
DlgButtonTypeSbm : "Submit",
DlgButtonTypeRst : "Reset",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "Name",
DlgCheckboxValue : "Value",
DlgCheckboxSelected : "Selected",
// Form Dialog
DlgFormName : "Name",
DlgFormAction : "Action",
DlgFormMethod : "Method",
// Select Field Dialog
DlgSelectName : "Name",
DlgSelectValue : "Value",
DlgSelectSize : "Size",
DlgSelectLines : "lines",
DlgSelectChkMulti : "Allow multiple selections",
DlgSelectOpAvail : "Available Options",
DlgSelectOpText : "Text",
DlgSelectOpValue : "Value",
DlgSelectBtnAdd : "Add",
DlgSelectBtnModify : "Modify",
DlgSelectBtnUp : "Up",
DlgSelectBtnDown : "Down",
DlgSelectBtnSetValue : "Set as selected value",
DlgSelectBtnDelete : "Delete",
// Textarea Dialog
DlgTextareaName : "Name",
DlgTextareaCols : "Columns",
DlgTextareaRows : "Rows",
// Text Field Dialog
DlgTextName : "Name",
DlgTextValue : "Value",
DlgTextCharWidth : "Character Width",
DlgTextMaxChars : "Maximum Characters",
DlgTextType : "Type",
DlgTextTypeText : "Text",
DlgTextTypePass : "Password",
// Hidden Field Dialog
DlgHiddenName : "Name",
DlgHiddenValue : "Value",
// Bulleted List Dialog
BulletedListProp : "Bulleted List Properties",
NumberedListProp : "Numbered List Properties",
DlgLstStart : "Start",
DlgLstType : "Type",
DlgLstTypeCircle : "Circle",
DlgLstTypeDisc : "Disc",
DlgLstTypeSquare : "Square",
DlgLstTypeNumbers : "Numbers (1, 2, 3)",
DlgLstTypeLCase : "Lowercase Letters (a, b, c)",
DlgLstTypeUCase : "Uppercase Letters (A, B, C)",
DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)",
DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "General",
DlgDocBackTab : "Background",
DlgDocColorsTab : "Colors and Margins",
DlgDocMetaTab : "Meta Data",
DlgDocPageTitle : "Page Title",
DlgDocLangDir : "Language Direction",
DlgDocLangDirLTR : "Left to Right (LTR)",
DlgDocLangDirRTL : "Right to Left (RTL)",
DlgDocLangCode : "Language Code",
DlgDocCharSet : "Character Set Encoding",
DlgDocCharSetCE : "Central European",
DlgDocCharSetCT : "Chinese Traditional (Big5)",
DlgDocCharSetCR : "Cyrillic",
DlgDocCharSetGR : "Greek",
DlgDocCharSetJP : "Japanese",
DlgDocCharSetKR : "Korean",
DlgDocCharSetTR : "Turkish",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "Western European",
DlgDocCharSetOther : "Other Character Set Encoding",
DlgDocDocType : "Document Type Heading",
DlgDocDocTypeOther : "Other Document Type Heading",
DlgDocIncXHTML : "Include XHTML Declarations",
DlgDocBgColor : "Background Color",
DlgDocBgImage : "Background Image URL",
DlgDocBgNoScroll : "Nonscrolling Background",
DlgDocCText : "Text",
DlgDocCLink : "Link",
DlgDocCVisited : "Visited Link",
DlgDocCActive : "Active Link",
DlgDocMargins : "Page Margins",
DlgDocMaTop : "Top",
DlgDocMaLeft : "Left",
DlgDocMaRight : "Right",
DlgDocMaBottom : "Bottom",
DlgDocMeIndex : "Document Indexing Keywords (comma separated)",
DlgDocMeDescr : "Document Description",
DlgDocMeAuthor : "Author",
DlgDocMeCopy : "Copyright",
DlgDocPreview : "Preview",
// Templates Dialog
Templates : "Templates",
DlgTemplatesTitle : "Content Templates",
DlgTemplatesSelMsg : "Please select the template to open in the editor<br />(the actual contents will be lost):",
DlgTemplatesLoading : "Loading templates list. Please wait...",
DlgTemplatesNoTpl : "(No templates defined)",
DlgTemplatesReplace : "Replace actual contents",
// About Dialog
DlgAboutAboutTab : "About",
DlgAboutBrowserInfoTab : "Browser Info",
DlgAboutLicenseTab : "License",
DlgAboutVersion : "version",
DlgAboutInfo : "For further information go to",
// Div Dialog
DlgDivGeneralTab : "General",
DlgDivAdvancedTab : "Advanced",
DlgDivStyle : "Style",
DlgDivInlineStyle : "Inline Style"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* English (Canadian) language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "Collapse Toolbar",
ToolbarExpand : "Expand Toolbar",
// Toolbar Items and Context Menu
Save : "Save",
NewPage : "New Page",
Preview : "Preview",
Cut : "Cut",
Copy : "Copy",
Paste : "Paste",
PasteText : "Paste as plain text",
PasteWord : "Paste from Word",
Print : "Print",
SelectAll : "Select All",
RemoveFormat : "Remove Format",
InsertLinkLbl : "Link",
InsertLink : "Insert/Edit Link",
RemoveLink : "Remove Link",
VisitLink : "Open Link",
Anchor : "Insert/Edit Anchor",
AnchorDelete : "Remove Anchor",
InsertImageLbl : "Image",
InsertImage : "Insert/Edit Image",
InsertFlashLbl : "Flash",
InsertFlash : "Insert/Edit Flash",
InsertTableLbl : "Table",
InsertTable : "Insert/Edit Table",
InsertLineLbl : "Line",
InsertLine : "Insert Horizontal Line",
InsertSpecialCharLbl: "Special Character",
InsertSpecialChar : "Insert Special Character",
InsertSmileyLbl : "Smiley",
InsertSmiley : "Insert Smiley",
About : "About FCKeditor",
Bold : "Bold",
Italic : "Italic",
Underline : "Underline",
StrikeThrough : "Strike Through",
Subscript : "Subscript",
Superscript : "Superscript",
LeftJustify : "Left Justify",
CenterJustify : "Centre Justify",
RightJustify : "Right Justify",
BlockJustify : "Block Justify",
DecreaseIndent : "Decrease Indent",
IncreaseIndent : "Increase Indent",
Blockquote : "Blockquote",
CreateDiv : "Create Div Container",
EditDiv : "Edit Div Container",
DeleteDiv : "Remove Div Container",
Undo : "Undo",
Redo : "Redo",
NumberedListLbl : "Numbered List",
NumberedList : "Insert/Remove Numbered List",
BulletedListLbl : "Bulleted List",
BulletedList : "Insert/Remove Bulleted List",
ShowTableBorders : "Show Table Borders",
ShowDetails : "Show Details",
Style : "Style",
FontFormat : "Format",
Font : "Font",
FontSize : "Size",
TextColor : "Text Colour",
BGColor : "Background Colour",
Source : "Source",
Find : "Find",
Replace : "Replace",
SpellCheck : "Check Spelling",
UniversalKeyboard : "Universal Keyboard",
PageBreakLbl : "Page Break",
PageBreak : "Insert Page Break",
Form : "Form",
Checkbox : "Checkbox",
RadioButton : "Radio Button",
TextField : "Text Field",
Textarea : "Textarea",
HiddenField : "Hidden Field",
Button : "Button",
SelectionField : "Selection Field",
ImageButton : "Image Button",
FitWindow : "Maximize the editor size",
ShowBlocks : "Show Blocks",
// Context Menu
EditLink : "Edit Link",
CellCM : "Cell",
RowCM : "Row",
ColumnCM : "Column",
InsertRowAfter : "Insert Row After",
InsertRowBefore : "Insert Row Before",
DeleteRows : "Delete Rows",
InsertColumnAfter : "Insert Column After",
InsertColumnBefore : "Insert Column Before",
DeleteColumns : "Delete Columns",
InsertCellAfter : "Insert Cell After",
InsertCellBefore : "Insert Cell Before",
DeleteCells : "Delete Cells",
MergeCells : "Merge Cells",
MergeRight : "Merge Right",
MergeDown : "Merge Down",
HorizontalSplitCell : "Split Cell Horizontally",
VerticalSplitCell : "Split Cell Vertically",
TableDelete : "Delete Table",
CellProperties : "Cell Properties",
TableProperties : "Table Properties",
ImageProperties : "Image Properties",
FlashProperties : "Flash Properties",
AnchorProp : "Anchor Properties",
ButtonProp : "Button Properties",
CheckboxProp : "Checkbox Properties",
HiddenFieldProp : "Hidden Field Properties",
RadioButtonProp : "Radio Button Properties",
ImageButtonProp : "Image Button Properties",
TextFieldProp : "Text Field Properties",
SelectionFieldProp : "Selection Field Properties",
TextareaProp : "Textarea Properties",
FormProp : "Form Properties",
FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)",
// Alerts and Messages
ProcessingXHTML : "Processing XHTML. Please wait...",
Done : "Done",
PasteWordConfirm : "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?",
NotCompatiblePaste : "This command is available for Internet Explorer version 5.5 or more. Do you want to paste without cleaning?",
UnknownToolbarItem : "Unknown toolbar item \"%1\"",
UnknownCommand : "Unknown command name \"%1\"",
NotImplemented : "Command not implemented",
UnknownToolbarSet : "Toolbar set \"%1\" doesn't exist",
NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.",
BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.",
DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.",
VisitLinkBlocked : "It was not possible to open a new window. Make sure all popup blockers are disabled.",
// Dialogs
DlgBtnOK : "OK",
DlgBtnCancel : "Cancel",
DlgBtnClose : "Close",
DlgBtnBrowseServer : "Browse Server",
DlgAdvancedTag : "Advanced",
DlgOpOther : "<Other>",
DlgInfoTab : "Info",
DlgAlertUrl : "Please insert the URL",
// General Dialogs Labels
DlgGenNotSet : "<not set>",
DlgGenId : "Id",
DlgGenLangDir : "Language Direction",
DlgGenLangDirLtr : "Left to Right (LTR)",
DlgGenLangDirRtl : "Right to Left (RTL)",
DlgGenLangCode : "Language Code",
DlgGenAccessKey : "Access Key",
DlgGenName : "Name",
DlgGenTabIndex : "Tab Index",
DlgGenLongDescr : "Long Description URL",
DlgGenClass : "Stylesheet Classes",
DlgGenTitle : "Advisory Title",
DlgGenContType : "Advisory Content Type",
DlgGenLinkCharset : "Linked Resource Charset",
DlgGenStyle : "Style",
// Image Dialog
DlgImgTitle : "Image Properties",
DlgImgInfoTab : "Image Info",
DlgImgBtnUpload : "Send it to the Server",
DlgImgURL : "URL",
DlgImgUpload : "Upload",
DlgImgAlt : "Alternative Text",
DlgImgWidth : "Width",
DlgImgHeight : "Height",
DlgImgLockRatio : "Lock Ratio",
DlgBtnResetSize : "Reset Size",
DlgImgBorder : "Border",
DlgImgHSpace : "HSpace",
DlgImgVSpace : "VSpace",
DlgImgAlign : "Align",
DlgImgAlignLeft : "Left",
DlgImgAlignAbsBottom: "Abs Bottom",
DlgImgAlignAbsMiddle: "Abs Middle",
DlgImgAlignBaseline : "Baseline",
DlgImgAlignBottom : "Bottom",
DlgImgAlignMiddle : "Middle",
DlgImgAlignRight : "Right",
DlgImgAlignTextTop : "Text Top",
DlgImgAlignTop : "Top",
DlgImgPreview : "Preview",
DlgImgAlertUrl : "Please type the image URL",
DlgImgLinkTab : "Link",
// Flash Dialog
DlgFlashTitle : "Flash Properties",
DlgFlashChkPlay : "Auto Play",
DlgFlashChkLoop : "Loop",
DlgFlashChkMenu : "Enable Flash Menu",
DlgFlashScale : "Scale",
DlgFlashScaleAll : "Show all",
DlgFlashScaleNoBorder : "No Border",
DlgFlashScaleFit : "Exact Fit",
// Link Dialog
DlgLnkWindowTitle : "Link",
DlgLnkInfoTab : "Link Info",
DlgLnkTargetTab : "Target",
DlgLnkType : "Link Type",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Link to anchor in the text",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protocol",
DlgLnkProtoOther : "<other>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "Select an Anchor",
DlgLnkAnchorByName : "By Anchor Name",
DlgLnkAnchorById : "By Element Id",
DlgLnkNoAnchors : "(No anchors available in the document)",
DlgLnkEMail : "E-Mail Address",
DlgLnkEMailSubject : "Message Subject",
DlgLnkEMailBody : "Message Body",
DlgLnkUpload : "Upload",
DlgLnkBtnUpload : "Send it to the Server",
DlgLnkTarget : "Target",
DlgLnkTargetFrame : "<frame>",
DlgLnkTargetPopup : "<popup window>",
DlgLnkTargetBlank : "New Window (_blank)",
DlgLnkTargetParent : "Parent Window (_parent)",
DlgLnkTargetSelf : "Same Window (_self)",
DlgLnkTargetTop : "Topmost Window (_top)",
DlgLnkTargetFrameName : "Target Frame Name",
DlgLnkPopWinName : "Popup Window Name",
DlgLnkPopWinFeat : "Popup Window Features",
DlgLnkPopResize : "Resizable",
DlgLnkPopLocation : "Location Bar",
DlgLnkPopMenu : "Menu Bar",
DlgLnkPopScroll : "Scroll Bars",
DlgLnkPopStatus : "Status Bar",
DlgLnkPopToolbar : "Toolbar",
DlgLnkPopFullScrn : "Full Screen (IE)",
DlgLnkPopDependent : "Dependent (Netscape)",
DlgLnkPopWidth : "Width",
DlgLnkPopHeight : "Height",
DlgLnkPopLeft : "Left Position",
DlgLnkPopTop : "Top Position",
DlnLnkMsgNoUrl : "Please type the link URL",
DlnLnkMsgNoEMail : "Please type the e-mail address",
DlnLnkMsgNoAnchor : "Please select an anchor",
DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces",
// Color Dialog
DlgColorTitle : "Select Colour",
DlgColorBtnClear : "Clear",
DlgColorHighlight : "Highlight",
DlgColorSelected : "Selected",
// Smiley Dialog
DlgSmileyTitle : "Insert a Smiley",
// Special Character Dialog
DlgSpecialCharTitle : "Select Special Character",
// Table Dialog
DlgTableTitle : "Table Properties",
DlgTableRows : "Rows",
DlgTableColumns : "Columns",
DlgTableBorder : "Border size",
DlgTableAlign : "Alignment",
DlgTableAlignNotSet : "<Not set>",
DlgTableAlignLeft : "Left",
DlgTableAlignCenter : "Centre",
DlgTableAlignRight : "Right",
DlgTableWidth : "Width",
DlgTableWidthPx : "pixels",
DlgTableWidthPc : "percent",
DlgTableHeight : "Height",
DlgTableCellSpace : "Cell spacing",
DlgTableCellPad : "Cell padding",
DlgTableCaption : "Caption",
DlgTableSummary : "Summary",
// Table Cell Dialog
DlgCellTitle : "Cell Properties",
DlgCellWidth : "Width",
DlgCellWidthPx : "pixels",
DlgCellWidthPc : "percent",
DlgCellHeight : "Height",
DlgCellWordWrap : "Word Wrap",
DlgCellWordWrapNotSet : "<Not set>",
DlgCellWordWrapYes : "Yes",
DlgCellWordWrapNo : "No",
DlgCellHorAlign : "Horizontal Alignment",
DlgCellHorAlignNotSet : "<Not set>",
DlgCellHorAlignLeft : "Left",
DlgCellHorAlignCenter : "Centre",
DlgCellHorAlignRight: "Right",
DlgCellVerAlign : "Vertical Alignment",
DlgCellVerAlignNotSet : "<Not set>",
DlgCellVerAlignTop : "Top",
DlgCellVerAlignMiddle : "Middle",
DlgCellVerAlignBottom : "Bottom",
DlgCellVerAlignBaseline : "Baseline",
DlgCellRowSpan : "Rows Span",
DlgCellCollSpan : "Columns Span",
DlgCellBackColor : "Background Colour",
DlgCellBorderColor : "Border Colour",
DlgCellBtnSelect : "Select...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "Find and Replace",
// Find Dialog
DlgFindTitle : "Find",
DlgFindFindBtn : "Find",
DlgFindNotFoundMsg : "The specified text was not found.",
// Replace Dialog
DlgReplaceTitle : "Replace",
DlgReplaceFindLbl : "Find what:",
DlgReplaceReplaceLbl : "Replace with:",
DlgReplaceCaseChk : "Match case",
DlgReplaceReplaceBtn : "Replace",
DlgReplaceReplAllBtn : "Replace All",
DlgReplaceWordChk : "Match whole word",
// Paste Operations / Dialog
PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).",
PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).",
PasteAsText : "Paste as Plain Text",
PasteFromWord : "Paste from Word",
DlgPasteMsg2 : "Please paste inside the following box using the keyboard (<strong>Ctrl+V</strong>) and hit <strong>OK</strong>.",
DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.",
DlgPasteIgnoreFont : "Ignore Font Face definitions",
DlgPasteRemoveStyles : "Remove Styles definitions",
// Color Picker
ColorAutomatic : "Automatic",
ColorMoreColors : "More Colours...",
// Document Properties
DocProps : "Document Properties",
// Anchor Dialog
DlgAnchorTitle : "Anchor Properties",
DlgAnchorName : "Anchor Name",
DlgAnchorErrorName : "Please type the anchor name",
// Speller Pages Dialog
DlgSpellNotInDic : "Not in dictionary",
DlgSpellChangeTo : "Change to",
DlgSpellBtnIgnore : "Ignore",
DlgSpellBtnIgnoreAll : "Ignore All",
DlgSpellBtnReplace : "Replace",
DlgSpellBtnReplaceAll : "Replace All",
DlgSpellBtnUndo : "Undo",
DlgSpellNoSuggestions : "- No suggestions -",
DlgSpellProgress : "Spell check in progress...",
DlgSpellNoMispell : "Spell check complete: No misspellings found",
DlgSpellNoChanges : "Spell check complete: No words changed",
DlgSpellOneChange : "Spell check complete: One word changed",
DlgSpellManyChanges : "Spell check complete: %1 words changed",
IeSpellDownload : "Spell checker not installed. Do you want to download it now?",
// Button Dialog
DlgButtonText : "Text (Value)",
DlgButtonType : "Type",
DlgButtonTypeBtn : "Button",
DlgButtonTypeSbm : "Submit",
DlgButtonTypeRst : "Reset",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "Name",
DlgCheckboxValue : "Value",
DlgCheckboxSelected : "Selected",
// Form Dialog
DlgFormName : "Name",
DlgFormAction : "Action",
DlgFormMethod : "Method",
// Select Field Dialog
DlgSelectName : "Name",
DlgSelectValue : "Value",
DlgSelectSize : "Size",
DlgSelectLines : "lines",
DlgSelectChkMulti : "Allow multiple selections",
DlgSelectOpAvail : "Available Options",
DlgSelectOpText : "Text",
DlgSelectOpValue : "Value",
DlgSelectBtnAdd : "Add",
DlgSelectBtnModify : "Modify",
DlgSelectBtnUp : "Up",
DlgSelectBtnDown : "Down",
DlgSelectBtnSetValue : "Set as selected value",
DlgSelectBtnDelete : "Delete",
// Textarea Dialog
DlgTextareaName : "Name",
DlgTextareaCols : "Columns",
DlgTextareaRows : "Rows",
// Text Field Dialog
DlgTextName : "Name",
DlgTextValue : "Value",
DlgTextCharWidth : "Character Width",
DlgTextMaxChars : "Maximum Characters",
DlgTextType : "Type",
DlgTextTypeText : "Text",
DlgTextTypePass : "Password",
// Hidden Field Dialog
DlgHiddenName : "Name",
DlgHiddenValue : "Value",
// Bulleted List Dialog
BulletedListProp : "Bulleted List Properties",
NumberedListProp : "Numbered List Properties",
DlgLstStart : "Start",
DlgLstType : "Type",
DlgLstTypeCircle : "Circle",
DlgLstTypeDisc : "Disc",
DlgLstTypeSquare : "Square",
DlgLstTypeNumbers : "Numbers (1, 2, 3)",
DlgLstTypeLCase : "Lowercase Letters (a, b, c)",
DlgLstTypeUCase : "Uppercase Letters (A, B, C)",
DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)",
DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "General",
DlgDocBackTab : "Background",
DlgDocColorsTab : "Colours and Margins",
DlgDocMetaTab : "Meta Data",
DlgDocPageTitle : "Page Title",
DlgDocLangDir : "Language Direction",
DlgDocLangDirLTR : "Left to Right (LTR)",
DlgDocLangDirRTL : "Right to Left (RTL)",
DlgDocLangCode : "Language Code",
DlgDocCharSet : "Character Set Encoding",
DlgDocCharSetCE : "Central European",
DlgDocCharSetCT : "Chinese Traditional (Big5)",
DlgDocCharSetCR : "Cyrillic",
DlgDocCharSetGR : "Greek",
DlgDocCharSetJP : "Japanese",
DlgDocCharSetKR : "Korean",
DlgDocCharSetTR : "Turkish",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "Western European",
DlgDocCharSetOther : "Other Character Set Encoding",
DlgDocDocType : "Document Type Heading",
DlgDocDocTypeOther : "Other Document Type Heading",
DlgDocIncXHTML : "Include XHTML Declarations",
DlgDocBgColor : "Background Colour",
DlgDocBgImage : "Background Image URL",
DlgDocBgNoScroll : "Nonscrolling Background",
DlgDocCText : "Text",
DlgDocCLink : "Link",
DlgDocCVisited : "Visited Link",
DlgDocCActive : "Active Link",
DlgDocMargins : "Page Margins",
DlgDocMaTop : "Top",
DlgDocMaLeft : "Left",
DlgDocMaRight : "Right",
DlgDocMaBottom : "Bottom",
DlgDocMeIndex : "Document Indexing Keywords (comma separated)",
DlgDocMeDescr : "Document Description",
DlgDocMeAuthor : "Author",
DlgDocMeCopy : "Copyright",
DlgDocPreview : "Preview",
// Templates Dialog
Templates : "Templates",
DlgTemplatesTitle : "Content Templates",
DlgTemplatesSelMsg : "Please select the template to open in the editor<br />(the actual contents will be lost):",
DlgTemplatesLoading : "Loading templates list. Please wait...",
DlgTemplatesNoTpl : "(No templates defined)",
DlgTemplatesReplace : "Replace actual contents",
// About Dialog
DlgAboutAboutTab : "About",
DlgAboutBrowserInfoTab : "Browser Info",
DlgAboutLicenseTab : "License",
DlgAboutVersion : "version",
DlgAboutInfo : "For further information go to",
// Div Dialog
DlgDivGeneralTab : "General",
DlgDivAdvancedTab : "Advanced",
DlgDivStyle : "Style",
DlgDivInlineStyle : "Inline Style"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Chinese Traditional language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "隱藏面板",
ToolbarExpand : "顯示面板",
// Toolbar Items and Context Menu
Save : "儲存",
NewPage : "開新檔案",
Preview : "預覽",
Cut : "剪下",
Copy : "複製",
Paste : "貼上",
PasteText : "貼為純文字格式",
PasteWord : "自 Word 貼上",
Print : "列印",
SelectAll : "全選",
RemoveFormat : "清除格式",
InsertLinkLbl : "超連結",
InsertLink : "插入/編輯超連結",
RemoveLink : "移除超連結",
VisitLink : "開啟超連結",
Anchor : "插入/編輯錨點",
AnchorDelete : "移除錨點",
InsertImageLbl : "影像",
InsertImage : "插入/編輯影像",
InsertFlashLbl : "Flash",
InsertFlash : "插入/編輯 Flash",
InsertTableLbl : "表格",
InsertTable : "插入/編輯表格",
InsertLineLbl : "水平線",
InsertLine : "插入水平線",
InsertSpecialCharLbl: "特殊符號",
InsertSpecialChar : "插入特殊符號",
InsertSmileyLbl : "表情符號",
InsertSmiley : "插入表情符號",
About : "關於 FCKeditor",
Bold : "粗體",
Italic : "斜體",
Underline : "底線",
StrikeThrough : "刪除線",
Subscript : "下標",
Superscript : "上標",
LeftJustify : "靠左對齊",
CenterJustify : "置中",
RightJustify : "靠右對齊",
BlockJustify : "左右對齊",
DecreaseIndent : "減少縮排",
IncreaseIndent : "增加縮排",
Blockquote : "引用文字",
CreateDiv : "新增 Div 標籤",
EditDiv : "變更 Div 標籤",
DeleteDiv : "移除 Div 標籤",
Undo : "復原",
Redo : "重複",
NumberedListLbl : "編號清單",
NumberedList : "插入/移除編號清單",
BulletedListLbl : "項目清單",
BulletedList : "插入/移除項目清單",
ShowTableBorders : "顯示表格邊框",
ShowDetails : "顯示詳細資料",
Style : "樣式",
FontFormat : "格式",
Font : "字體",
FontSize : "大小",
TextColor : "文字顏色",
BGColor : "背景顏色",
Source : "原始碼",
Find : "尋找",
Replace : "取代",
SpellCheck : "拼字檢查",
UniversalKeyboard : "萬國鍵盤",
PageBreakLbl : "分頁符號",
PageBreak : "插入分頁符號",
Form : "表單",
Checkbox : "核取方塊",
RadioButton : "選項按鈕",
TextField : "文字方塊",
Textarea : "文字區域",
HiddenField : "隱藏欄位",
Button : "按鈕",
SelectionField : "清單/選單",
ImageButton : "影像按鈕",
FitWindow : "編輯器最大化",
ShowBlocks : "顯示區塊",
// Context Menu
EditLink : "編輯超連結",
CellCM : "儲存格",
RowCM : "列",
ColumnCM : "欄",
InsertRowAfter : "向下插入列",
InsertRowBefore : "向上插入列",
DeleteRows : "刪除列",
InsertColumnAfter : "向右插入欄",
InsertColumnBefore : "向左插入欄",
DeleteColumns : "刪除欄",
InsertCellAfter : "向右插入儲存格",
InsertCellBefore : "向左插入儲存格",
DeleteCells : "刪除儲存格",
MergeCells : "合併儲存格",
MergeRight : "向右合併儲存格",
MergeDown : "向下合併儲存格",
HorizontalSplitCell : "橫向分割儲存格",
VerticalSplitCell : "縱向分割儲存格",
TableDelete : "刪除表格",
CellProperties : "儲存格屬性",
TableProperties : "表格屬性",
ImageProperties : "影像屬性",
FlashProperties : "Flash 屬性",
AnchorProp : "錨點屬性",
ButtonProp : "按鈕屬性",
CheckboxProp : "核取方塊屬性",
HiddenFieldProp : "隱藏欄位屬性",
RadioButtonProp : "選項按鈕屬性",
ImageButtonProp : "影像按鈕屬性",
TextFieldProp : "文字方塊屬性",
SelectionFieldProp : "清單/選單屬性",
TextareaProp : "文字區域屬性",
FormProp : "表單屬性",
FontFormats : "一般;已格式化;位址;標題 1;標題 2;標題 3;標題 4;標題 5;標題 6;一般 (DIV)",
// Alerts and Messages
ProcessingXHTML : "處理 XHTML 中,請稍候…",
Done : "完成",
PasteWordConfirm : "您想貼上的文字似乎是自 Word 複製而來,請問您是否要先清除 Word 的格式後再行貼上?",
NotCompatiblePaste : "此指令僅在 Internet Explorer 5.5 或以上的版本有效。請問您是否同意不清除格式即貼上?",
UnknownToolbarItem : "未知工具列項目 \"%1\"",
UnknownCommand : "未知指令名稱 \"%1\"",
NotImplemented : "尚未安裝此指令",
UnknownToolbarSet : "工具列設定 \"%1\" 不存在",
NoActiveX : "瀏覽器的安全性設定限制了本編輯器的某些功能。您必須啟用安全性設定中的「執行ActiveX控制項與外掛程式」項目,否則本編輯器將會出現錯誤並缺少某些功能",
BrowseServerBlocked : "無法開啟資源瀏覽器,請確定所有快顯視窗封鎖程式是否關閉",
DialogBlocked : "無法開啟對話視窗,請確定所有快顯視窗封鎖程式是否關閉",
VisitLinkBlocked : "無法開啟新視窗,請確定所有快顯視窗封鎖程式是否關閉",
// Dialogs
DlgBtnOK : "確定",
DlgBtnCancel : "取消",
DlgBtnClose : "關閉",
DlgBtnBrowseServer : "瀏覽伺服器端",
DlgAdvancedTag : "進階",
DlgOpOther : "<其他>",
DlgInfoTab : "資訊",
DlgAlertUrl : "請插入 URL",
// General Dialogs Labels
DlgGenNotSet : "<尚未設定>",
DlgGenId : "ID",
DlgGenLangDir : "語言方向",
DlgGenLangDirLtr : "由左而右 (LTR)",
DlgGenLangDirRtl : "由右而左 (RTL)",
DlgGenLangCode : "語言代碼",
DlgGenAccessKey : "存取鍵",
DlgGenName : "名稱",
DlgGenTabIndex : "定位順序",
DlgGenLongDescr : "詳細 URL",
DlgGenClass : "樣式表類別",
DlgGenTitle : "標題",
DlgGenContType : "內容類型",
DlgGenLinkCharset : "連結資源之編碼",
DlgGenStyle : "樣式",
// Image Dialog
DlgImgTitle : "影像屬性",
DlgImgInfoTab : "影像資訊",
DlgImgBtnUpload : "上傳至伺服器",
DlgImgURL : "URL",
DlgImgUpload : "上傳",
DlgImgAlt : "替代文字",
DlgImgWidth : "寬度",
DlgImgHeight : "高度",
DlgImgLockRatio : "等比例",
DlgBtnResetSize : "重設為原大小",
DlgImgBorder : "邊框",
DlgImgHSpace : "水平距離",
DlgImgVSpace : "垂直距離",
DlgImgAlign : "對齊",
DlgImgAlignLeft : "靠左對齊",
DlgImgAlignAbsBottom: "絕對下方",
DlgImgAlignAbsMiddle: "絕對中間",
DlgImgAlignBaseline : "基準線",
DlgImgAlignBottom : "靠下對齊",
DlgImgAlignMiddle : "置中對齊",
DlgImgAlignRight : "靠右對齊",
DlgImgAlignTextTop : "文字上方",
DlgImgAlignTop : "靠上對齊",
DlgImgPreview : "預覽",
DlgImgAlertUrl : "請輸入影像 URL",
DlgImgLinkTab : "超連結",
// Flash Dialog
DlgFlashTitle : "Flash 屬性",
DlgFlashChkPlay : "自動播放",
DlgFlashChkLoop : "重複",
DlgFlashChkMenu : "開啟選單",
DlgFlashScale : "縮放",
DlgFlashScaleAll : "全部顯示",
DlgFlashScaleNoBorder : "無邊框",
DlgFlashScaleFit : "精確符合",
// Link Dialog
DlgLnkWindowTitle : "超連結",
DlgLnkInfoTab : "超連結資訊",
DlgLnkTargetTab : "目標",
DlgLnkType : "超連接類型",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "本頁錨點",
DlgLnkTypeEMail : "電子郵件",
DlgLnkProto : "通訊協定",
DlgLnkProtoOther : "<其他>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "請選擇錨點",
DlgLnkAnchorByName : "依錨點名稱",
DlgLnkAnchorById : "依元件 ID",
DlgLnkNoAnchors : "(本文件尚無可用之錨點)",
DlgLnkEMail : "電子郵件",
DlgLnkEMailSubject : "郵件主旨",
DlgLnkEMailBody : "郵件內容",
DlgLnkUpload : "上傳",
DlgLnkBtnUpload : "傳送至伺服器",
DlgLnkTarget : "目標",
DlgLnkTargetFrame : "<框架>",
DlgLnkTargetPopup : "<快顯視窗>",
DlgLnkTargetBlank : "新視窗 (_blank)",
DlgLnkTargetParent : "父視窗 (_parent)",
DlgLnkTargetSelf : "本視窗 (_self)",
DlgLnkTargetTop : "最上層視窗 (_top)",
DlgLnkTargetFrameName : "目標框架名稱",
DlgLnkPopWinName : "快顯視窗名稱",
DlgLnkPopWinFeat : "快顯視窗屬性",
DlgLnkPopResize : "可調整大小",
DlgLnkPopLocation : "網址列",
DlgLnkPopMenu : "選單列",
DlgLnkPopScroll : "捲軸",
DlgLnkPopStatus : "狀態列",
DlgLnkPopToolbar : "工具列",
DlgLnkPopFullScrn : "全螢幕 (IE)",
DlgLnkPopDependent : "從屬 (NS)",
DlgLnkPopWidth : "寬",
DlgLnkPopHeight : "高",
DlgLnkPopLeft : "左",
DlgLnkPopTop : "右",
DlnLnkMsgNoUrl : "請輸入欲連結的 URL",
DlnLnkMsgNoEMail : "請輸入電子郵件位址",
DlnLnkMsgNoAnchor : "請選擇錨點",
DlnLnkMsgInvPopName : "快顯名稱必須以「英文字母」為開頭,且不得含有空白",
// Color Dialog
DlgColorTitle : "請選擇顏色",
DlgColorBtnClear : "清除",
DlgColorHighlight : "預覽",
DlgColorSelected : "選擇",
// Smiley Dialog
DlgSmileyTitle : "插入表情符號",
// Special Character Dialog
DlgSpecialCharTitle : "請選擇特殊符號",
// Table Dialog
DlgTableTitle : "表格屬性",
DlgTableRows : "列數",
DlgTableColumns : "欄數",
DlgTableBorder : "邊框",
DlgTableAlign : "對齊",
DlgTableAlignNotSet : "<未設定>",
DlgTableAlignLeft : "靠左對齊",
DlgTableAlignCenter : "置中",
DlgTableAlignRight : "靠右對齊",
DlgTableWidth : "寬度",
DlgTableWidthPx : "像素",
DlgTableWidthPc : "百分比",
DlgTableHeight : "高度",
DlgTableCellSpace : "間距",
DlgTableCellPad : "內距",
DlgTableCaption : "標題",
DlgTableSummary : "摘要",
// Table Cell Dialog
DlgCellTitle : "儲存格屬性",
DlgCellWidth : "寬度",
DlgCellWidthPx : "像素",
DlgCellWidthPc : "百分比",
DlgCellHeight : "高度",
DlgCellWordWrap : "自動換行",
DlgCellWordWrapNotSet : "<尚未設定>",
DlgCellWordWrapYes : "是",
DlgCellWordWrapNo : "否",
DlgCellHorAlign : "水平對齊",
DlgCellHorAlignNotSet : "<尚未設定>",
DlgCellHorAlignLeft : "靠左對齊",
DlgCellHorAlignCenter : "置中",
DlgCellHorAlignRight: "靠右對齊",
DlgCellVerAlign : "垂直對齊",
DlgCellVerAlignNotSet : "<尚未設定>",
DlgCellVerAlignTop : "靠上對齊",
DlgCellVerAlignMiddle : "置中",
DlgCellVerAlignBottom : "靠下對齊",
DlgCellVerAlignBaseline : "基準線",
DlgCellRowSpan : "合併列數",
DlgCellCollSpan : "合併欄数",
DlgCellBackColor : "背景顏色",
DlgCellBorderColor : "邊框顏色",
DlgCellBtnSelect : "請選擇…",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "尋找與取代",
// Find Dialog
DlgFindTitle : "尋找",
DlgFindFindBtn : "尋找",
DlgFindNotFoundMsg : "未找到指定的文字。",
// Replace Dialog
DlgReplaceTitle : "取代",
DlgReplaceFindLbl : "尋找:",
DlgReplaceReplaceLbl : "取代:",
DlgReplaceCaseChk : "大小寫須相符",
DlgReplaceReplaceBtn : "取代",
DlgReplaceReplAllBtn : "全部取代",
DlgReplaceWordChk : "全字相符",
// Paste Operations / Dialog
PasteErrorCut : "瀏覽器的安全性設定不允許編輯器自動執行剪下動作。請使用快捷鍵 (Ctrl+X) 剪下。",
PasteErrorCopy : "瀏覽器的安全性設定不允許編輯器自動執行複製動作。請使用快捷鍵 (Ctrl+C) 複製。",
PasteAsText : "貼為純文字格式",
PasteFromWord : "自 Word 貼上",
DlgPasteMsg2 : "請使用快捷鍵 (<strong>Ctrl+V</strong>) 貼到下方區域中並按下 <strong>確定</strong>",
DlgPasteSec : "因為瀏覽器的安全性設定,本編輯器無法直接存取您的剪貼簿資料,請您自行在本視窗進行貼上動作。",
DlgPasteIgnoreFont : "移除字型設定",
DlgPasteRemoveStyles : "移除樣式設定",
// Color Picker
ColorAutomatic : "自動",
ColorMoreColors : "更多顏色…",
// Document Properties
DocProps : "文件屬性",
// Anchor Dialog
DlgAnchorTitle : "命名錨點",
DlgAnchorName : "錨點名稱",
DlgAnchorErrorName : "請輸入錨點名稱",
// Speller Pages Dialog
DlgSpellNotInDic : "不在字典中",
DlgSpellChangeTo : "更改為",
DlgSpellBtnIgnore : "忽略",
DlgSpellBtnIgnoreAll : "全部忽略",
DlgSpellBtnReplace : "取代",
DlgSpellBtnReplaceAll : "全部取代",
DlgSpellBtnUndo : "復原",
DlgSpellNoSuggestions : "- 無建議值 -",
DlgSpellProgress : "進行拼字檢查中…",
DlgSpellNoMispell : "拼字檢查完成:未發現拼字錯誤",
DlgSpellNoChanges : "拼字檢查完成:未更改任何單字",
DlgSpellOneChange : "拼字檢查完成:更改了 1 個單字",
DlgSpellManyChanges : "拼字檢查完成:更改了 %1 個單字",
IeSpellDownload : "尚未安裝拼字檢查元件。您是否想要現在下載?",
// Button Dialog
DlgButtonText : "顯示文字 (值)",
DlgButtonType : "類型",
DlgButtonTypeBtn : "按鈕 (Button)",
DlgButtonTypeSbm : "送出 (Submit)",
DlgButtonTypeRst : "重設 (Reset)",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "名稱",
DlgCheckboxValue : "選取值",
DlgCheckboxSelected : "已選取",
// Form Dialog
DlgFormName : "名稱",
DlgFormAction : "動作",
DlgFormMethod : "方法",
// Select Field Dialog
DlgSelectName : "名稱",
DlgSelectValue : "選取值",
DlgSelectSize : "大小",
DlgSelectLines : "行",
DlgSelectChkMulti : "可多選",
DlgSelectOpAvail : "可用選項",
DlgSelectOpText : "顯示文字",
DlgSelectOpValue : "值",
DlgSelectBtnAdd : "新增",
DlgSelectBtnModify : "修改",
DlgSelectBtnUp : "上移",
DlgSelectBtnDown : "下移",
DlgSelectBtnSetValue : "設為預設值",
DlgSelectBtnDelete : "刪除",
// Textarea Dialog
DlgTextareaName : "名稱",
DlgTextareaCols : "字元寬度",
DlgTextareaRows : "列數",
// Text Field Dialog
DlgTextName : "名稱",
DlgTextValue : "值",
DlgTextCharWidth : "字元寬度",
DlgTextMaxChars : "最多字元數",
DlgTextType : "類型",
DlgTextTypeText : "文字",
DlgTextTypePass : "密碼",
// Hidden Field Dialog
DlgHiddenName : "名稱",
DlgHiddenValue : "值",
// Bulleted List Dialog
BulletedListProp : "項目清單屬性",
NumberedListProp : "編號清單屬性",
DlgLstStart : "起始編號",
DlgLstType : "清單類型",
DlgLstTypeCircle : "圓圈",
DlgLstTypeDisc : "圓點",
DlgLstTypeSquare : "方塊",
DlgLstTypeNumbers : "數字 (1, 2, 3)",
DlgLstTypeLCase : "小寫字母 (a, b, c)",
DlgLstTypeUCase : "大寫字母 (A, B, C)",
DlgLstTypeSRoman : "小寫羅馬數字 (i, ii, iii)",
DlgLstTypeLRoman : "大寫羅馬數字 (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "一般",
DlgDocBackTab : "背景",
DlgDocColorsTab : "顯色與邊界",
DlgDocMetaTab : "Meta 資料",
DlgDocPageTitle : "頁面標題",
DlgDocLangDir : "語言方向",
DlgDocLangDirLTR : "由左而右 (LTR)",
DlgDocLangDirRTL : "由右而左 (RTL)",
DlgDocLangCode : "語言代碼",
DlgDocCharSet : "字元編碼",
DlgDocCharSetCE : "中歐語系",
DlgDocCharSetCT : "正體中文 (Big5)",
DlgDocCharSetCR : "斯拉夫文",
DlgDocCharSetGR : "希臘文",
DlgDocCharSetJP : "日文",
DlgDocCharSetKR : "韓文",
DlgDocCharSetTR : "土耳其文",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "西歐語系",
DlgDocCharSetOther : "其他字元編碼",
DlgDocDocType : "文件類型",
DlgDocDocTypeOther : "其他文件類型",
DlgDocIncXHTML : "包含 XHTML 定義",
DlgDocBgColor : "背景顏色",
DlgDocBgImage : "背景影像",
DlgDocBgNoScroll : "浮水印",
DlgDocCText : "文字",
DlgDocCLink : "超連結",
DlgDocCVisited : "已瀏覽過的超連結",
DlgDocCActive : "作用中的超連結",
DlgDocMargins : "頁面邊界",
DlgDocMaTop : "上",
DlgDocMaLeft : "左",
DlgDocMaRight : "右",
DlgDocMaBottom : "下",
DlgDocMeIndex : "文件索引關鍵字 (用半形逗號[,]分隔)",
DlgDocMeDescr : "文件說明",
DlgDocMeAuthor : "作者",
DlgDocMeCopy : "版權所有",
DlgDocPreview : "預覽",
// Templates Dialog
Templates : "樣版",
DlgTemplatesTitle : "內容樣版",
DlgTemplatesSelMsg : "請選擇欲開啟的樣版<br> (原有的內容將會被清除):",
DlgTemplatesLoading : "讀取樣版清單中,請稍候…",
DlgTemplatesNoTpl : "(無樣版)",
DlgTemplatesReplace : "取代原有內容",
// About Dialog
DlgAboutAboutTab : "關於",
DlgAboutBrowserInfoTab : "瀏覽器資訊",
DlgAboutLicenseTab : "許可證",
DlgAboutVersion : "版本",
DlgAboutInfo : "想獲得更多資訊請至 ",
// Div Dialog
DlgDivGeneralTab : "一般",
DlgDivAdvancedTab : "進階",
DlgDivStyle : "樣式",
DlgDivInlineStyle : "CSS 樣式"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* English (Australia) language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "Collapse Toolbar",
ToolbarExpand : "Expand Toolbar",
// Toolbar Items and Context Menu
Save : "Save",
NewPage : "New Page",
Preview : "Preview",
Cut : "Cut",
Copy : "Copy",
Paste : "Paste",
PasteText : "Paste as plain text",
PasteWord : "Paste from Word",
Print : "Print",
SelectAll : "Select All",
RemoveFormat : "Remove Format",
InsertLinkLbl : "Link",
InsertLink : "Insert/Edit Link",
RemoveLink : "Remove Link",
VisitLink : "Open Link",
Anchor : "Insert/Edit Anchor",
AnchorDelete : "Remove Anchor",
InsertImageLbl : "Image",
InsertImage : "Insert/Edit Image",
InsertFlashLbl : "Flash",
InsertFlash : "Insert/Edit Flash",
InsertTableLbl : "Table",
InsertTable : "Insert/Edit Table",
InsertLineLbl : "Line",
InsertLine : "Insert Horizontal Line",
InsertSpecialCharLbl: "Special Character",
InsertSpecialChar : "Insert Special Character",
InsertSmileyLbl : "Smiley",
InsertSmiley : "Insert Smiley",
About : "About FCKeditor",
Bold : "Bold",
Italic : "Italic",
Underline : "Underline",
StrikeThrough : "Strike Through",
Subscript : "Subscript",
Superscript : "Superscript",
LeftJustify : "Left Justify",
CenterJustify : "Centre Justify",
RightJustify : "Right Justify",
BlockJustify : "Block Justify",
DecreaseIndent : "Decrease Indent",
IncreaseIndent : "Increase Indent",
Blockquote : "Blockquote",
CreateDiv : "Create Div Container",
EditDiv : "Edit Div Container",
DeleteDiv : "Remove Div Container",
Undo : "Undo",
Redo : "Redo",
NumberedListLbl : "Numbered List",
NumberedList : "Insert/Remove Numbered List",
BulletedListLbl : "Bulleted List",
BulletedList : "Insert/Remove Bulleted List",
ShowTableBorders : "Show Table Borders",
ShowDetails : "Show Details",
Style : "Style",
FontFormat : "Format",
Font : "Font",
FontSize : "Size",
TextColor : "Text Colour",
BGColor : "Background Colour",
Source : "Source",
Find : "Find",
Replace : "Replace",
SpellCheck : "Check Spelling",
UniversalKeyboard : "Universal Keyboard",
PageBreakLbl : "Page Break",
PageBreak : "Insert Page Break",
Form : "Form",
Checkbox : "Checkbox",
RadioButton : "Radio Button",
TextField : "Text Field",
Textarea : "Textarea",
HiddenField : "Hidden Field",
Button : "Button",
SelectionField : "Selection Field",
ImageButton : "Image Button",
FitWindow : "Maximize the editor size",
ShowBlocks : "Show Blocks",
// Context Menu
EditLink : "Edit Link",
CellCM : "Cell",
RowCM : "Row",
ColumnCM : "Column",
InsertRowAfter : "Insert Row After",
InsertRowBefore : "Insert Row Before",
DeleteRows : "Delete Rows",
InsertColumnAfter : "Insert Column After",
InsertColumnBefore : "Insert Column Before",
DeleteColumns : "Delete Columns",
InsertCellAfter : "Insert Cell After",
InsertCellBefore : "Insert Cell Before",
DeleteCells : "Delete Cells",
MergeCells : "Merge Cells",
MergeRight : "Merge Right",
MergeDown : "Merge Down",
HorizontalSplitCell : "Split Cell Horizontally",
VerticalSplitCell : "Split Cell Vertically",
TableDelete : "Delete Table",
CellProperties : "Cell Properties",
TableProperties : "Table Properties",
ImageProperties : "Image Properties",
FlashProperties : "Flash Properties",
AnchorProp : "Anchor Properties",
ButtonProp : "Button Properties",
CheckboxProp : "Checkbox Properties",
HiddenFieldProp : "Hidden Field Properties",
RadioButtonProp : "Radio Button Properties",
ImageButtonProp : "Image Button Properties",
TextFieldProp : "Text Field Properties",
SelectionFieldProp : "Selection Field Properties",
TextareaProp : "Textarea Properties",
FormProp : "Form Properties",
FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)",
// Alerts and Messages
ProcessingXHTML : "Processing XHTML. Please wait...",
Done : "Done",
PasteWordConfirm : "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?",
NotCompatiblePaste : "This command is available for Internet Explorer version 5.5 or more. Do you want to paste without cleaning?",
UnknownToolbarItem : "Unknown toolbar item \"%1\"",
UnknownCommand : "Unknown command name \"%1\"",
NotImplemented : "Command not implemented",
UnknownToolbarSet : "Toolbar set \"%1\" doesn't exist",
NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.",
BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.",
DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.",
VisitLinkBlocked : "It was not possible to open a new window. Make sure all popup blockers are disabled.",
// Dialogs
DlgBtnOK : "OK",
DlgBtnCancel : "Cancel",
DlgBtnClose : "Close",
DlgBtnBrowseServer : "Browse Server",
DlgAdvancedTag : "Advanced",
DlgOpOther : "<Other>",
DlgInfoTab : "Info",
DlgAlertUrl : "Please insert the URL",
// General Dialogs Labels
DlgGenNotSet : "<not set>",
DlgGenId : "Id",
DlgGenLangDir : "Language Direction",
DlgGenLangDirLtr : "Left to Right (LTR)",
DlgGenLangDirRtl : "Right to Left (RTL)",
DlgGenLangCode : "Language Code",
DlgGenAccessKey : "Access Key",
DlgGenName : "Name",
DlgGenTabIndex : "Tab Index",
DlgGenLongDescr : "Long Description URL",
DlgGenClass : "Stylesheet Classes",
DlgGenTitle : "Advisory Title",
DlgGenContType : "Advisory Content Type",
DlgGenLinkCharset : "Linked Resource Charset",
DlgGenStyle : "Style",
// Image Dialog
DlgImgTitle : "Image Properties",
DlgImgInfoTab : "Image Info",
DlgImgBtnUpload : "Send it to the Server",
DlgImgURL : "URL",
DlgImgUpload : "Upload",
DlgImgAlt : "Alternative Text",
DlgImgWidth : "Width",
DlgImgHeight : "Height",
DlgImgLockRatio : "Lock Ratio",
DlgBtnResetSize : "Reset Size",
DlgImgBorder : "Border",
DlgImgHSpace : "HSpace",
DlgImgVSpace : "VSpace",
DlgImgAlign : "Align",
DlgImgAlignLeft : "Left",
DlgImgAlignAbsBottom: "Abs Bottom",
DlgImgAlignAbsMiddle: "Abs Middle",
DlgImgAlignBaseline : "Baseline",
DlgImgAlignBottom : "Bottom",
DlgImgAlignMiddle : "Middle",
DlgImgAlignRight : "Right",
DlgImgAlignTextTop : "Text Top",
DlgImgAlignTop : "Top",
DlgImgPreview : "Preview",
DlgImgAlertUrl : "Please type the image URL",
DlgImgLinkTab : "Link",
// Flash Dialog
DlgFlashTitle : "Flash Properties",
DlgFlashChkPlay : "Auto Play",
DlgFlashChkLoop : "Loop",
DlgFlashChkMenu : "Enable Flash Menu",
DlgFlashScale : "Scale",
DlgFlashScaleAll : "Show all",
DlgFlashScaleNoBorder : "No Border",
DlgFlashScaleFit : "Exact Fit",
// Link Dialog
DlgLnkWindowTitle : "Link",
DlgLnkInfoTab : "Link Info",
DlgLnkTargetTab : "Target",
DlgLnkType : "Link Type",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Link to anchor in the text",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protocol",
DlgLnkProtoOther : "<other>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "Select an Anchor",
DlgLnkAnchorByName : "By Anchor Name",
DlgLnkAnchorById : "By Element Id",
DlgLnkNoAnchors : "(No anchors available in the document)",
DlgLnkEMail : "E-Mail Address",
DlgLnkEMailSubject : "Message Subject",
DlgLnkEMailBody : "Message Body",
DlgLnkUpload : "Upload",
DlgLnkBtnUpload : "Send it to the Server",
DlgLnkTarget : "Target",
DlgLnkTargetFrame : "<frame>",
DlgLnkTargetPopup : "<popup window>",
DlgLnkTargetBlank : "New Window (_blank)",
DlgLnkTargetParent : "Parent Window (_parent)",
DlgLnkTargetSelf : "Same Window (_self)",
DlgLnkTargetTop : "Topmost Window (_top)",
DlgLnkTargetFrameName : "Target Frame Name",
DlgLnkPopWinName : "Popup Window Name",
DlgLnkPopWinFeat : "Popup Window Features",
DlgLnkPopResize : "Resizable",
DlgLnkPopLocation : "Location Bar",
DlgLnkPopMenu : "Menu Bar",
DlgLnkPopScroll : "Scroll Bars",
DlgLnkPopStatus : "Status Bar",
DlgLnkPopToolbar : "Toolbar",
DlgLnkPopFullScrn : "Full Screen (IE)",
DlgLnkPopDependent : "Dependent (Netscape)",
DlgLnkPopWidth : "Width",
DlgLnkPopHeight : "Height",
DlgLnkPopLeft : "Left Position",
DlgLnkPopTop : "Top Position",
DlnLnkMsgNoUrl : "Please type the link URL",
DlnLnkMsgNoEMail : "Please type the e-mail address",
DlnLnkMsgNoAnchor : "Please select an anchor",
DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces",
// Color Dialog
DlgColorTitle : "Select Colour",
DlgColorBtnClear : "Clear",
DlgColorHighlight : "Highlight",
DlgColorSelected : "Selected",
// Smiley Dialog
DlgSmileyTitle : "Insert a Smiley",
// Special Character Dialog
DlgSpecialCharTitle : "Select Special Character",
// Table Dialog
DlgTableTitle : "Table Properties",
DlgTableRows : "Rows",
DlgTableColumns : "Columns",
DlgTableBorder : "Border size",
DlgTableAlign : "Alignment",
DlgTableAlignNotSet : "<Not set>",
DlgTableAlignLeft : "Left",
DlgTableAlignCenter : "Centre",
DlgTableAlignRight : "Right",
DlgTableWidth : "Width",
DlgTableWidthPx : "pixels",
DlgTableWidthPc : "percent",
DlgTableHeight : "Height",
DlgTableCellSpace : "Cell spacing",
DlgTableCellPad : "Cell padding",
DlgTableCaption : "Caption",
DlgTableSummary : "Summary",
// Table Cell Dialog
DlgCellTitle : "Cell Properties",
DlgCellWidth : "Width",
DlgCellWidthPx : "pixels",
DlgCellWidthPc : "percent",
DlgCellHeight : "Height",
DlgCellWordWrap : "Word Wrap",
DlgCellWordWrapNotSet : "<Not set>",
DlgCellWordWrapYes : "Yes",
DlgCellWordWrapNo : "No",
DlgCellHorAlign : "Horizontal Alignment",
DlgCellHorAlignNotSet : "<Not set>",
DlgCellHorAlignLeft : "Left",
DlgCellHorAlignCenter : "Centre",
DlgCellHorAlignRight: "Right",
DlgCellVerAlign : "Vertical Alignment",
DlgCellVerAlignNotSet : "<Not set>",
DlgCellVerAlignTop : "Top",
DlgCellVerAlignMiddle : "Middle",
DlgCellVerAlignBottom : "Bottom",
DlgCellVerAlignBaseline : "Baseline",
DlgCellRowSpan : "Rows Span",
DlgCellCollSpan : "Columns Span",
DlgCellBackColor : "Background Colour",
DlgCellBorderColor : "Border Colour",
DlgCellBtnSelect : "Select...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "Find and Replace",
// Find Dialog
DlgFindTitle : "Find",
DlgFindFindBtn : "Find",
DlgFindNotFoundMsg : "The specified text was not found.",
// Replace Dialog
DlgReplaceTitle : "Replace",
DlgReplaceFindLbl : "Find what:",
DlgReplaceReplaceLbl : "Replace with:",
DlgReplaceCaseChk : "Match case",
DlgReplaceReplaceBtn : "Replace",
DlgReplaceReplAllBtn : "Replace All",
DlgReplaceWordChk : "Match whole word",
// Paste Operations / Dialog
PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).",
PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).",
PasteAsText : "Paste as Plain Text",
PasteFromWord : "Paste from Word",
DlgPasteMsg2 : "Please paste inside the following box using the keyboard (<strong>Ctrl+V</strong>) and hit <strong>OK</strong>.",
DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.",
DlgPasteIgnoreFont : "Ignore Font Face definitions",
DlgPasteRemoveStyles : "Remove Styles definitions",
// Color Picker
ColorAutomatic : "Automatic",
ColorMoreColors : "More Colours...",
// Document Properties
DocProps : "Document Properties",
// Anchor Dialog
DlgAnchorTitle : "Anchor Properties",
DlgAnchorName : "Anchor Name",
DlgAnchorErrorName : "Please type the anchor name",
// Speller Pages Dialog
DlgSpellNotInDic : "Not in dictionary",
DlgSpellChangeTo : "Change to",
DlgSpellBtnIgnore : "Ignore",
DlgSpellBtnIgnoreAll : "Ignore All",
DlgSpellBtnReplace : "Replace",
DlgSpellBtnReplaceAll : "Replace All",
DlgSpellBtnUndo : "Undo",
DlgSpellNoSuggestions : "- No suggestions -",
DlgSpellProgress : "Spell check in progress...",
DlgSpellNoMispell : "Spell check complete: No misspellings found",
DlgSpellNoChanges : "Spell check complete: No words changed",
DlgSpellOneChange : "Spell check complete: One word changed",
DlgSpellManyChanges : "Spell check complete: %1 words changed",
IeSpellDownload : "Spell checker not installed. Do you want to download it now?",
// Button Dialog
DlgButtonText : "Text (Value)",
DlgButtonType : "Type",
DlgButtonTypeBtn : "Button",
DlgButtonTypeSbm : "Submit",
DlgButtonTypeRst : "Reset",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "Name",
DlgCheckboxValue : "Value",
DlgCheckboxSelected : "Selected",
// Form Dialog
DlgFormName : "Name",
DlgFormAction : "Action",
DlgFormMethod : "Method",
// Select Field Dialog
DlgSelectName : "Name",
DlgSelectValue : "Value",
DlgSelectSize : "Size",
DlgSelectLines : "lines",
DlgSelectChkMulti : "Allow multiple selections",
DlgSelectOpAvail : "Available Options",
DlgSelectOpText : "Text",
DlgSelectOpValue : "Value",
DlgSelectBtnAdd : "Add",
DlgSelectBtnModify : "Modify",
DlgSelectBtnUp : "Up",
DlgSelectBtnDown : "Down",
DlgSelectBtnSetValue : "Set as selected value",
DlgSelectBtnDelete : "Delete",
// Textarea Dialog
DlgTextareaName : "Name",
DlgTextareaCols : "Columns",
DlgTextareaRows : "Rows",
// Text Field Dialog
DlgTextName : "Name",
DlgTextValue : "Value",
DlgTextCharWidth : "Character Width",
DlgTextMaxChars : "Maximum Characters",
DlgTextType : "Type",
DlgTextTypeText : "Text",
DlgTextTypePass : "Password",
// Hidden Field Dialog
DlgHiddenName : "Name",
DlgHiddenValue : "Value",
// Bulleted List Dialog
BulletedListProp : "Bulleted List Properties",
NumberedListProp : "Numbered List Properties",
DlgLstStart : "Start",
DlgLstType : "Type",
DlgLstTypeCircle : "Circle",
DlgLstTypeDisc : "Disc",
DlgLstTypeSquare : "Square",
DlgLstTypeNumbers : "Numbers (1, 2, 3)",
DlgLstTypeLCase : "Lowercase Letters (a, b, c)",
DlgLstTypeUCase : "Uppercase Letters (A, B, C)",
DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)",
DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "General",
DlgDocBackTab : "Background",
DlgDocColorsTab : "Colours and Margins",
DlgDocMetaTab : "Meta Data",
DlgDocPageTitle : "Page Title",
DlgDocLangDir : "Language Direction",
DlgDocLangDirLTR : "Left to Right (LTR)",
DlgDocLangDirRTL : "Right to Left (RTL)",
DlgDocLangCode : "Language Code",
DlgDocCharSet : "Character Set Encoding",
DlgDocCharSetCE : "Central European",
DlgDocCharSetCT : "Chinese Traditional (Big5)",
DlgDocCharSetCR : "Cyrillic",
DlgDocCharSetGR : "Greek",
DlgDocCharSetJP : "Japanese",
DlgDocCharSetKR : "Korean",
DlgDocCharSetTR : "Turkish",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "Western European",
DlgDocCharSetOther : "Other Character Set Encoding",
DlgDocDocType : "Document Type Heading",
DlgDocDocTypeOther : "Other Document Type Heading",
DlgDocIncXHTML : "Include XHTML Declarations",
DlgDocBgColor : "Background Colour",
DlgDocBgImage : "Background Image URL",
DlgDocBgNoScroll : "Nonscrolling Background",
DlgDocCText : "Text",
DlgDocCLink : "Link",
DlgDocCVisited : "Visited Link",
DlgDocCActive : "Active Link",
DlgDocMargins : "Page Margins",
DlgDocMaTop : "Top",
DlgDocMaLeft : "Left",
DlgDocMaRight : "Right",
DlgDocMaBottom : "Bottom",
DlgDocMeIndex : "Document Indexing Keywords (comma separated)",
DlgDocMeDescr : "Document Description",
DlgDocMeAuthor : "Author",
DlgDocMeCopy : "Copyright",
DlgDocPreview : "Preview",
// Templates Dialog
Templates : "Templates",
DlgTemplatesTitle : "Content Templates",
DlgTemplatesSelMsg : "Please select the template to open in the editor<br />(the actual contents will be lost):",
DlgTemplatesLoading : "Loading templates list. Please wait...",
DlgTemplatesNoTpl : "(No templates defined)",
DlgTemplatesReplace : "Replace actual contents",
// About Dialog
DlgAboutAboutTab : "About",
DlgAboutBrowserInfoTab : "Browser Info",
DlgAboutLicenseTab : "License",
DlgAboutVersion : "version",
DlgAboutInfo : "For further information go to",
// Div Dialog
DlgDivGeneralTab : "General",
DlgDivAdvancedTab : "Advanced",
DlgDivStyle : "Style",
DlgDivInlineStyle : "Inline Style"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* English (United Kingdom) language file.
*/
var FCKLang =
{
// Language direction : "ltr" (left to right) or "rtl" (right to left).
Dir : "ltr",
ToolbarCollapse : "Collapse Toolbar",
ToolbarExpand : "Expand Toolbar",
// Toolbar Items and Context Menu
Save : "Save",
NewPage : "New Page",
Preview : "Preview",
Cut : "Cut",
Copy : "Copy",
Paste : "Paste",
PasteText : "Paste as plain text",
PasteWord : "Paste from Word",
Print : "Print",
SelectAll : "Select All",
RemoveFormat : "Remove Format",
InsertLinkLbl : "Link",
InsertLink : "Insert/Edit Link",
RemoveLink : "Remove Link",
VisitLink : "Open Link",
Anchor : "Insert/Edit Anchor",
AnchorDelete : "Remove Anchor",
InsertImageLbl : "Image",
InsertImage : "Insert/Edit Image",
InsertFlashLbl : "Flash",
InsertFlash : "Insert/Edit Flash",
InsertTableLbl : "Table",
InsertTable : "Insert/Edit Table",
InsertLineLbl : "Line",
InsertLine : "Insert Horizontal Line",
InsertSpecialCharLbl: "Special Character",
InsertSpecialChar : "Insert Special Character",
InsertSmileyLbl : "Smiley",
InsertSmiley : "Insert Smiley",
About : "About FCKeditor",
Bold : "Bold",
Italic : "Italic",
Underline : "Underline",
StrikeThrough : "Strike Through",
Subscript : "Subscript",
Superscript : "Superscript",
LeftJustify : "Left Justify",
CenterJustify : "Centre Justify",
RightJustify : "Right Justify",
BlockJustify : "Block Justify",
DecreaseIndent : "Decrease Indent",
IncreaseIndent : "Increase Indent",
Blockquote : "Blockquote",
CreateDiv : "Create Div Container",
EditDiv : "Edit Div Container",
DeleteDiv : "Remove Div Container",
Undo : "Undo",
Redo : "Redo",
NumberedListLbl : "Numbered List",
NumberedList : "Insert/Remove Numbered List",
BulletedListLbl : "Bulleted List",
BulletedList : "Insert/Remove Bulleted List",
ShowTableBorders : "Show Table Borders",
ShowDetails : "Show Details",
Style : "Style",
FontFormat : "Format",
Font : "Font",
FontSize : "Size",
TextColor : "Text Colour",
BGColor : "Background Colour",
Source : "Source",
Find : "Find",
Replace : "Replace",
SpellCheck : "Check Spelling",
UniversalKeyboard : "Universal Keyboard",
PageBreakLbl : "Page Break",
PageBreak : "Insert Page Break",
Form : "Form",
Checkbox : "Checkbox",
RadioButton : "Radio Button",
TextField : "Text Field",
Textarea : "Textarea",
HiddenField : "Hidden Field",
Button : "Button",
SelectionField : "Selection Field",
ImageButton : "Image Button",
FitWindow : "Maximize the editor size",
ShowBlocks : "Show Blocks",
// Context Menu
EditLink : "Edit Link",
CellCM : "Cell",
RowCM : "Row",
ColumnCM : "Column",
InsertRowAfter : "Insert Row After",
InsertRowBefore : "Insert Row Before",
DeleteRows : "Delete Rows",
InsertColumnAfter : "Insert Column After",
InsertColumnBefore : "Insert Column Before",
DeleteColumns : "Delete Columns",
InsertCellAfter : "Insert Cell After",
InsertCellBefore : "Insert Cell Before",
DeleteCells : "Delete Cells",
MergeCells : "Merge Cells",
MergeRight : "Merge Right",
MergeDown : "Merge Down",
HorizontalSplitCell : "Split Cell Horizontally",
VerticalSplitCell : "Split Cell Vertically",
TableDelete : "Delete Table",
CellProperties : "Cell Properties",
TableProperties : "Table Properties",
ImageProperties : "Image Properties",
FlashProperties : "Flash Properties",
AnchorProp : "Anchor Properties",
ButtonProp : "Button Properties",
CheckboxProp : "Checkbox Properties",
HiddenFieldProp : "Hidden Field Properties",
RadioButtonProp : "Radio Button Properties",
ImageButtonProp : "Image Button Properties",
TextFieldProp : "Text Field Properties",
SelectionFieldProp : "Selection Field Properties",
TextareaProp : "Textarea Properties",
FormProp : "Form Properties",
FontFormats : "Normal;Formatted;Address;Heading 1;Heading 2;Heading 3;Heading 4;Heading 5;Heading 6;Normal (DIV)",
// Alerts and Messages
ProcessingXHTML : "Processing XHTML. Please wait...",
Done : "Done",
PasteWordConfirm : "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?",
NotCompatiblePaste : "This command is available for Internet Explorer version 5.5 or more. Do you want to paste without cleaning?",
UnknownToolbarItem : "Unknown toolbar item \"%1\"",
UnknownCommand : "Unknown command name \"%1\"",
NotImplemented : "Command not implemented",
UnknownToolbarSet : "Toolbar set \"%1\" doesn't exist",
NoActiveX : "Your browser's security settings could limit some features of the editor. You must enable the option \"Run ActiveX controls and plug-ins\". You may experience errors and notice missing features.",
BrowseServerBlocked : "The resources browser could not be opened. Make sure that all popup blockers are disabled.",
DialogBlocked : "It was not possible to open the dialog window. Make sure all popup blockers are disabled.",
VisitLinkBlocked : "It was not possible to open a new window. Make sure all popup blockers are disabled.",
// Dialogs
DlgBtnOK : "OK",
DlgBtnCancel : "Cancel",
DlgBtnClose : "Close",
DlgBtnBrowseServer : "Browse Server",
DlgAdvancedTag : "Advanced",
DlgOpOther : "<Other>",
DlgInfoTab : "Info",
DlgAlertUrl : "Please insert the URL",
// General Dialogs Labels
DlgGenNotSet : "<not set>",
DlgGenId : "Id",
DlgGenLangDir : "Language Direction",
DlgGenLangDirLtr : "Left to Right (LTR)",
DlgGenLangDirRtl : "Right to Left (RTL)",
DlgGenLangCode : "Language Code",
DlgGenAccessKey : "Access Key",
DlgGenName : "Name",
DlgGenTabIndex : "Tab Index",
DlgGenLongDescr : "Long Description URL",
DlgGenClass : "Stylesheet Classes",
DlgGenTitle : "Advisory Title",
DlgGenContType : "Advisory Content Type",
DlgGenLinkCharset : "Linked Resource Charset",
DlgGenStyle : "Style",
// Image Dialog
DlgImgTitle : "Image Properties",
DlgImgInfoTab : "Image Info",
DlgImgBtnUpload : "Send it to the Server",
DlgImgURL : "URL",
DlgImgUpload : "Upload",
DlgImgAlt : "Alternative Text",
DlgImgWidth : "Width",
DlgImgHeight : "Height",
DlgImgLockRatio : "Lock Ratio",
DlgBtnResetSize : "Reset Size",
DlgImgBorder : "Border",
DlgImgHSpace : "HSpace",
DlgImgVSpace : "VSpace",
DlgImgAlign : "Align",
DlgImgAlignLeft : "Left",
DlgImgAlignAbsBottom: "Abs Bottom",
DlgImgAlignAbsMiddle: "Abs Middle",
DlgImgAlignBaseline : "Baseline",
DlgImgAlignBottom : "Bottom",
DlgImgAlignMiddle : "Middle",
DlgImgAlignRight : "Right",
DlgImgAlignTextTop : "Text Top",
DlgImgAlignTop : "Top",
DlgImgPreview : "Preview",
DlgImgAlertUrl : "Please type the image URL",
DlgImgLinkTab : "Link",
// Flash Dialog
DlgFlashTitle : "Flash Properties",
DlgFlashChkPlay : "Auto Play",
DlgFlashChkLoop : "Loop",
DlgFlashChkMenu : "Enable Flash Menu",
DlgFlashScale : "Scale",
DlgFlashScaleAll : "Show all",
DlgFlashScaleNoBorder : "No Border",
DlgFlashScaleFit : "Exact Fit",
// Link Dialog
DlgLnkWindowTitle : "Link",
DlgLnkInfoTab : "Link Info",
DlgLnkTargetTab : "Target",
DlgLnkType : "Link Type",
DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Link to anchor in the text",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protocol",
DlgLnkProtoOther : "<other>",
DlgLnkURL : "URL",
DlgLnkAnchorSel : "Select an Anchor",
DlgLnkAnchorByName : "By Anchor Name",
DlgLnkAnchorById : "By Element Id",
DlgLnkNoAnchors : "(No anchors available in the document)",
DlgLnkEMail : "E-Mail Address",
DlgLnkEMailSubject : "Message Subject",
DlgLnkEMailBody : "Message Body",
DlgLnkUpload : "Upload",
DlgLnkBtnUpload : "Send it to the Server",
DlgLnkTarget : "Target",
DlgLnkTargetFrame : "<frame>",
DlgLnkTargetPopup : "<popup window>",
DlgLnkTargetBlank : "New Window (_blank)",
DlgLnkTargetParent : "Parent Window (_parent)",
DlgLnkTargetSelf : "Same Window (_self)",
DlgLnkTargetTop : "Topmost Window (_top)",
DlgLnkTargetFrameName : "Target Frame Name",
DlgLnkPopWinName : "Popup Window Name",
DlgLnkPopWinFeat : "Popup Window Features",
DlgLnkPopResize : "Resizable",
DlgLnkPopLocation : "Location Bar",
DlgLnkPopMenu : "Menu Bar",
DlgLnkPopScroll : "Scroll Bars",
DlgLnkPopStatus : "Status Bar",
DlgLnkPopToolbar : "Toolbar",
DlgLnkPopFullScrn : "Full Screen (IE)",
DlgLnkPopDependent : "Dependent (Netscape)",
DlgLnkPopWidth : "Width",
DlgLnkPopHeight : "Height",
DlgLnkPopLeft : "Left Position",
DlgLnkPopTop : "Top Position",
DlnLnkMsgNoUrl : "Please type the link URL",
DlnLnkMsgNoEMail : "Please type the e-mail address",
DlnLnkMsgNoAnchor : "Please select an anchor",
DlnLnkMsgInvPopName : "The popup name must begin with an alphabetic character and must not contain spaces",
// Color Dialog
DlgColorTitle : "Select Colour",
DlgColorBtnClear : "Clear",
DlgColorHighlight : "Highlight",
DlgColorSelected : "Selected",
// Smiley Dialog
DlgSmileyTitle : "Insert a Smiley",
// Special Character Dialog
DlgSpecialCharTitle : "Select Special Character",
// Table Dialog
DlgTableTitle : "Table Properties",
DlgTableRows : "Rows",
DlgTableColumns : "Columns",
DlgTableBorder : "Border size",
DlgTableAlign : "Alignment",
DlgTableAlignNotSet : "<Not set>",
DlgTableAlignLeft : "Left",
DlgTableAlignCenter : "Centre",
DlgTableAlignRight : "Right",
DlgTableWidth : "Width",
DlgTableWidthPx : "pixels",
DlgTableWidthPc : "percent",
DlgTableHeight : "Height",
DlgTableCellSpace : "Cell spacing",
DlgTableCellPad : "Cell padding",
DlgTableCaption : "Caption",
DlgTableSummary : "Summary",
// Table Cell Dialog
DlgCellTitle : "Cell Properties",
DlgCellWidth : "Width",
DlgCellWidthPx : "pixels",
DlgCellWidthPc : "percent",
DlgCellHeight : "Height",
DlgCellWordWrap : "Word Wrap",
DlgCellWordWrapNotSet : "<Not set>",
DlgCellWordWrapYes : "Yes",
DlgCellWordWrapNo : "No",
DlgCellHorAlign : "Horizontal Alignment",
DlgCellHorAlignNotSet : "<Not set>",
DlgCellHorAlignLeft : "Left",
DlgCellHorAlignCenter : "Centre",
DlgCellHorAlignRight: "Right",
DlgCellVerAlign : "Vertical Alignment",
DlgCellVerAlignNotSet : "<Not set>",
DlgCellVerAlignTop : "Top",
DlgCellVerAlignMiddle : "Middle",
DlgCellVerAlignBottom : "Bottom",
DlgCellVerAlignBaseline : "Baseline",
DlgCellRowSpan : "Rows Span",
DlgCellCollSpan : "Columns Span",
DlgCellBackColor : "Background Colour",
DlgCellBorderColor : "Border Colour",
DlgCellBtnSelect : "Select...",
// Find and Replace Dialog
DlgFindAndReplaceTitle : "Find and Replace",
// Find Dialog
DlgFindTitle : "Find",
DlgFindFindBtn : "Find",
DlgFindNotFoundMsg : "The specified text was not found.",
// Replace Dialog
DlgReplaceTitle : "Replace",
DlgReplaceFindLbl : "Find what:",
DlgReplaceReplaceLbl : "Replace with:",
DlgReplaceCaseChk : "Match case",
DlgReplaceReplaceBtn : "Replace",
DlgReplaceReplAllBtn : "Replace All",
DlgReplaceWordChk : "Match whole word",
// Paste Operations / Dialog
PasteErrorCut : "Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl+X).",
PasteErrorCopy : "Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl+C).",
PasteAsText : "Paste as Plain Text",
PasteFromWord : "Paste from Word",
DlgPasteMsg2 : "Please paste inside the following box using the keyboard (<strong>Ctrl+V</strong>) and hit <strong>OK</strong>.",
DlgPasteSec : "Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.",
DlgPasteIgnoreFont : "Ignore Font Face definitions",
DlgPasteRemoveStyles : "Remove Styles definitions",
// Color Picker
ColorAutomatic : "Automatic",
ColorMoreColors : "More Colours...",
// Document Properties
DocProps : "Document Properties",
// Anchor Dialog
DlgAnchorTitle : "Anchor Properties",
DlgAnchorName : "Anchor Name",
DlgAnchorErrorName : "Please type the anchor name",
// Speller Pages Dialog
DlgSpellNotInDic : "Not in dictionary",
DlgSpellChangeTo : "Change to",
DlgSpellBtnIgnore : "Ignore",
DlgSpellBtnIgnoreAll : "Ignore All",
DlgSpellBtnReplace : "Replace",
DlgSpellBtnReplaceAll : "Replace All",
DlgSpellBtnUndo : "Undo",
DlgSpellNoSuggestions : "- No suggestions -",
DlgSpellProgress : "Spell check in progress...",
DlgSpellNoMispell : "Spell check complete: No misspellings found",
DlgSpellNoChanges : "Spell check complete: No words changed",
DlgSpellOneChange : "Spell check complete: One word changed",
DlgSpellManyChanges : "Spell check complete: %1 words changed",
IeSpellDownload : "Spell checker not installed. Do you want to download it now?",
// Button Dialog
DlgButtonText : "Text (Value)",
DlgButtonType : "Type",
DlgButtonTypeBtn : "Button",
DlgButtonTypeSbm : "Submit",
DlgButtonTypeRst : "Reset",
// Checkbox and Radio Button Dialogs
DlgCheckboxName : "Name",
DlgCheckboxValue : "Value",
DlgCheckboxSelected : "Selected",
// Form Dialog
DlgFormName : "Name",
DlgFormAction : "Action",
DlgFormMethod : "Method",
// Select Field Dialog
DlgSelectName : "Name",
DlgSelectValue : "Value",
DlgSelectSize : "Size",
DlgSelectLines : "lines",
DlgSelectChkMulti : "Allow multiple selections",
DlgSelectOpAvail : "Available Options",
DlgSelectOpText : "Text",
DlgSelectOpValue : "Value",
DlgSelectBtnAdd : "Add",
DlgSelectBtnModify : "Modify",
DlgSelectBtnUp : "Up",
DlgSelectBtnDown : "Down",
DlgSelectBtnSetValue : "Set as selected value",
DlgSelectBtnDelete : "Delete",
// Textarea Dialog
DlgTextareaName : "Name",
DlgTextareaCols : "Columns",
DlgTextareaRows : "Rows",
// Text Field Dialog
DlgTextName : "Name",
DlgTextValue : "Value",
DlgTextCharWidth : "Character Width",
DlgTextMaxChars : "Maximum Characters",
DlgTextType : "Type",
DlgTextTypeText : "Text",
DlgTextTypePass : "Password",
// Hidden Field Dialog
DlgHiddenName : "Name",
DlgHiddenValue : "Value",
// Bulleted List Dialog
BulletedListProp : "Bulleted List Properties",
NumberedListProp : "Numbered List Properties",
DlgLstStart : "Start",
DlgLstType : "Type",
DlgLstTypeCircle : "Circle",
DlgLstTypeDisc : "Disc",
DlgLstTypeSquare : "Square",
DlgLstTypeNumbers : "Numbers (1, 2, 3)",
DlgLstTypeLCase : "Lowercase Letters (a, b, c)",
DlgLstTypeUCase : "Uppercase Letters (A, B, C)",
DlgLstTypeSRoman : "Small Roman Numerals (i, ii, iii)",
DlgLstTypeLRoman : "Large Roman Numerals (I, II, III)",
// Document Properties Dialog
DlgDocGeneralTab : "General",
DlgDocBackTab : "Background",
DlgDocColorsTab : "Colours and Margins",
DlgDocMetaTab : "Meta Data",
DlgDocPageTitle : "Page Title",
DlgDocLangDir : "Language Direction",
DlgDocLangDirLTR : "Left to Right (LTR)",
DlgDocLangDirRTL : "Right to Left (RTL)",
DlgDocLangCode : "Language Code",
DlgDocCharSet : "Character Set Encoding",
DlgDocCharSetCE : "Central European",
DlgDocCharSetCT : "Chinese Traditional (Big5)",
DlgDocCharSetCR : "Cyrillic",
DlgDocCharSetGR : "Greek",
DlgDocCharSetJP : "Japanese",
DlgDocCharSetKR : "Korean",
DlgDocCharSetTR : "Turkish",
DlgDocCharSetUN : "Unicode (UTF-8)",
DlgDocCharSetWE : "Western European",
DlgDocCharSetOther : "Other Character Set Encoding",
DlgDocDocType : "Document Type Heading",
DlgDocDocTypeOther : "Other Document Type Heading",
DlgDocIncXHTML : "Include XHTML Declarations",
DlgDocBgColor : "Background Colour",
DlgDocBgImage : "Background Image URL",
DlgDocBgNoScroll : "Nonscrolling Background",
DlgDocCText : "Text",
DlgDocCLink : "Link",
DlgDocCVisited : "Visited Link",
DlgDocCActive : "Active Link",
DlgDocMargins : "Page Margins",
DlgDocMaTop : "Top",
DlgDocMaLeft : "Left",
DlgDocMaRight : "Right",
DlgDocMaBottom : "Bottom",
DlgDocMeIndex : "Document Indexing Keywords (comma separated)",
DlgDocMeDescr : "Document Description",
DlgDocMeAuthor : "Author",
DlgDocMeCopy : "Copyright",
DlgDocPreview : "Preview",
// Templates Dialog
Templates : "Templates",
DlgTemplatesTitle : "Content Templates",
DlgTemplatesSelMsg : "Please select the template to open in the editor<br />(the actual contents will be lost):",
DlgTemplatesLoading : "Loading templates list. Please wait...",
DlgTemplatesNoTpl : "(No templates defined)",
DlgTemplatesReplace : "Replace actual contents",
// About Dialog
DlgAboutAboutTab : "About",
DlgAboutBrowserInfoTab : "Browser Info",
DlgAboutLicenseTab : "License",
DlgAboutVersion : "version",
DlgAboutInfo : "For further information go to",
// Div Dialog
DlgDivGeneralTab : "General",
DlgDivAdvancedTab : "Advanced",
DlgDivStyle : "Style",
DlgDivInlineStyle : "Inline Style"
};
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts for the fck_select.html page.
*/
function Select( combo )
{
var iIndex = combo.selectedIndex ;
oListText.selectedIndex = iIndex ;
oListValue.selectedIndex = iIndex ;
var oTxtText = document.getElementById( "txtText" ) ;
var oTxtValue = document.getElementById( "txtValue" ) ;
oTxtText.value = oListText.value ;
oTxtValue.value = oListValue.value ;
}
function Add()
{
var oTxtText = document.getElementById( "txtText" ) ;
var oTxtValue = document.getElementById( "txtValue" ) ;
AddComboOption( oListText, oTxtText.value, oTxtText.value ) ;
AddComboOption( oListValue, oTxtValue.value, oTxtValue.value ) ;
oListText.selectedIndex = oListText.options.length - 1 ;
oListValue.selectedIndex = oListValue.options.length - 1 ;
oTxtText.value = '' ;
oTxtValue.value = '' ;
oTxtText.focus() ;
}
function Modify()
{
var iIndex = oListText.selectedIndex ;
if ( iIndex < 0 ) return ;
var oTxtText = document.getElementById( "txtText" ) ;
var oTxtValue = document.getElementById( "txtValue" ) ;
oListText.options[ iIndex ].innerHTML = HTMLEncode( oTxtText.value ) ;
oListText.options[ iIndex ].value = oTxtText.value ;
oListValue.options[ iIndex ].innerHTML = HTMLEncode( oTxtValue.value ) ;
oListValue.options[ iIndex ].value = oTxtValue.value ;
oTxtText.value = '' ;
oTxtValue.value = '' ;
oTxtText.focus() ;
}
function Move( steps )
{
ChangeOptionPosition( oListText, steps ) ;
ChangeOptionPosition( oListValue, steps ) ;
}
function Delete()
{
RemoveSelectedOptions( oListText ) ;
RemoveSelectedOptions( oListValue ) ;
}
function SetSelectedValue()
{
var iIndex = oListValue.selectedIndex ;
if ( iIndex < 0 ) return ;
var oTxtValue = document.getElementById( "txtSelValue" ) ;
oTxtValue.value = oListValue.options[ iIndex ].value ;
}
// Moves the selected option by a number of steps (also negative)
function ChangeOptionPosition( combo, steps )
{
var iActualIndex = combo.selectedIndex ;
if ( iActualIndex < 0 )
return ;
var iFinalIndex = iActualIndex + steps ;
if ( iFinalIndex < 0 )
iFinalIndex = 0 ;
if ( iFinalIndex > ( combo.options.length - 1 ) )
iFinalIndex = combo.options.length - 1 ;
if ( iActualIndex == iFinalIndex )
return ;
var oOption = combo.options[ iActualIndex ] ;
var sText = HTMLDecode( oOption.innerHTML ) ;
var sValue = oOption.value ;
combo.remove( iActualIndex ) ;
oOption = AddComboOption( combo, sText, sValue, null, iFinalIndex ) ;
oOption.selected = true ;
}
// Remove all selected options from a SELECT object
function RemoveSelectedOptions(combo)
{
// Save the selected index
var iSelectedIndex = combo.selectedIndex ;
var oOptions = combo.options ;
// Remove all selected options
for ( var i = oOptions.length - 1 ; i >= 0 ; i-- )
{
if (oOptions[i].selected) combo.remove(i) ;
}
// Reset the selection based on the original selected index
if ( combo.options.length > 0 )
{
if ( iSelectedIndex >= combo.options.length ) iSelectedIndex = combo.options.length - 1 ;
combo.selectedIndex = iSelectedIndex ;
}
}
// Add a new option to a SELECT object (combo or list)
function AddComboOption( combo, optionText, optionValue, documentObject, index )
{
var oOption ;
if ( documentObject )
oOption = documentObject.createElement("OPTION") ;
else
oOption = document.createElement("OPTION") ;
if ( index != null )
combo.options.add( oOption, index ) ;
else
combo.options.add( oOption ) ;
oOption.innerHTML = optionText.length > 0 ? HTMLEncode( optionText ) : ' ' ;
oOption.value = optionValue ;
return oOption ;
}
function HTMLEncode( text )
{
if ( !text )
return '' ;
text = text.replace( /&/g, '&' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( />/g, '>' ) ;
return text ;
}
function HTMLDecode( text )
{
if ( !text )
return '' ;
text = text.replace( />/g, '>' ) ;
text = text.replace( /</g, '<' ) ;
text = text.replace( /&/g, '&' ) ;
return text ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Link dialog window (see fck_link.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKRegexLib = oEditor.FCKRegexLib ;
var FCKTools = oEditor.FCKTools ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', FCKLang.DlgLnkInfoTab ) ;
if ( !FCKConfig.LinkDlgHideTarget )
dialog.AddTab( 'Target', FCKLang.DlgLnkTargetTab, true ) ;
if ( FCKConfig.LinkUpload )
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload, true ) ;
if ( !FCKConfig.LinkDlgHideAdvanced )
dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divInfo' , ( tabCode == 'Info' ) ) ;
ShowE('divTarget' , ( tabCode == 'Target' ) ) ;
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
ShowE('divAttribs' , ( tabCode == 'Advanced' ) ) ;
dialog.SetAutoSize( true ) ;
}
//#### Regular Expressions library.
var oRegex = new Object() ;
oRegex.UriProtocol = /^(((http|https|ftp|news):\/\/)|mailto:)/gi ;
oRegex.UrlOnChangeProtocol = /^(http|https|ftp|news):\/\/(?=.)/gi ;
oRegex.UrlOnChangeTestOther = /^((javascript:)|[#\/\.])/gi ;
oRegex.ReserveTarget = /^_(blank|self|top|parent)$/i ;
oRegex.PopupUri = /^javascript:void\(\s*window.open\(\s*'([^']+)'\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*\)\s*$/ ;
// Accessible popups
oRegex.OnClickPopup = /^\s*on[cC]lick="\s*window.open\(\s*this\.href\s*,\s*(?:'([^']*)'|null)\s*,\s*'([^']*)'\s*\)\s*;\s*return\s*false;*\s*"$/ ;
oRegex.PopupFeatures = /(?:^|,)([^=]+)=(\d+|yes|no)/gi ;
//#### Parser Functions
var oParser = new Object() ;
// This method simply returns the two inputs in numerical order. You can even
// provide strings, as the method would parseInt() the values.
oParser.SortNumerical = function(a, b)
{
return parseInt( a, 10 ) - parseInt( b, 10 ) ;
}
oParser.ParseEMailParams = function(sParams)
{
// Initialize the oEMailParams object.
var oEMailParams = new Object() ;
oEMailParams.Subject = '' ;
oEMailParams.Body = '' ;
var aMatch = sParams.match( /(^|^\?|&)subject=([^&]+)/i ) ;
if ( aMatch ) oEMailParams.Subject = decodeURIComponent( aMatch[2] ) ;
aMatch = sParams.match( /(^|^\?|&)body=([^&]+)/i ) ;
if ( aMatch ) oEMailParams.Body = decodeURIComponent( aMatch[2] ) ;
return oEMailParams ;
}
// This method returns either an object containing the email info, or FALSE
// if the parameter is not an email link.
oParser.ParseEMailUri = function( sUrl )
{
// Initializes the EMailInfo object.
var oEMailInfo = new Object() ;
oEMailInfo.Address = '' ;
oEMailInfo.Subject = '' ;
oEMailInfo.Body = '' ;
var aLinkInfo = sUrl.match( /^(\w+):(.*)$/ ) ;
if ( aLinkInfo && aLinkInfo[1] == 'mailto' )
{
// This seems to be an unprotected email link.
var aParts = aLinkInfo[2].match( /^([^\?]+)\??(.+)?/ ) ;
if ( aParts )
{
// Set the e-mail address.
oEMailInfo.Address = aParts[1] ;
// Look for the optional e-mail parameters.
if ( aParts[2] )
{
var oEMailParams = oParser.ParseEMailParams( aParts[2] ) ;
oEMailInfo.Subject = oEMailParams.Subject ;
oEMailInfo.Body = oEMailParams.Body ;
}
}
return oEMailInfo ;
}
else if ( aLinkInfo && aLinkInfo[1] == 'javascript' )
{
// This may be a protected email.
// Try to match the url against the EMailProtectionFunction.
var func = FCKConfig.EMailProtectionFunction ;
if ( func != null )
{
try
{
// Escape special chars.
func = func.replace( /([\/^$*+.?()\[\]])/g, '\\$1' ) ;
// Define the possible keys.
var keys = new Array('NAME', 'DOMAIN', 'SUBJECT', 'BODY') ;
// Get the order of the keys (hold them in the array <pos>) and
// the function replaced by regular expression patterns.
var sFunc = func ;
var pos = new Array() ;
for ( var i = 0 ; i < keys.length ; i ++ )
{
var rexp = new RegExp( keys[i] ) ;
var p = func.search( rexp ) ;
if ( p >= 0 )
{
sFunc = sFunc.replace( rexp, '\'([^\']*)\'' ) ;
pos[pos.length] = p + ':' + keys[i] ;
}
}
// Sort the available keys.
pos.sort( oParser.SortNumerical ) ;
// Replace the excaped single quotes in the url, such they do
// not affect the regexp afterwards.
aLinkInfo[2] = aLinkInfo[2].replace( /\\'/g, '###SINGLE_QUOTE###' ) ;
// Create the regexp and execute it.
var rFunc = new RegExp( '^' + sFunc + '$' ) ;
var aMatch = rFunc.exec( aLinkInfo[2] ) ;
if ( aMatch )
{
var aInfo = new Array();
for ( var i = 1 ; i < aMatch.length ; i ++ )
{
var k = pos[i-1].match(/^\d+:(.+)$/) ;
aInfo[k[1]] = aMatch[i].replace(/###SINGLE_QUOTE###/g, '\'') ;
}
// Fill the EMailInfo object that will be returned
oEMailInfo.Address = aInfo['NAME'] + '@' + aInfo['DOMAIN'] ;
oEMailInfo.Subject = decodeURIComponent( aInfo['SUBJECT'] ) ;
oEMailInfo.Body = decodeURIComponent( aInfo['BODY'] ) ;
return oEMailInfo ;
}
}
catch (e)
{
}
}
// Try to match the email against the encode protection.
var aMatch = aLinkInfo[2].match( /^location\.href='mailto:'\+(String\.fromCharCode\([\d,]+\))\+'(.*)'$/ ) ;
if ( aMatch )
{
// The link is encoded
oEMailInfo.Address = eval( aMatch[1] ) ;
if ( aMatch[2] )
{
var oEMailParams = oParser.ParseEMailParams( aMatch[2] ) ;
oEMailInfo.Subject = oEMailParams.Subject ;
oEMailInfo.Body = oEMailParams.Body ;
}
return oEMailInfo ;
}
}
return false;
}
oParser.CreateEMailUri = function( address, subject, body )
{
// Switch for the EMailProtection setting.
switch ( FCKConfig.EMailProtection )
{
case 'function' :
var func = FCKConfig.EMailProtectionFunction ;
if ( func == null )
{
if ( FCKConfig.Debug )
{
alert('EMailProtection alert!\nNo function defined. Please set "FCKConfig.EMailProtectionFunction"') ;
}
return '';
}
// Split the email address into name and domain parts.
var aAddressParts = address.split( '@', 2 ) ;
if ( aAddressParts[1] == undefined )
{
aAddressParts[1] = '' ;
}
// Replace the keys by their values (embedded in single quotes).
func = func.replace(/NAME/g, "'" + aAddressParts[0].replace(/'/g, '\\\'') + "'") ;
func = func.replace(/DOMAIN/g, "'" + aAddressParts[1].replace(/'/g, '\\\'') + "'") ;
func = func.replace(/SUBJECT/g, "'" + encodeURIComponent( subject ).replace(/'/g, '\\\'') + "'") ;
func = func.replace(/BODY/g, "'" + encodeURIComponent( body ).replace(/'/g, '\\\'') + "'") ;
return 'javascript:' + func ;
case 'encode' :
var aParams = [] ;
var aAddressCode = [] ;
if ( subject.length > 0 )
aParams.push( 'subject='+ encodeURIComponent( subject ) ) ;
if ( body.length > 0 )
aParams.push( 'body=' + encodeURIComponent( body ) ) ;
for ( var i = 0 ; i < address.length ; i++ )
aAddressCode.push( address.charCodeAt( i ) ) ;
return 'javascript:location.href=\'mailto:\'+String.fromCharCode(' + aAddressCode.join( ',' ) + ')+\'?' + aParams.join( '&' ) + '\'' ;
}
// EMailProtection 'none'
var sBaseUri = 'mailto:' + address ;
var sParams = '' ;
if ( subject.length > 0 )
sParams = '?subject=' + encodeURIComponent( subject ) ;
if ( body.length > 0 )
{
sParams += ( sParams.length == 0 ? '?' : '&' ) ;
sParams += 'body=' + encodeURIComponent( body ) ;
}
return sBaseUri + sParams ;
}
//#### Initialization Code
// oLink: The actual selected link in the editor.
var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ;
if ( oLink )
FCK.Selection.SelectNode( oLink ) ;
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
// Fill the Anchor Names and Ids combos.
LoadAnchorNamesAndIds() ;
// Load the selected link information (if any).
LoadSelection() ;
// Update the dialog box.
SetLinkType( GetE('cmbLinkType').value ) ;
// Show/Hide the "Browse Server" button.
GetE('divBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ;
// Show the initial dialog content.
GetE('divInfo').style.display = '' ;
// Set the actual uploader URL.
if ( FCKConfig.LinkUpload )
GetE('frmUpload').action = FCKConfig.LinkUploadURL ;
// Set the default target (from configuration).
SetDefaultTarget() ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
// Select the first field.
switch( GetE('cmbLinkType').value )
{
case 'url' :
SelectField( 'txtUrl' ) ;
break ;
case 'email' :
SelectField( 'txtEMailAddress' ) ;
break ;
case 'anchor' :
if ( GetE('divSelAnchor').style.display != 'none' )
SelectField( 'cmbAnchorName' ) ;
else
SelectField( 'cmbLinkType' ) ;
}
}
var bHasAnchors ;
function LoadAnchorNamesAndIds()
{
// Since version 2.0, the anchors are replaced in the DOM by IMGs so the user see the icon
// to edit them. So, we must look for that images now.
var aAnchors = new Array() ;
var i ;
var oImages = oEditor.FCK.EditorDocument.getElementsByTagName( 'IMG' ) ;
for( i = 0 ; i < oImages.length ; i++ )
{
if ( oImages[i].getAttribute('_fckanchor') )
aAnchors[ aAnchors.length ] = oEditor.FCK.GetRealElement( oImages[i] ) ;
}
// Add also real anchors
var oLinks = oEditor.FCK.EditorDocument.getElementsByTagName( 'A' ) ;
for( i = 0 ; i < oLinks.length ; i++ )
{
if ( oLinks[i].name && ( oLinks[i].name.length > 0 ) )
aAnchors[ aAnchors.length ] = oLinks[i] ;
}
var aIds = FCKTools.GetAllChildrenIds( oEditor.FCK.EditorDocument.body ) ;
bHasAnchors = ( aAnchors.length > 0 || aIds.length > 0 ) ;
for ( i = 0 ; i < aAnchors.length ; i++ )
{
var sName = aAnchors[i].name ;
if ( sName && sName.length > 0 )
FCKTools.AddSelectOption( GetE('cmbAnchorName'), sName, sName ) ;
}
for ( i = 0 ; i < aIds.length ; i++ )
{
FCKTools.AddSelectOption( GetE('cmbAnchorId'), aIds[i], aIds[i] ) ;
}
ShowE( 'divSelAnchor' , bHasAnchors ) ;
ShowE( 'divNoAnchor' , !bHasAnchors ) ;
}
function LoadSelection()
{
if ( !oLink ) return ;
var sType = 'url' ;
// Get the actual Link href.
var sHRef = oLink.getAttribute( '_fcksavedurl' ) ;
if ( sHRef == null )
sHRef = oLink.getAttribute( 'href' , 2 ) || '' ;
// Look for a popup javascript link.
var oPopupMatch = oRegex.PopupUri.exec( sHRef ) ;
if( oPopupMatch )
{
GetE('cmbTarget').value = 'popup' ;
sHRef = oPopupMatch[1] ;
FillPopupFields( oPopupMatch[2], oPopupMatch[3] ) ;
SetTarget( 'popup' ) ;
}
// Accessible popups, the popup data is in the onclick attribute
if ( !oPopupMatch )
{
var onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ;
if ( onclick )
{
// Decode the protected string
onclick = decodeURIComponent( onclick ) ;
oPopupMatch = oRegex.OnClickPopup.exec( onclick ) ;
if( oPopupMatch )
{
GetE( 'cmbTarget' ).value = 'popup' ;
FillPopupFields( oPopupMatch[1], oPopupMatch[2] ) ;
SetTarget( 'popup' ) ;
}
}
}
// Search for the protocol.
var sProtocol = oRegex.UriProtocol.exec( sHRef ) ;
// Search for a protected email link.
var oEMailInfo = oParser.ParseEMailUri( sHRef );
if ( oEMailInfo )
{
sType = 'email' ;
GetE('txtEMailAddress').value = oEMailInfo.Address ;
GetE('txtEMailSubject').value = oEMailInfo.Subject ;
GetE('txtEMailBody').value = oEMailInfo.Body ;
}
else if ( sProtocol )
{
sProtocol = sProtocol[0].toLowerCase() ;
GetE('cmbLinkProtocol').value = sProtocol ;
// Remove the protocol and get the remaining URL.
var sUrl = sHRef.replace( oRegex.UriProtocol, '' ) ;
sType = 'url' ;
GetE('txtUrl').value = sUrl ;
}
else if ( sHRef.substr(0,1) == '#' && sHRef.length > 1 ) // It is an anchor link.
{
sType = 'anchor' ;
GetE('cmbAnchorName').value = GetE('cmbAnchorId').value = sHRef.substr(1) ;
}
else // It is another type of link.
{
sType = 'url' ;
GetE('cmbLinkProtocol').value = '' ;
GetE('txtUrl').value = sHRef ;
}
if ( !oPopupMatch )
{
// Get the target.
var sTarget = oLink.target ;
if ( sTarget && sTarget.length > 0 )
{
if ( oRegex.ReserveTarget.test( sTarget ) )
{
sTarget = sTarget.toLowerCase() ;
GetE('cmbTarget').value = sTarget ;
}
else
GetE('cmbTarget').value = 'frame' ;
GetE('txtTargetFrame').value = sTarget ;
}
}
// Get Advances Attributes
GetE('txtAttId').value = oLink.id ;
GetE('txtAttName').value = oLink.name ;
GetE('cmbAttLangDir').value = oLink.dir ;
GetE('txtAttLangCode').value = oLink.lang ;
GetE('txtAttAccessKey').value = oLink.accessKey ;
GetE('txtAttTabIndex').value = oLink.tabIndex <= 0 ? '' : oLink.tabIndex ;
GetE('txtAttTitle').value = oLink.title ;
GetE('txtAttContentType').value = oLink.type ;
GetE('txtAttCharSet').value = oLink.charset ;
var sClass ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
sClass = oLink.getAttribute('className',2) || '' ;
// Clean up temporary classes for internal use:
sClass = sClass.replace( FCKRegexLib.FCK_Class, '' ) ;
GetE('txtAttStyle').value = oLink.style.cssText ;
}
else
{
sClass = oLink.getAttribute('class',2) || '' ;
GetE('txtAttStyle').value = oLink.getAttribute('style',2) || '' ;
}
GetE('txtAttClasses').value = sClass ;
// Update the Link type combo.
GetE('cmbLinkType').value = sType ;
}
//#### Link type selection.
function SetLinkType( linkType )
{
ShowE('divLinkTypeUrl' , (linkType == 'url') ) ;
ShowE('divLinkTypeAnchor' , (linkType == 'anchor') ) ;
ShowE('divLinkTypeEMail' , (linkType == 'email') ) ;
if ( !FCKConfig.LinkDlgHideTarget )
dialog.SetTabVisibility( 'Target' , (linkType == 'url') ) ;
if ( FCKConfig.LinkUpload )
dialog.SetTabVisibility( 'Upload' , (linkType == 'url') ) ;
if ( !FCKConfig.LinkDlgHideAdvanced )
dialog.SetTabVisibility( 'Advanced' , (linkType != 'anchor' || bHasAnchors) ) ;
if ( linkType == 'email' )
dialog.SetAutoSize( true ) ;
}
//#### Target type selection.
function SetTarget( targetType )
{
GetE('tdTargetFrame').style.display = ( targetType == 'popup' ? 'none' : '' ) ;
GetE('tdPopupName').style.display =
GetE('tablePopupFeatures').style.display = ( targetType == 'popup' ? '' : 'none' ) ;
switch ( targetType )
{
case "_blank" :
case "_self" :
case "_parent" :
case "_top" :
GetE('txtTargetFrame').value = targetType ;
break ;
case "" :
GetE('txtTargetFrame').value = '' ;
break ;
}
if ( targetType == 'popup' )
dialog.SetAutoSize( true ) ;
}
//#### Called while the user types the URL.
function OnUrlChange()
{
var sUrl = GetE('txtUrl').value ;
var sProtocol = oRegex.UrlOnChangeProtocol.exec( sUrl ) ;
if ( sProtocol )
{
sUrl = sUrl.substr( sProtocol[0].length ) ;
GetE('txtUrl').value = sUrl ;
GetE('cmbLinkProtocol').value = sProtocol[0].toLowerCase() ;
}
else if ( oRegex.UrlOnChangeTestOther.test( sUrl ) )
{
GetE('cmbLinkProtocol').value = '' ;
}
}
//#### Called while the user types the target name.
function OnTargetNameChange()
{
var sFrame = GetE('txtTargetFrame').value ;
if ( sFrame.length == 0 )
GetE('cmbTarget').value = '' ;
else if ( oRegex.ReserveTarget.test( sFrame ) )
GetE('cmbTarget').value = sFrame.toLowerCase() ;
else
GetE('cmbTarget').value = 'frame' ;
}
// Accessible popups
function BuildOnClickPopup()
{
var sWindowName = "'" + GetE('txtPopupName').value.replace(/\W/gi, "") + "'" ;
var sFeatures = '' ;
var aChkFeatures = document.getElementsByName( 'chkFeature' ) ;
for ( var i = 0 ; i < aChkFeatures.length ; i++ )
{
if ( i > 0 ) sFeatures += ',' ;
sFeatures += aChkFeatures[i].value + '=' + ( aChkFeatures[i].checked ? 'yes' : 'no' ) ;
}
if ( GetE('txtPopupWidth').value.length > 0 ) sFeatures += ',width=' + GetE('txtPopupWidth').value ;
if ( GetE('txtPopupHeight').value.length > 0 ) sFeatures += ',height=' + GetE('txtPopupHeight').value ;
if ( GetE('txtPopupLeft').value.length > 0 ) sFeatures += ',left=' + GetE('txtPopupLeft').value ;
if ( GetE('txtPopupTop').value.length > 0 ) sFeatures += ',top=' + GetE('txtPopupTop').value ;
if ( sFeatures != '' )
sFeatures = sFeatures + ",status" ;
return ( "window.open(this.href," + sWindowName + ",'" + sFeatures + "'); return false" ) ;
}
//#### Fills all Popup related fields.
function FillPopupFields( windowName, features )
{
if ( windowName )
GetE('txtPopupName').value = windowName ;
var oFeatures = new Object() ;
var oFeaturesMatch ;
while( ( oFeaturesMatch = oRegex.PopupFeatures.exec( features ) ) != null )
{
var sValue = oFeaturesMatch[2] ;
if ( sValue == ( 'yes' || '1' ) )
oFeatures[ oFeaturesMatch[1] ] = true ;
else if ( ! isNaN( sValue ) && sValue != 0 )
oFeatures[ oFeaturesMatch[1] ] = sValue ;
}
// Update all features check boxes.
var aChkFeatures = document.getElementsByName('chkFeature') ;
for ( var i = 0 ; i < aChkFeatures.length ; i++ )
{
if ( oFeatures[ aChkFeatures[i].value ] )
aChkFeatures[i].checked = true ;
}
// Update position and size text boxes.
if ( oFeatures['width'] ) GetE('txtPopupWidth').value = oFeatures['width'] ;
if ( oFeatures['height'] ) GetE('txtPopupHeight').value = oFeatures['height'] ;
if ( oFeatures['left'] ) GetE('txtPopupLeft').value = oFeatures['left'] ;
if ( oFeatures['top'] ) GetE('txtPopupTop').value = oFeatures['top'] ;
}
//#### The OK button was hit.
function Ok()
{
var sUri, sInnerHtml ;
oEditor.FCKUndo.SaveUndoStep() ;
switch ( GetE('cmbLinkType').value )
{
case 'url' :
sUri = GetE('txtUrl').value ;
if ( sUri.length == 0 )
{
alert( FCKLang.DlnLnkMsgNoUrl ) ;
return false ;
}
sUri = GetE('cmbLinkProtocol').value + sUri ;
break ;
case 'email' :
sUri = GetE('txtEMailAddress').value ;
if ( sUri.length == 0 )
{
alert( FCKLang.DlnLnkMsgNoEMail ) ;
return false ;
}
sUri = oParser.CreateEMailUri(
sUri,
GetE('txtEMailSubject').value,
GetE('txtEMailBody').value ) ;
break ;
case 'anchor' :
var sAnchor = GetE('cmbAnchorName').value ;
if ( sAnchor.length == 0 ) sAnchor = GetE('cmbAnchorId').value ;
if ( sAnchor.length == 0 )
{
alert( FCKLang.DlnLnkMsgNoAnchor ) ;
return false ;
}
sUri = '#' + sAnchor ;
break ;
}
// If no link is selected, create a new one (it may result in more than one link creation - #220).
var aLinks = oLink ? [ oLink ] : oEditor.FCK.CreateLink( sUri, true ) ;
// If no selection, no links are created, so use the uri as the link text (by dom, 2006-05-26)
var aHasSelection = ( aLinks.length > 0 ) ;
if ( !aHasSelection )
{
sInnerHtml = sUri;
// Built a better text for empty links.
switch ( GetE('cmbLinkType').value )
{
// anchor: use old behavior --> return true
case 'anchor':
sInnerHtml = sInnerHtml.replace( /^#/, '' ) ;
break ;
// url: try to get path
case 'url':
var oLinkPathRegEx = new RegExp("//?([^?\"']+)([?].*)?$") ;
var asLinkPath = oLinkPathRegEx.exec( sUri ) ;
if (asLinkPath != null)
sInnerHtml = asLinkPath[1]; // use matched path
break ;
// mailto: try to get email address
case 'email':
sInnerHtml = GetE('txtEMailAddress').value ;
break ;
}
// Create a new (empty) anchor.
aLinks = [ oEditor.FCK.InsertElement( 'a' ) ] ;
}
for ( var i = 0 ; i < aLinks.length ; i++ )
{
oLink = aLinks[i] ;
if ( aHasSelection )
sInnerHtml = oLink.innerHTML ; // Save the innerHTML (IE changes it if it is like an URL).
oLink.href = sUri ;
SetAttribute( oLink, '_fcksavedurl', sUri ) ;
var onclick;
// Accessible popups
if( GetE('cmbTarget').value == 'popup' )
{
onclick = BuildOnClickPopup() ;
// Encode the attribute
onclick = encodeURIComponent( " onclick=\"" + onclick + "\"" ) ;
SetAttribute( oLink, 'onclick_fckprotectedatt', onclick ) ;
}
else
{
// Check if the previous onclick was for a popup:
// In that case remove the onclick handler.
onclick = oLink.getAttribute( 'onclick_fckprotectedatt' ) ;
if ( onclick )
{
// Decode the protected string
onclick = decodeURIComponent( onclick ) ;
if( oRegex.OnClickPopup.test( onclick ) )
SetAttribute( oLink, 'onclick_fckprotectedatt', '' ) ;
}
}
oLink.innerHTML = sInnerHtml ; // Set (or restore) the innerHTML
// Target
if( GetE('cmbTarget').value != 'popup' )
SetAttribute( oLink, 'target', GetE('txtTargetFrame').value ) ;
else
SetAttribute( oLink, 'target', null ) ;
// Let's set the "id" only for the first link to avoid duplication.
if ( i == 0 )
SetAttribute( oLink, 'id', GetE('txtAttId').value ) ;
// Advances Attributes
SetAttribute( oLink, 'name' , GetE('txtAttName').value ) ;
SetAttribute( oLink, 'dir' , GetE('cmbAttLangDir').value ) ;
SetAttribute( oLink, 'lang' , GetE('txtAttLangCode').value ) ;
SetAttribute( oLink, 'accesskey', GetE('txtAttAccessKey').value ) ;
SetAttribute( oLink, 'tabindex' , ( GetE('txtAttTabIndex').value > 0 ? GetE('txtAttTabIndex').value : null ) ) ;
SetAttribute( oLink, 'title' , GetE('txtAttTitle').value ) ;
SetAttribute( oLink, 'type' , GetE('txtAttContentType').value ) ;
SetAttribute( oLink, 'charset' , GetE('txtAttCharSet').value ) ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
var sClass = GetE('txtAttClasses').value ;
// If it's also an anchor add an internal class
if ( GetE('txtAttName').value.length != 0 )
sClass += ' FCK__AnchorC' ;
SetAttribute( oLink, 'className', sClass ) ;
oLink.style.cssText = GetE('txtAttStyle').value ;
}
else
{
SetAttribute( oLink, 'class', GetE('txtAttClasses').value ) ;
SetAttribute( oLink, 'style', GetE('txtAttStyle').value ) ;
}
}
// Select the (first) link.
oEditor.FCKSelection.SelectNode( aLinks[0] );
return true ;
}
function BrowseServer()
{
OpenFileBrowser( FCKConfig.LinkBrowserURL, FCKConfig.LinkBrowserWindowWidth, FCKConfig.LinkBrowserWindowHeight ) ;
}
function SetUrl( url )
{
GetE('txtUrl').value = url ;
OnUrlChange() ;
dialog.SetSelectedTab( 'Info' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.LinkUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.LinkUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile = GetE('txtUploadFile').value ;
if ( sFile.length == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
if ( ( FCKConfig.LinkUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
( FCKConfig.LinkUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
{
OnUploadCompleted( 202 ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
}
function SetDefaultTarget()
{
var target = FCKConfig.DefaultLinkTarget || '' ;
if ( oLink || target.length == 0 )
return ;
switch ( target )
{
case '_blank' :
case '_self' :
case '_parent' :
case '_top' :
GetE('cmbTarget').value = target ;
break ;
default :
GetE('cmbTarget').value = 'frame' ;
break ;
}
GetE('txtTargetFrame').value = target ;
}
| JavaScript |
////////////////////////////////////////////////////
// wordWindow object
////////////////////////////////////////////////////
function wordWindow() {
// private properties
this._forms = [];
// private methods
this._getWordObject = _getWordObject;
//this._getSpellerObject = _getSpellerObject;
this._wordInputStr = _wordInputStr;
this._adjustIndexes = _adjustIndexes;
this._isWordChar = _isWordChar;
this._lastPos = _lastPos;
// public properties
this.wordChar = /[a-zA-Z]/;
this.windowType = "wordWindow";
this.originalSpellings = new Array();
this.suggestions = new Array();
this.checkWordBgColor = "pink";
this.normWordBgColor = "white";
this.text = "";
this.textInputs = new Array();
this.indexes = new Array();
//this.speller = this._getSpellerObject();
// public methods
this.resetForm = resetForm;
this.totalMisspellings = totalMisspellings;
this.totalWords = totalWords;
this.totalPreviousWords = totalPreviousWords;
//this.getTextObjectArray = getTextObjectArray;
this.getTextVal = getTextVal;
this.setFocus = setFocus;
this.removeFocus = removeFocus;
this.setText = setText;
//this.getTotalWords = getTotalWords;
this.writeBody = writeBody;
this.printForHtml = printForHtml;
}
function resetForm() {
if( this._forms ) {
for( var i = 0; i < this._forms.length; i++ ) {
this._forms[i].reset();
}
}
return true;
}
function totalMisspellings() {
var total_words = 0;
for( var i = 0; i < this.textInputs.length; i++ ) {
total_words += this.totalWords( i );
}
return total_words;
}
function totalWords( textIndex ) {
return this.originalSpellings[textIndex].length;
}
function totalPreviousWords( textIndex, wordIndex ) {
var total_words = 0;
for( var i = 0; i <= textIndex; i++ ) {
for( var j = 0; j < this.totalWords( i ); j++ ) {
if( i == textIndex && j == wordIndex ) {
break;
} else {
total_words++;
}
}
}
return total_words;
}
//function getTextObjectArray() {
// return this._form.elements;
//}
function getTextVal( textIndex, wordIndex ) {
var word = this._getWordObject( textIndex, wordIndex );
if( word ) {
return word.value;
}
}
function setFocus( textIndex, wordIndex ) {
var word = this._getWordObject( textIndex, wordIndex );
if( word ) {
if( word.type == "text" ) {
word.focus();
word.style.backgroundColor = this.checkWordBgColor;
}
}
}
function removeFocus( textIndex, wordIndex ) {
var word = this._getWordObject( textIndex, wordIndex );
if( word ) {
if( word.type == "text" ) {
word.blur();
word.style.backgroundColor = this.normWordBgColor;
}
}
}
function setText( textIndex, wordIndex, newText ) {
var word = this._getWordObject( textIndex, wordIndex );
var beginStr;
var endStr;
if( word ) {
var pos = this.indexes[textIndex][wordIndex];
var oldText = word.value;
// update the text given the index of the string
beginStr = this.textInputs[textIndex].substring( 0, pos );
endStr = this.textInputs[textIndex].substring(
pos + oldText.length,
this.textInputs[textIndex].length
);
this.textInputs[textIndex] = beginStr + newText + endStr;
// adjust the indexes on the stack given the differences in
// length between the new word and old word.
var lengthDiff = newText.length - oldText.length;
this._adjustIndexes( textIndex, wordIndex, lengthDiff );
word.size = newText.length;
word.value = newText;
this.removeFocus( textIndex, wordIndex );
}
}
function writeBody() {
var d = window.document;
var is_html = false;
d.open();
// iterate through each text input.
for( var txtid = 0; txtid < this.textInputs.length; txtid++ ) {
var end_idx = 0;
var begin_idx = 0;
d.writeln( '<form name="textInput'+txtid+'">' );
var wordtxt = this.textInputs[txtid];
this.indexes[txtid] = [];
if( wordtxt ) {
var orig = this.originalSpellings[txtid];
if( !orig ) break;
//!!! plain text, or HTML mode?
d.writeln( '<div class="plainText">' );
// iterate through each occurrence of a misspelled word.
for( var i = 0; i < orig.length; i++ ) {
// find the position of the current misspelled word,
// starting at the last misspelled word.
// and keep looking if it's a substring of another word
do {
begin_idx = wordtxt.indexOf( orig[i], end_idx );
end_idx = begin_idx + orig[i].length;
// word not found? messed up!
if( begin_idx == -1 ) break;
// look at the characters immediately before and after
// the word. If they are word characters we'll keep looking.
var before_char = wordtxt.charAt( begin_idx - 1 );
var after_char = wordtxt.charAt( end_idx );
} while (
this._isWordChar( before_char )
|| this._isWordChar( after_char )
);
// keep track of its position in the original text.
this.indexes[txtid][i] = begin_idx;
// write out the characters before the current misspelled word
for( var j = this._lastPos( txtid, i ); j < begin_idx; j++ ) {
// !!! html mode? make it html compatible
d.write( this.printForHtml( wordtxt.charAt( j )));
}
// write out the misspelled word.
d.write( this._wordInputStr( orig[i] ));
// if it's the last word, write out the rest of the text
if( i == orig.length-1 ){
d.write( printForHtml( wordtxt.substr( end_idx )));
}
}
d.writeln( '</div>' );
}
d.writeln( '</form>' );
}
//for ( var j = 0; j < d.forms.length; j++ ) {
// alert( d.forms[j].name );
// for( var k = 0; k < d.forms[j].elements.length; k++ ) {
// alert( d.forms[j].elements[k].name + ": " + d.forms[j].elements[k].value );
// }
//}
// set the _forms property
this._forms = d.forms;
d.close();
}
// return the character index in the full text after the last word we evaluated
function _lastPos( txtid, idx ) {
if( idx > 0 )
return this.indexes[txtid][idx-1] + this.originalSpellings[txtid][idx-1].length;
else
return 0;
}
function printForHtml( n ) {
return n ; // by FredCK
/*
var htmlstr = n;
if( htmlstr.length == 1 ) {
// do simple case statement if it's just one character
switch ( n ) {
case "\n":
htmlstr = '<br/>';
break;
case "<":
htmlstr = '<';
break;
case ">":
htmlstr = '>';
break;
}
return htmlstr;
} else {
htmlstr = htmlstr.replace( /</g, '<' );
htmlstr = htmlstr.replace( />/g, '>' );
htmlstr = htmlstr.replace( /\n/g, '<br/>' );
return htmlstr;
}
*/
}
function _isWordChar( letter ) {
if( letter.search( this.wordChar ) == -1 ) {
return false;
} else {
return true;
}
}
function _getWordObject( textIndex, wordIndex ) {
if( this._forms[textIndex] ) {
if( this._forms[textIndex].elements[wordIndex] ) {
return this._forms[textIndex].elements[wordIndex];
}
}
return null;
}
function _wordInputStr( word ) {
var str = '<input readonly ';
str += 'class="blend" type="text" value="' + word + '" size="' + word.length + '">';
return str;
}
function _adjustIndexes( textIndex, wordIndex, lengthDiff ) {
for( var i = wordIndex + 1; i < this.originalSpellings[textIndex].length; i++ ) {
this.indexes[textIndex][i] = this.indexes[textIndex][i] + lengthDiff;
}
}
| JavaScript |
////////////////////////////////////////////////////
// controlWindow object
////////////////////////////////////////////////////
function controlWindow( controlForm ) {
// private properties
this._form = controlForm;
// public properties
this.windowType = "controlWindow";
// this.noSuggestionSelection = "- No suggestions -"; // by FredCK
this.noSuggestionSelection = FCKLang.DlgSpellNoSuggestions ;
// set up the properties for elements of the given control form
this.suggestionList = this._form.sugg;
this.evaluatedText = this._form.misword;
this.replacementText = this._form.txtsugg;
this.undoButton = this._form.btnUndo;
// public methods
this.addSuggestion = addSuggestion;
this.clearSuggestions = clearSuggestions;
this.selectDefaultSuggestion = selectDefaultSuggestion;
this.resetForm = resetForm;
this.setSuggestedText = setSuggestedText;
this.enableUndo = enableUndo;
this.disableUndo = disableUndo;
}
function resetForm() {
if( this._form ) {
this._form.reset();
}
}
function setSuggestedText() {
var slct = this.suggestionList;
var txt = this.replacementText;
var str = "";
if( (slct.options[0].text) && slct.options[0].text != this.noSuggestionSelection ) {
str = slct.options[slct.selectedIndex].text;
}
txt.value = str;
}
function selectDefaultSuggestion() {
var slct = this.suggestionList;
var txt = this.replacementText;
if( slct.options.length == 0 ) {
this.addSuggestion( this.noSuggestionSelection );
} else {
slct.options[0].selected = true;
}
this.setSuggestedText();
}
function addSuggestion( sugg_text ) {
var slct = this.suggestionList;
if( sugg_text ) {
var i = slct.options.length;
var newOption = new Option( sugg_text, 'sugg_text'+i );
slct.options[i] = newOption;
}
}
function clearSuggestions() {
var slct = this.suggestionList;
for( var j = slct.length - 1; j > -1; j-- ) {
if( slct.options[j] ) {
slct.options[j] = null;
}
}
}
function enableUndo() {
if( this.undoButton ) {
if( this.undoButton.disabled == true ) {
this.undoButton.disabled = false;
}
}
}
function disableUndo() {
if( this.undoButton ) {
if( this.undoButton.disabled == false ) {
this.undoButton.disabled = true;
}
}
}
| JavaScript |
////////////////////////////////////////////////////
// spellChecker.js
//
// spellChecker object
//
// This file is sourced on web pages that have a textarea object to evaluate
// for spelling. It includes the implementation for the spellCheckObject.
//
////////////////////////////////////////////////////
// constructor
function spellChecker( textObject ) {
// public properties - configurable
// this.popUpUrl = '/speller/spellchecker.html'; // by FredCK
this.popUpUrl = 'fck_spellerpages/spellerpages/spellchecker.html'; // by FredCK
this.popUpName = 'spellchecker';
// this.popUpProps = "menu=no,width=440,height=350,top=70,left=120,resizable=yes,status=yes"; // by FredCK
this.popUpProps = null ; // by FredCK
// this.spellCheckScript = '/speller/server-scripts/spellchecker.php'; // by FredCK
//this.spellCheckScript = '/cgi-bin/spellchecker.pl';
// values used to keep track of what happened to a word
this.replWordFlag = "R"; // single replace
this.ignrWordFlag = "I"; // single ignore
this.replAllFlag = "RA"; // replace all occurances
this.ignrAllFlag = "IA"; // ignore all occurances
this.fromReplAll = "~RA"; // an occurance of a "replace all" word
this.fromIgnrAll = "~IA"; // an occurance of a "ignore all" word
// properties set at run time
this.wordFlags = new Array();
this.currentTextIndex = 0;
this.currentWordIndex = 0;
this.spellCheckerWin = null;
this.controlWin = null;
this.wordWin = null;
this.textArea = textObject; // deprecated
this.textInputs = arguments;
// private methods
this._spellcheck = _spellcheck;
this._getSuggestions = _getSuggestions;
this._setAsIgnored = _setAsIgnored;
this._getTotalReplaced = _getTotalReplaced;
this._setWordText = _setWordText;
this._getFormInputs = _getFormInputs;
// public methods
this.openChecker = openChecker;
this.startCheck = startCheck;
this.checkTextBoxes = checkTextBoxes;
this.checkTextAreas = checkTextAreas;
this.spellCheckAll = spellCheckAll;
this.ignoreWord = ignoreWord;
this.ignoreAll = ignoreAll;
this.replaceWord = replaceWord;
this.replaceAll = replaceAll;
this.terminateSpell = terminateSpell;
this.undo = undo;
// set the current window's "speller" property to the instance of this class.
// this object can now be referenced by child windows/frames.
window.speller = this;
}
// call this method to check all text boxes (and only text boxes) in the HTML document
function checkTextBoxes() {
this.textInputs = this._getFormInputs( "^text$" );
this.openChecker();
}
// call this method to check all textareas (and only textareas ) in the HTML document
function checkTextAreas() {
this.textInputs = this._getFormInputs( "^textarea$" );
this.openChecker();
}
// call this method to check all text boxes and textareas in the HTML document
function spellCheckAll() {
this.textInputs = this._getFormInputs( "^text(area)?$" );
this.openChecker();
}
// call this method to check text boxe(s) and/or textarea(s) that were passed in to the
// object's constructor or to the textInputs property
function openChecker() {
this.spellCheckerWin = window.open( this.popUpUrl, this.popUpName, this.popUpProps );
if( !this.spellCheckerWin.opener ) {
this.spellCheckerWin.opener = window;
}
}
function startCheck( wordWindowObj, controlWindowObj ) {
// set properties from args
this.wordWin = wordWindowObj;
this.controlWin = controlWindowObj;
// reset properties
this.wordWin.resetForm();
this.controlWin.resetForm();
this.currentTextIndex = 0;
this.currentWordIndex = 0;
// initialize the flags to an array - one element for each text input
this.wordFlags = new Array( this.wordWin.textInputs.length );
// each element will be an array that keeps track of each word in the text
for( var i=0; i<this.wordFlags.length; i++ ) {
this.wordFlags[i] = [];
}
// start
this._spellcheck();
return true;
}
function ignoreWord() {
var wi = this.currentWordIndex;
var ti = this.currentTextIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
if( !this.wordWin.getTextVal( ti, wi )) {
alert( 'Error: "Not in dictionary" text is missing.' );
return false;
}
// set as ignored
if( this._setAsIgnored( ti, wi, this.ignrWordFlag )) {
this.currentWordIndex++;
this._spellcheck();
}
return true;
}
function ignoreAll() {
var wi = this.currentWordIndex;
var ti = this.currentTextIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
// get the word that is currently being evaluated.
var s_word_to_repl = this.wordWin.getTextVal( ti, wi );
if( !s_word_to_repl ) {
alert( 'Error: "Not in dictionary" text is missing' );
return false;
}
// set this word as an "ignore all" word.
this._setAsIgnored( ti, wi, this.ignrAllFlag );
// loop through all the words after this word
for( var i = ti; i < this.wordWin.textInputs.length; i++ ) {
for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == ti && j > wi ) || i > ti ) {
// future word: set as "from ignore all" if
// 1) do not already have a flag and
// 2) have the same value as current word
if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl )
&& ( !this.wordFlags[i][j] )) {
this._setAsIgnored( i, j, this.fromIgnrAll );
}
}
}
}
// finally, move on
this.currentWordIndex++;
this._spellcheck();
return true;
}
function replaceWord() {
var wi = this.currentWordIndex;
var ti = this.currentTextIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
if( !this.wordWin.getTextVal( ti, wi )) {
alert( 'Error: "Not in dictionary" text is missing' );
return false;
}
if( !this.controlWin.replacementText ) {
return false ;
}
var txt = this.controlWin.replacementText;
if( txt.value ) {
var newspell = new String( txt.value );
if( this._setWordText( ti, wi, newspell, this.replWordFlag )) {
this.currentWordIndex++;
this._spellcheck();
}
}
return true;
}
function replaceAll() {
var ti = this.currentTextIndex;
var wi = this.currentWordIndex;
if( !this.wordWin ) {
alert( 'Error: Word frame not available.' );
return false;
}
var s_word_to_repl = this.wordWin.getTextVal( ti, wi );
if( !s_word_to_repl ) {
alert( 'Error: "Not in dictionary" text is missing' );
return false;
}
var txt = this.controlWin.replacementText;
if( !txt.value ) return false;
var newspell = new String( txt.value );
// set this word as a "replace all" word.
this._setWordText( ti, wi, newspell, this.replAllFlag );
// loop through all the words after this word
for( var i = ti; i < this.wordWin.textInputs.length; i++ ) {
for( var j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == ti && j > wi ) || i > ti ) {
// future word: set word text to s_word_to_repl if
// 1) do not already have a flag and
// 2) have the same value as s_word_to_repl
if(( this.wordWin.getTextVal( i, j ) == s_word_to_repl )
&& ( !this.wordFlags[i][j] )) {
this._setWordText( i, j, newspell, this.fromReplAll );
}
}
}
}
// finally, move on
this.currentWordIndex++;
this._spellcheck();
return true;
}
function terminateSpell() {
// called when we have reached the end of the spell checking.
var msg = ""; // by FredCK
var numrepl = this._getTotalReplaced();
if( numrepl == 0 ) {
// see if there were no misspellings to begin with
if( !this.wordWin ) {
msg = "";
} else {
if( this.wordWin.totalMisspellings() ) {
// msg += "No words changed."; // by FredCK
msg += FCKLang.DlgSpellNoChanges ; // by FredCK
} else {
// msg += "No misspellings found."; // by FredCK
msg += FCKLang.DlgSpellNoMispell ; // by FredCK
}
}
} else if( numrepl == 1 ) {
// msg += "One word changed."; // by FredCK
msg += FCKLang.DlgSpellOneChange ; // by FredCK
} else {
// msg += numrepl + " words changed."; // by FredCK
msg += FCKLang.DlgSpellManyChanges.replace( /%1/g, numrepl ) ;
}
if( msg ) {
// msg += "\n"; // by FredCK
alert( msg );
}
if( numrepl > 0 ) {
// update the text field(s) on the opener window
for( var i = 0; i < this.textInputs.length; i++ ) {
// this.textArea.value = this.wordWin.text;
if( this.wordWin ) {
if( this.wordWin.textInputs[i] ) {
this.textInputs[i].value = this.wordWin.textInputs[i];
}
}
}
}
// return back to the calling window
// this.spellCheckerWin.close(); // by FredCK
if ( typeof( this.OnFinished ) == 'function' ) // by FredCK
this.OnFinished(numrepl) ; // by FredCK
return true;
}
function undo() {
// skip if this is the first word!
var ti = this.currentTextIndex;
var wi = this.currentWordIndex;
if( this.wordWin.totalPreviousWords( ti, wi ) > 0 ) {
this.wordWin.removeFocus( ti, wi );
// go back to the last word index that was acted upon
do {
// if the current word index is zero then reset the seed
if( this.currentWordIndex == 0 && this.currentTextIndex > 0 ) {
this.currentTextIndex--;
this.currentWordIndex = this.wordWin.totalWords( this.currentTextIndex )-1;
if( this.currentWordIndex < 0 ) this.currentWordIndex = 0;
} else {
if( this.currentWordIndex > 0 ) {
this.currentWordIndex--;
}
}
} while (
this.wordWin.totalWords( this.currentTextIndex ) == 0
|| this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromIgnrAll
|| this.wordFlags[this.currentTextIndex][this.currentWordIndex] == this.fromReplAll
);
var text_idx = this.currentTextIndex;
var idx = this.currentWordIndex;
var preReplSpell = this.wordWin.originalSpellings[text_idx][idx];
// if we got back to the first word then set the Undo button back to disabled
if( this.wordWin.totalPreviousWords( text_idx, idx ) == 0 ) {
this.controlWin.disableUndo();
}
var i, j, origSpell ;
// examine what happened to this current word.
switch( this.wordFlags[text_idx][idx] ) {
// replace all: go through this and all the future occurances of the word
// and revert them all to the original spelling and clear their flags
case this.replAllFlag :
for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) {
for( j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == text_idx && j >= idx ) || i > text_idx ) {
origSpell = this.wordWin.originalSpellings[i][j];
if( origSpell == preReplSpell ) {
this._setWordText ( i, j, origSpell, undefined );
}
}
}
}
break;
// ignore all: go through all the future occurances of the word
// and clear their flags
case this.ignrAllFlag :
for( i = text_idx; i < this.wordWin.textInputs.length; i++ ) {
for( j = 0; j < this.wordWin.totalWords( i ); j++ ) {
if(( i == text_idx && j >= idx ) || i > text_idx ) {
origSpell = this.wordWin.originalSpellings[i][j];
if( origSpell == preReplSpell ) {
this.wordFlags[i][j] = undefined;
}
}
}
}
break;
// replace: revert the word to its original spelling
case this.replWordFlag :
this._setWordText ( text_idx, idx, preReplSpell, undefined );
break;
}
// For all four cases, clear the wordFlag of this word. re-start the process
this.wordFlags[text_idx][idx] = undefined;
this._spellcheck();
}
}
function _spellcheck() {
var ww = this.wordWin;
// check if this is the last word in the current text element
if( this.currentWordIndex == ww.totalWords( this.currentTextIndex) ) {
this.currentTextIndex++;
this.currentWordIndex = 0;
// keep going if we're not yet past the last text element
if( this.currentTextIndex < this.wordWin.textInputs.length ) {
this._spellcheck();
return;
} else {
this.terminateSpell();
return;
}
}
// if this is after the first one make sure the Undo button is enabled
if( this.currentWordIndex > 0 ) {
this.controlWin.enableUndo();
}
// skip the current word if it has already been worked on
if( this.wordFlags[this.currentTextIndex][this.currentWordIndex] ) {
// increment the global current word index and move on.
this.currentWordIndex++;
this._spellcheck();
} else {
var evalText = ww.getTextVal( this.currentTextIndex, this.currentWordIndex );
if( evalText ) {
this.controlWin.evaluatedText.value = evalText;
ww.setFocus( this.currentTextIndex, this.currentWordIndex );
this._getSuggestions( this.currentTextIndex, this.currentWordIndex );
}
}
}
function _getSuggestions( text_num, word_num ) {
this.controlWin.clearSuggestions();
// add suggestion in list for each suggested word.
// get the array of suggested words out of the
// three-dimensional array containing all suggestions.
var a_suggests = this.wordWin.suggestions[text_num][word_num];
if( a_suggests ) {
// got an array of suggestions.
for( var ii = 0; ii < a_suggests.length; ii++ ) {
this.controlWin.addSuggestion( a_suggests[ii] );
}
}
this.controlWin.selectDefaultSuggestion();
}
function _setAsIgnored( text_num, word_num, flag ) {
// set the UI
this.wordWin.removeFocus( text_num, word_num );
// do the bookkeeping
this.wordFlags[text_num][word_num] = flag;
return true;
}
function _getTotalReplaced() {
var i_replaced = 0;
for( var i = 0; i < this.wordFlags.length; i++ ) {
for( var j = 0; j < this.wordFlags[i].length; j++ ) {
if(( this.wordFlags[i][j] == this.replWordFlag )
|| ( this.wordFlags[i][j] == this.replAllFlag )
|| ( this.wordFlags[i][j] == this.fromReplAll )) {
i_replaced++;
}
}
}
return i_replaced;
}
function _setWordText( text_num, word_num, newText, flag ) {
// set the UI and form inputs
this.wordWin.setText( text_num, word_num, newText );
// keep track of what happened to this word:
this.wordFlags[text_num][word_num] = flag;
return true;
}
function _getFormInputs( inputPattern ) {
var inputs = new Array();
for( var i = 0; i < document.forms.length; i++ ) {
for( var j = 0; j < document.forms[i].elements.length; j++ ) {
if( document.forms[i].elements[j].type.match( inputPattern )) {
inputs[inputs.length] = document.forms[i].elements[j];
}
}
}
return inputs;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Useful functions used by almost all dialog window pages.
* Dialogs should link to this file as the very first script on the page.
*/
// Automatically detect the correct document.domain (#123).
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.parent.document.domain ;
break ;
}
catch( e ) {}
// Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ...
d = d.replace( /.*?(?:\.|$)/, '' ) ;
if ( d.length == 0 )
break ; // It was not able to detect the domain.
try
{
document.domain = d ;
}
catch (e)
{
break ;
}
}
})() ;
// Attention: FCKConfig must be available in the page.
function GetCommonDialogCss( prefix )
{
// CSS minified by http://iceyboard.no-ip.org/projects/css_compressor (see _dev/css_compression.txt).
return FCKConfig.BasePath + 'dialog/common/' + '|.ImagePreviewArea{border:#000 1px solid;overflow:auto;width:100%;height:170px;background-color:#fff}.FlashPreviewArea{border:#000 1px solid;padding:5px;overflow:auto;width:100%;height:170px;background-color:#fff}.BtnReset{float:left;background-position:center center;background-image:url(images/reset.gif);width:16px;height:16px;background-repeat:no-repeat;border:1px none;font-size:1px}.BtnLocked,.BtnUnlocked{float:left;background-position:center center;background-image:url(images/locked.gif);width:16px;height:16px;background-repeat:no-repeat;border:none 1px;font-size:1px}.BtnUnlocked{background-image:url(images/unlocked.gif)}.BtnOver{border:outset 1px;cursor:pointer;cursor:hand}' ;
}
// Gets a element by its Id. Used for shorter coding.
function GetE( elementId )
{
return document.getElementById( elementId ) ;
}
function ShowE( element, isVisible )
{
if ( typeof( element ) == 'string' )
element = GetE( element ) ;
element.style.display = isVisible ? '' : 'none' ;
}
function SetAttribute( element, attName, attValue )
{
if ( attValue == null || attValue.length == 0 )
element.removeAttribute( attName, 0 ) ; // 0 : Case Insensitive
else
element.setAttribute( attName, attValue, 0 ) ; // 0 : Case Insensitive
}
function GetAttribute( element, attName, valueIfNull )
{
var oAtt = element.attributes[attName] ;
if ( oAtt == null || !oAtt.specified )
return valueIfNull ? valueIfNull : '' ;
var oValue = element.getAttribute( attName, 2 ) ;
if ( oValue == null )
oValue = oAtt.nodeValue ;
return ( oValue == null ? valueIfNull : oValue ) ;
}
function SelectField( elementId )
{
var element = GetE( elementId ) ;
element.focus() ;
// element.select may not be available for some fields (like <select>).
if ( element.select )
element.select() ;
}
// Functions used by text fields to accept numbers only.
var IsDigit = ( function()
{
var KeyIdentifierMap =
{
End : 35,
Home : 36,
Left : 37,
Right : 39,
'U+00007F' : 46 // Delete
} ;
return function ( e )
{
if ( !e )
e = event ;
var iCode = ( e.keyCode || e.charCode ) ;
if ( !iCode && e.keyIdentifier && ( e.keyIdentifier in KeyIdentifierMap ) )
iCode = KeyIdentifierMap[ e.keyIdentifier ] ;
return (
( iCode >= 48 && iCode <= 57 ) // Numbers
|| (iCode >= 35 && iCode <= 40) // Arrows, Home, End
|| iCode == 8 // Backspace
|| iCode == 46 // Delete
|| iCode == 9 // Tab
) ;
}
} )() ;
String.prototype.Trim = function()
{
return this.replace( /(^\s*)|(\s*$)/g, '' ) ;
}
String.prototype.StartsWith = function( value )
{
return ( this.substr( 0, value.length ) == value ) ;
}
String.prototype.Remove = function( start, length )
{
var s = '' ;
if ( start > 0 )
s = this.substring( 0, start ) ;
if ( start + length < this.length )
s += this.substring( start + length , this.length ) ;
return s ;
}
String.prototype.ReplaceAll = function( searchArray, replaceArray )
{
var replaced = this ;
for ( var i = 0 ; i < searchArray.length ; i++ )
{
replaced = replaced.replace( searchArray[i], replaceArray[i] ) ;
}
return replaced ;
}
function OpenFileBrowser( url, width, height )
{
// oEditor must be defined.
var iLeft = ( oEditor.FCKConfig.ScreenWidth - width ) / 2 ;
var iTop = ( oEditor.FCKConfig.ScreenHeight - height ) / 2 ;
var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes" ;
sOptions += ",width=" + width ;
sOptions += ",height=" + height ;
sOptions += ",left=" + iLeft ;
sOptions += ",top=" + iTop ;
window.open( url, 'FCKBrowseWindow', sOptions ) ;
}
/**
Utility function to create/update an element with a name attribute in IE, so it behaves properly when moved around
It also allows to change the name or other special attributes in an existing node
oEditor : instance of FCKeditor where the element will be created
oOriginal : current element being edited or null if it has to be created
nodeName : string with the name of the element to create
oAttributes : Hash object with the attributes that must be set at creation time in IE
Those attributes will be set also after the element has been
created for any other browser to avoid redudant code
*/
function CreateNamedElement( oEditor, oOriginal, nodeName, oAttributes )
{
var oNewNode ;
// IE doesn't allow easily to change properties of an existing object,
// so remove the old and force the creation of a new one.
var oldNode = null ;
if ( oOriginal && oEditor.FCKBrowserInfo.IsIE )
{
// Force the creation only if some of the special attributes have changed:
var bChanged = false;
for( var attName in oAttributes )
bChanged |= ( oOriginal.getAttribute( attName, 2) != oAttributes[attName] ) ;
if ( bChanged )
{
oldNode = oOriginal ;
oOriginal = null ;
}
}
// If the node existed (and it's not IE), then we just have to update its attributes
if ( oOriginal )
{
oNewNode = oOriginal ;
}
else
{
// #676, IE doesn't play nice with the name or type attribute
if ( oEditor.FCKBrowserInfo.IsIE )
{
var sbHTML = [] ;
sbHTML.push( '<' + nodeName ) ;
for( var prop in oAttributes )
{
sbHTML.push( ' ' + prop + '="' + oAttributes[prop] + '"' ) ;
}
sbHTML.push( '>' ) ;
if ( !oEditor.FCKListsLib.EmptyElements[nodeName.toLowerCase()] )
sbHTML.push( '</' + nodeName + '>' ) ;
oNewNode = oEditor.FCK.EditorDocument.createElement( sbHTML.join('') ) ;
// Check if we are just changing the properties of an existing node: copy its properties
if ( oldNode )
{
CopyAttributes( oldNode, oNewNode, oAttributes ) ;
oEditor.FCKDomTools.MoveChildren( oldNode, oNewNode ) ;
oldNode.parentNode.removeChild( oldNode ) ;
oldNode = null ;
if ( oEditor.FCK.Selection.SelectionData )
{
// Trick to refresh the selection object and avoid error in
// fckdialog.html Selection.EnsureSelection
var oSel = oEditor.FCK.EditorDocument.selection ;
oEditor.FCK.Selection.SelectionData = oSel.createRange() ; // Now oSel.type will be 'None' reflecting the real situation
}
}
oNewNode = oEditor.FCK.InsertElement( oNewNode ) ;
// FCK.Selection.SelectionData is broken by now since we've
// deleted the previously selected element. So we need to reassign it.
if ( oEditor.FCK.Selection.SelectionData )
{
var range = oEditor.FCK.EditorDocument.body.createControlRange() ;
range.add( oNewNode ) ;
oEditor.FCK.Selection.SelectionData = range ;
}
}
else
{
oNewNode = oEditor.FCK.InsertElement( nodeName ) ;
}
}
// Set the basic attributes
for( var attName in oAttributes )
oNewNode.setAttribute( attName, oAttributes[attName], 0 ) ; // 0 : Case Insensitive
return oNewNode ;
}
// Copy all the attributes from one node to the other, kinda like a clone
// But oSkipAttributes is an object with the attributes that must NOT be copied
function CopyAttributes( oSource, oDest, oSkipAttributes )
{
var aAttributes = oSource.attributes ;
for ( var n = 0 ; n < aAttributes.length ; n++ )
{
var oAttribute = aAttributes[n] ;
if ( oAttribute.specified )
{
var sAttName = oAttribute.nodeName ;
// We can set the type only once, so do it with the proper value, not copying it.
if ( sAttName in oSkipAttributes )
continue ;
var sAttValue = oSource.getAttribute( sAttName, 2 ) ;
if ( sAttValue == null )
sAttValue = oAttribute.nodeValue ;
oDest.setAttribute( sAttName, sAttValue, 0 ) ; // 0 : Case Insensitive
}
}
// The style:
oDest.style.cssText = oSource.style.cssText ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Image dialog window (see fck_image.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKDebug = oEditor.FCKDebug ;
var FCKTools = oEditor.FCKTools ;
var bImageButton = ( document.location.search.length > 0 && document.location.search.substr(1) == 'ImageButton' ) ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', FCKLang.DlgImgInfoTab ) ;
if ( !bImageButton && !FCKConfig.ImageDlgHideLink )
dialog.AddTab( 'Link', FCKLang.DlgImgLinkTab ) ;
if ( FCKConfig.ImageUpload )
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ;
if ( !FCKConfig.ImageDlgHideAdvanced )
dialog.AddTab( 'Advanced', FCKLang.DlgAdvancedTag ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divInfo' , ( tabCode == 'Info' ) ) ;
ShowE('divLink' , ( tabCode == 'Link' ) ) ;
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ;
}
// Get the selected image (if available).
var oImage = dialog.Selection.GetSelectedElement() ;
if ( oImage && oImage.tagName != 'IMG' && !( oImage.tagName == 'INPUT' && oImage.type == 'image' ) )
oImage = null ;
// Get the active link.
var oLink = dialog.Selection.GetSelection().MoveToAncestorNode( 'A' ) ;
var oImageOriginal ;
function UpdateOriginal( resetSize )
{
if ( !eImgPreview )
return ;
if ( GetE('txtUrl').value.length == 0 )
{
oImageOriginal = null ;
return ;
}
oImageOriginal = document.createElement( 'IMG' ) ; // new Image() ;
if ( resetSize )
{
oImageOriginal.onload = function()
{
this.onload = null ;
ResetSizes() ;
}
}
oImageOriginal.src = eImgPreview.src ;
}
var bPreviewInitialized ;
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
GetE('btnLockSizes').title = FCKLang.DlgImgLockRatio ;
GetE('btnResetSize').title = FCKLang.DlgBtnResetSize ;
// Load the selected element information (if any).
LoadSelection() ;
// Show/Hide the "Browse Server" button.
GetE('tdBrowse').style.display = FCKConfig.ImageBrowser ? '' : 'none' ;
GetE('divLnkBrowseServer').style.display = FCKConfig.LinkBrowser ? '' : 'none' ;
UpdateOriginal() ;
// Set the actual uploader URL.
if ( FCKConfig.ImageUpload )
GetE('frmUpload').action = FCKConfig.ImageUploadURL ;
dialog.SetAutoSize( true ) ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
SelectField( 'txtUrl' ) ;
}
function LoadSelection()
{
if ( ! oImage ) return ;
var sUrl = oImage.getAttribute( '_fcksavedurl' ) ;
if ( sUrl == null )
sUrl = GetAttribute( oImage, 'src', '' ) ;
GetE('txtUrl').value = sUrl ;
GetE('txtAlt').value = GetAttribute( oImage, 'alt', '' ) ;
GetE('txtVSpace').value = GetAttribute( oImage, 'vspace', '' ) ;
GetE('txtHSpace').value = GetAttribute( oImage, 'hspace', '' ) ;
GetE('txtBorder').value = GetAttribute( oImage, 'border', '' ) ;
GetE('cmbAlign').value = GetAttribute( oImage, 'align', '' ) ;
var iWidth, iHeight ;
var regexSize = /^\s*(\d+)px\s*$/i ;
if ( oImage.style.width )
{
var aMatchW = oImage.style.width.match( regexSize ) ;
if ( aMatchW )
{
iWidth = aMatchW[1] ;
oImage.style.width = '' ;
SetAttribute( oImage, 'width' , iWidth ) ;
}
}
if ( oImage.style.height )
{
var aMatchH = oImage.style.height.match( regexSize ) ;
if ( aMatchH )
{
iHeight = aMatchH[1] ;
oImage.style.height = '' ;
SetAttribute( oImage, 'height', iHeight ) ;
}
}
GetE('txtWidth').value = iWidth ? iWidth : GetAttribute( oImage, "width", '' ) ;
GetE('txtHeight').value = iHeight ? iHeight : GetAttribute( oImage, "height", '' ) ;
// Get Advances Attributes
GetE('txtAttId').value = oImage.id ;
GetE('cmbAttLangDir').value = oImage.dir ;
GetE('txtAttLangCode').value = oImage.lang ;
GetE('txtAttTitle').value = oImage.title ;
GetE('txtLongDesc').value = oImage.longDesc ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
GetE('txtAttClasses').value = oImage.className || '' ;
GetE('txtAttStyle').value = oImage.style.cssText ;
}
else
{
GetE('txtAttClasses').value = oImage.getAttribute('class',2) || '' ;
GetE('txtAttStyle').value = oImage.getAttribute('style',2) ;
}
if ( oLink )
{
var sLinkUrl = oLink.getAttribute( '_fcksavedurl' ) ;
if ( sLinkUrl == null )
sLinkUrl = oLink.getAttribute('href',2) ;
GetE('txtLnkUrl').value = sLinkUrl ;
GetE('cmbLnkTarget').value = oLink.target ;
}
UpdatePreview() ;
}
//#### The OK button was hit.
function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
dialog.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( FCKLang.DlgImgAlertUrl ) ;
return false ;
}
var bHasImage = ( oImage != null ) ;
if ( bHasImage && bImageButton && oImage.tagName == 'IMG' )
{
if ( confirm( 'Do you want to transform the selected image on a image button?' ) )
oImage = null ;
}
else if ( bHasImage && !bImageButton && oImage.tagName == 'INPUT' )
{
if ( confirm( 'Do you want to transform the selected image button on a simple image?' ) )
oImage = null ;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !bHasImage )
{
if ( bImageButton )
{
oImage = FCK.EditorDocument.createElement( 'input' ) ;
oImage.type = 'image' ;
oImage = FCK.InsertElement( oImage ) ;
}
else
oImage = FCK.InsertElement( 'img' ) ;
}
UpdateImage( oImage ) ;
var sLnkUrl = GetE('txtLnkUrl').value.Trim() ;
if ( sLnkUrl.length == 0 )
{
if ( oLink )
FCK.ExecuteNamedCommand( 'Unlink' ) ;
}
else
{
if ( oLink ) // Modifying an existent link.
oLink.href = sLnkUrl ;
else // Creating a new link.
{
if ( !bHasImage )
oEditor.FCKSelection.SelectNode( oImage ) ;
oLink = oEditor.FCK.CreateLink( sLnkUrl )[0] ;
if ( !bHasImage )
{
oEditor.FCKSelection.SelectNode( oLink ) ;
oEditor.FCKSelection.Collapse( false ) ;
}
}
SetAttribute( oLink, '_fcksavedurl', sLnkUrl ) ;
SetAttribute( oLink, 'target', GetE('cmbLnkTarget').value ) ;
}
return true ;
}
function UpdateImage( e, skipId )
{
e.src = GetE('txtUrl').value ;
SetAttribute( e, "_fcksavedurl", GetE('txtUrl').value ) ;
SetAttribute( e, "alt" , GetE('txtAlt').value ) ;
SetAttribute( e, "width" , GetE('txtWidth').value ) ;
SetAttribute( e, "height", GetE('txtHeight').value ) ;
SetAttribute( e, "vspace", GetE('txtVSpace').value ) ;
SetAttribute( e, "hspace", GetE('txtHSpace').value ) ;
SetAttribute( e, "border", GetE('txtBorder').value ) ;
SetAttribute( e, "align" , GetE('cmbAlign').value ) ;
// Advances Attributes
if ( ! skipId )
SetAttribute( e, 'id', GetE('txtAttId').value ) ;
SetAttribute( e, 'dir' , GetE('cmbAttLangDir').value ) ;
SetAttribute( e, 'lang' , GetE('txtAttLangCode').value ) ;
SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ;
SetAttribute( e, 'longDesc' , GetE('txtLongDesc').value ) ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
e.className = GetE('txtAttClasses').value ;
e.style.cssText = GetE('txtAttStyle').value ;
}
else
{
SetAttribute( e, 'class' , GetE('txtAttClasses').value ) ;
SetAttribute( e, 'style', GetE('txtAttStyle').value ) ;
}
}
var eImgPreview ;
var eImgPreviewLink ;
function SetPreviewElements( imageElement, linkElement )
{
eImgPreview = imageElement ;
eImgPreviewLink = linkElement ;
UpdatePreview() ;
UpdateOriginal() ;
bPreviewInitialized = true ;
}
function UpdatePreview()
{
if ( !eImgPreview || !eImgPreviewLink )
return ;
if ( GetE('txtUrl').value.length == 0 )
eImgPreviewLink.style.display = 'none' ;
else
{
UpdateImage( eImgPreview, true ) ;
if ( GetE('txtLnkUrl').value.Trim().length > 0 )
eImgPreviewLink.href = 'javascript:void(null);' ;
else
SetAttribute( eImgPreviewLink, 'href', '' ) ;
eImgPreviewLink.style.display = '' ;
}
}
var bLockRatio = true ;
function SwitchLock( lockButton )
{
bLockRatio = !bLockRatio ;
lockButton.className = bLockRatio ? 'BtnLocked' : 'BtnUnlocked' ;
lockButton.title = bLockRatio ? 'Lock sizes' : 'Unlock sizes' ;
if ( bLockRatio )
{
if ( GetE('txtWidth').value.length > 0 )
OnSizeChanged( 'Width', GetE('txtWidth').value ) ;
else
OnSizeChanged( 'Height', GetE('txtHeight').value ) ;
}
}
// Fired when the width or height input texts change
function OnSizeChanged( dimension, value )
{
// Verifies if the aspect ration has to be maintained
if ( oImageOriginal && bLockRatio )
{
var e = dimension == 'Width' ? GetE('txtHeight') : GetE('txtWidth') ;
if ( value.length == 0 || isNaN( value ) )
{
e.value = '' ;
return ;
}
if ( dimension == 'Width' )
value = value == 0 ? 0 : Math.round( oImageOriginal.height * ( value / oImageOriginal.width ) ) ;
else
value = value == 0 ? 0 : Math.round( oImageOriginal.width * ( value / oImageOriginal.height ) ) ;
if ( !isNaN( value ) )
e.value = value ;
}
UpdatePreview() ;
}
// Fired when the Reset Size button is clicked
function ResetSizes()
{
if ( ! oImageOriginal ) return ;
if ( oEditor.FCKBrowserInfo.IsGecko && !oImageOriginal.complete )
{
setTimeout( ResetSizes, 50 ) ;
return ;
}
GetE('txtWidth').value = oImageOriginal.width ;
GetE('txtHeight').value = oImageOriginal.height ;
UpdatePreview() ;
}
function BrowseServer()
{
OpenServerBrowser(
'Image',
FCKConfig.ImageBrowserURL,
FCKConfig.ImageBrowserWindowWidth,
FCKConfig.ImageBrowserWindowHeight ) ;
}
function LnkBrowseServer()
{
OpenServerBrowser(
'Link',
FCKConfig.LinkBrowserURL,
FCKConfig.LinkBrowserWindowWidth,
FCKConfig.LinkBrowserWindowHeight ) ;
}
function OpenServerBrowser( type, url, width, height )
{
sActualBrowser = type ;
OpenFileBrowser( url, width, height ) ;
}
var sActualBrowser ;
function SetUrl( url, width, height, alt )
{
if ( sActualBrowser == 'Link' )
{
GetE('txtLnkUrl').value = url ;
UpdatePreview() ;
}
else
{
GetE('txtUrl').value = url ;
GetE('txtWidth').value = width ? width : '' ;
GetE('txtHeight').value = height ? height : '' ;
if ( alt )
GetE('txtAlt').value = alt;
UpdatePreview() ;
UpdateOriginal( true ) ;
}
dialog.SetSelectedTab( 'Info' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
sActualBrowser = '' ;
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.ImageUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.ImageUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile = GetE('txtUploadFile').value ;
if ( sFile.length == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
if ( ( FCKConfig.ImageUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
( FCKConfig.ImageUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
{
OnUploadCompleted( 202 ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Scripts related to the Flash dialog window (see fck_flash.html).
*/
var dialog = window.parent ;
var oEditor = dialog.InnerDialogLoaded() ;
var FCK = oEditor.FCK ;
var FCKLang = oEditor.FCKLang ;
var FCKConfig = oEditor.FCKConfig ;
var FCKTools = oEditor.FCKTools ;
//#### Dialog Tabs
// Set the dialog tabs.
dialog.AddTab( 'Info', oEditor.FCKLang.DlgInfoTab ) ;
if ( FCKConfig.FlashUpload )
dialog.AddTab( 'Upload', FCKLang.DlgLnkUpload ) ;
if ( !FCKConfig.FlashDlgHideAdvanced )
dialog.AddTab( 'Advanced', oEditor.FCKLang.DlgAdvancedTag ) ;
// Function called when a dialog tag is selected.
function OnDialogTabChange( tabCode )
{
ShowE('divInfo' , ( tabCode == 'Info' ) ) ;
ShowE('divUpload' , ( tabCode == 'Upload' ) ) ;
ShowE('divAdvanced' , ( tabCode == 'Advanced' ) ) ;
}
// Get the selected flash embed (if available).
var oFakeImage = dialog.Selection.GetSelectedElement() ;
var oEmbed ;
if ( oFakeImage )
{
if ( oFakeImage.tagName == 'IMG' && oFakeImage.getAttribute('_fckflash') )
oEmbed = FCK.GetRealElement( oFakeImage ) ;
else
oFakeImage = null ;
}
window.onload = function()
{
// Translate the dialog box texts.
oEditor.FCKLanguageManager.TranslatePage(document) ;
// Load the selected element information (if any).
LoadSelection() ;
// Show/Hide the "Browse Server" button.
GetE('tdBrowse').style.display = FCKConfig.FlashBrowser ? '' : 'none' ;
// Set the actual uploader URL.
if ( FCKConfig.FlashUpload )
GetE('frmUpload').action = FCKConfig.FlashUploadURL ;
dialog.SetAutoSize( true ) ;
// Activate the "OK" button.
dialog.SetOkButton( true ) ;
SelectField( 'txtUrl' ) ;
}
function LoadSelection()
{
if ( ! oEmbed ) return ;
GetE('txtUrl').value = GetAttribute( oEmbed, 'src', '' ) ;
GetE('txtWidth').value = GetAttribute( oEmbed, 'width', '' ) ;
GetE('txtHeight').value = GetAttribute( oEmbed, 'height', '' ) ;
// Get Advances Attributes
GetE('txtAttId').value = oEmbed.id ;
GetE('chkAutoPlay').checked = GetAttribute( oEmbed, 'play', 'true' ) == 'true' ;
GetE('chkLoop').checked = GetAttribute( oEmbed, 'loop', 'true' ) == 'true' ;
GetE('chkMenu').checked = GetAttribute( oEmbed, 'menu', 'true' ) == 'true' ;
GetE('cmbScale').value = GetAttribute( oEmbed, 'scale', '' ).toLowerCase() ;
GetE('txtAttTitle').value = oEmbed.title ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
GetE('txtAttClasses').value = oEmbed.getAttribute('className') || '' ;
GetE('txtAttStyle').value = oEmbed.style.cssText ;
}
else
{
GetE('txtAttClasses').value = oEmbed.getAttribute('class',2) || '' ;
GetE('txtAttStyle').value = oEmbed.getAttribute('style',2) || '' ;
}
UpdatePreview() ;
}
//#### The OK button was hit.
function Ok()
{
if ( GetE('txtUrl').value.length == 0 )
{
dialog.SetSelectedTab( 'Info' ) ;
GetE('txtUrl').focus() ;
alert( oEditor.FCKLang.DlgAlertUrl ) ;
return false ;
}
oEditor.FCKUndo.SaveUndoStep() ;
if ( !oEmbed )
{
oEmbed = FCK.EditorDocument.createElement( 'EMBED' ) ;
oFakeImage = null ;
}
UpdateEmbed( oEmbed ) ;
if ( !oFakeImage )
{
oFakeImage = oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ;
oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ;
oFakeImage = FCK.InsertElement( oFakeImage ) ;
}
oEditor.FCKEmbedAndObjectProcessor.RefreshView( oFakeImage, oEmbed ) ;
return true ;
}
function UpdateEmbed( e )
{
SetAttribute( e, 'type' , 'application/x-shockwave-flash' ) ;
SetAttribute( e, 'pluginspage' , 'http://www.macromedia.com/go/getflashplayer' ) ;
SetAttribute( e, 'src', GetE('txtUrl').value ) ;
SetAttribute( e, "width" , GetE('txtWidth').value ) ;
SetAttribute( e, "height", GetE('txtHeight').value ) ;
// Advances Attributes
SetAttribute( e, 'id' , GetE('txtAttId').value ) ;
SetAttribute( e, 'scale', GetE('cmbScale').value ) ;
SetAttribute( e, 'play', GetE('chkAutoPlay').checked ? 'true' : 'false' ) ;
SetAttribute( e, 'loop', GetE('chkLoop').checked ? 'true' : 'false' ) ;
SetAttribute( e, 'menu', GetE('chkMenu').checked ? 'true' : 'false' ) ;
SetAttribute( e, 'title' , GetE('txtAttTitle').value ) ;
if ( oEditor.FCKBrowserInfo.IsIE )
{
SetAttribute( e, 'className', GetE('txtAttClasses').value ) ;
e.style.cssText = GetE('txtAttStyle').value ;
}
else
{
SetAttribute( e, 'class', GetE('txtAttClasses').value ) ;
SetAttribute( e, 'style', GetE('txtAttStyle').value ) ;
}
}
var ePreview ;
function SetPreviewElement( previewEl )
{
ePreview = previewEl ;
if ( GetE('txtUrl').value.length > 0 )
UpdatePreview() ;
}
function UpdatePreview()
{
if ( !ePreview )
return ;
while ( ePreview.firstChild )
ePreview.removeChild( ePreview.firstChild ) ;
if ( GetE('txtUrl').value.length == 0 )
ePreview.innerHTML = ' ' ;
else
{
var oDoc = ePreview.ownerDocument || ePreview.document ;
var e = oDoc.createElement( 'EMBED' ) ;
SetAttribute( e, 'src', GetE('txtUrl').value ) ;
SetAttribute( e, 'type', 'application/x-shockwave-flash' ) ;
SetAttribute( e, 'width', '100%' ) ;
SetAttribute( e, 'height', '100%' ) ;
ePreview.appendChild( e ) ;
}
}
// <embed id="ePreview" src="fck_flash/claims.swf" width="100%" height="100%" style="visibility:hidden" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
function BrowseServer()
{
OpenFileBrowser( FCKConfig.FlashBrowserURL, FCKConfig.FlashBrowserWindowWidth, FCKConfig.FlashBrowserWindowHeight ) ;
}
function SetUrl( url, width, height )
{
GetE('txtUrl').value = url ;
if ( width )
GetE('txtWidth').value = width ;
if ( height )
GetE('txtHeight').value = height ;
UpdatePreview() ;
dialog.SetSelectedTab( 'Info' ) ;
}
function OnUploadCompleted( errorNumber, fileUrl, fileName, customMsg )
{
// Remove animation
window.parent.Throbber.Hide() ;
GetE( 'divUpload' ).style.display = '' ;
switch ( errorNumber )
{
case 0 : // No errors
alert( 'Your file has been successfully uploaded' ) ;
break ;
case 1 : // Custom error
alert( customMsg ) ;
return ;
case 101 : // Custom warning
alert( customMsg ) ;
break ;
case 201 :
alert( 'A file with the same name is already available. The uploaded file has been renamed to "' + fileName + '"' ) ;
break ;
case 202 :
alert( 'Invalid file type' ) ;
return ;
case 203 :
alert( "Security error. You probably don't have enough permissions to upload. Please check your server." ) ;
return ;
case 500 :
alert( 'The connector is disabled' ) ;
break ;
default :
alert( 'Error on file upload. Error number: ' + errorNumber ) ;
return ;
}
SetUrl( fileUrl ) ;
GetE('frmUpload').reset() ;
}
var oUploadAllowedExtRegex = new RegExp( FCKConfig.FlashUploadAllowedExtensions, 'i' ) ;
var oUploadDeniedExtRegex = new RegExp( FCKConfig.FlashUploadDeniedExtensions, 'i' ) ;
function CheckUpload()
{
var sFile = GetE('txtUploadFile').value ;
if ( sFile.length == 0 )
{
alert( 'Please select a file to upload' ) ;
return false ;
}
if ( ( FCKConfig.FlashUploadAllowedExtensions.length > 0 && !oUploadAllowedExtRegex.test( sFile ) ) ||
( FCKConfig.FlashUploadDeniedExtensions.length > 0 && oUploadDeniedExtRegex.test( sFile ) ) )
{
OnUploadCompleted( 202 ) ;
return false ;
}
// Show animation
window.parent.Throbber.Show( 100 ) ;
GetE( 'divUpload' ).style.display = 'none' ;
return true ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Plugin to insert "Placeholders" in the editor.
*/
// Register the related command.
FCKCommands.RegisterCommand( 'Placeholder', new FCKDialogCommand( 'Placeholder', FCKLang.PlaceholderDlgTitle, FCKPlugins.Items['placeholder'].Path + 'fck_placeholder.html', 340, 160 ) ) ;
// Create the "Plaholder" toolbar button.
var oPlaceholderItem = new FCKToolbarButton( 'Placeholder', FCKLang.PlaceholderBtn ) ;
oPlaceholderItem.IconPath = FCKPlugins.Items['placeholder'].Path + 'placeholder.gif' ;
FCKToolbarItems.RegisterItem( 'Placeholder', oPlaceholderItem ) ;
// The object used for all Placeholder operations.
var FCKPlaceholders = new Object() ;
// Add a new placeholder at the actual selection.
FCKPlaceholders.Add = function( name )
{
var oSpan = FCK.InsertElement( 'span' ) ;
this.SetupSpan( oSpan, name ) ;
}
FCKPlaceholders.SetupSpan = function( span, name )
{
span.innerHTML = '[[ ' + name + ' ]]' ;
span.style.backgroundColor = '#ffff00' ;
span.style.color = '#000000' ;
if ( FCKBrowserInfo.IsGecko )
span.style.cursor = 'default' ;
span._fckplaceholder = name ;
span.contentEditable = false ;
// To avoid it to be resized.
span.onresizestart = function()
{
FCK.EditorWindow.event.returnValue = false ;
return false ;
}
}
// On Gecko we must do this trick so the user select all the SPAN when clicking on it.
FCKPlaceholders._SetupClickListener = function()
{
FCKPlaceholders._ClickListener = function( e )
{
if ( e.target.tagName == 'SPAN' && e.target._fckplaceholder )
FCKSelection.SelectNode( e.target ) ;
}
FCK.EditorDocument.addEventListener( 'click', FCKPlaceholders._ClickListener, true ) ;
}
// Open the Placeholder dialog on double click.
FCKPlaceholders.OnDoubleClick = function( span )
{
if ( span.tagName == 'SPAN' && span._fckplaceholder )
FCKCommands.GetCommand( 'Placeholder' ).Execute() ;
}
FCK.RegisterDoubleClickHandler( FCKPlaceholders.OnDoubleClick, 'SPAN' ) ;
// Check if a Placholder name is already in use.
FCKPlaceholders.Exist = function( name )
{
var aSpans = FCK.EditorDocument.getElementsByTagName( 'SPAN' ) ;
for ( var i = 0 ; i < aSpans.length ; i++ )
{
if ( aSpans[i]._fckplaceholder == name )
return true ;
}
return false ;
}
if ( FCKBrowserInfo.IsIE )
{
FCKPlaceholders.Redraw = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
var aPlaholders = FCK.EditorDocument.body.innerText.match( /\[\[[^\[\]]+\]\]/g ) ;
if ( !aPlaholders )
return ;
var oRange = FCK.EditorDocument.body.createTextRange() ;
for ( var i = 0 ; i < aPlaholders.length ; i++ )
{
if ( oRange.findText( aPlaholders[i] ) )
{
var sName = aPlaholders[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ;
oRange.pasteHTML( '<span style="color: #000000; background-color: #ffff00" contenteditable="false" _fckplaceholder="' + sName + '">' + aPlaholders[i] + '</span>' ) ;
}
}
}
}
else
{
FCKPlaceholders.Redraw = function()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
var oInteractor = FCK.EditorDocument.createTreeWalker( FCK.EditorDocument.body, NodeFilter.SHOW_TEXT, FCKPlaceholders._AcceptNode, true ) ;
var aNodes = new Array() ;
while ( ( oNode = oInteractor.nextNode() ) )
{
aNodes[ aNodes.length ] = oNode ;
}
for ( var n = 0 ; n < aNodes.length ; n++ )
{
var aPieces = aNodes[n].nodeValue.split( /(\[\[[^\[\]]+\]\])/g ) ;
for ( var i = 0 ; i < aPieces.length ; i++ )
{
if ( aPieces[i].length > 0 )
{
if ( aPieces[i].indexOf( '[[' ) == 0 )
{
var sName = aPieces[i].match( /\[\[\s*([^\]]*?)\s*\]\]/ )[1] ;
var oSpan = FCK.EditorDocument.createElement( 'span' ) ;
FCKPlaceholders.SetupSpan( oSpan, sName ) ;
aNodes[n].parentNode.insertBefore( oSpan, aNodes[n] ) ;
}
else
aNodes[n].parentNode.insertBefore( FCK.EditorDocument.createTextNode( aPieces[i] ) , aNodes[n] ) ;
}
}
aNodes[n].parentNode.removeChild( aNodes[n] ) ;
}
FCKPlaceholders._SetupClickListener() ;
}
FCKPlaceholders._AcceptNode = function( node )
{
if ( /\[\[[^\[\]]+\]\]/.test( node.nodeValue ) )
return NodeFilter.FILTER_ACCEPT ;
else
return NodeFilter.FILTER_SKIP ;
}
}
FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKPlaceholders.Redraw ) ;
// We must process the SPAN tags to replace then with the real resulting value of the placeholder.
FCKXHtml.TagProcessors['span'] = function( node, htmlNode )
{
if ( htmlNode._fckplaceholder )
node = FCKXHtml.XML.createTextNode( '[[' + htmlNode._fckplaceholder + ']]' ) ;
else
FCKXHtml._AppendChildNodes( node, htmlNode, false ) ;
return node ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placholder Italian language file.
*/
FCKLang.PlaceholderBtn = 'Aggiungi/Modifica Placeholder' ;
FCKLang.PlaceholderDlgTitle = 'Proprietà del Placeholder' ;
FCKLang.PlaceholderDlgName = 'Nome del Placeholder' ;
FCKLang.PlaceholderErrNoName = 'Digitare il nome del placeholder' ;
FCKLang.PlaceholderErrNameInUse = 'Il nome inserito è già in uso' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placholder German language file.
*/
FCKLang.PlaceholderBtn = 'Einfügen/editieren Platzhalter' ;
FCKLang.PlaceholderDlgTitle = 'Platzhalter Eigenschaften' ;
FCKLang.PlaceholderDlgName = 'Platzhalter Name' ;
FCKLang.PlaceholderErrNoName = 'Bitte den Namen des Platzhalters schreiben' ;
FCKLang.PlaceholderErrNameInUse = 'Der angegebene Namen ist schon in Gebrauch' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placholder Polish language file.
*/
FCKLang.PlaceholderBtn = 'Wstaw/Edytuj nagłówek' ;
FCKLang.PlaceholderDlgTitle = 'Właśności nagłówka' ;
FCKLang.PlaceholderDlgName = 'Nazwa nagłówka' ;
FCKLang.PlaceholderErrNoName = 'Proszę wprowadzić nazwę nagłówka' ;
FCKLang.PlaceholderErrNameInUse = 'Podana nazwa jest już w użyciu' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placeholder French language file.
*/
FCKLang.PlaceholderBtn = "Insérer/Modifier l'Espace réservé" ;
FCKLang.PlaceholderDlgTitle = "Propriétés de l'Espace réservé" ;
FCKLang.PlaceholderDlgName = "Nom de l'Espace réservé" ;
FCKLang.PlaceholderErrNoName = "Veuillez saisir le nom de l'Espace réservé" ;
FCKLang.PlaceholderErrNameInUse = "Ce nom est déjà utilisé" ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placholder English language file.
*/
FCKLang.PlaceholderBtn = 'Insert/Edit Placeholder' ;
FCKLang.PlaceholderDlgTitle = 'Placeholder Properties' ;
FCKLang.PlaceholderDlgName = 'Placeholder Name' ;
FCKLang.PlaceholderErrNoName = 'Please type the placeholder name' ;
FCKLang.PlaceholderErrNameInUse = 'The specified name is already in use' ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placholder Spanish language file.
*/
FCKLang.PlaceholderBtn = 'Insertar/Editar contenedor' ;
FCKLang.PlaceholderDlgTitle = 'Propiedades del contenedor ' ;
FCKLang.PlaceholderDlgName = 'Nombre de contenedor' ;
FCKLang.PlaceholderErrNoName = 'Por favor escriba el nombre de contenedor' ;
FCKLang.PlaceholderErrNameInUse = 'El nombre especificado ya esta en uso' ;
| JavaScript |
var FCKDragTableHandler =
{
"_DragState" : 0,
"_LeftCell" : null,
"_RightCell" : null,
"_MouseMoveMode" : 0, // 0 - find candidate cells for resizing, 1 - drag to resize
"_ResizeBar" : null,
"_OriginalX" : null,
"_MinimumX" : null,
"_MaximumX" : null,
"_LastX" : null,
"_TableMap" : null,
"_doc" : document,
"_IsInsideNode" : function( w, domNode, pos )
{
var myCoords = FCKTools.GetWindowPosition( w, domNode ) ;
var xMin = myCoords.x ;
var yMin = myCoords.y ;
var xMax = parseInt( xMin, 10 ) + parseInt( domNode.offsetWidth, 10 ) ;
var yMax = parseInt( yMin, 10 ) + parseInt( domNode.offsetHeight, 10 ) ;
if ( pos.x >= xMin && pos.x <= xMax && pos.y >= yMin && pos.y <= yMax )
return true;
return false;
},
"_GetBorderCells" : function( w, tableNode, tableMap, mouse )
{
// Enumerate all the cells in the table.
var cells = [] ;
for ( var i = 0 ; i < tableNode.rows.length ; i++ )
{
var r = tableNode.rows[i] ;
for ( var j = 0 ; j < r.cells.length ; j++ )
cells.push( r.cells[j] ) ;
}
if ( cells.length < 1 )
return null ;
// Get the cells whose right or left border is nearest to the mouse cursor's x coordinate.
var minRxDist = null ;
var lxDist = null ;
var minYDist = null ;
var rbCell = null ;
var lbCell = null ;
for ( var i = 0 ; i < cells.length ; i++ )
{
var pos = FCKTools.GetWindowPosition( w, cells[i] ) ;
var rightX = pos.x + parseInt( cells[i].clientWidth, 10 ) ;
var rxDist = mouse.x - rightX ;
var yDist = mouse.y - ( pos.y + ( cells[i].clientHeight / 2 ) ) ;
if ( minRxDist == null ||
( Math.abs( rxDist ) <= Math.abs( minRxDist ) &&
( minYDist == null || Math.abs( yDist ) <= Math.abs( minYDist ) ) ) )
{
minRxDist = rxDist ;
minYDist = yDist ;
rbCell = cells[i] ;
}
}
/*
var rowNode = FCKTools.GetElementAscensor( rbCell, "tr" ) ;
var cellIndex = rbCell.cellIndex + 1 ;
if ( cellIndex >= rowNode.cells.length )
return null ;
lbCell = rowNode.cells.item( cellIndex ) ;
*/
var rowIdx = rbCell.parentNode.rowIndex ;
var colIdx = FCKTableHandler._GetCellIndexSpan( tableMap, rowIdx, rbCell ) ;
var colSpan = isNaN( rbCell.colSpan ) ? 1 : rbCell.colSpan ;
lbCell = tableMap[rowIdx][colIdx + colSpan] ;
if ( ! lbCell )
return null ;
// Abort if too far from the border.
lxDist = mouse.x - FCKTools.GetWindowPosition( w, lbCell ).x ;
if ( lxDist < 0 && minRxDist < 0 && minRxDist < -2 )
return null ;
if ( lxDist > 0 && minRxDist > 0 && lxDist > 3 )
return null ;
return { "leftCell" : rbCell, "rightCell" : lbCell } ;
},
"_GetResizeBarPosition" : function()
{
var row = FCKTools.GetElementAscensor( this._RightCell, "tr" ) ;
return FCKTableHandler._GetCellIndexSpan( this._TableMap, row.rowIndex, this._RightCell ) ;
},
"_ResizeBarMouseDownListener" : function( evt )
{
if ( FCKDragTableHandler._LeftCell )
FCKDragTableHandler._MouseMoveMode = 1 ;
if ( FCKBrowserInfo.IsIE )
FCKDragTableHandler._ResizeBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 50 ;
else
FCKDragTableHandler._ResizeBar.style.opacity = 0.5 ;
FCKDragTableHandler._OriginalX = evt.clientX ;
// Calculate maximum and minimum x-coordinate delta.
var borderIndex = FCKDragTableHandler._GetResizeBarPosition() ;
var offset = FCKDragTableHandler._GetIframeOffset();
var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" );
var minX = null ;
var maxX = null ;
for ( var r = 0 ; r < FCKDragTableHandler._TableMap.length ; r++ )
{
var leftCell = FCKDragTableHandler._TableMap[r][borderIndex - 1] ;
var rightCell = FCKDragTableHandler._TableMap[r][borderIndex] ;
var leftPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, leftCell ) ;
var rightPosition = FCKTools.GetWindowPosition( FCK.EditorWindow, rightCell ) ;
var leftPadding = FCKDragTableHandler._GetCellPadding( table, leftCell ) ;
var rightPadding = FCKDragTableHandler._GetCellPadding( table, rightCell ) ;
if ( minX == null || leftPosition.x + leftPadding > minX )
minX = leftPosition.x + leftPadding ;
if ( maxX == null || rightPosition.x + rightCell.clientWidth - rightPadding < maxX )
maxX = rightPosition.x + rightCell.clientWidth - rightPadding ;
}
FCKDragTableHandler._MinimumX = minX + offset.x ;
FCKDragTableHandler._MaximumX = maxX + offset.x ;
FCKDragTableHandler._LastX = null ;
if (evt.preventDefault)
evt.preventDefault();
else
evt.returnValue = false;
},
"_ResizeBarMouseUpListener" : function( evt )
{
FCKDragTableHandler._MouseMoveMode = 0 ;
FCKDragTableHandler._HideResizeBar() ;
if ( FCKDragTableHandler._LastX == null )
return ;
// Calculate the delta value.
var deltaX = FCKDragTableHandler._LastX - FCKDragTableHandler._OriginalX ;
// Then, build an array of current column width values.
// This algorithm can be very slow if the cells have insane colSpan values. (e.g. colSpan=1000).
var table = FCKTools.GetElementAscensor( FCKDragTableHandler._LeftCell, "table" ) ;
var colArray = [] ;
var tableMap = FCKDragTableHandler._TableMap ;
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
var cell = tableMap[i][j] ;
var width = FCKDragTableHandler._GetCellWidth( table, cell ) ;
var colSpan = isNaN( cell.colSpan) ? 1 : cell.colSpan ;
if ( colArray.length <= j )
colArray.push( { width : width / colSpan, colSpan : colSpan } ) ;
else
{
var guessItem = colArray[j] ;
if ( guessItem.colSpan > colSpan )
{
guessItem.width = width / colSpan ;
guessItem.colSpan = colSpan ;
}
}
}
}
// Find out the equivalent column index of the two cells selected for resizing.
colIndex = FCKDragTableHandler._GetResizeBarPosition() ;
// Note that colIndex must be at least 1 here, so it's safe to subtract 1 from it.
colIndex-- ;
// Modify the widths in the colArray according to the mouse coordinate delta value.
colArray[colIndex].width += deltaX ;
colArray[colIndex + 1].width -= deltaX ;
// Clear all cell widths, delete all <col> elements from the table.
for ( var r = 0 ; r < table.rows.length ; r++ )
{
var row = table.rows.item( r ) ;
for ( var c = 0 ; c < row.cells.length ; c++ )
{
var cell = row.cells.item( c ) ;
cell.width = "" ;
cell.style.width = "" ;
}
}
var colElements = table.getElementsByTagName( "col" ) ;
for ( var i = colElements.length - 1 ; i >= 0 ; i-- )
colElements[i].parentNode.removeChild( colElements[i] ) ;
// Set new cell widths.
var processedCells = [] ;
for ( var i = 0 ; i < tableMap.length ; i++ )
{
for ( var j = 0 ; j < tableMap[i].length ; j++ )
{
var cell = tableMap[i][j] ;
if ( cell._Processed )
continue ;
if ( tableMap[i][j-1] != cell )
cell.width = colArray[j].width ;
else
cell.width = parseInt( cell.width, 10 ) + parseInt( colArray[j].width, 10 ) ;
if ( tableMap[i][j+1] != cell )
{
processedCells.push( cell ) ;
cell._Processed = true ;
}
}
}
for ( var i = 0 ; i < processedCells.length ; i++ )
{
if ( FCKBrowserInfo.IsIE )
processedCells[i].removeAttribute( '_Processed' ) ;
else
delete processedCells[i]._Processed ;
}
FCKDragTableHandler._LastX = null ;
},
"_ResizeBarMouseMoveListener" : function( evt )
{
if ( FCKDragTableHandler._MouseMoveMode == 0 )
return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ;
else
return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ;
},
// Calculate the padding of a table cell.
// It returns the value of paddingLeft + paddingRight of a table cell.
// This function is used, in part, to calculate the width parameter that should be used for setting cell widths.
// The equation in question is clientWidth = paddingLeft + paddingRight + width.
// So that width = clientWidth - paddingLeft - paddingRight.
// The return value of this function must be pixel accurate acorss all supported browsers, so be careful if you need to modify it.
"_GetCellPadding" : function( table, cell )
{
var attrGuess = parseInt( table.cellPadding, 10 ) * 2 ;
var cssGuess = null ;
if ( typeof( window.getComputedStyle ) == "function" )
{
var styleObj = window.getComputedStyle( cell, null ) ;
cssGuess = parseInt( styleObj.getPropertyValue( "padding-left" ), 10 ) +
parseInt( styleObj.getPropertyValue( "padding-right" ), 10 ) ;
}
else
cssGuess = parseInt( cell.currentStyle.paddingLeft, 10 ) + parseInt (cell.currentStyle.paddingRight, 10 ) ;
var cssRuntime = cell.style.padding ;
if ( isFinite( cssRuntime ) )
cssGuess = parseInt( cssRuntime, 10 ) * 2 ;
else
{
cssRuntime = cell.style.paddingLeft ;
if ( isFinite( cssRuntime ) )
cssGuess = parseInt( cssRuntime, 10 ) ;
cssRuntime = cell.style.paddingRight ;
if ( isFinite( cssRuntime ) )
cssGuess += parseInt( cssRuntime, 10 ) ;
}
attrGuess = parseInt( attrGuess, 10 ) ;
cssGuess = parseInt( cssGuess, 10 ) ;
if ( isNaN( attrGuess ) )
attrGuess = 0 ;
if ( isNaN( cssGuess ) )
cssGuess = 0 ;
return Math.max( attrGuess, cssGuess ) ;
},
// Calculate the real width of the table cell.
// The real width of the table cell is the pixel width that you can set to the width attribute of the table cell and after
// that, the table cell should be of exactly the same width as before.
// The real width of a table cell can be calculated as:
// width = clientWidth - paddingLeft - paddingRight.
"_GetCellWidth" : function( table, cell )
{
var clientWidth = cell.clientWidth ;
if ( isNaN( clientWidth ) )
clientWidth = 0 ;
return clientWidth - this._GetCellPadding( table, cell ) ;
},
"MouseMoveListener" : function( FCK, evt )
{
if ( FCKDragTableHandler._MouseMoveMode == 0 )
return FCKDragTableHandler._MouseFindHandler( FCK, evt ) ;
else
return FCKDragTableHandler._MouseDragHandler( FCK, evt ) ;
},
"_MouseFindHandler" : function( FCK, evt )
{
if ( FCK.MouseDownFlag )
return ;
var node = evt.srcElement || evt.target ;
try
{
if ( ! node || node.nodeType != 1 )
{
this._HideResizeBar() ;
return ;
}
}
catch ( e )
{
this._HideResizeBar() ;
return ;
}
// Since this function might be called from the editing area iframe or the outer fckeditor iframe,
// the mouse point coordinates from evt.clientX/Y can have different reference points.
// We need to resolve the mouse pointer position relative to the editing area iframe.
var mouseX = evt.clientX ;
var mouseY = evt.clientY ;
if ( FCKTools.GetElementDocument( node ) == document )
{
var offset = this._GetIframeOffset() ;
mouseX -= offset.x ;
mouseY -= offset.y ;
}
if ( this._ResizeBar && this._LeftCell )
{
var leftPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._LeftCell ) ;
var rightPos = FCKTools.GetWindowPosition( FCK.EditorWindow, this._RightCell ) ;
var rxDist = mouseX - ( leftPos.x + this._LeftCell.clientWidth ) ;
var lxDist = mouseX - rightPos.x ;
var inRangeFlag = false ;
if ( lxDist >= 0 && rxDist <= 0 )
inRangeFlag = true ;
else if ( rxDist > 0 && lxDist <= 3 )
inRangeFlag = true ;
else if ( lxDist < 0 && rxDist >= -2 )
inRangeFlag = true ;
if ( inRangeFlag )
{
this._ShowResizeBar( FCK.EditorWindow,
FCKTools.GetElementAscensor( this._LeftCell, "table" ),
{ "x" : mouseX, "y" : mouseY } ) ;
return ;
}
}
var tagName = node.tagName.toLowerCase() ;
if ( tagName != "table" && tagName != "td" && tagName != "th" )
{
if ( this._LeftCell )
this._LeftCell = this._RightCell = this._TableMap = null ;
this._HideResizeBar() ;
return ;
}
node = FCKTools.GetElementAscensor( node, "table" ) ;
var tableMap = FCKTableHandler._CreateTableMap( node ) ;
var cellTuple = this._GetBorderCells( FCK.EditorWindow, node, tableMap, { "x" : mouseX, "y" : mouseY } ) ;
if ( cellTuple == null )
{
if ( this._LeftCell )
this._LeftCell = this._RightCell = this._TableMap = null ;
this._HideResizeBar() ;
}
else
{
this._LeftCell = cellTuple["leftCell"] ;
this._RightCell = cellTuple["rightCell"] ;
this._TableMap = tableMap ;
this._ShowResizeBar( FCK.EditorWindow,
FCKTools.GetElementAscensor( this._LeftCell, "table" ),
{ "x" : mouseX, "y" : mouseY } ) ;
}
},
"_MouseDragHandler" : function( FCK, evt )
{
var mouse = { "x" : evt.clientX, "y" : evt.clientY } ;
// Convert mouse coordinates in reference to the outer iframe.
var node = evt.srcElement || evt.target ;
if ( FCKTools.GetElementDocument( node ) == FCK.EditorDocument )
{
var offset = this._GetIframeOffset() ;
mouse.x += offset.x ;
mouse.y += offset.y ;
}
// Calculate the mouse position delta and see if we've gone out of range.
if ( mouse.x >= this._MaximumX - 5 )
mouse.x = this._MaximumX - 5 ;
if ( mouse.x <= this._MinimumX + 5 )
mouse.x = this._MinimumX + 5 ;
var docX = mouse.x + FCKTools.GetScrollPosition( window ).X ;
this._ResizeBar.style.left = ( docX - this._ResizeBar.offsetWidth / 2 ) + "px" ;
this._LastX = mouse.x ;
},
"_ShowResizeBar" : function( w, table, mouse )
{
if ( this._ResizeBar == null )
{
this._ResizeBar = this._doc.createElement( "div" ) ;
var paddingBar = this._ResizeBar ;
var paddingStyles = { 'position' : 'absolute', 'cursor' : 'e-resize' } ;
if ( FCKBrowserInfo.IsIE )
paddingStyles.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=10,enabled=true)" ;
else
paddingStyles.opacity = 0.10 ;
FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ;
this._avoidStyles( paddingBar );
paddingBar.setAttribute('_fcktemp', true);
this._doc.body.appendChild( paddingBar ) ;
FCKTools.AddEventListener( paddingBar, "mousemove", this._ResizeBarMouseMoveListener ) ;
FCKTools.AddEventListener( paddingBar, "mousedown", this._ResizeBarMouseDownListener ) ;
FCKTools.AddEventListener( document, "mouseup", this._ResizeBarMouseUpListener ) ;
FCKTools.AddEventListener( FCK.EditorDocument, "mouseup", this._ResizeBarMouseUpListener ) ;
// IE doesn't let the tranparent part of the padding block to receive mouse events unless there's something inside.
// So we need to create a spacer image to fill the block up.
var filler = this._doc.createElement( "img" ) ;
filler.setAttribute('_fcktemp', true);
filler.border = 0 ;
filler.src = FCKConfig.BasePath + "images/spacer.gif" ;
filler.style.position = "absolute" ;
paddingBar.appendChild( filler ) ;
// Disable drag and drop, and selection for the filler image.
var disabledListener = function( evt )
{
if ( evt.preventDefault )
evt.preventDefault() ;
else
evt.returnValue = false ;
}
FCKTools.AddEventListener( filler, "dragstart", disabledListener ) ;
FCKTools.AddEventListener( filler, "selectstart", disabledListener ) ;
}
var paddingBar = this._ResizeBar ;
var offset = this._GetIframeOffset() ;
var tablePos = this._GetTablePosition( w, table ) ;
var barHeight = table.offsetHeight ;
var barTop = offset.y + tablePos.y ;
// Do not let the resize bar intrude into the toolbar area.
if ( tablePos.y < 0 )
{
barHeight += tablePos.y ;
barTop -= tablePos.y ;
}
var bw = parseInt( table.border, 10 ) ;
if ( isNaN( bw ) )
bw = 0 ;
var cs = parseInt( table.cellSpacing, 10 ) ;
if ( isNaN( cs ) )
cs = 0 ;
var barWidth = Math.max( bw+100, cs+100 ) ;
var paddingStyles =
{
'top' : barTop + 'px',
'height' : barHeight + 'px',
'width' : barWidth + 'px',
'left' : ( offset.x + mouse.x + FCKTools.GetScrollPosition( w ).X - barWidth / 2 ) + 'px'
} ;
if ( FCKBrowserInfo.IsIE )
paddingBar.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 10 ;
else
paddingStyles.opacity = 0.1 ;
FCKDomTools.SetElementStyles( paddingBar, paddingStyles ) ;
var filler = paddingBar.getElementsByTagName( "img" )[0] ;
FCKDomTools.SetElementStyles( filler,
{
width : paddingBar.offsetWidth + 'px',
height : barHeight + 'px'
} ) ;
barWidth = Math.max( bw, cs, 3 ) ;
var visibleBar = null ;
if ( paddingBar.getElementsByTagName( "div" ).length < 1 )
{
visibleBar = this._doc.createElement( "div" ) ;
this._avoidStyles( visibleBar );
visibleBar.setAttribute('_fcktemp', true);
paddingBar.appendChild( visibleBar ) ;
}
else
visibleBar = paddingBar.getElementsByTagName( "div" )[0] ;
FCKDomTools.SetElementStyles( visibleBar,
{
position : 'absolute',
backgroundColor : 'blue',
width : barWidth + 'px',
height : barHeight + 'px',
left : '50px',
top : '0px'
} ) ;
},
"_HideResizeBar" : function()
{
if ( this._ResizeBar )
// IE bug: display : none does not hide the resize bar for some reason.
// so set the position to somewhere invisible.
FCKDomTools.SetElementStyles( this._ResizeBar,
{
top : '-100000px',
left : '-100000px'
} ) ;
},
"_GetIframeOffset" : function ()
{
return FCKTools.GetDocumentPosition( window, FCK.EditingArea.IFrame ) ;
},
"_GetTablePosition" : function ( w, table )
{
return FCKTools.GetWindowPosition( w, table ) ;
},
"_avoidStyles" : function( element )
{
FCKDomTools.SetElementStyles( element,
{
padding : '0',
backgroundImage : 'none',
border : '0'
} ) ;
}
};
FCK.Events.AttachEvent( "OnMouseMove", FCKDragTableHandler.MouseMoveListener ) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Plugin: automatically resizes the editor until a configurable maximun
* height (FCKConfig.AutoGrowMax), based on its contents.
*/
var FCKAutoGrow_Min = window.frameElement.offsetHeight ;
function FCKAutoGrow_Check()
{
var oInnerDoc = FCK.EditorDocument ;
var iFrameHeight, iInnerHeight ;
if ( FCKBrowserInfo.IsIE )
{
iFrameHeight = FCK.EditorWindow.frameElement.offsetHeight ;
iInnerHeight = oInnerDoc.body.scrollHeight ;
}
else
{
iFrameHeight = FCK.EditorWindow.innerHeight ;
iInnerHeight = oInnerDoc.body.offsetHeight ;
}
var iDiff = iInnerHeight - iFrameHeight ;
if ( iDiff != 0 )
{
var iMainFrameSize = window.frameElement.offsetHeight ;
if ( iDiff > 0 && iMainFrameSize < FCKConfig.AutoGrowMax )
{
iMainFrameSize += iDiff ;
if ( iMainFrameSize > FCKConfig.AutoGrowMax )
iMainFrameSize = FCKConfig.AutoGrowMax ;
}
else if ( iDiff < 0 && iMainFrameSize > FCKAutoGrow_Min )
{
iMainFrameSize += iDiff ;
if ( iMainFrameSize < FCKAutoGrow_Min )
iMainFrameSize = FCKAutoGrow_Min ;
}
else
return ;
window.frameElement.height = iMainFrameSize ;
// Gecko browsers use an onresize handler to update the innermost
// IFRAME's height. If the document is modified before the onresize
// is triggered, the plugin will miscalculate the new height. Thus,
// forcibly trigger onresize. #1336
if ( typeof window.onresize == 'function' )
window.onresize() ;
}
}
FCK.AttachToOnSelectionChange( FCKAutoGrow_Check ) ;
function FCKAutoGrow_SetListeners()
{
if ( FCK.EditMode != FCK_EDITMODE_WYSIWYG )
return ;
FCK.EditorWindow.attachEvent( 'onscroll', FCKAutoGrow_Check ) ;
FCK.EditorDocument.attachEvent( 'onkeyup', FCKAutoGrow_Check ) ;
}
if ( FCKBrowserInfo.IsIE )
{
// FCKAutoGrow_SetListeners() ;
FCK.Events.AttachEvent( 'OnAfterSetHTML', FCKAutoGrow_SetListeners ) ;
}
function FCKAutoGrow_CheckEditorStatus( sender, status )
{
if ( status == FCK_STATUS_COMPLETE )
FCKAutoGrow_Check() ;
}
FCK.Events.AttachEvent( 'OnStatusChange', FCKAutoGrow_CheckEditorStatus ) ;
| JavaScript |
FCKCommands.RegisterCommand('insertcodeRun',new FCKDialogCommand( 'insertcodeRun', FCKLang["InsertCodeBtn"], FCKPlugins.Items['insertcodeRun'].Path + 'fck_insertcode.html', 500, 420 ) ) ;
var oInsertCode=new FCKToolbarButton('insertcodeRun',null,FCKLang["InsertCodeBtn"],null,false,true,74);
oInsertCode.IconPath = FCKPlugins.Items['insertcodeRun'].Path + 'insertcodeRun.jpg';
FCKToolbarItems.RegisterItem('insertcodeRun',oInsertCode);
var m_shhao=false; //是否显示行号
var m_shhao_css="margin-left:5px;list-style-type:none;border:0px;";
var FCKInsertCode = new Object() ;
//语言 ,语言文字,代码,是否显示行号,是否折叠,是否显示语言名词,是否文本域显示,是否有演示按钮
FCKInsertCode.Add = function( lan,lantxt,txt,hh,zd,yy,wby,ys)
{
m_shhao = hh;
var coText = FCK.CreateElement('DIV');
coText.className = 'codeText';
var tmpHtml=""; //tmpHtml是用于存储处理后的字符
var rndnum = Math.floor((Math.random()*100000)).toString().substr(0,4);
var codeDiv = 'code_'+rndnum;
var hitDiv = 'hit_'+rndnum;
var hitDiv2 = 'hit2_'+rndnum;
var wbyName= 'wby'+rndnum; //文本域
var wbyWin = 'win'+rndnum;
//下面是在文本域中显示代码,不用高亮关键字符,处理后直接返回
if(wby)
{
tmpHtml += "<textarea class='wbyText' id='"+wbyName+"' name='"+wbyName+"' rows='16' cols='80'>"+ txt +"</textarea>";
tmpHtml += "<br>";
if(ys)tmpHtml +="<input type='button' value=' 运行代码 ' onclick=\"winEx=window.open('', 'winEx', 'width=800,height=600,resizable=yes,top=0,left=0');winEx.document.write("+wbyName+".value);winEx.document.close()\">"
tmpHtml +=" <input type='button' value=' 选择代码 ' onclick='"+wbyName+".select()'> 提示:可以修改后运行."
coText.innerHTML=tmpHtml;
//alert(tmpHtml);
return 1;
}
//下面开始高亮关键字符
var registered = new Object();
for(var brush in dp.sh.Brushes)
{
var aliases = dp.sh.Brushes[brush].Aliases;
if(aliases == null) continue;
for(var i=0;i<aliases.length;i++) registered[aliases[i]] = brush;
};
var ht = new dp.sh.Brushes[registered[lan]]();
ht.Highlight(txt);
//高亮字符结束
if(yy || zd) tmpHtml="<div class='codeHead'>";
if(zd){
tmpHtml += "<span class='zhedie' id='"+hitDiv+"' style='cursor:pointer' onclick=\"javascript:"+codeDiv+".style.display='none';"+hitDiv2+".style.display='';"+hitDiv+".style.display='none';\">折叠</span>";
tmpHtml += "<span class='zhedie' id='"+hitDiv2+"' style='cursor:pointer;display:none;' onclick=\"javascript:"+codeDiv+".style.display='';"+hitDiv+".style.display='';"+hitDiv2+".style.display='none';\">展开</span>";
}
if(yy) tmpHtml += "<span class='lantxt'>"+lantxt+" Code</span>";
tmpHtml +="<span class='copyCodeText' style='cursor:pointer' onclick=\"copyIdText('"+codeDiv+"')\">复制内容到剪贴板</span>";
if(yy || zd) tmpHtml += "</div>";
tmpHtml += "<div id='"+ codeDiv +"'>"+ht.div.innerHTML+"</div>";
coText.innerHTML=tmpHtml;
}
var dp = {
sh :
{
Utils : {},
RegexLib: {},
Brushes : {}
}
};
// make an alias
dp.SyntaxHighlighter = dp.sh;
//
// Common reusable regular expressions
//
dp.sh.RegexLib = {
MultiLineCComments : new RegExp('/\\*[\\s\\S]*?\\*/', 'gm'),
SingleLineCComments : new RegExp('//.*$', 'gm'),
SingleLinePerlComments : new RegExp('#.*$', 'gm'),
DoubleQuotedString : new RegExp('"(?:\\.|(\\\\\\")|[^\\""])*"','g'),
SingleQuotedString : new RegExp("'(?:\\.|(\\\\\\')|[^\\''])*'", 'g')
};
//
// Match object
//
dp.sh.Match = function(value, index, css)
{
this.value = value;
this.index = index;
this.length = value.length;
this.css = css;
}
//
// Highlighter object
//
dp.sh.Highlighter = function()
{
this.tabsToSpaces = true;
this.wrapColumn = 80;
this.showColumns = true;
this.firstLine = 1;
}
// static callback for the match sorting
dp.sh.Highlighter.SortCallback = function(m1, m2)
{
// sort matches by index first
if(m1.index < m2.index)
return -1;
else if(m1.index > m2.index)
return 1;
else
{
// if index is the same, sort by length
if(m1.length < m2.length)
return -1;
else if(m1.length > m2.length)
return 1;
}
return 0;
}
dp.sh.Highlighter.prototype.CreateElement = function(name)
{
var result = document.createElement(name);
result.highlighter = this;
return result;
}
// gets a list of all matches for a given regular expression
dp.sh.Highlighter.prototype.GetMatches = function(regex, css)
{
var index = 0;
var match = null;
while((match = regex.exec(this.code)) != null)
this.matches[this.matches.length] = new dp.sh.Match(match[0], match.index, css);
}
dp.sh.Highlighter.prototype.AddBit = function(str, css)
{
if(str == null || str.length == 0)
return;
var span = this.CreateElement('SPAN');
str = str.replace(/ /g, ' ');
str = str.replace(/</g, '<');
str = str.replace(/\n/gm, ' <br>');
// when adding a piece of code, check to see if it has line breaks in it
// and if it does, wrap individual line breaks with span tags
if(css != null)
{
if((/br/gi).test(str))
{
var lines = str.split(' <br>');
for(var i = 0; i < lines.length; i++)
{
span = this.CreateElement('SPAN');
span.className = css;
span.innerHTML = lines[i];
this.div.appendChild(span);
// don't add a <BR> for the last line
if(i + 1 < lines.length)
this.div.appendChild(this.CreateElement('BR'));
}
}
else
{
span.className = css;
span.innerHTML = str;
this.div.appendChild(span);
}
}
else
{
span.innerHTML = str;
this.div.appendChild(span);
}
}
// checks if one match is inside any other match
dp.sh.Highlighter.prototype.IsInside = function(match)
{
if(match == null || match.length == 0)
return false;
for(var i = 0; i < this.matches.length; i++)
{
var c = this.matches[i];
if(c == null)
continue;
if((match.index > c.index) && (match.index < c.index + c.length))
return true;
}
return false;
}
dp.sh.Highlighter.prototype.ProcessRegexList = function()
{
for(var i = 0; i < this.regexList.length; i++)
this.GetMatches(this.regexList[i].regex, this.regexList[i].css);
}
dp.sh.Highlighter.prototype.ProcessSmartTabs = function(code)
{
var lines = code.split('\n');
var result = '';
var tabSize = 4;
var tab = '\t';
// This function inserts specified amount of spaces in the string
// where a tab is while removing that given tab.
function InsertSpaces(line, pos, count)
{
var left = line.substr(0, pos);
var right = line.substr(pos + 1, line.length); // pos + 1 will get rid of the tab
var spaces = '';
for(var i = 0; i < count; i++)
spaces += ' ';
return left + spaces + right;
}
// This function process one line for 'smart tabs'
function ProcessLine(line, tabSize)
{
if(line.indexOf(tab) == -1)
return line;
var pos = 0;
while((pos = line.indexOf(tab)) != -1)
{
// This is pretty much all there is to the 'smart tabs' logic.
// Based on the position within the line and size of a tab,
// calculate the amount of spaces we need to insert.
var spaces = tabSize - pos % tabSize;
line = InsertSpaces(line, pos, spaces);
}
return line;
}
// Go through all the lines and do the 'smart tabs' magic.
for(var i = 0; i < lines.length; i++)
result += ProcessLine(lines[i], tabSize) + '\n';
return result;
}
dp.sh.Highlighter.prototype.SwitchToList = function()
{
// thanks to Lachlan Donald from SitePoint.com for this <br/> tag fix.
var html = this.div.innerHTML.replace(/<(br)\/?>/gi, '\n');
var lines = html.split('\n');
for(var i = 0, lineIndex = this.firstLine; i < lines.length - 1; i++, lineIndex++)
{
var li = this.CreateElement('LI');
var span = this.CreateElement('SPAN');
// uses .line1 and .line2 css styles for alternating lines
li.className = (i % 2 == 0) ? 'alt' : '';
span.innerHTML = lines[i] + ' ';
li.appendChild(span);
this.ol.appendChild(li);
}
this.div.innerHTML = '';
}
dp.sh.Highlighter.prototype.Highlight = function(code)
{
function Trim(str)
{
return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1');
}
function Chop(str)
{
return str.replace(/\n*$/, '').replace(/^\n*/, '');
}
function Unindent(str)
{
var lines = str.split('\n');
var indents = new Array();
var regex = new RegExp('^\\s*', 'g');
var min = 1000;
// go through every line and check for common number of indents
for(var i = 0; i < lines.length && min > 0; i++)
{
if(Trim(lines[i]).length == 0)
continue;
var matches = regex.exec(lines[i]);
if(matches != null && matches.length > 0)
min = Math.min(matches[0].length, min);
}
// trim minimum common number of white space from the begining of every line
if(min > 0)
for(var i = 0; i < lines.length; i++)
lines[i] = lines[i].substr(min);
return lines.join('\n');
}
// This function returns a portions of the string from pos1 to pos2 inclusive
function Copy(string, pos1, pos2)
{
return string.substr(pos1, pos2 - pos1);
}
var pos = 0;
if(code == null)
code = '';
this.originalCode = code;
this.code = Chop(Unindent(code));
this.div = this.CreateElement('DIV');
this.ol = this.CreateElement('OL');
this.matches = new Array();
this.div.className = 'dp-highlighter';
this.div.highlighter = this;
// set the first line
this.ol.start = this.firstLine;
if(this.CssClass != null)
this.ol.className = this.CssClass;
if(m_shhao==false)
this.ol.Style=m_shhao_css; //是否显示行号
// replace tabs with spaces
if(this.tabsToSpaces == true)
this.code = this.ProcessSmartTabs(this.code);
this.ProcessRegexList();
// if no matches found, add entire code as plain text
if(this.matches.length == 0)
{
this.AddBit(this.code, null);
this.SwitchToList();
this.div.appendChild(this.ol);
return;
}
// sort the matches
this.matches = this.matches.sort(dp.sh.Highlighter.SortCallback);
// The following loop checks to see if any of the matches are inside
// of other matches. This process would get rid of highligted strings
// inside comments, keywords inside strings and so on.
for(var i = 0; i < this.matches.length; i++)
if(this.IsInside(this.matches[i]))
this.matches[i] = null;
// Finally, go through the final list of matches and pull the all
// together adding everything in between that isn't a match.
for(var i = 0; i < this.matches.length; i++)
{
var match = this.matches[i];
if(match == null || match.length == 0)
continue;
this.AddBit(Copy(this.code, pos, match.index), null);
this.AddBit(match.value, match.css);
pos = match.index + match.length;
}
this.AddBit(this.code.substr(pos), null);
this.SwitchToList();
this.div.appendChild(this.ol);
}
dp.sh.Highlighter.prototype.GetKeywords = function(str)
{
return '\\b' + str.replace(/ /g, '\\b|\\b') + '\\b';
}
dp.sh.Brushes.Xml = function()
{
this.CssClass = 'dp-xml';
this.Style = '.dp-xml .cdata { color: #ff1493; }' +
'.dp-xml .tag, .dp-xml .tag-name { color: #069; font-weight: bold; }' +
'.dp-xml .attribute { color: red; }' +
'.dp-xml .attribute-value { color: blue; }';
}
dp.sh.Brushes.Xml.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Xml.Aliases = ['xml', 'xhtml', 'xslt', 'html', 'xhtml'];
dp.sh.Brushes.Xml.prototype.ProcessRegexList = function()
{
function push(array, value)
{
array[array.length] = value;
}
var index = 0;
var match = null;
var regex = null;
this.GetMatches(new RegExp('(\<|<)\\!\\[[\\w\\s]*?\\[(.|\\s)*?\\]\\](\>|>)', 'gm'), 'cdata');
this.GetMatches(new RegExp('(\<|<)!--\\s*.*\\s*?--(\>|>)', 'gm'), 'comments');
regex = new RegExp('([:\\w-\.]+)\\s*=\\s*(".*?"|\'.*?\'|\\w+)*|(\\w+)', 'gm');
while((match = regex.exec(this.code)) != null)
{
if(match[1] == null)
{
continue;
}
push(this.matches, new dp.sh.Match(match[1], match.index, 'attribute'));
// if xml is invalid and attribute has no property value, ignore it
if(match[2] != undefined)
{
push(this.matches, new dp.sh.Match(match[2], match.index + match[0].indexOf(match[2]), 'attribute-value'));
}
}
this.GetMatches(new RegExp('(\<|<)/*\\?*(?!\\!)|/*\\?*(\>|>)', 'gm'), 'tag');
regex = new RegExp('(?:\<|<)/*\\?*\\s*([:\\w-\.]+)', 'gm');
while((match = regex.exec(this.code)) != null)
{
push(this.matches, new dp.sh.Match(match[1], match.index + match[0].indexOf(match[1]), 'tag-name'));
}
}
dp.sh.Brushes.Vb = function()
{
var keywords = 'AddHandler AddressOf AndAlso Alias And Ansi As Assembly Auto ' +
'Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate ' +
'CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType ' +
'Date Decimal Declare Default Delegate Dim DirectCast Do Double Each ' +
'Else ElseIf End Enum Erase Error Event Exit False Finally For Friend ' +
'Function Get GetType GoSub GoTo Handles If Implements Imports In ' +
'Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module ' +
'MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing ' +
'NotInheritable NotOverridable Object On Option Optional Or OrElse ' +
'Overloads Overridable Overrides ParamArray Preserve Private Property ' +
'Protected Public RaiseEvent ReadOnly ReDim REM RemoveHandler Resume ' +
'Return Select Set Shadows Shared Short Single Static Step Stop String ' +
'Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until ' +
'Variant When While With WithEvents WriteOnly Xor';
this.regexList = [
{ regex: new RegExp('\'.*$', 'gm'), css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // strings
{ regex: new RegExp('^\\s*#.*', 'gm'), css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' } // c# keyword
];
this.CssClass = 'dp-vb';
}
dp.sh.Brushes.Vb.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Vb.Aliases = ['vb', 'vb.net'];
dp.sh.Brushes.Sql = function()
{
var funcs = 'abs avg case cast coalesce convert count current_timestamp ' +
'current_user day isnull left lower month nullif replace right ' +
'session_user space substring sum system_user upper user year';
var keywords = 'absolute action add after alter as asc at authorization begin bigint ' +
'binary bit by cascade char character check checkpoint close collate ' +
'column commit committed connect connection constraint contains continue ' +
'create cube current current_date current_time cursor database date ' +
'deallocate dec decimal declare default delete desc distinct double drop ' +
'dynamic else end end-exec escape except exec execute false fetch first ' +
'float for force foreign forward free from full function global goto grant ' +
'group grouping having hour ignore index inner insensitive insert instead ' +
'int integer intersect into is isolation key last level load local max min ' +
'minute modify move name national nchar next no numeric of off on only ' +
'open option order out output partial password precision prepare primary ' +
'prior privileges procedure public read real references relative repeatable ' +
'restrict return returns revoke rollback rollup rows rule schema scroll ' +
'second section select sequence serializable set size smallint static ' +
'statistics table temp temporary then time timestamp to top transaction ' +
'translation trigger true truncate uncommitted union unique update values ' +
'varchar varying view when where with work';
var operators = 'all and any between cross in join like not null or outer some';
this.regexList = [
{ regex: new RegExp('--(.*)$', 'gm'), css: 'comment' }, // one line and multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp(this.GetKeywords(funcs), 'gmi'), css: 'func' }, // functions
{ regex: new RegExp(this.GetKeywords(operators), 'gmi'), css: 'op' }, // operators and such
{ regex: new RegExp(this.GetKeywords(keywords), 'gmi'), css: 'keyword' } // keyword
];
this.CssClass = 'dp-sql';
this.Style = '.dp-sql .func { color: #ff1493; }' +
'.dp-sql .op { color: #808080; }';
}
dp.sh.Brushes.Sql.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Sql.Aliases = ['sql'];
dp.sh.Brushes.Ruby = function()
{
var keywords = 'alias and BEGIN begin break case class def define_method defined do each else elsif ' +
'END end ensure false for if in module new next nil not or raise redo rescue retry return ' +
'self super then throw true undef unless until when while yield';
var builtins = 'Array Bignum Binding Class Continuation Dir Exception FalseClass File::Stat File Fixnum Fload ' +
'Hash Integer IO MatchData Method Module NilClass Numeric Object Proc Range Regexp String Struct::TMS Symbol ' +
'ThreadGroup Thread Time TrueClass'
this.regexList = [
{ regex: dp.sh.RegexLib.SingleLinePerlComments, css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp(':[a-z][A-Za-z0-9_]*', 'g'), css: 'symbol' }, // symbols
{ regex: new RegExp('(\\$|@@|@)\\w+', 'g'), css: 'variable' }, // $global, @instance, and @@class variables
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
{ regex: new RegExp(this.GetKeywords(builtins), 'gm'), css: 'builtin' } // builtins
];
this.CssClass = 'dp-rb';
this.Style = '.dp-rb .symbol { color: #a70; }' +
'.dp-rb .variable { color: #a70; font-weight: bold; }';
}
dp.sh.Brushes.Ruby.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Ruby.Aliases = ['ruby', 'rails', 'ror'];
dp.sh.Brushes.Python = function()
{
var keywords = 'and assert break class continue def del elif else ' +
'except exec finally for from global if import in is ' +
'lambda not or pass print raise return try yield while';
var special = 'None True False self cls class_'
this.regexList = [
{ regex: dp.sh.RegexLib.SingleLinePerlComments, css: 'comment' },
{ regex: new RegExp("^\\s*@\\w+", 'gm'), css: 'decorator' },
{ regex: new RegExp("(['\"]{3})([^\\1])*?\\1", 'gm'), css: 'comment' },
{ regex: new RegExp('"(?!")(?:\\.|\\\\\\"|[^\\""\\n\\r])*"', 'gm'), css: 'string' },
{ regex: new RegExp("'(?!')*(?:\\.|(\\\\\\')|[^\\''\\n\\r])*'", 'gm'), css: 'string' },
{ regex: new RegExp("\\b\\d+\\.?\\w*", 'g'), css: 'number' },
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' },
{ regex: new RegExp(this.GetKeywords(special), 'gm'), css: 'special' },
];
this.CssClass = 'dp-py';
this.Style = '.dp-py .builtins { color: #ff1493; }' +
'.dp-py .magicmethods { color: #808080; }' +
'.dp-py .exceptions { color: brown; }' +
'.dp-py .types { color: brown; font-style: italic; }' +
'.dp-py .commonlibs { color: #8A2BE2; font-style: italic; }';
}
dp.sh.Brushes.Python.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Python.Aliases = ['py', 'python'];
dp.sh.Brushes.Php = function()
{
var funcs = 'abs acos acosh addcslashes addslashes ' +
'array_change_key_case array_chunk array_combine array_count_values array_diff '+
'array_diff_assoc array_diff_key array_diff_uassoc array_diff_ukey array_fill '+
'array_filter array_flip array_intersect array_intersect_assoc array_intersect_key '+
'array_intersect_uassoc array_intersect_ukey array_key_exists array_keys array_map '+
'array_merge array_merge_recursive array_multisort array_pad array_pop array_product '+
'array_push array_rand array_reduce array_reverse array_search array_shift '+
'array_slice array_splice array_sum array_udiff array_udiff_assoc '+
'array_udiff_uassoc array_uintersect array_uintersect_assoc '+
'array_uintersect_uassoc array_unique array_unshift array_values array_walk '+
'array_walk_recursive atan atan2 atanh base64_decode base64_encode base_convert '+
'basename bcadd bccomp bcdiv bcmod bcmul bindec bindtextdomain bzclose bzcompress '+
'bzdecompress bzerrno bzerror bzerrstr bzflush bzopen bzread bzwrite ceil chdir '+
'checkdate checkdnsrr chgrp chmod chop chown chr chroot chunk_split class_exists '+
'closedir closelog copy cos cosh count count_chars date decbin dechex decoct '+
'deg2rad delete ebcdic2ascii echo empty end ereg ereg_replace eregi eregi_replace error_log '+
'error_reporting escapeshellarg escapeshellcmd eval exec exit exp explode extension_loaded '+
'feof fflush fgetc fgetcsv fgets fgetss file_exists file_get_contents file_put_contents '+
'fileatime filectime filegroup fileinode filemtime fileowner fileperms filesize filetype '+
'floatval flock floor flush fmod fnmatch fopen fpassthru fprintf fputcsv fputs fread fscanf '+
'fseek fsockopen fstat ftell ftok getallheaders getcwd getdate getenv gethostbyaddr gethostbyname '+
'gethostbynamel getimagesize getlastmod getmxrr getmygid getmyinode getmypid getmyuid getopt '+
'getprotobyname getprotobynumber getrandmax getrusage getservbyname getservbyport gettext '+
'gettimeofday gettype glob gmdate gmmktime ini_alter ini_get ini_get_all ini_restore ini_set '+
'interface_exists intval ip2long is_a is_array is_bool is_callable is_dir is_double '+
'is_executable is_file is_finite is_float is_infinite is_int is_integer is_link is_long '+
'is_nan is_null is_numeric is_object is_readable is_real is_resource is_scalar is_soap_fault '+
'is_string is_subclass_of is_uploaded_file is_writable is_writeable mkdir mktime nl2br '+
'parse_ini_file parse_str parse_url passthru pathinfo readlink realpath rewind rewinddir rmdir '+
'round str_ireplace str_pad str_repeat str_replace str_rot13 str_shuffle str_split '+
'str_word_count strcasecmp strchr strcmp strcoll strcspn strftime strip_tags stripcslashes '+
'stripos stripslashes stristr strlen strnatcasecmp strnatcmp strncasecmp strncmp strpbrk '+
'strpos strptime strrchr strrev strripos strrpos strspn strstr strtok strtolower strtotime '+
'strtoupper strtr strval substr substr_compare';
var keywords = 'and or xor __FILE__ __LINE__ array as break case ' +
'cfunction class const continue declare default die do else ' +
'elseif empty enddeclare endfor endforeach endif endswitch endwhile ' +
'extends for foreach function include include_once global if ' +
'new old_function return static switch use require require_once ' +
'var while __FUNCTION__ __CLASS__ ' +
'__METHOD__ abstract interface public implements extends private protected throw';
this.regexList = [
{ regex: dp.sh.RegexLib.SingleLineCComments, css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.MultiLineCComments, css: 'comment' }, // multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp('\\$\\w+', 'g'), css: 'vars' }, // variables
{ regex: new RegExp(this.GetKeywords(funcs), 'gmi'), css: 'func' }, // functions
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' } // keyword
];
this.CssClass = 'dp-c';
}
dp.sh.Brushes.Php.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Php.Aliases = ['php'];
dp.sh.Brushes.JScript = function()
{
var keywords = 'abstract boolean break byte case catch char class const continue debugger ' +
'default delete do double else enum export extends false final finally float ' +
'for function goto if implements import in instanceof int interface long native ' +
'new null package private protected public return short static super switch ' +
'synchronized this throw throws transient true try typeof var void volatile while with';
this.regexList = [
{ regex: dp.sh.RegexLib.SingleLineCComments, css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.MultiLineCComments, css: 'comment' }, // multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp('^\\s*#.*', 'gm'), css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' } // keywords
];
this.CssClass = 'dp-c';
}
dp.sh.Brushes.JScript.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.JScript.Aliases = ['js', 'jscript', 'javascript'];
dp.sh.Brushes.Java = function()
{
var keywords = 'abstract assert boolean break byte case catch char class const ' +
'continue default do double else enum extends ' +
'false final finally float for goto if implements import ' +
'instanceof int interface long native new null ' +
'package private protected public return ' +
'short static strictfp super switch synchronized this throw throws true ' +
'transient try void volatile while';
this.regexList = [
{ regex: dp.sh.RegexLib.SingleLineCComments, css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.MultiLineCComments, css: 'comment' }, // multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // strings
{ regex: new RegExp('\\b([\\d]+(\\.[\\d]+)?|0x[a-f0-9]+)\\b', 'gi'), css: 'number' }, // numbers
{ regex: new RegExp('(?!\\@interface\\b)\\@[\\$\\w]+\\b', 'g'), css: 'annotation' }, // annotation @anno
{ regex: new RegExp('\\@interface\\b', 'g'), css: 'keyword' }, // @interface keyword
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' } // java keyword
];
this.CssClass = 'dp-j';
this.Style = '.dp-j .annotation { color: #646464; }' +
'.dp-j .number { color: #C00000; }';
}
dp.sh.Brushes.Java.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Java.Aliases = ['java'];
/* Delphi brush is contributed by Eddie Shipman */
dp.sh.Brushes.Delphi = function()
{
var keywords = 'abs addr and ansichar ansistring array as asm begin boolean byte cardinal ' +
'case char class comp const constructor currency destructor div do double ' +
'downto else end except exports extended false file finalization finally ' +
'for function goto if implementation in inherited int64 initialization ' +
'integer interface is label library longint longword mod nil not object ' +
'of on or packed pansichar pansistring pchar pcurrency pdatetime pextended ' +
'pint64 pointer private procedure program property pshortstring pstring ' +
'pvariant pwidechar pwidestring protected public published raise real real48 ' +
'record repeat set shl shortint shortstring shr single smallint string then ' +
'threadvar to true try type unit until uses val var varirnt while widechar ' +
'widestring with word write writeln xor';
this.regexList = [
{ regex: new RegExp('\\(\\*[\\s\\S]*?\\*\\)', 'gm'), css: 'comment' }, // multiline comments (* *)
{ regex: new RegExp('{(?!\\$)[\\s\\S]*?}', 'gm'), css: 'comment' }, // multiline comments { }
{ regex: dp.sh.RegexLib.SingleLineCComments, css: 'comment' }, // one line
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // strings
{ regex: new RegExp('\\{\\$[a-zA-Z]+ .+\\}', 'g'), css: 'directive' }, // Compiler Directives and Region tags
{ regex: new RegExp('\\b[\\d\\.]+\\b', 'g'), css: 'number' }, // numbers 12345
{ regex: new RegExp('\\$[a-zA-Z0-9]+\\b', 'g'), css: 'number' }, // numbers $F5D3
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' } // keyword
];
this.CssClass = 'dp-delphi';
this.Style = '.dp-delphi .number { color: blue; }' +
'.dp-delphi .directive { color: #008284; }' +
'.dp-delphi .vars { color: #000; }';
}
dp.sh.Brushes.Delphi.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Delphi.Aliases = ['delphi', 'pascal'];
dp.sh.Brushes.CSS = function()
{
var keywords = 'ascent azimuth background-attachment background-color background-image background-position ' +
'background-repeat background baseline bbox border-collapse border-color border-spacing border-style border-top ' +
'border-right border-bottom border-left border-top-color border-right-color border-bottom-color border-left-color ' +
'border-top-style border-right-style border-bottom-style border-left-style border-top-width border-right-width ' +
'border-bottom-width border-left-width border-width border bottom cap-height caption-side centerline clear clip color ' +
'content counter-increment counter-reset cue-after cue-before cue cursor definition-src descent direction display ' +
'elevation empty-cells float font-size-adjust font-family font-size font-stretch font-style font-variant font-weight font ' +
'height letter-spacing line-height list-style-image list-style-position list-style-type list-style margin-top ' +
'margin-right margin-bottom margin-left margin marker-offset marks mathline max-height max-width min-height min-width orphans ' +
'outline-color outline-style outline-width outline overflow padding-top padding-right padding-bottom padding-left padding page ' +
'page-break-after page-break-before page-break-inside pause pause-after pause-before pitch pitch-range play-during position ' +
'quotes richness right size slope src speak-header speak-numeral speak-punctuation speak speech-rate stemh stemv stress ' +
'table-layout text-align text-decoration text-indent text-shadow text-transform unicode-bidi unicode-range units-per-em ' +
'vertical-align visibility voice-family volume white-space widows width widths word-spacing x-height z-index important';
var values = 'above absolute all always aqua armenian attr aural auto avoid baseline behind below bidi-override black blink block blue bold bolder '+
'both bottom braille capitalize caption center center-left center-right circle close-quote code collapse compact condensed '+
'continuous counter counters crop cross crosshair cursive dashed decimal decimal-leading-zero default digits disc dotted double '+
'embed embossed e-resize expanded extra-condensed extra-expanded fantasy far-left far-right fast faster fixed format fuchsia '+
'gray green groove handheld hebrew help hidden hide high higher icon inline-table inline inset inside invert italic '+
'justify landscape large larger left-side left leftwards level lighter lime line-through list-item local loud lower-alpha '+
'lowercase lower-greek lower-latin lower-roman lower low ltr marker maroon medium message-box middle mix move narrower '+
'navy ne-resize no-close-quote none no-open-quote no-repeat normal nowrap n-resize nw-resize oblique olive once open-quote outset '+
'outside overline pointer portrait pre print projection purple red relative repeat repeat-x repeat-y rgb ridge right right-side '+
'rightwards rtl run-in screen scroll semi-condensed semi-expanded separate se-resize show silent silver slower slow '+
'small small-caps small-caption smaller soft solid speech spell-out square s-resize static status-bar sub super sw-resize '+
'table-caption table-cell table-column table-column-group table-footer-group table-header-group table-row table-row-group teal '+
'text-bottom text-top thick thin top transparent tty tv ultra-condensed ultra-expanded underline upper-alpha uppercase upper-latin '+
'upper-roman url visible wait white wider w-resize x-fast x-high x-large x-loud x-low x-slow x-small x-soft xx-large xx-small yellow';
var fonts = '[mM]onospace [tT]ahoma [vV]erdana [aA]rial [hH]elvetica [sS]ans-serif [sS]erif';
this.regexList = [
{ regex: dp.sh.RegexLib.MultiLineCComments, css: 'comment' }, // multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // double quoted strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // single quoted strings
{ regex: new RegExp('\\#[a-zA-Z0-9]{3,6}', 'g'), css: 'colors' }, // html colors
{ regex: new RegExp('(\\d+)(px|pt|\:)', 'g'), css: 'string' }, // size specifications
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' }, // keywords
{ regex: new RegExp(this.GetKeywords(values), 'g'), css: 'string' }, // values
{ regex: new RegExp(this.GetKeywords(fonts), 'g'), css: 'string' } // fonts
];
this.CssClass = 'dp-css';
this.Style = '.dp-css .colors { color: darkred; }' +
'.dp-css .vars { color: #d00; }';
}
dp.sh.Brushes.CSS.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.CSS.Aliases = ['css'];
dp.sh.Brushes.CSharp = function()
{
var keywords = 'abstract as base bool break byte case catch char checked class const ' +
'continue decimal default delegate do double else enum event explicit ' +
'extern false finally fixed float for foreach get goto if implicit in int ' +
'interface internal is lock long namespace new null object operator out ' +
'override params private protected public readonly ref return sbyte sealed set ' +
'short sizeof stackalloc static string struct switch this throw true try ' +
'typeof uint ulong unchecked unsafe ushort using virtual void while';
this.regexList = [
// There's a slight problem with matching single line comments and figuring out
// a difference between // and ///. Using lookahead and lookbehind solves the
// problem, unfortunately JavaScript doesn't support lookbehind. So I'm at a
// loss how to translate that regular expression to JavaScript compatible one.
// { regex: new RegExp('(?<!/)//(?!/).*$|(?<!/)////(?!/).*$|/\\*[^\\*]*(.)*?\\*/', 'gm'), css: 'comment' }, // one line comments starting with anything BUT '///' and multiline comments
// { regex: new RegExp('(?<!/)///(?!/).*$', 'gm'), css: 'comments' }, // XML comments starting with ///
{ regex: dp.sh.RegexLib.SingleLineCComments, css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.MultiLineCComments, css: 'comment' }, // multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // strings
{ regex: new RegExp('^\\s*#.*', 'gm'), css: 'preprocessor' }, // preprocessor tags like #region and #endregion
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' } // c# keyword
];
this.CssClass = 'dp-c';
this.Style = '.dp-c .vars { color: #d00; }';
}
dp.sh.Brushes.CSharp.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.CSharp.Aliases = ['c#', 'c-sharp', 'csharp'];
dp.sh.Brushes.Cpp = function()
{
var datatypes =
'ATOM BOOL BOOLEAN BYTE CHAR COLORREF DWORD DWORDLONG DWORD_PTR ' +
'DWORD32 DWORD64 FLOAT HACCEL HALF_PTR HANDLE HBITMAP HBRUSH ' +
'HCOLORSPACE HCONV HCONVLIST HCURSOR HDC HDDEDATA HDESK HDROP HDWP ' +
'HENHMETAFILE HFILE HFONT HGDIOBJ HGLOBAL HHOOK HICON HINSTANCE HKEY ' +
'HKL HLOCAL HMENU HMETAFILE HMODULE HMONITOR HPALETTE HPEN HRESULT ' +
'HRGN HRSRC HSZ HWINSTA HWND INT INT_PTR INT32 INT64 LANGID LCID LCTYPE ' +
'LGRPID LONG LONGLONG LONG_PTR LONG32 LONG64 LPARAM LPBOOL LPBYTE LPCOLORREF ' +
'LPCSTR LPCTSTR LPCVOID LPCWSTR LPDWORD LPHANDLE LPINT LPLONG LPSTR LPTSTR ' +
'LPVOID LPWORD LPWSTR LRESULT PBOOL PBOOLEAN PBYTE PCHAR PCSTR PCTSTR PCWSTR ' +
'PDWORDLONG PDWORD_PTR PDWORD32 PDWORD64 PFLOAT PHALF_PTR PHANDLE PHKEY PINT ' +
'PINT_PTR PINT32 PINT64 PLCID PLONG PLONGLONG PLONG_PTR PLONG32 PLONG64 POINTER_32 ' +
'POINTER_64 PSHORT PSIZE_T PSSIZE_T PSTR PTBYTE PTCHAR PTSTR PUCHAR PUHALF_PTR ' +
'PUINT PUINT_PTR PUINT32 PUINT64 PULONG PULONGLONG PULONG_PTR PULONG32 PULONG64 ' +
'PUSHORT PVOID PWCHAR PWORD PWSTR SC_HANDLE SC_LOCK SERVICE_STATUS_HANDLE SHORT ' +
'SIZE_T SSIZE_T TBYTE TCHAR UCHAR UHALF_PTR UINT UINT_PTR UINT32 UINT64 ULONG ' +
'ULONGLONG ULONG_PTR ULONG32 ULONG64 USHORT USN VOID WCHAR WORD WPARAM WPARAM WPARAM ' +
'char bool short int __int32 __int64 __int8 __int16 long float double __wchar_t ' +
'clock_t _complex _dev_t _diskfree_t div_t ldiv_t _exception _EXCEPTION_POINTERS ' +
'FILE _finddata_t _finddatai64_t _wfinddata_t _wfinddatai64_t __finddata64_t ' +
'__wfinddata64_t _FPIEEE_RECORD fpos_t _HEAPINFO _HFILE lconv intptr_t ' +
'jmp_buf mbstate_t _off_t _onexit_t _PNH ptrdiff_t _purecall_handler ' +
'sig_atomic_t size_t _stat __stat64 _stati64 terminate_function ' +
'time_t __time64_t _timeb __timeb64 tm uintptr_t _utimbuf ' +
'va_list wchar_t wctrans_t wctype_t wint_t signed TRUE FALSE';
var keywords =
'break case catch class const __finally __exception __try ' +
'const_cast continue private public protected __declspec ' +
'default delete deprecated dllexport dllimport do dynamic_cast ' +
'else enum explicit extern if for friend goto inline ' +
'mutable naked namespace new noinline noreturn nothrow ' +
'register reinterpret_cast return selectany ' +
'sizeof static static_cast struct switch template this ' +
'thread throw true false try typedef typeid typename union ' +
'using uuid virtual void volatile whcar_t while';
this.regexList = [
{ regex: dp.sh.RegexLib.SingleLineCComments, css: 'comment' }, // one line comments
{ regex: dp.sh.RegexLib.MultiLineCComments, css: 'comment' }, // multiline comments
{ regex: dp.sh.RegexLib.DoubleQuotedString, css: 'string' }, // strings
{ regex: dp.sh.RegexLib.SingleQuotedString, css: 'string' }, // strings
{ regex: new RegExp('^ *#.*', 'gm'), css: 'preprocessor' },
{ regex: new RegExp(this.GetKeywords(datatypes), 'gm'), css: 'datatypes' },
{ regex: new RegExp(this.GetKeywords(keywords), 'gm'), css: 'keyword' }
];
this.CssClass = 'dp-cpp';
this.Style = '.dp-cpp .datatypes { color: #2E8B57; font-weight: bold; }';
}
dp.sh.Brushes.Cpp.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.Cpp.Aliases = ['cpp', 'c', 'c++']; | JavaScript |
function $(id)
{
return document.getElementById(id);
}
function copyIdText(id)
{
copy( $(id).innerText,$(id) );
}
function copyIdHtml(id)
{
copy( $(id).innerHTML,$(id) );
}
function copy(txt,obj)
{
if(window.clipboardData)
{
window.clipboardData.clearData();
window.clipboardData.setData("Text", txt);
alert("复制成功!")
if(obj.style.display != 'none'){
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.scrollIntoView();
rng.select();
rng.collapse(false);
}
}
else
alert("请选中文本 , 使用 Ctrl + C 复制!");
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is a sample implementation for a custom Data Processor for basic BBCode.
*/
FCK.DataProcessor =
{
/*
* Returns a string representing the HTML format of "data". The returned
* value will be loaded in the editor.
* The HTML must be from <html> to </html>, eventually including
* the DOCTYPE.
* @param {String} data The data to be converted in the
* DataProcessor specific format.
*/
ConvertToHtml : function( data )
{
// Convert < and > to their HTML entities.
data = data.replace( /</g, '<' ) ;
data = data.replace( />/g, '>' ) ;
// Convert line breaks to <br>.
data = data.replace( /(?:\r\n|\n|\r)/g, '<br>' ) ;
// [url]
data = data.replace( /\[url\](.+?)\[\/url]/gi, '<a href="$1">$1</a>' ) ;
data = data.replace( /\[url\=([^\]]+)](.+?)\[\/url]/gi, '<a href="$1">$2</a>' ) ;
// [b]
data = data.replace( /\[b\](.+?)\[\/b]/gi, '<b>$1</b>' ) ;
// [i]
data = data.replace( /\[i\](.+?)\[\/i]/gi, '<i>$1</i>' ) ;
// [u]
data = data.replace( /\[u\](.+?)\[\/u]/gi, '<u>$1</u>' ) ;
return '<html><head><title></title></head><body>' + data + '</body></html>' ;
},
/*
* Converts a DOM (sub-)tree to a string in the data format.
* @param {Object} rootNode The node that contains the DOM tree to be
* converted to the data format.
* @param {Boolean} excludeRoot Indicates that the root node must not
* be included in the conversion, only its children.
* @param {Boolean} format Indicates that the data must be formatted
* for human reading. Not all Data Processors may provide it.
*/
ConvertToDataFormat : function( rootNode, excludeRoot, ignoreIfEmptyParagraph, format )
{
var data = rootNode.innerHTML ;
// Convert <br> to line breaks.
data = data.replace( /<br(?=[ \/>]).*?>/gi, '\r\n') ;
// [url]
data = data.replace( /<a .*?href=(["'])(.+?)\1.*?>(.+?)<\/a>/gi, '[url=$2]$3[/url]') ;
// [b]
data = data.replace( /<(?:b|strong)>/gi, '[b]') ;
data = data.replace( /<\/(?:b|strong)>/gi, '[/b]') ;
// [i]
data = data.replace( /<(?:i|em)>/gi, '[i]') ;
data = data.replace( /<\/(?:i|em)>/gi, '[/i]') ;
// [u]
data = data.replace( /<u>/gi, '[u]') ;
data = data.replace( /<\/u>/gi, '[/u]') ;
// Remove remaining tags.
data = data.replace( /<[^>]+>/g, '') ;
return data ;
},
/*
* Makes any necessary changes to a piece of HTML for insertion in the
* editor selection position.
* @param {String} html The HTML to be fixed.
*/
FixHtml : function( html )
{
return html ;
}
} ;
// This Data Processor doesn't support <p>, so let's use <br>.
FCKConfig.EnterMode = 'br' ;
// To avoid pasting invalid markup (which is discarded in any case), let's
// force pasting to plain text.
FCKConfig.ForcePasteAsPlainText = true ;
// Rename the "Source" buttom to "BBCode".
FCKToolbarItems.RegisterItem( 'Source', new FCKToolbarButton( 'Source', 'BBCode', null, FCK_TOOLBARITEM_ICONTEXT, true, true, 1 ) ) ;
// Let's enforce the toolbar to the limits of this Data Processor. A custom
// toolbar set may be defined in the configuration file with more or less entries.
FCKConfig.ToolbarSets["Default"] = [
['Source'],
['Bold','Italic','Underline','-','Link'],
['About']
] ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Sample custom configuration settings used by the BBCode plugin. It simply
* loads the plugin. All the rest is done by the plugin itself.
*/
// Add the BBCode plugin.
FCKConfig.Plugins.Add( 'bbcode' ) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This plugin register the required Toolbar items to be able to insert the
* table commands in the toolbar.
*/
FCKToolbarItems.RegisterItem( 'TableInsertRowAfter' , new FCKToolbarButton( 'TableInsertRowAfter' , FCKLang.InsertRowAfter, null, null, null, true, 62 ) ) ;
FCKToolbarItems.RegisterItem( 'TableDeleteRows' , new FCKToolbarButton( 'TableDeleteRows' , FCKLang.DeleteRows, null, null, null, true, 63 ) ) ;
FCKToolbarItems.RegisterItem( 'TableInsertColumnAfter' , new FCKToolbarButton( 'TableInsertColumnAfter' , FCKLang.InsertColumnAfter, null, null, null, true, 64 ) ) ;
FCKToolbarItems.RegisterItem( 'TableDeleteColumns' , new FCKToolbarButton( 'TableDeleteColumns', FCKLang.DeleteColumns, null, null, null, true, 65 ) ) ;
FCKToolbarItems.RegisterItem( 'TableInsertCellAfter' , new FCKToolbarButton( 'TableInsertCellAfter' , FCKLang.InsertCellAfter, null, null, null, true, 58 ) ) ;
FCKToolbarItems.RegisterItem( 'TableDeleteCells' , new FCKToolbarButton( 'TableDeleteCells' , FCKLang.DeleteCells, null, null, null, true, 59 ) ) ;
FCKToolbarItems.RegisterItem( 'TableMergeCells' , new FCKToolbarButton( 'TableMergeCells' , FCKLang.MergeCells, null, null, null, true, 60 ) ) ;
FCKToolbarItems.RegisterItem( 'TableHorizontalSplitCell' , new FCKToolbarButton( 'TableHorizontalSplitCell' , FCKLang.SplitCell, null, null, null, true, 61 ) ) ;
FCKToolbarItems.RegisterItem( 'TableCellProp' , new FCKToolbarButton( 'TableCellProp' , FCKLang.CellProperties, null, null, null, true, 57 ) ) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This plugin register Toolbar items for the combos modifying the style to
* not show the box.
*/
FCKToolbarItems.RegisterItem( 'SourceSimple' , new FCKToolbarButton( 'Source', FCKLang.Source, null, FCK_TOOLBARITEM_ONLYICON, true, true, 1 ) ) ;
FCKToolbarItems.RegisterItem( 'StyleSimple' , new FCKToolbarStyleCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
FCKToolbarItems.RegisterItem( 'FontNameSimple' , new FCKToolbarFontsCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
FCKToolbarItems.RegisterItem( 'FontSizeSimple' , new FCKToolbarFontSizeCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
FCKToolbarItems.RegisterItem( 'FontFormatSimple', new FCKToolbarFontFormatCombo( null, FCK_TOOLBARITEM_ONLYTEXT ) ) ;
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Common objects and functions shared by all pages that compose the
* File Browser dialog window.
*/
// Automatically detect the correct document.domain (#1919).
(function()
{
var d = document.domain ;
while ( true )
{
// Test if we can access a parent property.
try
{
var test = window.top.opener.document.domain ;
break ;
}
catch( e )
{}
// Remove a domain part: www.mytest.example.com => mytest.example.com => example.com ...
d = d.replace( /.*?(?:\.|$)/, '' ) ;
if ( d.length == 0 )
break ; // It was not able to detect the domain.
try
{
document.domain = d ;
}
catch (e)
{
break ;
}
}
})() ;
function AddSelectOption( selectElement, optionText, optionValue )
{
var oOption = document.createElement("OPTION") ;
oOption.text = optionText ;
oOption.value = optionValue ;
selectElement.options.add(oOption) ;
return oOption ;
}
var oConnector = window.parent.oConnector ;
var oIcons = window.parent.oIcons ;
function StringBuilder( value )
{
this._Strings = new Array( value || '' ) ;
}
StringBuilder.prototype.Append = function( value )
{
if ( value )
this._Strings.push( value ) ;
}
StringBuilder.prototype.ToString = function()
{
return this._Strings.join( '' ) ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKXml object that is used for XML data calls
* and XML processing.
*
* This script is shared by almost all pages that compose the
* File Browser frameset.
*/
var FCKXml = function()
{}
FCKXml.prototype.GetHttpRequest = function()
{
// Gecko / IE7
try { return new XMLHttpRequest(); }
catch(e) {}
// IE6
try { return new ActiveXObject( 'Msxml2.XMLHTTP' ) ; }
catch(e) {}
// IE5
try { return new ActiveXObject( 'Microsoft.XMLHTTP' ) ; }
catch(e) {}
return null ;
}
FCKXml.prototype.LoadUrl = function( urlToCall, asyncFunctionPointer )
{
var oFCKXml = this ;
var bAsync = ( typeof(asyncFunctionPointer) == 'function' ) ;
var oXmlHttp = this.GetHttpRequest() ;
oXmlHttp.open( "GET", urlToCall, bAsync ) ;
if ( bAsync )
{
oXmlHttp.onreadystatechange = function()
{
if ( oXmlHttp.readyState == 4 )
{
var oXml ;
try
{
// this is the same test for an FF2 bug as in fckxml_gecko.js
// but we've moved the responseXML assignment into the try{}
// so we don't even have to check the return status codes.
var test = oXmlHttp.responseXML.firstChild ;
oXml = oXmlHttp.responseXML ;
}
catch ( e )
{
try
{
oXml = (new DOMParser()).parseFromString( oXmlHttp.responseText, 'text/xml' ) ;
}
catch ( e ) {}
}
if ( !oXml || !oXml.firstChild || oXml.firstChild.nodeName == 'parsererror' )
{
alert( 'The server didn\'t send back a proper XML response. Please contact your system administrator.\n\n' +
'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')\n\n' +
'Requested URL:\n' + urlToCall + '\n\n' +
'Response text:\n' + oXmlHttp.responseText ) ;
return ;
}
oFCKXml.DOMDocument = oXml ;
asyncFunctionPointer( oFCKXml ) ;
}
}
}
oXmlHttp.send( null ) ;
if ( ! bAsync )
{
if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 )
this.DOMDocument = oXmlHttp.responseXML ;
else
{
alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ;
}
}
}
FCKXml.prototype.SelectNodes = function( xpath )
{
if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE
return this.DOMDocument.selectNodes( xpath ) ;
else // Gecko
{
var aNodeArray = new Array();
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument,
this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
if ( xPathResult )
{
var oNode = xPathResult.iterateNext() ;
while( oNode )
{
aNodeArray[aNodeArray.length] = oNode ;
oNode = xPathResult.iterateNext();
}
}
return aNodeArray ;
}
}
FCKXml.prototype.SelectSingleNode = function( xpath )
{
if ( navigator.userAgent.indexOf('MSIE') >= 0 ) // IE
return this.DOMDocument.selectSingleNode( xpath ) ;
else // Gecko
{
var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument,
this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null);
if ( xPathResult && xPathResult.singleNodeValue )
return xPathResult.singleNodeValue ;
else
return null ;
}
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* This is the integration file for JavaScript.
*
* It defines the FCKeditor class that can be used to create editor
* instances in a HTML page in the client side. For server side
* operations, use the specific integration system.
*/
// FCKeditor Class
var FCKeditor = function( instanceName, width, height, toolbarSet, value )
{
// Properties
this.InstanceName = instanceName ;
this.Width = width || '100%' ;
this.Height = height || '200' ;
this.ToolbarSet = toolbarSet || 'Default' ;
this.Value = value || '' ;
this.BasePath = FCKeditor.BasePath ;
this.CheckBrowser = true ;
this.DisplayErrors = true ;
this.Config = new Object() ;
// Events
this.OnError = null ; // function( source, errorNumber, errorDescription )
}
/**
* This is the default BasePath used by all editor instances.
*/
FCKeditor.BasePath = '/fckeditor/' ;
/**
* The minimum height used when replacing textareas.
*/
FCKeditor.MinHeight = 200 ;
/**
* The minimum width used when replacing textareas.
*/
FCKeditor.MinWidth = 750 ;
FCKeditor.prototype.Version = '2.6.3' ;
FCKeditor.prototype.VersionBuild = '19836' ;
FCKeditor.prototype.Create = function()
{
document.write( this.CreateHtml() ) ;
}
FCKeditor.prototype.CreateHtml = function()
{
// Check for errors
if ( !this.InstanceName || this.InstanceName.length == 0 )
{
this._ThrowError( 701, 'You must specify an instance name.' ) ;
return '' ;
}
var sHtml = '' ;
if ( !this.CheckBrowser || this._IsCompatibleBrowser() )
{
sHtml += '<input type="hidden" id="' + this.InstanceName + '" name="' + this.InstanceName + '" value="' + this._HTMLEncode( this.Value ) + '" style="display:none" />' ;
sHtml += this._GetConfigHtml() ;
sHtml += this._GetIFrameHtml() ;
}
else
{
var sWidth = this.Width.toString().indexOf('%') > 0 ? this.Width : this.Width + 'px' ;
var sHeight = this.Height.toString().indexOf('%') > 0 ? this.Height : this.Height + 'px' ;
sHtml += '<textarea name="' + this.InstanceName +
'" rows="4" cols="40" style="width:' + sWidth +
';height:' + sHeight ;
if ( this.TabIndex )
sHtml += '" tabindex="' + this.TabIndex ;
sHtml += '">' +
this._HTMLEncode( this.Value ) +
'<\/textarea>' ;
}
return sHtml ;
}
FCKeditor.prototype.ReplaceTextarea = function()
{
if ( !this.CheckBrowser || this._IsCompatibleBrowser() )
{
// We must check the elements firstly using the Id and then the name.
var oTextarea = document.getElementById( this.InstanceName ) ;
var colElementsByName = document.getElementsByName( this.InstanceName ) ;
var i = 0;
while ( oTextarea || i == 0 )
{
if ( oTextarea && oTextarea.tagName.toLowerCase() == 'textarea' )
break ;
oTextarea = colElementsByName[i++] ;
}
if ( !oTextarea )
{
alert( 'Error: The TEXTAREA with id or name set to "' + this.InstanceName + '" was not found' ) ;
return ;
}
oTextarea.style.display = 'none' ;
if ( oTextarea.tabIndex )
this.TabIndex = oTextarea.tabIndex ;
this._InsertHtmlBefore( this._GetConfigHtml(), oTextarea ) ;
this._InsertHtmlBefore( this._GetIFrameHtml(), oTextarea ) ;
}
}
FCKeditor.prototype._InsertHtmlBefore = function( html, element )
{
if ( element.insertAdjacentHTML ) // IE
element.insertAdjacentHTML( 'beforeBegin', html ) ;
else // Gecko
{
var oRange = document.createRange() ;
oRange.setStartBefore( element ) ;
var oFragment = oRange.createContextualFragment( html );
element.parentNode.insertBefore( oFragment, element ) ;
}
}
FCKeditor.prototype._GetConfigHtml = function()
{
var sConfig = '' ;
for ( var o in this.Config )
{
if ( sConfig.length > 0 ) sConfig += '&' ;
sConfig += encodeURIComponent( o ) + '=' + encodeURIComponent( this.Config[o] ) ;
}
return '<input type="hidden" id="' + this.InstanceName + '___Config" value="' + sConfig + '" style="display:none" />' ;
}
FCKeditor.prototype._GetIFrameHtml = function()
{
var sFile = 'fckeditor.html' ;
try
{
if ( (/fcksource=true/i).test( window.top.location.search ) )
sFile = 'fckeditor.original.html' ;
}
catch (e) { /* Ignore it. Much probably we are inside a FRAME where the "top" is in another domain (security error). */ }
var sLink = this.BasePath + 'editor/' + sFile + '?InstanceName=' + encodeURIComponent( this.InstanceName ) ;
if (this.ToolbarSet)
sLink += '&Toolbar=' + this.ToolbarSet ;
html = '<iframe id="' + this.InstanceName +
'___Frame" src="' + sLink +
'" width="' + this.Width +
'" height="' + this.Height ;
if ( this.TabIndex )
html += '" tabindex="' + this.TabIndex ;
html += '" frameborder="0" scrolling="no"></iframe>' ;
return html ;
}
FCKeditor.prototype._IsCompatibleBrowser = function()
{
return FCKeditor_IsCompatibleBrowser() ;
}
FCKeditor.prototype._ThrowError = function( errorNumber, errorDescription )
{
this.ErrorNumber = errorNumber ;
this.ErrorDescription = errorDescription ;
if ( this.DisplayErrors )
{
document.write( '<div style="COLOR: #ff0000">' ) ;
document.write( '[ FCKeditor Error ' + this.ErrorNumber + ': ' + this.ErrorDescription + ' ]' ) ;
document.write( '</div>' ) ;
}
if ( typeof( this.OnError ) == 'function' )
this.OnError( this, errorNumber, errorDescription ) ;
}
FCKeditor.prototype._HTMLEncode = function( text )
{
if ( typeof( text ) != "string" )
text = text.toString() ;
text = text.replace(
/&/g, "&").replace(
/"/g, """).replace(
/</g, "<").replace(
/>/g, ">") ;
return text ;
}
;(function()
{
var textareaToEditor = function( textarea )
{
var editor = new FCKeditor( textarea.name ) ;
editor.Width = Math.max( textarea.offsetWidth, FCKeditor.MinWidth ) ;
editor.Height = Math.max( textarea.offsetHeight, FCKeditor.MinHeight ) ;
return editor ;
}
/**
* Replace all <textarea> elements available in the document with FCKeditor
* instances.
*
* // Replace all <textarea> elements in the page.
* FCKeditor.ReplaceAllTextareas() ;
*
* // Replace all <textarea class="myClassName"> elements in the page.
* FCKeditor.ReplaceAllTextareas( 'myClassName' ) ;
*
* // Selectively replace <textarea> elements, based on custom assertions.
* FCKeditor.ReplaceAllTextareas( function( textarea, editor )
* {
* // Custom code to evaluate the replace, returning false if it
* // must not be done.
* // It also passes the "editor" parameter, so the developer can
* // customize the instance.
* } ) ;
*/
FCKeditor.ReplaceAllTextareas = function()
{
var textareas = document.getElementsByTagName( 'textarea' ) ;
for ( var i = 0 ; i < textareas.length ; i++ )
{
var editor = null ;
var textarea = textareas[i] ;
var name = textarea.name ;
// The "name" attribute must exist.
if ( !name || name.length == 0 )
continue ;
if ( typeof arguments[0] == 'string' )
{
// The textarea class name could be passed as the function
// parameter.
var classRegex = new RegExp( '(?:^| )' + arguments[0] + '(?:$| )' ) ;
if ( !classRegex.test( textarea.className ) )
continue ;
}
else if ( typeof arguments[0] == 'function' )
{
// An assertion function could be passed as the function parameter.
// It must explicitly return "false" to ignore a specific <textarea>.
editor = textareaToEditor( textarea ) ;
if ( arguments[0]( textarea, editor ) === false )
continue ;
}
if ( !editor )
editor = textareaToEditor( textarea ) ;
editor.ReplaceTextarea() ;
}
}
})() ;
function FCKeditor_IsCompatibleBrowser()
{
var sAgent = navigator.userAgent.toLowerCase() ;
// Internet Explorer 5.5+
if ( /*@cc_on!@*/false && sAgent.indexOf("mac") == -1 )
{
var sBrowserVersion = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
return ( sBrowserVersion >= 5.5 ) ;
}
// Gecko (Opera 9 tries to behave like Gecko at this point).
if ( navigator.product == "Gecko" && navigator.productSub >= 20030210 && !( typeof(opera) == 'object' && opera.postError ) )
return true ;
// Opera 9.50+
if ( window.opera && window.opera.version && parseFloat( window.opera.version() ) >= 9.5 )
return true ;
// Adobe AIR
// Checked before Safari because AIR have the WebKit rich text editor
// features from Safari 3.0.4, but the version reported is 420.
if ( sAgent.indexOf( ' adobeair/' ) != -1 )
return ( sAgent.match( / adobeair\/(\d+)/ )[1] >= 1 ) ; // Build must be at least v1
// Safari 3+
if ( sAgent.indexOf( ' applewebkit/' ) != -1 )
return ( sAgent.match( / applewebkit\/(\d+)/ )[1] >= 522 ) ; // Build must be at least 522 (v3)
return false ;
}
| JavaScript |
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Editor configuration settings.
*
* Follow this link for more information:
* http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options
*/
FCKConfig.CustomConfigurationsPath = '' ;
FCKConfig.EditorAreaCSS = FCKConfig.BasePath + 'css/fck_editorarea.css' ;
FCKConfig.EditorAreaStyles = '' ;
FCKConfig.ToolbarComboPreviewCSS = '' ;
FCKConfig.DocType = '' ;
FCKConfig.BaseHref = '' ;
FCKConfig.FullPage = false ;
// The following option determines whether the "Show Blocks" feature is enabled or not at startup.
FCKConfig.StartupShowBlocks = false ;
FCKConfig.Debug = false ;
FCKConfig.AllowQueryStringDebug = true ;
FCKConfig.SkinPath = FCKConfig.BasePath + 'skins/default/' ;
FCKConfig.SkinEditorCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.SkinDialogCSS = '' ; // FCKConfig.SkinPath + "|<minified css>" ;
FCKConfig.PreloadImages = [ FCKConfig.SkinPath + 'images/toolbar.start.gif', FCKConfig.SkinPath + 'images/toolbar.buttonarrow.gif' ] ;
FCKConfig.PluginsPath = FCKConfig.BasePath + 'plugins/' ;
FCKConfig.Plugins.Add( 'insertcodeRun' ) ;
// FCKConfig.Plugins.Add( 'autogrow' ) ;
// FCKConfig.Plugins.Add( 'dragresizetable' );
FCKConfig.AutoGrowMax = 400 ;
// FCKConfig.ProtectedSource.Add( /<%[\s\S]*?%>/g ) ; // ASP style server side code <%...%>
// FCKConfig.ProtectedSource.Add( /<\?[\s\S]*?\?>/g ) ; // PHP style server side code
// FCKConfig.ProtectedSource.Add( /(<asp:[^\>]+>[\s|\S]*?<\/asp:[^\>]+>)|(<asp:[^\>]+\/>)/gi ) ; // ASP.Net style tags <asp:control>
FCKConfig.AutoDetectLanguage = true ;
FCKConfig.DefaultLanguage = 'zh-cn' ;
FCKConfig.ContentLangDirection = 'zh-cn' ;
FCKConfig.ProcessHTMLEntities = true ;
FCKConfig.IncludeLatinEntities = true ;
FCKConfig.IncludeGreekEntities = true ;
FCKConfig.ProcessNumericEntities = false ;
FCKConfig.AdditionalNumericEntities = '' ; // Single Quote: "'"
FCKConfig.FillEmptyBlocks = true ;
FCKConfig.FormatSource = true ;
FCKConfig.FormatOutput = true ;
FCKConfig.FormatIndentator = ' ' ;
FCKConfig.EMailProtection = 'encode' ; // none | encode | function
FCKConfig.EMailProtectionFunction = 'mt(NAME,DOMAIN,SUBJECT,BODY)' ;
FCKConfig.StartupFocus = false ;
FCKConfig.ForcePasteAsPlainText = false ;
FCKConfig.AutoDetectPasteFromWord = true ; // IE only.
FCKConfig.ShowDropDialog = true ;
FCKConfig.ForceSimpleAmpersand = false ;
FCKConfig.TabSpaces = 0 ;
FCKConfig.ShowBorders = true ;
FCKConfig.SourcePopup = false ;
FCKConfig.ToolbarStartExpanded = true ;
FCKConfig.ToolbarCanCollapse = true ;
FCKConfig.IgnoreEmptyParagraphValue = true ;
FCKConfig.FloatingPanelsZIndex = 10000 ;
FCKConfig.HtmlEncodeOutput = false ;
FCKConfig.TemplateReplaceAll = true ;
FCKConfig.TemplateReplaceCheckbox = true ;
FCKConfig.ToolbarLocation = 'In' ;
FCKConfig.ToolbarSets["Default"] = [
['Source','DocProps','-','Save','NewPage','Preview','-','Templates'],
['Cut','Copy','Paste','PasteText','PasteWord','-','Print','SpellCheck'],
['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
'/',
['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript','insertcodeRun'],
['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote','CreateDiv'],
['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink','Anchor'],
['Image','Flash','Table','Rule','Smiley','SpecialChar','PageBreak'],
'/',
['Style','FontFormat','FontName','FontSize'],
['TextColor','BGColor'],
['FitWindow','ShowBlocks','-','About'] // No comma for the last row.
] ;
FCKConfig.ToolbarSets["Basic"] = [
['Bold','Italic','-','OrderedList','UnorderedList','-','Link','Unlink','-','About']
] ;
FCKConfig.EnterMode = 'p' ; // p | div | br
FCKConfig.ShiftEnterMode = 'br' ; // p | div | br
FCKConfig.Keystrokes = [
[ CTRL + 65 /*A*/, true ],
[ CTRL + 67 /*C*/, true ],
[ CTRL + 70 /*F*/, true ],
[ CTRL + 83 /*S*/, true ],
[ CTRL + 84 /*T*/, true ],
[ CTRL + 88 /*X*/, true ],
[ CTRL + 86 /*V*/, 'Paste' ],
[ CTRL + 45 /*INS*/, true ],
[ SHIFT + 45 /*INS*/, 'Paste' ],
[ CTRL + 88 /*X*/, 'Cut' ],
[ SHIFT + 46 /*DEL*/, 'Cut' ],
[ CTRL + 90 /*Z*/, 'Undo' ],
[ CTRL + 89 /*Y*/, 'Redo' ],
[ CTRL + SHIFT + 90 /*Z*/, 'Redo' ],
[ CTRL + 76 /*L*/, 'Link' ],
[ CTRL + 66 /*B*/, 'Bold' ],
[ CTRL + 73 /*I*/, 'Italic' ],
[ CTRL + 85 /*U*/, 'Underline' ],
[ CTRL + SHIFT + 83 /*S*/, 'Save' ],
[ CTRL + ALT + 13 /*ENTER*/, 'FitWindow' ],
[ SHIFT + 32 /*SPACE*/, 'Nbsp' ]
] ;
FCKConfig.ContextMenu = ['Generic','Link','Anchor','Image','Flash','Select','Textarea','Checkbox','Radio','TextField','HiddenField','ImageButton','Button','BulletedList','NumberedList','Table','Form','DivContainer'] ;
FCKConfig.BrowserContextMenuOnCtrl = false ;
FCKConfig.BrowserContextMenu = false ;
FCKConfig.EnableMoreFontColors = true ;
FCKConfig.FontColors = '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,808080,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF' ;
FCKConfig.FontFormats = 'p;h1;h2;h3;h4;h5;h6;pre;address;div' ;
FCKConfig.FontNames = 'Arial;Comic Sans MS;Courier New;Tahoma;Times New Roman;Verdana' ;
FCKConfig.FontSizes = 'smaller;larger;xx-small;x-small;small;medium;large;x-large;xx-large' ;
FCKConfig.StylesXmlPath = FCKConfig.EditorPath + 'fckstyles.xml' ;
FCKConfig.TemplatesXmlPath = FCKConfig.EditorPath + 'fcktemplates.xml' ;
FCKConfig.SpellChecker = 'ieSpell' ; // 'ieSpell' | 'SpellerPages'
FCKConfig.IeSpellDownloadUrl = 'http://www.iespell.com/download.php' ;
FCKConfig.SpellerPagesServerScript = 'server-scripts/spellchecker.php' ; // Available extension: .php .cfm .pl
FCKConfig.FirefoxSpellChecker = false ;
FCKConfig.MaxUndoLevels = 15 ;
FCKConfig.DisableObjectResizing = false ;
FCKConfig.DisableFFTableHandles = true ;
FCKConfig.LinkDlgHideTarget = false ;
FCKConfig.LinkDlgHideAdvanced = false ;
FCKConfig.ImageDlgHideLink = false ;
FCKConfig.ImageDlgHideAdvanced = false ;
FCKConfig.FlashDlgHideAdvanced = false ;
FCKConfig.ProtectedTags = '' ;
// This will be applied to the body element of the editor
FCKConfig.BodyId = '' ;
FCKConfig.BodyClass = '' ;
FCKConfig.DefaultStyleLabel = '' ;
FCKConfig.DefaultFontFormatLabel = '' ;
FCKConfig.DefaultFontLabel = '' ;
FCKConfig.DefaultFontSizeLabel = '' ;
FCKConfig.DefaultLinkTarget = '' ;
// The option switches between trying to keep the html structure or do the changes so the content looks like it was in Word
FCKConfig.CleanWordKeepsStructure = false ;
// Only inline elements are valid.
FCKConfig.RemoveFormatTags = 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var' ;
// Attributes that will be removed
FCKConfig.RemoveAttributes = 'class,style,lang,width,height,align,hspace,valign' ;
FCKConfig.CustomStyles =
{
'Red Title' : { Element : 'h3', Styles : { 'color' : 'Red' } }
};
// Do not add, rename or remove styles here. Only apply definition changes.
FCKConfig.CoreStyles =
{
// Basic Inline Styles.
'Bold' : { Element : 'strong', Overrides : 'b' },
'Italic' : { Element : 'em', Overrides : 'i' },
'Underline' : { Element : 'u' },
'StrikeThrough' : { Element : 'strike' },
'Subscript' : { Element : 'sub' },
'Superscript' : { Element : 'sup' },
// Basic Block Styles (Font Format Combo).
'p' : { Element : 'p' },
'div' : { Element : 'div' },
'pre' : { Element : 'pre' },
'address' : { Element : 'address' },
'h1' : { Element : 'h1' },
'h2' : { Element : 'h2' },
'h3' : { Element : 'h3' },
'h4' : { Element : 'h4' },
'h5' : { Element : 'h5' },
'h6' : { Element : 'h6' },
// Other formatting features.
'FontFace' :
{
Element : 'span',
Styles : { 'font-family' : '#("Font")' },
Overrides : [ { Element : 'font', Attributes : { 'face' : null } } ]
},
'Size' :
{
Element : 'span',
Styles : { 'font-size' : '#("Size","fontSize")' },
Overrides : [ { Element : 'font', Attributes : { 'size' : null } } ]
},
'Color' :
{
Element : 'span',
Styles : { 'color' : '#("Color","color")' },
Overrides : [ { Element : 'font', Attributes : { 'color' : null } } ]
},
'BackColor' : { Element : 'span', Styles : { 'background-color' : '#("Color","color")' } },
'SelectionHighlight' : { Element : 'span', Styles : { 'background-color' : 'navy', 'color' : 'white' } }
};
// The distance of an indentation step.
FCKConfig.IndentLength = 40 ;
FCKConfig.IndentUnit = 'px' ;
// Alternatively, FCKeditor allows the use of CSS classes for block indentation.
// This overrides the IndentLength/IndentUnit settings.
FCKConfig.IndentClasses = [] ;
// [ Left, Center, Right, Justified ]
FCKConfig.JustifyClasses = [] ;
// The following value defines which File Browser connector and Quick Upload
// "uploader" to use. It is valid for the default implementaion and it is here
// just to make this configuration file cleaner.
// It is not possible to change this value using an external file or even
// inline when creating the editor instance. In that cases you must set the
// values of LinkBrowserURL, ImageBrowserURL and so on.
// Custom implementations should just ignore it.
var _FileBrowserLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
var _QuickUploadLanguage = 'php' ; // asp | aspx | cfm | lasso | perl | php | py
// Don't care about the following two lines. It just calculates the correct connector
// extension to use for the default File Browser (Perl uses "cgi").
var _FileBrowserExtension = _FileBrowserLanguage == 'perl' ? 'cgi' : _FileBrowserLanguage ;
var _QuickUploadExtension = _QuickUploadLanguage == 'perl' ? 'cgi' : _QuickUploadLanguage ;
FCKConfig.LinkBrowser = false ;
FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ;
FCKConfig.LinkBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70%
FCKConfig.LinkBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70%
FCKConfig.ImageBrowser = false ;
FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Image&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ;
FCKConfig.ImageBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; // 70% ;
FCKConfig.ImageBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; // 70% ;
FCKConfig.FlashBrowser = false ;
FCKConfig.FlashBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Type=Flash&Connector=' + encodeURIComponent( FCKConfig.BasePath + 'filemanager/connectors/' + _FileBrowserLanguage + '/connector.' + _FileBrowserExtension ) ;
FCKConfig.FlashBrowserWindowWidth = FCKConfig.ScreenWidth * 0.7 ; //70% ;
FCKConfig.FlashBrowserWindowHeight = FCKConfig.ScreenHeight * 0.7 ; //70% ;
FCKConfig.LinkUpload = true ;
FCKConfig.LinkUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension ;
FCKConfig.LinkUploadAllowedExtensions = ".(7z|aiff|asf|avi|bmp|csv|doc|fla|flv|gif|gz|gzip|jpeg|jpg|mid|mov|mp3|mp4|mpc|mpeg|mpg|ods|odt|pdf|png|ppt|pxd|qt|ram|rar|rm|rmi|rmvb|rtf|sdc|sitd|swf|sxc|sxw|tar|tgz|tif|tiff|txt|vsd|wav|wma|wmv|xls|xml|zip)$" ; // empty for all
FCKConfig.LinkUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.ImageUpload = true ;
FCKConfig.ImageUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Image' ;
FCKConfig.ImageUploadAllowedExtensions = ".(jpg|gif|jpeg|png|bmp)$" ; // empty for all
FCKConfig.ImageUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.FlashUpload = true ;
FCKConfig.FlashUploadURL = FCKConfig.BasePath + 'filemanager/connectors/' + _QuickUploadLanguage + '/upload.' + _QuickUploadExtension + '?Type=Flash' ;
FCKConfig.FlashUploadAllowedExtensions = ".(swf|flv)$" ; // empty for all
FCKConfig.FlashUploadDeniedExtensions = "" ; // empty for no one
FCKConfig.SmileyPath = FCKConfig.BasePath + 'images/smiley/msn/' ;
FCKConfig.SmileyImages = ['regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ;
FCKConfig.SmileyColumns = 8 ;
FCKConfig.SmileyWindowWidth = 320 ;
FCKConfig.SmileyWindowHeight = 210 ;
FCKConfig.BackgroundBlockerColor = '#ffffff' ;
FCKConfig.BackgroundBlockerOpacity = 0.50 ;
FCKConfig.MsWebBrowserControlCompat = false ;
FCKConfig.PreventSubmitHandler = false ;
| JavaScript |
<!--
//xmlhttp和xmldom对象
var XHTTP = null;
var XDOM = null;
var Container = null;
var ShowError = false;
var ShowWait = false;
var ErrCon = "";
var ErrDisplay = "下载数据失败";
var WaitDisplay = "正在下载数据...";
//获取指定ID的元素
//function $(eid){
// return document.getElementById(eid);
//}
function $DE(id) {
return document.getElementById(id);
}
//gcontainer 是保存下载完成的内容的容器
//mShowError 是否提示错误信息
//ShowWait 是否提示等待信息
//mErrCon 服务器返回什么字符串视为错误
//mErrDisplay 发生错误时显示的信息
//mWaitDisplay 等待时提示信息
//默认调用 Ajax('divid',false,false,'','','')
function Ajax(gcontainer,mShowError,mShowWait,mErrCon,mErrDisplay,mWaitDisplay){
Container = gcontainer;
ShowError = mShowError;
ShowWait = mShowWait;
if(mErrCon!="") ErrCon = mErrCon;
if(mErrDisplay!="") ErrDisplay = mErrDisplay;
if(mErrDisplay=="x") ErrDisplay = "";
if(mWaitDisplay!="") WaitDisplay = mWaitDisplay;
//post或get发送数据的键值对
this.keys = Array();
this.values = Array();
this.keyCount = -1;
//http请求头
this.rkeys = Array();
this.rvalues = Array();
this.rkeyCount = -1;
//请求头类型
this.rtype = 'text';
//初始化xmlhttp
if(window.ActiveXObject){//IE6、IE5
try { XHTTP = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) { }
if (XHTTP == null) try { XHTTP = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { }
}
else{
XHTTP = new XMLHttpRequest();
}
//增加一个POST或GET键值对
this.AddKey = function(skey,svalue){
this.keyCount++;
this.keys[this.keyCount] = skey;
svalue = svalue.replace(/\+/g,'$#$');
this.values[this.keyCount] = escape(svalue);
};
//增加一个Http请求头键值对
this.AddHead = function(skey,svalue){
this.rkeyCount++;
this.rkeys[this.rkeyCount] = skey;
this.rvalues[this.rkeyCount] = svalue;
};
//清除当前对象的哈希表参数
this.ClearSet = function(){
this.keyCount = -1;
this.keys = Array();
this.values = Array();
this.rkeyCount = -1;
this.rkeys = Array();
this.rvalues = Array();
};
XHTTP.onreadystatechange = function(){
//在IE6中不管阻断或异步模式都会执行这个事件的
if(XHTTP.readyState == 4){
if(XHTTP.status == 200){
if(XHTTP.responseText!=ErrCon){
Container.innerHTML = XHTTP.responseText;
}else{
if(ShowError) Container.innerHTML = ErrDisplay;
}
XHTTP = null;
}else{ if(ShowError) Container.innerHTML = ErrDisplay; }
}else{ if(ShowWait) Container.innerHTML = WaitDisplay; }
};
//检测阻断模式的状态
this.BarrageStat = function(){
if(XHTTP==null) return;
if(typeof(XHTTP.status)!=undefined && XHTTP.status == 200)
{
if(XHTTP.responseText!=ErrCon){
Container.innerHTML = XHTTP.responseText;
}else{
if(ShowError) Container.innerHTML = ErrDisplay;
}
}
};
//发送http请求头
this.SendHead = function(){
if(this.rkeyCount!=-1){ //发送用户自行设定的请求头
for(;i<=this.rkeyCount;i++){
XHTTP.setRequestHeader(this.rkeys[i],this.rvalues[i]);
}
}
if(this.rtype=='binary'){
XHTTP.setRequestHeader("Content-Type","multipart/form-data");
}else{
XHTTP.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
};
//用Post方式发送数据
this.SendPost = function(purl){
var pdata = "";
var i=0;
this.state = 0;
XHTTP.open("POST", purl, true);
this.SendHead();
if(this.keyCount!=-1){ //post数据
for(;i<=this.keyCount;i++){
if(pdata=="") pdata = this.keys[i]+'='+this.values[i];
else pdata += "&"+this.keys[i]+'='+this.values[i];
}
}
XHTTP.send(pdata);
};
//用GET方式发送数据
this.SendGet = function(purl){
var gkey = "";
var i=0;
this.state = 0;
if(this.keyCount!=-1){ //get参数
for(;i<=this.keyCount;i++){
if(gkey=="") gkey = this.keys[i]+'='+this.values[i];
else gkey += "&"+this.keys[i]+'='+this.values[i];
}
if(purl.indexOf('?')==-1) purl = purl + '?' + gkey;
else purl = purl + '&' + gkey;
}
XHTTP.open("GET", purl, true);
this.SendHead();
XHTTP.send(null);
};
//用GET方式发送数据,阻塞模式
this.SendGet2 = function(purl){
var gkey = "";
var i=0;
this.state = 0;
if(this.keyCount!=-1){ //get参数
for(;i<=this.keyCount;i++){
if(gkey=="") gkey = this.keys[i]+'='+this.values[i];
else gkey += "&"+this.keys[i]+'='+this.values[i];
}
if(purl.indexOf('?')==-1) purl = purl + '?' + gkey;
else purl = purl + '&' + gkey;
}
XHTTP.open("GET", purl, false);
this.SendHead();
XHTTP.send(null);
//firefox中直接检测XHTTP状态
this.BarrageStat();
};
//用Post方式发送数据
this.SendPost2 = function(purl){
var pdata = "";
var i=0;
this.state = 0;
XHTTP.open("POST", purl, false);
this.SendHead();
if(this.keyCount!=-1){ //post数据
for(;i<=this.keyCount;i++){
if(pdata=="") pdata = this.keys[i]+'='+this.values[i];
else pdata += "&"+this.keys[i]+'='+this.values[i];
}
}
XHTTP.send(pdata);
//firefox中直接检测XHTTP状态
this.BarrageStat();
};
} // End Class Ajax
//初始化xmldom
function InitXDom(){
if(XDOM!=null) return;
var obj = null;
if (typeof(DOMParser) != "undefined") { // Gecko、Mozilla、Firefox
var parser = new DOMParser();
obj = parser.parseFromString(xmlText, "text/xml");
} else { // IE
try { obj = new ActiveXObject("MSXML2.DOMDocument");} catch (e) { }
if (obj == null) try { obj = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) { }
}
XDOM = obj;
};
-->
| JavaScript |
/**
* Copyright (c) 2010 Maxim Vasiliev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Maxim Vasiliev
* Date: 09.09.2010
* Time: 19:02:33
*/
(function()
{
/**
* Returns form values represented as Javascript object
* "name" attribute defines structure of resulting object
*
* @param rootNode {Element|String} root form element (or it's id) or array of root elements
* @param delimiter {String} structure parts delimiter defaults to '.'
* @param skipEmpty {Boolean} should skip empty text values, defaults to true
* @param nodeCallback {Function} custom function to get node value
*/
window.form2object = function(rootNode, delimiter, skipEmpty, nodeCallback)
{
if (typeof skipEmpty == 'undefined' || skipEmpty == null) skipEmpty = true;
if (typeof delimiter == 'undefined' || delimiter == null) delimiter = '.';
rootNode = typeof rootNode == 'string' ? document.getElementById(rootNode) : rootNode;
var formValues = [],
currNode,
i = 0;
/* If rootNode is array - combine values */
if (rootNode.constructor == Array || (typeof NodeList != "undefined" && rootNode.constructor == NodeList))
{
while(currNode = rootNode[i++])
{
formValues = formValues.concat(getFormValues(currNode, nodeCallback));
}
}
else
{
formValues = getFormValues(rootNode, nodeCallback);
}
return processNameValues(formValues, skipEmpty, delimiter);
};
/**
* Processes collection of { name: 'name', value: 'value' } objects.
* @param nameValues
* @param skipEmpty if true skips elements with value == '' or value == null
* @param delimiter
*/
function processNameValues(nameValues, skipEmpty, delimiter)
{
var result = {},
arrays = {},
i, j, k, l,
value,
nameParts,
currResult,
arrNameFull,
arrName,
arrIdx,
namePart,
name,
_nameParts;
for (i = 0; i < nameValues.length; i++)
{
value = nameValues[i].value;
if (skipEmpty && value === '') continue;
name = nameValues[i].name;
_nameParts = name.split(delimiter);
nameParts = [];
currResult = result;
arrNameFull = '';
for(j = 0; j < _nameParts.length; j++)
{
namePart = _nameParts[j].split('][');
if (namePart.length > 1)
{
for(k = 0; k < namePart.length; k++)
{
if (k == 0)
{
namePart[k] = namePart[k] + ']';
}
else if (k == namePart.length - 1)
{
namePart[k] = '[' + namePart[k];
}
else
{
namePart[k] = '[' + namePart[k] + ']';
}
arrIdx = namePart[k].match(/([a-z_]+)?\[([a-z_][a-z0-9]+?)\]/i);
if (arrIdx)
{
for(l = 1; l < arrIdx.length; l++)
{
if (arrIdx[l]) nameParts.push(arrIdx[l]);
}
}
else{
nameParts.push(namePart[k]);
}
}
}
else
nameParts = nameParts.concat(namePart);
}
for (j = 0; j < nameParts.length; j++)
{
namePart = nameParts[j];
if (namePart.indexOf('[]') > -1 && j == nameParts.length - 1)
{
arrName = namePart.substr(0, namePart.indexOf('['));
arrNameFull += arrName;
if (!currResult[arrName]) currResult[arrName] = [];
currResult[arrName].push(value);
}
else if (namePart.indexOf('[') > -1)
{
arrName = namePart.substr(0, namePart.indexOf('['));
arrIdx = namePart.replace(/(^([a-z_]+)?\[)|(\]$)/gi, '');
/* Unique array name */
arrNameFull += '_' + arrName + '_' + arrIdx;
/*
* Because arrIdx in field name can be not zero-based and step can be
* other than 1, we can't use them in target array directly.
* Instead we're making a hash where key is arrIdx and value is a reference to
* added array element
*/
if (!arrays[arrNameFull]) arrays[arrNameFull] = {};
if (arrName != '' && !currResult[arrName]) currResult[arrName] = [];
if (j == nameParts.length - 1)
{
if (arrName == '')
{
currResult.push(value);
arrays[arrNameFull][arrIdx] = currResult[currResult.length - 1];
}
else
{
currResult[arrName].push(value);
arrays[arrNameFull][arrIdx] = currResult[arrName][currResult[arrName].length - 1];
}
}
else
{
if (!arrays[arrNameFull][arrIdx])
{
if ((/^[a-z_]+\[?/i).test(nameParts[j+1])) currResult[arrName].push({});
else currResult[arrName].push([]);
arrays[arrNameFull][arrIdx] = currResult[arrName][currResult[arrName].length - 1];
}
}
currResult = arrays[arrNameFull][arrIdx];
}
else
{
arrNameFull += namePart;
if (j < nameParts.length - 1) /* Not the last part of name - means object */
{
if (!currResult[namePart]) currResult[namePart] = {};
currResult = currResult[namePart];
}
else
{
currResult[namePart] = value;
}
}
}
}
return result;
}
function getFormValues(rootNode, nodeCallback)
{
var result = extractNodeValues(rootNode, nodeCallback);
return result.length > 0 ? result : getSubFormValues(rootNode, nodeCallback);
}
function getSubFormValues(rootNode, nodeCallback)
{
var result = [],
currentNode = rootNode.firstChild,
callbackResult, fieldValue, subresult;
while (currentNode)
{
result = result.concat(extractNodeValues(currentNode, nodeCallback));
currentNode = currentNode.nextSibling;
}
return result;
}
function extractNodeValues(node, nodeCallback) {
var callbackResult, fieldValue, result = [];
callbackResult = nodeCallback && nodeCallback(node);
if (callbackResult && callbackResult.name) {
result = [callbackResult];
}
else if (node.nodeName.match(/INPUT|TEXTAREA/i)) {
fieldValue = getFieldValue(node);
if (fieldValue !== null)
result = [ { name: node.name, value: fieldValue} ];
}
else if (node.nodeName.match(/SELECT/i)) {
fieldValue = getFieldValue(node);
if (fieldValue !== null)
result = [ { name: node.name.replace(/\[\]$/, ''), value: fieldValue } ];
}
else{
result = getSubFormValues(node, nodeCallback);
}
return result;
}
function getFieldValue(fieldNode)
{
switch (fieldNode.nodeName) {
case 'INPUT':
case 'TEXTAREA':
switch (fieldNode.type.toLowerCase()) {
case 'radio':
case 'checkbox':
if (fieldNode.checked) return fieldNode.value;
break;
case 'button':
case 'reset':
case 'submit':
case 'image':
return '';
break;
default:
return fieldNode.value;
break;
}
break;
case 'SELECT':
return getSelectedOptionValue(fieldNode);
break;
default:
break;
}
return null;
}
function getSelectedOptionValue(selectNode)
{
var multiple = selectNode.multiple,
result = [],
options;
if (!multiple) return selectNode.value;
for (options = selectNode.getElementsByTagName("option"), i = 0, l = options.length; i < l; i++)
{
if (options[i].selected) result.push(options[i].value);
}
return result;
}
/**
* @deprecated Use form2object() instead
* @param rootNode
* @param delimiter
*/
window.form2json = window.form2object;
})(); | JavaScript |
/**
* @author Maxim Vasiliev
* Date: 29.06.11
* Time: 20:09
*/
(function($){
/**
* jQuery wrapper for form2object()
* Extracts data from child inputs into javascript object
*/
$.fn.toObject = function(options)
{
var result = [],
settings = {
mode: 'first', // what to convert: 'all' or 'first' matched node
delimiter: ".",
skipEmpty: true,
nodeCallback: null
};
if (options)
{
$.extend(settings, options);
}
switch(settings.mode)
{
case 'first':
return form2object(this.get(0), settings.delimiter, settings.skipEmpty, settings.nodeCallback);
break;
case 'all':
this.each(function(){
result.push(form2object(this, settings.delimiter, settings.skipEmpty, settings.nodeCallback));
});
return result;
break;
case 'combine':
return form2object(Array.prototype.slice.call(this), settings.delimiter, settings.skipEmpty, settings.nodeCallback);
break;
}
}
})(jQuery); | JavaScript |
/*
http://www.JSON.org/json2.js
2010-08-25
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, strict: false */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON) {
this.JSON = {};
}
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
| JavaScript |
/**
* 우편번호 검색
* data : 2014.11
* writer : me
*/
function winOpenInit() {
document.getElementById("btnFind").onclick = search;
}
function search() {
win = window.open("./win_sub.html", "win","");
}
function winSubInit() {
tar = window.opener.document.frm;
tar.address.value="우편번호를 검색하세요";
var postNum = document.getElementById("sel");
postNum.onchange = function() {
var pos = postNum.selectedIndex;
var zip = postNum[pos].value.split('-');
var address = postNum[pos].text;
tar.zip1.value = zip[0];
tar.zip2.value = zip[1];
tar.address.value = address;
}
}
| JavaScript |
/**
* 게시판과 관련된 자바스크립트
* date : 2014.11
* writer : me
*/
var btnList;
var btnInput;
var btnModify;
var btnDelete;
var btnView;
var url = 'index.jsp?inc=../Score/';
function general(){ // 게시판과 관련된 공통 모듈
btnList = document.getElementById("btnList");
if (btnList != null){
btnList.onclick = function (){
location.href = url + 'list.jsp';
}
}
btnInput = document.getElementById("btnInput")
if( btnInput != null){
btnInput.onclick = function (){
location.href = url + 'input.jsp';
}
}
btnModify = document.getElementById("btnModify")
if( btnModify != null){
btnModify.onclick = function (){
location.href = url + 'modify.jsp';
}
}
btnDelete = document.getElementById("btnDelete")
if( btnDelete != null){
btnDelete.onclick = function (){
location.href = url + 'delete_result.jsp';
}
}
btnView = document.getElementById("btnView")
if( btnView != null){
btnView.onclick = function (){
location.href = url + 'view.jsp';
}
}
}
function goPage(page) {
location.href = url + "view.jsp&page=" + page;
}
function inputInit() { // input 에관련된 모듈
general();
document.getElementById("btnSave").onclick = function() {
var f = document.frm;
if(f.mid.value == ""){
alert("아이디를 입력하세요");
f.mid.focus();
}
else{
f.submit();
}
}
}
function listInit() { // input 에관련된 모듈
general();
}
function viewInit() { // input 에관련된 모듈
general();
}
function modifyInit() { // input 에관련된 모듈
general();
document.getElementById("btnSave").onclick = function() {
var f = document.frm;
if(f.mid.value == ""){
alert("아이디를 입력하세요");
f.mid.focus();
}
else{
f.submit();
}
}
}
function deleteInit() { // input 에관련된 모듈
general();
} | JavaScript |
/**
* date : 2014.11
* writer : me
*/
var count = 0;
var interval;
function init() {
var f = document.frm;
document.getElementById(f.btnStart).onclick = "btnS";
document.getElementById(f.btnEnd).onclick = "btnE";
}
function btnS() {
function run() {
var div = document.getElementById("result");
var now = new Date();
var str = now.getFullYear() + "년";
str += (now.getMonth()+1) + "월";
str += now.getDate() + "일(";
// str += now.week[now.getDay()] + "요일)";
str += now.getHours() + "시";
str += now.getMinutes() + "분";
str += now.getSeconds() + "초)";
div.innerHTML = str ;
}
if(count == 0){
interval = setInterval(run, 1000);
count++;
}
}
function btnE() {
if(count == 1){
clearInterval(interval);
count--;
}
} | JavaScript |
/**
* date: 2014.10
* writer: young
*/
var start = false;
var startX = 0;
var srartY = 0;
var ctx ;
function init() {
document.getElementById("canvas").onmousedown = set;
document.getElementById("canvas").onmousemove = drawing;
ctx = document.getElementById("canvas").getContext("2d");
}
function colo(){
var col ="#";
for(i = 0; i<6; i++){
var ran = Math.floor(Math.random()*15);
if(ran == 10){
col +="a";
}
else if(ran == 11){
col +="b";
}
else if(ran == 12){
col +="c";
}
else if(ran == 13){
col +="d";
}
else if(ran == 14){
col +="e";
}
else if(ran == 14){
col +="f";
}
else{
col +=ran;
}
}
return col;
}
function set(e) {
var lc;
var lw;
start = !start;
startX = e.x-12;
startY = e.y-12;
// 선 그리기 시작점 설정
if(start){
ctx.beginPath();
ctx.moveTo(startX,startY);
lc = document.getElementById("linecolor");
lw = document.getElementById("linewidth");
//ctx.strokeStyle= colo();
ctx.strokeStyle= colo();
ctx.lineWidth=lw.value;
}
else{
ctx.closePath();
}
}
function drawing(e) {
var resultValue = document.getElementById("result");
var x = e.x;
var y = e.y;
if(start){
ctx.strokeStyle= colo();
ctx.lineTo(x,y);
ctx.stroke();
}
resultValue.innerHTML = "x = " + x + "y = " + y;
}
| JavaScript |
/**
* if test2
* date : 2014.10
* writer : me
*/
function ifTest2() {
var btnclk = document.getElementById("btn");
var frm;
btnclk.onclick = function(){
frm = document.frm;
var num1 = Number(frm.num1.value) ;
var num2 = Number(frm.num2.value) ;
var total = num1 + num2;
alert("합계 : " + total + "평균 : " + (total/2));
}
} | JavaScript |
/**
* if test3
* date : 2014.10
* writer : me
*/
function ifTest3() {
var btnclk = document.getElementById("btn");
var frm;
btnclk.onclick = function(){
frm = document.frm;
var num1 = Number(frm.num1.value);
if(num1%2 == 0){
alert("짝수");
}
else{
alert("홀수");
}
}
} | JavaScript |
/**
*
*/ | JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.