code
stringlengths
1
2.08M
language
stringclasses
1 value
jQuery( function ($){ if( typeof codepeople_theme_switch != 'undefined' ) { function getWidth() { var myWidth = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE myWidth = window.innerWidth; } else if( document.documentElement && document.documentElement.clientWidth ) { //IE 6+ in 'standards compliant mode' myWidth = document.documentElement.clientWidth; } else if( document.body && document.body.clientWidth ) { //IE 4 compatible myWidth = document.body.clientWidth; } if( typeof window.devicePixelRatio != 'undefined' && window.devicePixelRatio ) myWidth = myWidth/window.devicePixelRatio; return ( typeof screen != 'undefined' ) ? Math.min( screen.width, myWidth ) : myWidth; }; var width = getWidth(); if( width < codepeople_theme_switch[ 'width' ] ) { var selection = window.confirm( codepeople_theme_switch[ 'message' ] ); if( selection ) { var loc = document.location.href; loc += ( ( loc.indexOf( '?' ) == -1 ) ? '?' : '&' ) + 'theme_switch_width=' + width; document.location = loc; } else { var loc = codepeople_theme_switch[ 'url' ]; loc += ( ( loc.indexOf( '?' ) == -1 ) ? '?' : '&' ) + 'theme_switch_denied=1'; $( 'body' ).append( $( '<img style="width:1px;height:1px;display:none;" src="' + loc + '" />' ) ); } } } });
JavaScript
(function ($){ function empty( v ) { return typeof v != 'undefined' && /^\s*$/.test( v ); }; function clear() { // Clear $( '#cpts_screen_width' ).val( '' ); $( '#cpts_predefined_screen option:first' ).prop( 'selected', true ); }; window[ 'cptsDisplayPreview' ] = function() { var t = $( '[name="cpts_theme"]:checked' ), w = $( '#cpts_screen_width' ).val(), p = $( '.cp-preview-container' ); if( empty( w ) ) { alert( 'The screen width is required' ); return; } p.show().html( '' ); $( '<iframe width="' + w + '" height="480px" src="' + cptsObj[ 'home' ] + '/?preview=1&preview_iframe=1&template=' + escape( t.attr( 'template' ) ) + '&stylesheet=' + escape( t.attr( 'stylesheet' ) ) + '"></iframe>' ).appendTo( p ); }; window[ 'cptsLoadScreenSizes' ] = function( e ) { var o = $( e.options[ e.selectedIndex ] ); if( o.attr( 'w' ) ) { $( '#cpts_screen_width' ).val( o.attr( 'w' ) ); } }; })(jQuery);
JavaScript
//socket javascript jQuery(document).ready(function(){ //tao doi tuong websocket // var wsUri = "ws://localhost:9070/server.php"; //wsocket = new WebSocket(wsUri); //khi ket noi duoc mo // wsocket.onopen = function(ev) { // alert('đã kết nối'); // } //khi nhan dc message tu sever // wsocket.onmessage = function(ev) { // var msg = JSON.parse(ev.data); // var time = msg.message; // alert(time); // }; //wsocket.onerror = function(ev){alert('loi'+ev.data);}; //wsocket.onclose = function(ev){alert('ngắt kết nối')}; }); function likeThis(e, l, s) { "" != e && (jQuery("#wp-ulike-" + e + " .counter").html('<a class="loading"></a><span class="count-box">...</span>'), jQuery.ajax({ type: "POST", url: ulike_obj.ajaxurl, data: { action: "ulikeprocess", id: e }, success: function(a) { l + s == 1 ? jQuery("#wp-ulike-" + e + " .counter").html("<a id='like_button' onclick='likeThis(" + e + ",1,1)' class='text'>" + ulike_obj.likeText + "</a><span class='count-box'>" + a + "</span>") : l + s == 2 ? jQuery("#wp-ulike-" + e + " .counter").html("<a onclick='likeThis(" + e + ",1,0)' class='text'>" + ulike_obj.disLikeText + "</a><span class='count-box'>" + a + "</span>") : l + s == 3 && jQuery("#wp-ulike-" + e + " .counter").html("<a class='text user-tooltip' title='Already Voted'>" + ulike_obj.likeText + "</a><span class='count-box'>" + a + "</span>") } })); jQuery.ajax({ type: "POST", url: ulike_obj.ajaxurl, data: { action: "like_clicked", actor_id: ulike_obj.current_user_id, image_id:e, notification_type:'like', like_status:s }, success: function(data) { //var myWindow = window.open("", "MsgWindow", "width=1000, height=1000"); //myWindow.document.write(data); var json = JSON.parse(data); alert(json.receiver_id); var msg = { receiver_id: json.receiver_id, type:'like' } wsocket.send(JSON.stringify(msg)); } }); //gui thong tin di } if (! function(t) { "use strict"; var e = function(t, e) { this.init("tooltip", t, e) }; e.prototype = { constructor: e, init: function(e, i, n) { var o, s, r, a, l; for (this.type = e, this.$element = t(i), this.options = this.getOptions(n), this.enabled = !0, r = this.options.trigger.split(" "), l = r.length; l--;) a = r[l], "click" == a ? this.$element.on("click." + this.type, this.options.selector, t.proxy(this.toggle, this)) : "manual" != a && (o = "hover" == a ? "mouseenter" : "focus", s = "hover" == a ? "mouseleave" : "blur", this.$element.on(o + "." + this.type, this.options.selector, t.proxy(this.enter, this)), this.$element.on(s + "." + this.type, this.options.selector, t.proxy(this.leave, this))); this.options.selector ? this._options = t.extend({}, this.options, { trigger: "manual", selector: "" }) : this.fixTitle() }, getOptions: function(e) { return e = t.extend({}, t.fn[this.type].defaults, this.$element.data(), e), e.delay && "number" == typeof e.delay && (e.delay = { show: e.delay, hide: e.delay }), e }, enter: function(e) { var i, n = t.fn[this.type].defaults, o = {}; return this._options && t.each(this._options, function(t, e) { n[t] != e && (o[t] = e) }, this), i = t(e.currentTarget)[this.type](o).data(this.type), i.options.delay && i.options.delay.show ? (clearTimeout(this.timeout), i.hoverState = "in", void(this.timeout = setTimeout(function() { "in" == i.hoverState && i.show() }, i.options.delay.show))) : i.show() }, leave: function(e) { var i = t(e.currentTarget)[this.type](this._options).data(this.type); return this.timeout && clearTimeout(this.timeout), i.options.delay && i.options.delay.hide ? (i.hoverState = "out", void(this.timeout = setTimeout(function() { "out" == i.hoverState && i.hide() }, i.options.delay.hide))) : i.hide() }, show: function() { var e, i, n, o, s, r, a = t.Event("show"); if (this.hasContent() && this.enabled) { if (this.$element.trigger(a), a.isDefaultPrevented()) return; switch (e = this.tip(), this.setContent(), this.options.animation && e.addClass("fade"), s = "function" == typeof this.options.placement ? this.options.placement.call(this, e[0], this.$element[0]) : this.options.placement, e.detach().css({ top: 0, left: 0, display: "block" }), this.options.container ? e.appendTo(this.options.container) : e.insertAfter(this.$element), i = this.getPosition(), n = e[0].offsetWidth, o = e[0].offsetHeight, s) { case "bottom": r = { top: i.top + i.height, left: i.left + i.width / 2 - n / 2 }; break; case "top": r = { top: i.top - o, left: i.left + i.width / 2 - n / 2 }; break; case "left": r = { top: i.top + i.height / 2 - o / 2, left: i.left - n }; break; case "right": r = { top: i.top + i.height / 2 - o / 2, left: i.left + i.width } } this.applyPlacement(r, s), this.$element.trigger("shown") } }, applyPlacement: function(t, e) { var i, n, o, s, r = this.tip(), a = r[0].offsetWidth, l = r[0].offsetHeight; r.offset(t).addClass(e).addClass("in"), i = r[0].offsetWidth, n = r[0].offsetHeight, "top" == e && n != l && (t.top = t.top + l - n, s = !0), "bottom" == e || "top" == e ? (o = 0, t.left < 0 && (o = -2 * t.left, t.left = 0, r.offset(t), i = r[0].offsetWidth, n = r[0].offsetHeight), this.replaceArrow(o - a + i, i, "left")) : this.replaceArrow(n - l, n, "top"), s && r.offset(t) }, replaceArrow: function(t, e, i) { this.arrow().css(i, t ? 50 * (1 - t / e) + "%" : "") }, setContent: function() { var t = this.tip(), e = this.getTitle(); t.find(".tooltip-inner")[this.options.html ? "html" : "text"](e), t.removeClass("fade in top bottom left right") }, hide: function() { function e() { var e = setTimeout(function() { i.off(t.support.transition.end).detach() }, 500); i.one(t.support.transition.end, function() { clearTimeout(e), i.detach() }) } var i = this.tip(), n = t.Event("hide"); return this.$element.trigger(n), n.isDefaultPrevented() ? void 0 : (i.removeClass("in"), t.support.transition && this.$tip.hasClass("fade") ? e() : i.detach(), this.$element.trigger("hidden"), this) }, fixTitle: function() { var t = this.$element; (t.attr("title") || "string" != typeof t.attr("data-original-title")) && t.attr("data-original-title", t.attr("title") || "").attr("title", "") }, hasContent: function() { return this.getTitle() }, getPosition: function() { var e = this.$element[0]; return t.extend({}, "function" == typeof e.getBoundingClientRect ? e.getBoundingClientRect() : { width: e.offsetWidth, height: e.offsetHeight }, this.$element.offset()) }, getTitle: function() { var t, e = this.$element, i = this.options; return t = e.attr("data-original-title") || ("function" == typeof i.title ? i.title.call(e[0]) : i.title) }, tip: function() { return this.$tip = this.$tip || t(this.options.template) }, arrow: function() { return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") }, validate: function() { this.$element[0].parentNode || (this.hide(), this.$element = null, this.options = null) }, enable: function() { this.enabled = !0 }, disable: function() { this.enabled = !1 }, toggleEnabled: function() { this.enabled = !this.enabled }, toggle: function(e) { var i = e ? t(e.currentTarget)[this.type](this._options).data(this.type) : this; i.tip().hasClass("in") ? i.hide() : i.show() }, destroy: function() { this.hide().$element.off("." + this.type).removeData(this.type) } }; var i = t.fn.tooltip; t.fn.tooltip = function(i) { return this.each(function() { var n = t(this), o = n.data("tooltip"), s = "object" == typeof i && i; o || n.data("tooltip", o = new e(this, s)), "string" == typeof i && o[i]() }) }, t.fn.tooltip.Constructor = e, t.fn.tooltip.defaults = { animation: !0, placement: "top", selector: !1, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: "hover focus", title: "", delay: 0, html: !1, container: !1 }, t.fn.tooltip.noConflict = function() { return t.fn.tooltip = i, this } }(window.jQuery), "undefined" == typeof jQuery) throw new Error("WP Ulike's JavaScript requires jQuery"); if (+ function(t) { "use strict"; function e() { var t = document.createElement("bootstrap"), e = { WebkitTransition: "webkitTransitionEnd", MozTransition: "transitionend", OTransition: "oTransitionEnd otransitionend", transition: "transitionend" }; for (var i in e) if (void 0 !== t.style[i]) return { end: e[i] }; return !1 } t.fn.emulateTransitionEnd = function(e) { var i = !1, n = this; t(this).one("bsTransitionEnd", function() { i = !0 }); var o = function() { i || t(n).trigger(t.support.transition.end) }; return setTimeout(o, e), this }, t(function() { t.support.transition = e(), t.support.transition && (t.event.special.bsTransitionEnd = { bindType: t.support.transition.end, delegateType: t.support.transition.end, handle: function(e) { return t(e.target).is(this) ? e.handleObj.handler.apply(this, arguments) : void 0 } }) }) }(jQuery), "undefined" == typeof jQuery) throw new Error("WP Ulike's JavaScript requires jQuery"); + function(t) { "use strict"; function e(e) { return this.each(function() { var i = t(this), o = i.data("bs.alert"); o || i.data("bs.alert", o = new n(this)), "string" == typeof e && o[e].call(i) }) } var i = '[data-dismiss="alert"]', n = function(e) { t(e).on("click", i, this.close) }; n.VERSION = "3.2.0", n.prototype.close = function(e) { function i() { s.detach().trigger("closed.bs.alert").remove() } var n = t(this), o = n.attr("data-target"); o || (o = n.attr("href"), o = o && o.replace(/.*(?=#[^\s]*$)/, "")); var s = t(o); e && e.preventDefault(), s.length || (s = n.hasClass("alert") ? n : n.parent()), s.trigger(e = t.Event("close.bs.alert")), e.isDefaultPrevented() || (s.removeClass("in"), t.support.transition && s.hasClass("fade") ? s.one("bsTransitionEnd", i).emulateTransitionEnd(150) : i()) }; var o = t.fn.alert; t.fn.alert = e, t.fn.alert.Constructor = n, t.fn.alert.noConflict = function() { return t.fn.alert = o, this }, t(document).on("click.bs.alert.data-api", i, n.prototype.close) }(jQuery), jQuery(document).ready(function(t) { t(".user-tooltip").tooltip() });
JavaScript
jQuery(document).ready(function($){ function evaluate(){ var item = $(this); var relatedItem = $('.checktoshow'); if(item.is(":checked")){ relatedItem.fadeIn(); }else{ relatedItem.fadeOut(); } } $('#wp_ulike_style').click(evaluate).each(evaluate); $('.my-color-field').wpColorPicker(); });
JavaScript
var ak_js = document.getElementById( "ak_js" ); if ( ! ak_js ) { ak_js = document.createElement( 'input' ); ak_js.setAttribute( 'id', 'ak_js' ); ak_js.setAttribute( 'name', 'ak_js' ); ak_js.setAttribute( 'type', 'hidden' ); } else { ak_js.parentNode.removeChild( ak_js ); } ak_js.setAttribute( 'value', ( new Date() ).getTime() ); var commentForm = document.getElementById( 'commentform' ); if ( commentForm ) { commentForm.appendChild( ak_js ); } else { var replyRowContainer = document.getElementById( 'replyrow' ); if ( replyRowContainer ) { var children = replyRowContainer.getElementsByTagName( 'td' ); if ( children.length > 0 ) { children[0].appendChild( ak_js ); } } }
JavaScript
jQuery( function ( $ ) { $( 'a.activate-option' ).click( function(){ var link = $( this ); if ( link.hasClass( 'clicked' ) ) { link.removeClass( 'clicked' ); } else { link.addClass( 'clicked' ); } $( '.toggle-have-key' ).slideToggle( 'slow', function() {}); return false; }); $('.akismet-status').each(function () { var thisId = $(this).attr('commentid'); $(this).prependTo('#comment-' + thisId + ' .column-comment'); }); $('.akismet-user-comment-count').each(function () { var thisId = $(this).attr('commentid'); $(this).insertAfter('#comment-' + thisId + ' .author strong:first').show(); }); $('#the-comment-list').find('tr.comment, tr[id ^= "comment-"]').find('.column-author a[title ^= "http://"]').each(function () { var thisTitle = $(this).attr('title'); thisCommentId = $(this).parents('tr:first').attr('id').split("-"); $(this).attr("id", "author_comment_url_"+ thisCommentId[1]); if (thisTitle) { $(this).after( $( '<a href="#" class="remove_url">x</a>' ) .attr( 'commentid', thisCommentId[1] ) .attr( 'title', WPAkismet.strings['Remove this URL'] ) ); } }); $('.remove_url').live('click', function () { var thisId = $(this).attr('commentid'); var data = { action: 'comment_author_deurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId }; $.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Removes "x" link $("a[commentid='"+ thisId +"']").hide(); // Show temp status $("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Removing...'] ) ); }, success: function (response) { if (response) { // Show status/undo link $("#author_comment_url_"+ thisId) .attr('cid', thisId) .addClass('akismet_undo_link_removal') .html( $( '<span/>' ).text( WPAkismet.strings['URL removed'] ) ) .append( ' ' ) .append( $( '<span/>' ) .text( WPAkismet.strings['(undo)'] ) .addClass( 'akismet-span-link' ) ); } } }); return false; }); $('.akismet_undo_link_removal').live('click', function () { var thisId = $(this).attr('cid'); var thisUrl = $(this).attr('href').replace("http://www.", "").replace("http://", ""); var data = { action: 'comment_author_reurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId, url: thisUrl }; $.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Show temp status $("#author_comment_url_"+ thisId).html( $( '<span/>' ).text( WPAkismet.strings['Re-adding...'] ) ); }, success: function (response) { if (response) { // Add "x" link $("a[commentid='"+ thisId +"']").show(); // Show link $("#author_comment_url_"+ thisId).removeClass('akismet_undo_link_removal').html(thisUrl); } } }); return false; }); $('a[id^="author_comment_url"], tr.pingback td.column-author a:first-of-type').mouseover(function () { var wpcomProtocol = ( 'https:' === location.protocol ) ? 'https://' : 'http://'; // Need to determine size of author column var thisParentWidth = $(this).parent().width(); // It changes based on if there is a gravatar present thisParentWidth = ($(this).parent().find('.grav-hijack').length) ? thisParentWidth - 42 + 'px' : thisParentWidth + 'px'; if ($(this).find('.mShot').length == 0 && !$(this).hasClass('akismet_undo_link_removal')) { var self = $( this ); $('.widefat td').css('overflow', 'visible'); $(this).css('position', 'relative'); var thisHref = $.URLEncode( $(this).attr('href') ); $(this).append('<div class="mShot mshot-container" style="left: '+thisParentWidth+'"><div class="mshot-arrow"></div><img src="//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450" width="450" class="mshot-image" style="margin: 0;" /></div>'); setTimeout(function () { self.find( '.mshot-image' ).attr('src', '//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=2'); }, 6000); setTimeout(function () { self.find( '.mshot-image' ).attr('src', '//s0.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=3'); }, 12000); } else { $(this).find('.mShot').css('left', thisParentWidth).show(); } }).mouseout(function () { $(this).find('.mShot').hide(); }); $('.checkforspam:not(.button-disabled)').click( function(e) { $('.checkforspam:not(.button-disabled)').addClass('button-disabled'); $('.checkforspam-spinner').addClass( 'spinner' ); akismet_check_for_spam(0, 100); e.preventDefault(); }); function akismet_check_for_spam(offset, limit) { $.post( ajaxurl, { 'action': 'akismet_recheck_queue', 'offset': offset, 'limit': limit }, function(result) { if (result.processed < limit) { window.location.reload(); } else { akismet_check_for_spam(offset + limit, limit); } } ); } }); // URL encode plugin jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;} });
JavaScript
jQuery(function(){ //hover states on the static widgets jQuery('#dialog_link, ul#icons li').hover( function() { jQuery(this).addClass('ui-state-hover'); }, function() { jQuery(this).removeClass('ui-state-hover'); } ); }); /* initialize datepicker */ jQuery(function(){ // Datepicker jQuery('.wppb_datepicker').datepicker({ inline: true, changeMonth: true, changeYear: true }); });
JavaScript
function wppb_insertAtCursor(myField,value) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = value; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + value + myField.value.substring(endPos, myField.value.length); } else { myField.value += value; } } function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function wppb_replaceSelection (input, replaceString) { if (input.setSelectionRange) { var selectionStart = input.selectionStart; var selectionEnd = input.selectionEnd; input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd); if (selectionStart != selectionEnd){ setSelectionRange(input, selectionStart, selectionStart + replaceString.length); }else{ setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length); } }else if (document.selection) { var range = document.selection.createRange(); if (range.parentElement() == input) { var isCollapsed = range.text == ''; range.text = replaceString; if (!isCollapsed) { range.moveStart('character', -replaceString.length); range.select(); } } } } // We are going to catch the TAB key so that we can use it, Hooray! function wppb_catchTab(item,e){ if(navigator.userAgent.match("Gecko")){ c=e.which; }else{ c=e.keyCode; } if(c==9){ wppb_replaceSelection(item,String.fromCharCode(9)); setTimeout("document.getElementById('"+item.id+"').focus();",0); return false; } }
JavaScript
/** * * Delay * * Creates a way to delay events * Dependencies: jQuery * */ /* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ (function ($) { $.fn.delay = function(time,func){ return this.each(function(){ setTimeout(func,time); }); }; })(jQuery); /** * * Center AJAX * * Creates a way to center the AJAX message * Dependencies: jQuery * */ (function ($) { $.fn.ajaxMessage = function(html){ if (html) { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()}); } else { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()}); } }; })(jQuery); /** * * Style File * * Creates a way to cover file input with a better styled version * Dependencies: jQuery * */ (function ($) { styleFile = { init: function () { $('input.file').each(function(){ var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />'; $(this).wrap('<div class="file_wrap" />'); $(this).addClass('file').css('opacity', 0); //set to invisible $(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton)); $(this).bind('change', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); $(this).bind('mouseout', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); }); } }; $(document).ready(function () { styleFile.init() }) })(jQuery); /** * * Style Select * * Replace Select text * Dependencies: jQuery * */ (function ($) { styleSelect = { init: function () { $('.select_wrapper').each(function () { $(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>'); }); $('.select').live('change', function () { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); $('.select').bind($.browser.msie ? 'click' : 'change', function(event) { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); } }; $(document).ready(function () { styleSelect.init() }) })(jQuery); /** * * Activate Tabs * * Tab style UI toggle * Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs * */ (function ($) { activateTabs = { init: function () { // Activate $("#options_tabs").tabs(); // Append Toggle Button $('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>'); // Toggle Tabs $('.toggle_tabs').toggle(function() { $("#options_tabs").tabs('destroy'); $(this).addClass('off'); }, function() { $("#options_tabs").tabs(); $(this).removeClass('off'); }); } }; $(document).ready(function () { activateTabs.init() }) })(jQuery); /** * * Upload Option * * Allows window.send_to_editor to function properly using a private post_id * Dependencies: jQuery, Media Upload, Thickbox * */ (function ($) { uploadOption = { init: function () { var formfield, formID, btnContent = true; // On Click $('.upload_button').live("click", function () { formfield = $(this).prev('input').attr('name'); formID = $(this).attr('rel'); tb_show('', 'media-upload.php?post_id='+formID+'&type=image&amp;TB_iframe=1'); return false; }); window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html) { if (formfield) { itemurl = $(html).attr('href'); var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi; var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi; var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi; var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi; if (itemurl.match(image)) { btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>'; } else { btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>'; } $('#' + formfield).val(itemurl); $('#' + formfield).next().next('div').slideDown().html(btnContent); tb_remove(); } else { window.original_send_to_editor(html); } } } }; $(document).ready(function () { uploadOption.init() }) })(jQuery); /** * * Inline Edit Options * * Creates & Updates Options via Ajax * Dependencies: jQuery * */ (function ($) { inlineEditOption = { init: function () { var c = this, d = $("tr.inline-edit-option"); $('.save-options', '#the-theme-options').live("click", function () { inlineEditOption.save_options(this); return false; }); $("a.edit-inline").live("click", function (event) { if ($("a.edit-inline").hasClass('disable')) { event.preventDefault(); return false; } else { inlineEditOption.edit(this); return false; } }); $("a.save").live("click", function () { if ($("a.save").hasClass('add-save')) { inlineEditOption.addSave(this); return false; } else { inlineEditOption.editSave(this); return false; } }); $("a.cancel").live("click", function () { if ($("a.cancel").hasClass('undo-add')) { inlineEditOption.undoAdd(); return false; } else { inlineEditOption.revert(); return false; } }); $("a.add-option").live("click", function (event) { if (1) { event.preventDefault(); return false; } else { $.post( ajaxurl, { action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() }, function (response) { c = parseInt(response) + 1; inlineEditOption.add(c); } ); return false; } }); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); $('.delete-inline').live("click", function (event) { if ($("a.delete-inline").hasClass('disable')) { event.preventDefault(); return false; } else { var agree = confirm("Are you sure you want to delete this input?"); if (agree) { inlineEditOption.remove(this); return false; } else { return false; } } }); // Fade out message div if ($('.ajax-message').hasClass('show')) { $('.ajax-message').ajaxMessage(); } // Remove Uploaded Image $('.remove').live('click', function(event) { $(this).hide(); $(this).parents().prev().prev('.upload').attr('value', ''); $(this).parents('.screenshot').slideUp(); }); }, save_options: function (e) { var d = { action: "profile_builder_array_save" }; b = $(':input', '#the-theme-options').serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r != -1) { $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Theme Options were saved</div>'); $(".option-tree-slider-body").hide(); $('.option-tree-slider .edit').removeClass('down'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>Theme Options could not be saved</div>'); } }); return false; }, remove: function (b) { var c = true; // Set ID c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); d = { action: "profile_builder_delete", id: c, _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (r) { if (r) { r=$.trim(r); if (r == 'removed') { $("#option-" + c).remove(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input deleted.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, add: function (c) { var e = this, addRow, editRow = true, temp_select; e.revert(); // Clone the blank main row addRow = $('#inline-add').clone(true); addRow = $(addRow).attr('id', 'option-'+c); // Clone the blank edit row editRow = $('#inline-edit').clone(true); $('a.cancel', editRow).addClass('undo-add'); $('a.save', editRow).addClass('add-save'); $('a.edit-inline').addClass('disable'); $('a.delete-inline').addClass('disable'); $('a.add-option').addClass('disable'); // Set Colspan to 6 $('td', editRow).attr('colspan', 6); // Add Row $("#framework-settings tr:last").after(addRow); // Add Row and hide $(addRow).hide().after(editRow); $('.item-data', addRow).attr('id', 'inline_'+c); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); $('.item_title', '#edit-'+c).focus(); // Item MetaKey $('.item_metaName', editRow).attr('value', 'custom_field_'+c); //internal id $('.internal_id', editRow).attr('value', c); $('.select').each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).hide(); } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative3').hide(); $('.alternative').hide(); $('.regular').show(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); $('.option-required', '#edit-'+c).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /* avatar */ }else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); $('.option-required', '#edit-'+c).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).show(); } } }); // Scroll $('html, body').animate({ scrollTop: 2000 }, 500); return false; }, undoAdd: function (b) { var e = this, c = true; e.revert(); c = $("#framework-settings tr:last").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); $("a.edit-inline").removeClass('disable'); $("a.delete-inline").removeClass('disable'); $("a.add-option").removeClass('disable'); $("#option-" + c).remove(); return false; }, addSave: function (e) { var d, b, c, f, g, itemMN; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemMN) { itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_add", id: e, item_metaName: itemMN, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (jQuery.trim(r) == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input added.</div>'); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, edit: function (b) { var e = this, c, editRow, rowData, item_title, itemMN, item_type, item_desc, item_options = true, temp_select, item_required; e.revert(); c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); // Clone the blank row editRow = $('#inline-edit').clone(true); $('td', editRow).attr('colspan', 6); $("#option-" + c).hide().after(editRow); // First Option Settings if ("#option-" + c == '#option-1') { $('.option').hide(); $('.option-title').show().css({"paddingBottom":"1px"}); //$('.option-title', editRow).html('<strong>Title:</strong> The title of the item.<br/>First item must be a heading.'); $('.option-internal_id', editRow).show(); } // Populate the option data rowData = $('#inline_' + c); // Item Title item_title = $('.item_title', rowData).text(); $('.item_title', editRow).attr('value', item_title); // Item MetaKey item_metaName = $('.item_metaName', rowData).text(); $('.item_metaName', editRow).attr('value', 'custom_field_'+c); // Item MetaNames itemMN = $('.item_metaName', rowData).text(); $('.item_metaName', editRow).attr('value', itemMN); // Internal ID internal_id = $('.internal_id', rowData).text(); $('.internal_id', editRow).attr('value', c); // Item Type item_type = $('.item_type', rowData).text(); $('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true); var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text(); $('.select_wrapper span', editRow).text(temp_item_type); // Item Description item_desc = $('.item_desc', rowData).text(); $('.item_desc', editRow).attr('value', item_desc); // Avatar size item_avatar = $('.item_avatar', rowData).text(); $('.item_avatar', editRow).attr('value', item_avatar); // Hidden field value item_hiddenField = $('.item_hiddenField', rowData).text(); $('.item_hiddenField', editRow).attr('value', item_hiddenField); // Item Options item_options = $('.item_options', rowData).text(); $('.item_options', editRow).attr('value', item_options); //Item Required checkbox item_required = $('.item_required', rowData).text(); if(item_required == "yes") { $('.item_required', editRow).attr('checked', 'checked'); } $('.select', editRow).each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /*avatar */ } else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); } else { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.alternative3').hide(); $('.regular').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /*avatar */ } else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); } else { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } } }); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); // Scroll var target = $('#edit-'+c); if (c > 1) { var top = target.offset().top; $('html,body').animate({scrollTop: top}, 500); return false; } return false; }, editSave: function (e) { var d, b, c, f, g, itemMN; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemMN) { itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_edit", id: e, item_metaName: itemMN, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (jQuery.trim(r) == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input Saved.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, afterSave: function (e) { var x, y, z, n, m, o, p, q, r = true, t, itemMN; x = $("#edit-" + e); y = $("#option-" + e); z = $("#inline_" + e); $('.option').show(); $('a.cancel', x).removeClass('undo-add'); $('a.save', x).removeClass('add-save'); $("a.add-option").removeClass('disable'); $('a.edit-inline').removeClass('disable'); $('a.delete-inline').removeClass('disable'); if (n = $("input.item_title", x).val()) { if ($("select.item_type", x).val() != 'heading') { $(y).removeClass('col-heading'); $('.col-title', y).attr('colspan', 1); $(".col-type", y).show(); $(".col-metaName", y).show(); itemMN = $("input.item_metaName", x).val(); if (itemMN == '') itemMN = n; itemMN = itemMN.replace(" ","_"); $(".col-metaName", y).text(itemMN); $(".col-internal_id", y).show(); $(".col-internal_id", y).text(e); $(".col-item_required", y).show(); t = $("input.item_required", x).attr('checked'); if (t == 'checked'){ $(".col-item_required", y).text('Yes'); $('.item_required', z).text('yes'); } else{ $(".col-item_required", y).text('No'); $('.item_required', z).text('no'); } $(".col-title", y).text('- ' + n); } else { $(y).addClass('col-heading'); $('.col-title', y).attr('colspan', 5); $(".col-internal_id", y).hide(); $(".col-type", y).hide(); $(".col-metaName", y).hide(); $(".col-item_required", y).hide(); $(".col-title", y).text(n); } $(".item_title", z).text(n); } if (m = $.trim($("input.item_metaName", x).val().toLowerCase()).replace(/(\s+)/g,'_')) { $(".col-key", y).text(m); $(".item_metaName", z).text(m); } else { m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_'); $(".col-key", y).text(m); $(".item_metaName", z).text(m); } if (o = $("select.item_type option:selected", x).val()) { $(".col-type", y).text(o); $(".item_type", z).text(o); } if (p = $("textarea.item_desc", x).val()) { $(".item_desc", z).text(p); } if (r = $("input.item_options", x).val()) { $(".item_options", z).text(r); } }, revert: function () { var b, n, m, o, p, q, r = true; if (b = $(".inline-editor").attr("id")) { $('#'+ b).remove(); b = b.substr(b.lastIndexOf("-") + 1); $('.option').show(); $("#option-" + b).show(); } return false; } }; $(document).ready(function () { inlineEditOption.init(); }) })(jQuery);
JavaScript
/* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ /** * TableDnD plug-in for JQuery, allows you to drag and drop table rows * You can set up various options to control how the system will work * Copyright (c) Denis Howlett <denish@isocra.com> * Licensed like jQuery, see http://docs.jquery.com/License. * * Configuration options: * * onDragStyle * This is the style that is assigned to the row during drag. There are limitations to the styles that can be * associated with a row (such as you can't assign a border--well you can, but it won't be * displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as * a map (as used in the jQuery css(...) function). * onDropStyle * This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations * to what you can do. Also this replaces the original style, so again consider using onDragClass which * is simply added and then removed on drop. * onDragClass * This class is added for the duration of the drag and then removed when the row is dropped. It is more * flexible than using onDragStyle since it can be inherited by the row cells and other content. The default * is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your * stylesheet. * onDrop * Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table * and the row that was dropped. You can work out the new order of the rows by using * table.rows. * onDragStart * Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the * table and the row which the user has started to drag. * onAllowDrop * Pass a function that will be called as a row is over another row. If the function returns true, allow * dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under * the cursor. It returns a boolean: true allows the drop, false doesn't allow it. * scrollAmount * This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the * window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2, * FF3 beta * dragHandle * This is the name of a class that you assign to one or more cells in each row that is draggable. If you * specify this class, then you are responsible for setting cursor: move in the CSS and only these cells * will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where * the whole row is draggable. * * Other ways to control behaviour: * * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows * that you don't want to be draggable. * * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have * an ID as must all the rows. * * Other methods: * * $("...").tableDnDUpdate() * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells). * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again. * The table maintains the original configuration (so you don't have to specify it again). * * $("...").tableDnDSerialize() * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be * called from anywhere and isn't dependent on the currentTable being set up correctly before calling * * Known problems: * - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0 * * Version 0.2: 2008-02-20 First public version * Version 0.3: 2008-02-07 Added onDragStart option * Made the scroll amount configurable (default is 5 as before) * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes * Added onAllowDrop to control dropping * Fixed a bug which meant that you couldn't set the scroll amount in both directions * Added serialize method * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row * draggable * Improved the serialize method to use a default (and settable) regular expression. * Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table */ jQuery.tableDnD = { /** Keep hold of the current table being dragged */ currentTable : null, /** Keep hold of the current drag object if any */ dragObject: null, /** The current mouse offset */ mouseOffset: null, /** Remember the old value of Y so that we don't do too much processing */ oldY: 0, /** Actually build the structure */ build: function(options) { // Set up the defaults if any this.each(function() { // This is bound to each matching table, set up the defaults and override with user options this.tableDnDConfig = jQuery.extend({ onDragStyle: null, onDropStyle: null, // Add in the default class for whileDragging onDragClass: "tDnD_whileDrag", onDrop: null, onDragStart: null, scrollAmount: 5, serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs serializeParamName: null, // If you want to specify another parameter name instead of the table ID dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable }, options || {}); // Now make the rows draggable jQuery.tableDnD.makeDraggable(this); }); // Now we need to capture the mouse up and mouse move event // We can use bind so that we don't interfere with other event handlers jQuery(document) .bind('mousemove', jQuery.tableDnD.mousemove) .bind('mouseup', jQuery.tableDnD.mouseup); // Don't break the chain return this; }, /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */ makeDraggable: function(table) { var config = table.tableDnDConfig; if (table.tableDnDConfig.dragHandle) { // We only need to add the event to the specified cells var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table); cells.each(function() { // The cell is bound to "this" jQuery(this).mousedown(function(ev) { jQuery.tableDnD.dragObject = this.parentNode; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; }); }) } else { // For backwards compatibility, we add the event to the whole row var rows = jQuery("tr", table); // get all the rows as a wrapped set rows.each(function() { // Iterate through each row, the row is bound to "this" var row = jQuery(this); if (! row.hasClass("nodrag")) { row.mousedown(function(ev) { if (ev.target.tagName == "TD") { jQuery.tableDnD.dragObject = this; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; } }).css("cursor", "move"); // Store the tableDnD object } }); } }, updateTables: function() { this.each(function() { // this is now bound to each matching table if (this.tableDnDConfig) { jQuery.tableDnD.makeDraggable(this); } }) }, /** Get the mouse coordinates from the event (allowing for browser differences) */ mouseCoords: function(ev){ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; }, /** Given a target element and a mouse event, get the mouse offset from that element. To do this we need the element's position and the mouse position */ getMouseOffset: function(target, ev) { ev = ev || window.event; var docPos = this.getPosition(target); var mousePos = this.mouseCoords(ev); return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}; }, /** Get the position of an element by going up the DOM tree and adding up all the offsets */ getPosition: function(e){ var left = 0; var top = 0; /** Safari fix -- thanks to Luis Chato for this! */ if (e.offsetHeight == 0) { /** Safari 2 doesn't correctly grab the offsetTop of a table row this is detailed here: http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/ the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild. note that firefox will return a text node as a first child, so designing a more thorough solution may need to take that into account, for now this seems to work in firefox, safari, ie */ e = e.firstChild; // a table cell } while (e.offsetParent){ left += e.offsetLeft; top += e.offsetTop; e = e.offsetParent; } left += e.offsetLeft; top += e.offsetTop; return {x:left, y:top}; }, mousemove: function(ev) { if (jQuery.tableDnD.dragObject == null) { return; } var dragObj = jQuery(jQuery.tableDnD.dragObject); var config = jQuery.tableDnD.currentTable.tableDnDConfig; var mousePos = jQuery.tableDnD.mouseCoords(ev); var y = mousePos.y - jQuery.tableDnD.mouseOffset.y; //auto scroll the window var yOffset = window.pageYOffset; if (document.all) { // Windows version //yOffset=document.body.scrollTop; if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') { yOffset = document.documentElement.scrollTop; } else if (typeof document.body != 'undefined') { yOffset=document.body.scrollTop; } } if (mousePos.y-yOffset < config.scrollAmount) { window.scrollBy(0, -config.scrollAmount); } else { var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight; if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) { window.scrollBy(0, config.scrollAmount); } } if (y != jQuery.tableDnD.oldY) { // work out if we're going up or down... var movingDown = y > jQuery.tableDnD.oldY; // update the old value jQuery.tableDnD.oldY = y; // update the style to show we're dragging if (config.onDragClass) { dragObj.addClass(config.onDragClass); } else { dragObj.css(config.onDragStyle); } // If we're over a row then move the dragged row to there so that the user sees the // effect dynamically var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y); if (currentRow) { // TODO worry about what happens when there are multiple TBODIES if (movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } } } return false; }, /** We're only worried about the y position really, because we can only move rows up and down */ findDropTargetRow: function(draggedRow, y) { var rows = jQuery.tableDnD.currentTable.rows; for (var i=0; i<rows.length; i++) { var row = rows[i]; var rowY = this.getPosition(row).y; var rowHeight = parseInt(row.offsetHeight)/2; if (row.offsetHeight == 0) { rowY = this.getPosition(row.firstChild).y; rowHeight = parseInt(row.firstChild.offsetHeight)/2; } // Because we always have to insert before, we need to offset the height a bit if ((y > rowY - rowHeight) && (y < (rowY + rowHeight + rowHeight))) { // that's the row we're over // If it's the same as the current row, ignore it if (row == draggedRow) {return null;} var config = jQuery.tableDnD.currentTable.tableDnDConfig; if (config.onAllowDrop) { if (config.onAllowDrop(draggedRow, row)) { return row; } else { return null; } } else { // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic) var nodrop = jQuery(row).hasClass("nodrop"); if (! nodrop) { return row; } else { return null; } } return row; } } return null; }, mouseup: function(e) { if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) { var droppedRow = jQuery.tableDnD.dragObject; var config = jQuery.tableDnD.currentTable.tableDnDConfig; // If we have a dragObject, then we need to release it, // The row will already have been moved to the right place so we just reset stuff if (config.onDragClass) { jQuery(droppedRow).removeClass(config.onDragClass); } else { jQuery(droppedRow).css(config.onDropStyle); } jQuery.tableDnD.dragObject = null; if (config.onDrop) { // Call the onDrop method if there is one config.onDrop(jQuery.tableDnD.currentTable, droppedRow); } jQuery.tableDnD.currentTable = null; // let go of the table too } }, serialize: function() { if (jQuery.tableDnD.currentTable) { return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable); } else { return "Error: No Table id set, you need to set an id on your table and every row"; } }, serializeTable: function(table) { var result = ""; var tableId = table.id; var rows = table.rows; for (var i=0; i<rows.length; i++) { if (result.length > 0) result += "&"; var rowId = rows[i].id; if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) { rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0]; } result += tableId + '[]=' + rowId; } return result; }, serializeTables: function() { var result = ""; this.each(function() { // this is now bound to each matching table result += jQuery.tableDnD.serializeTable(this); }); return result; } } jQuery.fn.extend( { tableDnD : jQuery.tableDnD.build, tableDnDUpdate : jQuery.tableDnD.updateTables, tableDnDSerialize: jQuery.tableDnD.serializeTables } );
JavaScript
/** * * Delay * * Creates a way to delay events * Dependencies: jQuery * */ /* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ (function ($) { $.fn.delay = function(time,func){ return this.each(function(){ setTimeout(func,time); }); }; })(jQuery); /** * * Center AJAX * * Creates a way to center the AJAX message * Dependencies: jQuery * */ (function ($) { $.fn.ajaxMessage = function(html){ if (html) { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()}); } else { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()}); } }; })(jQuery); /** * * Style File * * Creates a way to cover file input with a better styled version * Dependencies: jQuery * */ (function ($) { styleFile = { init: function () { $('input.file').each(function(){ var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />'; $(this).wrap('<div class="file_wrap" />'); $(this).addClass('file').css('opacity', 0); //set to invisible $(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton)); $(this).bind('change', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); $(this).bind('mouseout', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); }); } }; $(document).ready(function () { styleFile.init() }) })(jQuery); /** * * Style Select * * Replace Select text * Dependencies: jQuery * */ (function ($) { styleSelect = { init: function () { $('.select_wrapper').each(function () { $(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>'); }); $('.select').live('change', function () { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); $('.select').bind($.browser.msie ? 'click' : 'change', function(event) { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); } }; $(document).ready(function () { styleSelect.init() }) })(jQuery); /** * * Activate Tabs * * Tab style UI toggle * Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs * */ (function ($) { activateTabs = { init: function () { // Activate $("#options_tabs").tabs(); // Append Toggle Button $('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>'); // Toggle Tabs $('.toggle_tabs').toggle(function() { $("#options_tabs").tabs('destroy'); $(this).addClass('off'); }, function() { $("#options_tabs").tabs(); $(this).removeClass('off'); }); } }; $(document).ready(function () { activateTabs.init() }) })(jQuery); /** * * Upload Option * * Allows window.send_to_editor to function properly using a private post_id * Dependencies: jQuery, Media Upload, Thickbox * */ (function ($) { uploadOption = { init: function () { var formfield, formID, btnContent = true; // On Click $('.upload_button').live("click", function () { formfield = $(this).prev('input').attr('name'); formID = $(this).attr('rel'); tb_show('', 'media-upload.php?post_id='+formID+'&type=image&amp;TB_iframe=1'); return false; }); window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html) { if (formfield) { itemurl = $(html).attr('href'); var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi; var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi; var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi; var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi; if (itemurl.match(image)) { btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>'; } else { btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>'; } $('#' + formfield).val(itemurl); $('#' + formfield).next().next('div').slideDown().html(btnContent); tb_remove(); } else { window.original_send_to_editor(html); } } } }; $(document).ready(function () { uploadOption.init() }) })(jQuery); /** * * Inline Edit Options * * Creates & Updates Options via Ajax * Dependencies: jQuery * */ (function ($) { inlineEditOption = { init: function () { var c = this, d = $("tr.inline-edit-option"); $('.save-options', '#the-theme-options').live("click", function () { inlineEditOption.save_options(this); return false; }); $("a.edit-inline").live("click", function (event) { if ($("a.edit-inline").hasClass('disable')) { event.preventDefault(); return false; } else { inlineEditOption.edit(this); return false; } }); $("a.save").live("click", function () { if ($("a.save").hasClass('add-save')) { inlineEditOption.addSave(this); return false; } else { inlineEditOption.editSave(this); return false; } }); $("a.cancel").live("click", function () { if ($("a.cancel").hasClass('undo-add')) { inlineEditOption.undoAdd(); return false; } else { inlineEditOption.revert(); return false; } }); $("a.add-option").live("click", function (event) { if ($(this).hasClass('disable')) { event.preventDefault(); return false; } else { $.post( ajaxurl, { action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() }, function (response) { c = parseInt(response) + 1; inlineEditOption.add(c); } ); return false; } }); $('.delete-inline').live("click", function (event) { if ($("a.delete-inline").hasClass('disable')) { event.preventDefault(); return false; } else { var agree = confirm("Are you sure you want to delete this input?"); if (agree) { inlineEditOption.remove(this); return false; } else { return false; } } }); // Fade out message div if ($('.ajax-message').hasClass('show')) { $('.ajax-message').ajaxMessage(); } // Remove Uploaded Image $('.remove').live('click', function(event) { $(this).hide(); $(this).parents().prev().prev('.upload').attr('value', ''); $(this).parents('.screenshot').slideUp(); }); }, save_options: function (e) { var d = { action: "profile_builder_array_save" }; b = $(':input', '#the-theme-options').serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r != -1) { $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Theme Options were saved</div>'); $(".option-tree-slider-body").hide(); $('.option-tree-slider .edit').removeClass('down'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>Theme Options could not be saved</div>'); } }); return false; }, remove: function (b) { var c = true; // Set ID c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); d = { action: "profile_builder_delete", id: c, _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (r) { if (r) { if (r == 'removed') { $("#option-" + c).remove(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input deleted.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, add: function (c) { var e = this, addRow, editRow = true, temp_select; e.revert(); // Clone the blank main row addRow = $('#inline-add').clone(true); addRow = $(addRow).attr('id', 'option-'+c); // Clone the blank edit row editRow = $('#inline-edit').clone(true); $('a.cancel', editRow).addClass('undo-add'); $('a.save', editRow).addClass('add-save'); $('a.edit-inline').addClass('disable'); $('a.delete-inline').addClass('disable'); $('a.add-option').addClass('disable'); // Set Colspan to 5 $('td', editRow).attr('colspan', 5); // Add Row $("#framework-settings tr:last").after(addRow); // Add Row and hide $(addRow).hide().after(editRow); $('.item-data', addRow).attr('id', 'inline_'+c); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); $('.item_title', '#edit-'+c).focus(); $('.select').each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.regular').show(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); /* avatar */ }else if (temp_select == 'Avatar'){ $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /* end avatar */ } else { if (temp_select == 'Textarea') { $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else { $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).hide(); } } }); // Scroll $('html, body').animate({ scrollTop: 2000 }, 500); return false; }, undoAdd: function (b) { var e = this, c = true; e.revert(); c = $("#framework-settings tr:last").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); $("a.edit-inline").removeClass('disable'); $("a.delete-inline").removeClass('disable'); $("a.add-option").removeClass('disable'); $("#option-" + c).remove(); return false; }, addSave: function (e) { var d, b, c, f, g, itemId; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemId) { itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_add", id: e, item_id: itemId, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (r == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input added.</div>'); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, edit: function (b) { var e = this, c, editRow, rowData, item_title, item_id, item_type, item_desc, item_options = true, temp_select; e.revert(); c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); // Clone the blank row editRow = $('#inline-edit').clone(true); $('td', editRow).attr('colspan', 5); $("#option-" + c).hide().after(editRow); // First Option Settings if ("#option-" + c == '#option-1') { $('.option').hide(); $('.option-title').show().css({"paddingBottom":"1px"}); $('.description', editRow).html('First item must be a heading.'); } // Populate the option data rowData = $('#inline_' + c); // Item Title item_title = $('.item_title', rowData).text(); $('.item_title', editRow).attr('value', item_title); // Item ID item_id = $('.item_id', rowData).text(); $('.item_id', editRow).attr('value', item_id); // Item Type item_type = $('.item_type', rowData).text(); $('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true); var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text(); $('.select_wrapper span', editRow).text(temp_item_type); // Item Description item_desc = $('.item_desc', rowData).text(); $('.item_desc', editRow).attr('value', item_desc); // Avatar size item_avatar = $('.item_avatar', rowData).text(); $('.item_avatar', editRow).attr('value', item_avatar); // Item Options item_options = $('.item_options', rowData).text(); $('.item_options', editRow).attr('value', item_options); $('.select', editRow).each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /*avatar */ } else if (temp_select == 'Avatar'){ $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /* end avatar */ } else { if (temp_select == 'Textarea') { $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else { $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); } } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.regular').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /*avatar */ } else if (temp_select == 'Avatar'){ $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /* end avatar */ } else { if (temp_select == 'Textarea') { $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else { $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); } } }); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); // Scroll var target = $('#edit-'+c); if (c > 1) { var top = target.offset().top; $('html,body').animate({scrollTop: top}, 500); return false; } return false; }, editSave: function (e) { var d, b, c, f, g, itemId; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemId) { itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_edit", id: e, item_id: itemId, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (r == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Option Saved.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, afterSave: function (e) { var x, y, z, n, m, o, p, q, r = true; x = $("#edit-" + e); y = $("#option-" + e); z = $("#inline_" + e); $('.option').show(); $('a.cancel', x).removeClass('undo-add'); $('a.save', x).removeClass('add-save'); $("a.add-option").removeClass('disable'); $('a.edit-inline').removeClass('disable'); $('a.delete-inline').removeClass('disable'); if (n = $("input.item_title", x).val()) { if ($("select.item_type", x).val() != 'heading') { $(y).removeClass('col-heading'); $('.col-title', y).attr('colspan', 1); $(".col-key", y).show(); $(".col-type", y).show(); $(".col-title", y).text('- ' + n); } else { $(y).addClass('col-heading'); $('.col-title', y).attr('colspan', 3); $(".col-key", y).hide(); $(".col-type", y).hide(); $(".col-title", y).text(n); } $(".item_title", z).text(n); } if (m = $.trim($("input.item_id", x).val().toLowerCase()).replace(/(\s+)/g,'_')) { $(".col-key", y).text(m); $(".item_id", z).text(m); } else { m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_'); $(".col-key", y).text(m); $(".item_id", z).text(m); } if (o = $("select.item_type option:selected", x).val()) { $(".col-type", y).text(o); $(".item_type", z).text(o); } if (p = $("textarea.item_desc", x).val()) { $(".item_desc", z).text(p); } if (r = $("input.item_options", x).val()) { $(".item_options", z).text(r); } }, revert: function () { var b, n, m, o, p, q, r = true; if (b = $(".inline-editor").attr("id")) { $('#'+ b).remove(); b = b.substr(b.lastIndexOf("-") + 1); $('.option').show(); $("#option-" + b).show(); } return false; } }; $(document).ready(function () { inlineEditOption.init(); }) })(jQuery);
JavaScript
var map; var markers = []; var infowindow = new google.maps.InfoWindow(); var current_latLng; var current_address; function initialize() { var map_lat = 1; var map_lng=1; var image_latLgns_array = map_object.image_latLgns.split(';'); for(var i=0;i<image_latLgns_array.length-1;i++) { var latLng_array=image_latLgns_array[i].split(','); map_lat=latLng_array[0]; map_lng=latLng_array[1]; var latLng_set=new google.maps.LatLng(latLng_array[0], latLng_array[1]); add_Exist_Marker(latLng_set); } var mapOptions = { center: new google.maps.LatLng(map_lat,map_lng), zoom: 13 }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Create the search box and link it to the UI element. var input = /** @type {HTMLInputElement} */( document.getElementById('pac-input')); var types = document.getElementById('save-location'); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(types); var searchBox = new google.maps.places.SearchBox( /** @type {HTMLInputElement} */(input)); // Listen for the event fired when the user selects an item from the // pick list. Retrieve the matching places for that item. if(map_object.viewmode!='yes') google.maps.event.addListener(searchBox, 'places_changed', function() { var places = searchBox.getPlaces(); if (places.length == 0) { return; } for (var i = 0, marker; marker = markers[i]; i++) { marker.setMap(null); } // For each place, get the icon, place name, and location. markers = []; var bounds = new google.maps.LatLngBounds(); for (var i = 0, place; place = places[i]; i++) { bounds.extend(place.geometry.location); } map.fitBounds(bounds); }); // Bias the SearchBox results towards places that are within the bounds of the // current map's viewport. if(map_object.viewmode!='yes') google.maps.event.addListener(map, 'bounds_changed', function() { var bounds = map.getBounds(); searchBox.setBounds(bounds); }); if(map_object.viewmode!='yes') google.maps.event.addListener(map, 'click', function(event) { deleteMarkers(); addMarker(event.latLng); }); //them cac marker cho cac vi tri anh dc chon } function addMarker(location) { var geocoder = new google.maps.Geocoder(); geocoder.geocode({'latLng': location}, function(results, status) { var marker = new google.maps.Marker({ position: location, map: map }); current_address=results[1].formatted_address; current_latLng=location.lat()+','+location.lng(); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); markers.push(marker); }); } function add_Exist_Marker(location) { var geocoder = new google.maps.Geocoder(); geocoder.geocode({'latLng': location}, function() { var marker = new google.maps.Marker({ position: location, map: map }); markers.push(marker); }); } function clearMarkers() { for (var i = 0; i < markers.length; i++) { markers[i].setMap(null); } } function deleteMarkers() { clearMarkers(); markers = []; } google.maps.event.addDomListener(window, 'load', initialize); jQuery(document).ready(function() { jQuery("#save-location").click(function() { jQuery.ajax({ type:'POST', url:map_object.ajaxurl, data: { action:'save_location', image_ids:map_object.image_ids, address:current_address, latLng:current_latLng }, success:function(data) { window.close(); //jQuery('#page-content').html(data); } }); }); });
JavaScript
/* * @package WP Admin Bar Removal * @subpackage External JS Enqueue Script * @branche 2014 * @build 2014-08-15 * @since 3.7+ * @tested 3.9+ * @version 2014.0816.0392 * @target 2014.1210.0410 * @status STABLE (trunk) release * @development Code in Becoming! * @author slangjis * @license GPLv2 or later * @indentation GNU style coding standard */ /** * Please contact me @ slangji.wordpress.com/contact/ * to know how to get this file and test new features * that will be developed offline on github.com/slangji */
JavaScript
jQuery(document).ready(function(){ jQuery('.btn_comment').click(function(){ var counter = jQuery('.comment_counter'); var val = parseInt(counter.text()); val++; jQuery('.comment_counter').css({opacity: 0}); jQuery('.comment_counter').text(val); jQuery('.comment_counter').css({top: '-10px'}); jQuery('.comment_counter').animate({top: '-2px', opacity: 1}); }); jQuery('.btn_like').click(function(){ var counter = jQuery('.like_counter'); var val = parseInt(counter.text()); val++; jQuery('.like_counter').css({opacity: 0}); jQuery('.like_counter').text(val); jQuery('.like_counter').css({top: '-10px'}); jQuery('.like_counter').animate({top: '-2px', opacity: 1}); }); jQuery('.btn_image').click(function(){ var counter = jQuery('.image_counter'); var val = parseInt(counter.text()); val++; jQuery('.image_counter').css({opacity: 0}); jQuery('.image_counter').text(val); jQuery('.image_counter').css({top: '-10px'}); jQuery('.image_counter').animate({top: '-2px', opacity: 1}); }); //khi nhan dc message tu sever wsocket.onmessage = function(ev) { var msg = JSON.parse(ev.data); //chuyen chuoi JSON thanh doi tuong JSON var type = msg.type; //kieu message var user_id =msg.receiver_id; if(type == 'like') //neu la message cua user { jQuery.ajax({ type: "POST", url: ulike_obj.ajaxurl, data: { action: "get_like_counter", receiver_id: user_id, notification_type:'like', }, success: function(data) { var json = JSON.parse(data); var counter=json.counter; alert(data); jQuery('.like_counter').css({opacity: 0}); jQuery('.like_counter').text(counter); jQuery('.like_counter').css({top: '-10px'}); jQuery('.like_counter').animate({top: '-2px', opacity: 1}); } }); } if(type == 'comment') //neu la message cua he thong { jQuery('.comment_counter').css({opacity: 0}); jQuery('.comment_counter').text(counter); jQuery('.comment_counter').css({top: '-10px'}); jQuery('.comment_counter').animate({top: '-2px', opacity: 1}); } if(type == 'image') //neu la message cua he thong { jQuery('.image_counter').css({opacity: 0}); jQuery('.image_counter').text(counter); jQuery('.image_counter').css({top: '-10px'}); jQuery('.image_counter').animate({top: '-2px', opacity: 1}); } if(type == 'message') //neu la message cua he thong { jQuery('.image_counter').css({opacity: 0}); jQuery('.image_counter').text(counter); jQuery('.image_counter').css({top: '-10px'}); jQuery('.image_counter').animate({top: '-2px', opacity: 1}); } }; }); //socket javascript // jQuery(document).ready(function(){ // //tao doi tuong websocket // var wsUri = "ws://localhost:9000/server.php"; // wsocket = new WebSocket(wsUri); // //khi ket noi duoc mo // wsocket.onopen = function(ev) { // jQuery('#msgbox').append("<div class='msgsys'>Đã kết nối</div>"); // } // jQuery('#message').keypress(function(e) { // if (e.keyCode == 13 ) { // jQuery('#sendbtn').click(); // } // }) // jQuery('#sendbtn').click(function(){ // var msg = jQuery('#message').val(); // if(msg == ""){ //chua nhap message // alert("Vui lòng nhập thông điệp"); // return; // } // //tao doi tuong JSON // var msg = { // message: msg, // name: name, // }; // //gui chuoi json len server // wsocket.send(JSON.stringify(msg)); // jQuery('#message').val(''); //reset text // }); // //khi nhan dc message tu sever // wsocket.onmessage = function(ev) { // var msg = JSON.parse(ev.data); //chuyen chuoi JSON thanh doi tuong JSON // var type = msg.type; //kieu message // var counter=msg.counter; // var umsg = msg.message; //message // var uname = msg.name; //ten // var time = msg.time; // if(type == 'like') //neu la message cua user // { // jQuery('.comment_counter').css({opacity: 0}); // jQuery('.comment_counter').text(counter); // jQuery('.comment_counter').css({top: '-10px'}); // jQuery('.comment_counter').animate({top: '-2px', opacity: 1}); // } // if(type == 'comment') //neu la message cua he thong // { // jQuery('.like_counter').css({opacity: 0}); // jQuery('.like_counter').text(counter); // jQuery('.like_counter').css({top: '-10px'}); // jQuery('.like_counter').animate({top: '-2px', opacity: 1}); // } // if(type == 'image') //neu la message cua he thong // { // jQuery('.image_counter').css({opacity: 0}); // jQuery('.image_counter').text(counter); // jQuery('.image_counter').css({top: '-10px'}); // jQuery('.image_counter').animate({top: '-2px', opacity: 1}); // } // if(type == 'message') //neu la message cua he thong // { // jQuery('.image_counter').css({opacity: 0}); // jQuery('.image_counter').text(counter); // jQuery('.image_counter').css({top: '-10px'}); // jQuery('.image_counter').animate({top: '-2px', opacity: 1}); // } // }; // wsocket.onerror = function(ev){alert(ev.data);}; // wsocket.onclose = function(ev){jQuery('#msgbox').append("<div class='msgsys'>Ngat ket noi</div>");}; // }); jQuery(document).ready(function(){ //tao doi tuong websocket // var wsUri = "ws://localhost:9070/server.php"; // wsocket = new WebSocket(wsUri); // //khi ket noi duoc mo // wsocket.onopen = function(ev) { // jQuery('#msgbox').append("<div class='msgsys'>Đã kết nối</div>"); // } // jQuery('#message').keypress(function(e) { // if (e.keyCode == 13 ) { // jQuery('#sendbtn').click(); // } // }) // jQuery('#sendbtn').click(function(){ // var msg = jQuery('#message').val(); // if(msg == ""){ //chua nhap message // alert("Vui lòng nhập thông điệp"); // return; // } // //tao doi tuong JSON // var msg = { // message: msg, // name: name, // }; // //gui chuoi json len server // wsocket.send(JSON.stringify(msg)); // jQuery('#message').val(''); //reset text // }); // //khi nhan dc message tu sever // wsocket.onmessage = function(ev) { // var msg = JSON.parse(ev.data); //chuyen chuoi JSON thanh doi tuong JSON // var type = msg.type; //kieu message // var umsg = msg.message; //message // var uname = msg.name; //ten // var time = msg.time; // if(type == 'usermsg') //neu la message cua user // { // jQuery('#msgbox').append("<div><span>"+time+"</span> | <span class='user_name'>"+uname+"</span> : <span class='user_message'>"+umsg+"</span></div>"); // } // if(type == 'system') //neu la message cua he thong // { // jQuery('#msgbox').append("<div class='msgsys'>"+umsg+"</div>"); // } // //jQuery('#msgbox').scrollTop(jQuery('#msgbox')[0].scrollHeight); // }; // wsocket.onerror = function(ev){jQuery('#msgbox').append("<div class='errorsys'>Co loi xay ra - "+ev.data+"</div>");}; // wsocket.onclose = function(ev){jQuery('#msgbox').append("<div class='msgsys'>Ngat ket noi</div>");}; });
JavaScript
jQuery(function(){ //hover states on the static widgets jQuery('#dialog_link, ul#icons li').hover( function() { jQuery(this).addClass('ui-state-hover'); }, function() { jQuery(this).removeClass('ui-state-hover'); } ); }); /* initialize datepicker */ jQuery(function(){ // Datepicker jQuery('.wppb_datepicker').datepicker({ inline: true, changeMonth: true, changeYear: true }); });
JavaScript
function wppb_insertAtCursor(myField,value) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = value; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + value + myField.value.substring(endPos, myField.value.length); } else { myField.value += value; } } function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function wppb_replaceSelection (input, replaceString) { if (input.setSelectionRange) { var selectionStart = input.selectionStart; var selectionEnd = input.selectionEnd; input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd); if (selectionStart != selectionEnd){ setSelectionRange(input, selectionStart, selectionStart + replaceString.length); }else{ setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length); } }else if (document.selection) { var range = document.selection.createRange(); if (range.parentElement() == input) { var isCollapsed = range.text == ''; range.text = replaceString; if (!isCollapsed) { range.moveStart('character', -replaceString.length); range.select(); } } } } // We are going to catch the TAB key so that we can use it, Hooray! function wppb_catchTab(item,e){ if(navigator.userAgent.match("Gecko")){ c=e.which; }else{ c=e.keyCode; } if(c==9){ wppb_replaceSelection(item,String.fromCharCode(9)); setTimeout("document.getElementById('"+item.id+"').focus();",0); return false; } }
JavaScript
/** * * Delay * * Creates a way to delay events * Dependencies: jQuery * */ /* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ (function ($) { $.fn.delay = function(time,func){ return this.each(function(){ setTimeout(func,time); }); }; })(jQuery); /** * * Center AJAX * * Creates a way to center the AJAX message * Dependencies: jQuery * */ (function ($) { $.fn.ajaxMessage = function(html){ if (html) { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()}); } else { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()}); } }; })(jQuery); /** * * Style File * * Creates a way to cover file input with a better styled version * Dependencies: jQuery * */ (function ($) { styleFile = { init: function () { $('input.file').each(function(){ var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />'; $(this).wrap('<div class="file_wrap" />'); $(this).addClass('file').css('opacity', 0); //set to invisible $(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton)); $(this).bind('change', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); $(this).bind('mouseout', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); }); } }; $(document).ready(function () { styleFile.init() }) })(jQuery); /** * * Style Select * * Replace Select text * Dependencies: jQuery * */ (function ($) { styleSelect = { init: function () { $('.select_wrapper').each(function () { $(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>'); }); $('.select').live('change', function () { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); $('.select').bind($.browser.msie ? 'click' : 'change', function(event) { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); } }; $(document).ready(function () { styleSelect.init() }) })(jQuery); /** * * Activate Tabs * * Tab style UI toggle * Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs * */ (function ($) { activateTabs = { init: function () { // Activate $("#options_tabs").tabs(); // Append Toggle Button $('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>'); // Toggle Tabs $('.toggle_tabs').toggle(function() { $("#options_tabs").tabs('destroy'); $(this).addClass('off'); }, function() { $("#options_tabs").tabs(); $(this).removeClass('off'); }); } }; $(document).ready(function () { activateTabs.init() }) })(jQuery); /** * * Upload Option * * Allows window.send_to_editor to function properly using a private post_id * Dependencies: jQuery, Media Upload, Thickbox * */ (function ($) { uploadOption = { init: function () { var formfield, formID, btnContent = true; // On Click $('.upload_button').live("click", function () { formfield = $(this).prev('input').attr('name'); formID = $(this).attr('rel'); tb_show('', 'media-upload.php?post_id='+formID+'&type=image&amp;TB_iframe=1'); return false; }); window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html) { if (formfield) { itemurl = $(html).attr('href'); var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi; var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi; var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi; var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi; if (itemurl.match(image)) { btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>'; } else { btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>'; } $('#' + formfield).val(itemurl); $('#' + formfield).next().next('div').slideDown().html(btnContent); tb_remove(); } else { window.original_send_to_editor(html); } } } }; $(document).ready(function () { uploadOption.init() }) })(jQuery); /** * * Inline Edit Options * * Creates & Updates Options via Ajax * Dependencies: jQuery * */ (function ($) { inlineEditOption = { init: function () { var c = this, d = $("tr.inline-edit-option"); $('.save-options', '#the-theme-options').live("click", function () { inlineEditOption.save_options(this); return false; }); $("a.edit-inline").live("click", function (event) { if ($("a.edit-inline").hasClass('disable')) { event.preventDefault(); return false; } else { inlineEditOption.edit(this); return false; } }); $("a.save").live("click", function () { if ($("a.save").hasClass('add-save')) { inlineEditOption.addSave(this); return false; } else { inlineEditOption.editSave(this); return false; } }); $("a.cancel").live("click", function () { if ($("a.cancel").hasClass('undo-add')) { inlineEditOption.undoAdd(); return false; } else { inlineEditOption.revert(); return false; } }); $("a.add-option").live("click", function (event) { if ($(this).hasClass('disable')) { event.preventDefault(); return false; } else { $.post( ajaxurl, { action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() }, function (response) { c = parseInt(response) + 1; inlineEditOption.add(c); } ); return false; } }); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); $('.delete-inline').live("click", function (event) { if ($("a.delete-inline").hasClass('disable')) { event.preventDefault(); return false; } else { var agree = confirm("Are you sure you want to delete this input?"); if (agree) { inlineEditOption.remove(this); return false; } else { return false; } } }); // Fade out message div if ($('.ajax-message').hasClass('show')) { $('.ajax-message').ajaxMessage(); } // Remove Uploaded Image $('.remove').live('click', function(event) { $(this).hide(); $(this).parents().prev().prev('.upload').attr('value', ''); $(this).parents('.screenshot').slideUp(); }); }, save_options: function (e) { var d = { action: "profile_builder_array_save" }; b = $(':input', '#the-theme-options').serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r != -1) { $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Theme Options were saved</div>'); $(".option-tree-slider-body").hide(); $('.option-tree-slider .edit').removeClass('down'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>Theme Options could not be saved</div>'); } }); return false; }, remove: function (b) { var c = true; // Set ID c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); d = { action: "profile_builder_delete", id: c, _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (r) { if (r) { r=$.trim(r); if (r == 'removed') { $("#option-" + c).remove(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input deleted.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, add: function (c) { var e = this, addRow, editRow = true, temp_select; e.revert(); // Clone the blank main row addRow = $('#inline-add').clone(true); addRow = $(addRow).attr('id', 'option-'+c); // Clone the blank edit row editRow = $('#inline-edit').clone(true); $('a.cancel', editRow).addClass('undo-add'); $('a.save', editRow).addClass('add-save'); $('a.edit-inline').addClass('disable'); $('a.delete-inline').addClass('disable'); $('a.add-option').addClass('disable'); // Set Colspan to 6 $('td', editRow).attr('colspan', 6); // Add Row $("#framework-settings tr:last").after(addRow); // Add Row and hide $(addRow).hide().after(editRow); $('.item-data', addRow).attr('id', 'inline_'+c); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); $('.item_title', '#edit-'+c).focus(); // Item MetaKey $('.item_metaName', editRow).attr('value', 'custom_field_'+c); //internal id $('.internal_id', editRow).attr('value', c); $('.select').each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).hide(); } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative3').hide(); $('.alternative').hide(); $('.regular').show(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); $('.option-required', '#edit-'+c).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /* avatar */ }else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); $('.option-required', '#edit-'+c).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).show(); } } }); // Scroll $('html, body').animate({ scrollTop: 2000 }, 500); return false; }, undoAdd: function (b) { var e = this, c = true; e.revert(); c = $("#framework-settings tr:last").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); $("a.edit-inline").removeClass('disable'); $("a.delete-inline").removeClass('disable'); $("a.add-option").removeClass('disable'); $("#option-" + c).remove(); return false; }, addSave: function (e) { var d, b, c, f, g, itemMN; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemMN) { itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_add", id: e, item_metaName: itemMN, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (jQuery.trim(r) == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input added.</div>'); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, edit: function (b) { var e = this, c, editRow, rowData, item_title, itemMN, item_type, item_desc, item_options = true, temp_select, item_required; e.revert(); c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); // Clone the blank row editRow = $('#inline-edit').clone(true); $('td', editRow).attr('colspan', 6); $("#option-" + c).hide().after(editRow); // First Option Settings if ("#option-" + c == '#option-1') { $('.option').hide(); $('.option-title').show().css({"paddingBottom":"1px"}); //$('.option-title', editRow).html('<strong>Title:</strong> The title of the item.<br/>First item must be a heading.'); $('.option-internal_id', editRow).show(); } // Populate the option data rowData = $('#inline_' + c); // Item Title item_title = $('.item_title', rowData).text(); $('.item_title', editRow).attr('value', item_title); // Item MetaKey item_metaName = $('.item_metaName', rowData).text(); $('.item_metaName', editRow).attr('value', 'custom_field_'+c); // Item MetaNames itemMN = $('.item_metaName', rowData).text(); $('.item_metaName', editRow).attr('value', itemMN); // Internal ID internal_id = $('.internal_id', rowData).text(); $('.internal_id', editRow).attr('value', c); // Item Type item_type = $('.item_type', rowData).text(); $('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true); var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text(); $('.select_wrapper span', editRow).text(temp_item_type); // Item Description item_desc = $('.item_desc', rowData).text(); $('.item_desc', editRow).attr('value', item_desc); // Avatar size item_avatar = $('.item_avatar', rowData).text(); $('.item_avatar', editRow).attr('value', item_avatar); // Hidden field value item_hiddenField = $('.item_hiddenField', rowData).text(); $('.item_hiddenField', editRow).attr('value', item_hiddenField); // Item Options item_options = $('.item_options', rowData).text(); $('.item_options', editRow).attr('value', item_options); //Item Required checkbox item_required = $('.item_required', rowData).text(); if(item_required == "yes") { $('.item_required', editRow).attr('checked', 'checked'); } $('.select', editRow).each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /*avatar */ } else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); } else { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.alternative3').hide(); $('.regular').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /*avatar */ } else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); } else { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } } }); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); // Scroll var target = $('#edit-'+c); if (c > 1) { var top = target.offset().top; $('html,body').animate({scrollTop: top}, 500); return false; } return false; }, editSave: function (e) { var d, b, c, f, g, itemMN; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemMN) { itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_edit", id: e, item_metaName: itemMN, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (jQuery.trim(r) == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input Saved.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, afterSave: function (e) { var x, y, z, n, m, o, p, q, r = true, t, itemMN; x = $("#edit-" + e); y = $("#option-" + e); z = $("#inline_" + e); $('.option').show(); $('a.cancel', x).removeClass('undo-add'); $('a.save', x).removeClass('add-save'); $("a.add-option").removeClass('disable'); $('a.edit-inline').removeClass('disable'); $('a.delete-inline').removeClass('disable'); if (n = $("input.item_title", x).val()) { if ($("select.item_type", x).val() != 'heading') { $(y).removeClass('col-heading'); $('.col-title', y).attr('colspan', 1); $(".col-type", y).show(); $(".col-metaName", y).show(); itemMN = $("input.item_metaName", x).val(); if (itemMN == '') itemMN = n; itemMN = itemMN.replace(" ","_"); $(".col-metaName", y).text(itemMN); $(".col-internal_id", y).show(); $(".col-internal_id", y).text(e); $(".col-item_required", y).show(); t = $("input.item_required", x).attr('checked'); if (t == 'checked'){ $(".col-item_required", y).text('Yes'); $('.item_required', z).text('yes'); } else{ $(".col-item_required", y).text('No'); $('.item_required', z).text('no'); } $(".col-title", y).text('- ' + n); } else { $(y).addClass('col-heading'); $('.col-title', y).attr('colspan', 5); $(".col-internal_id", y).hide(); $(".col-type", y).hide(); $(".col-metaName", y).hide(); $(".col-item_required", y).hide(); $(".col-title", y).text(n); } $(".item_title", z).text(n); } if (m = $.trim($("input.item_metaName", x).val().toLowerCase()).replace(/(\s+)/g,'_')) { $(".col-key", y).text(m); $(".item_metaName", z).text(m); } else { m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_'); $(".col-key", y).text(m); $(".item_metaName", z).text(m); } if (o = $("select.item_type option:selected", x).val()) { $(".col-type", y).text(o); $(".item_type", z).text(o); } if (p = $("textarea.item_desc", x).val()) { $(".item_desc", z).text(p); } if (r = $("input.item_options", x).val()) { $(".item_options", z).text(r); } }, revert: function () { var b, n, m, o, p, q, r = true; if (b = $(".inline-editor").attr("id")) { $('#'+ b).remove(); b = b.substr(b.lastIndexOf("-") + 1); $('.option').show(); $("#option-" + b).show(); } return false; } }; $(document).ready(function () { inlineEditOption.init(); }) })(jQuery);
JavaScript
/* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ /** * TableDnD plug-in for JQuery, allows you to drag and drop table rows * You can set up various options to control how the system will work * Copyright (c) Denis Howlett <denish@isocra.com> * Licensed like jQuery, see http://docs.jquery.com/License. * * Configuration options: * * onDragStyle * This is the style that is assigned to the row during drag. There are limitations to the styles that can be * associated with a row (such as you can't assign a border--well you can, but it won't be * displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as * a map (as used in the jQuery css(...) function). * onDropStyle * This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations * to what you can do. Also this replaces the original style, so again consider using onDragClass which * is simply added and then removed on drop. * onDragClass * This class is added for the duration of the drag and then removed when the row is dropped. It is more * flexible than using onDragStyle since it can be inherited by the row cells and other content. The default * is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your * stylesheet. * onDrop * Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table * and the row that was dropped. You can work out the new order of the rows by using * table.rows. * onDragStart * Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the * table and the row which the user has started to drag. * onAllowDrop * Pass a function that will be called as a row is over another row. If the function returns true, allow * dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under * the cursor. It returns a boolean: true allows the drop, false doesn't allow it. * scrollAmount * This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the * window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2, * FF3 beta * dragHandle * This is the name of a class that you assign to one or more cells in each row that is draggable. If you * specify this class, then you are responsible for setting cursor: move in the CSS and only these cells * will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where * the whole row is draggable. * * Other ways to control behaviour: * * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows * that you don't want to be draggable. * * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have * an ID as must all the rows. * * Other methods: * * $("...").tableDnDUpdate() * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells). * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again. * The table maintains the original configuration (so you don't have to specify it again). * * $("...").tableDnDSerialize() * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be * called from anywhere and isn't dependent on the currentTable being set up correctly before calling * * Known problems: * - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0 * * Version 0.2: 2008-02-20 First public version * Version 0.3: 2008-02-07 Added onDragStart option * Made the scroll amount configurable (default is 5 as before) * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes * Added onAllowDrop to control dropping * Fixed a bug which meant that you couldn't set the scroll amount in both directions * Added serialize method * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row * draggable * Improved the serialize method to use a default (and settable) regular expression. * Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table */ jQuery.tableDnD = { /** Keep hold of the current table being dragged */ currentTable : null, /** Keep hold of the current drag object if any */ dragObject: null, /** The current mouse offset */ mouseOffset: null, /** Remember the old value of Y so that we don't do too much processing */ oldY: 0, /** Actually build the structure */ build: function(options) { // Set up the defaults if any this.each(function() { // This is bound to each matching table, set up the defaults and override with user options this.tableDnDConfig = jQuery.extend({ onDragStyle: null, onDropStyle: null, // Add in the default class for whileDragging onDragClass: "tDnD_whileDrag", onDrop: null, onDragStart: null, scrollAmount: 5, serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs serializeParamName: null, // If you want to specify another parameter name instead of the table ID dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable }, options || {}); // Now make the rows draggable jQuery.tableDnD.makeDraggable(this); }); // Now we need to capture the mouse up and mouse move event // We can use bind so that we don't interfere with other event handlers jQuery(document) .bind('mousemove', jQuery.tableDnD.mousemove) .bind('mouseup', jQuery.tableDnD.mouseup); // Don't break the chain return this; }, /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */ makeDraggable: function(table) { var config = table.tableDnDConfig; if (table.tableDnDConfig.dragHandle) { // We only need to add the event to the specified cells var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table); cells.each(function() { // The cell is bound to "this" jQuery(this).mousedown(function(ev) { jQuery.tableDnD.dragObject = this.parentNode; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; }); }) } else { // For backwards compatibility, we add the event to the whole row var rows = jQuery("tr", table); // get all the rows as a wrapped set rows.each(function() { // Iterate through each row, the row is bound to "this" var row = jQuery(this); if (! row.hasClass("nodrag")) { row.mousedown(function(ev) { if (ev.target.tagName == "TD") { jQuery.tableDnD.dragObject = this; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; } }).css("cursor", "move"); // Store the tableDnD object } }); } }, updateTables: function() { this.each(function() { // this is now bound to each matching table if (this.tableDnDConfig) { jQuery.tableDnD.makeDraggable(this); } }) }, /** Get the mouse coordinates from the event (allowing for browser differences) */ mouseCoords: function(ev){ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; }, /** Given a target element and a mouse event, get the mouse offset from that element. To do this we need the element's position and the mouse position */ getMouseOffset: function(target, ev) { ev = ev || window.event; var docPos = this.getPosition(target); var mousePos = this.mouseCoords(ev); return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}; }, /** Get the position of an element by going up the DOM tree and adding up all the offsets */ getPosition: function(e){ var left = 0; var top = 0; /** Safari fix -- thanks to Luis Chato for this! */ if (e.offsetHeight == 0) { /** Safari 2 doesn't correctly grab the offsetTop of a table row this is detailed here: http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/ the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild. note that firefox will return a text node as a first child, so designing a more thorough solution may need to take that into account, for now this seems to work in firefox, safari, ie */ e = e.firstChild; // a table cell } while (e.offsetParent){ left += e.offsetLeft; top += e.offsetTop; e = e.offsetParent; } left += e.offsetLeft; top += e.offsetTop; return {x:left, y:top}; }, mousemove: function(ev) { if (jQuery.tableDnD.dragObject == null) { return; } var dragObj = jQuery(jQuery.tableDnD.dragObject); var config = jQuery.tableDnD.currentTable.tableDnDConfig; var mousePos = jQuery.tableDnD.mouseCoords(ev); var y = mousePos.y - jQuery.tableDnD.mouseOffset.y; //auto scroll the window var yOffset = window.pageYOffset; if (document.all) { // Windows version //yOffset=document.body.scrollTop; if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') { yOffset = document.documentElement.scrollTop; } else if (typeof document.body != 'undefined') { yOffset=document.body.scrollTop; } } if (mousePos.y-yOffset < config.scrollAmount) { window.scrollBy(0, -config.scrollAmount); } else { var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight; if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) { window.scrollBy(0, config.scrollAmount); } } if (y != jQuery.tableDnD.oldY) { // work out if we're going up or down... var movingDown = y > jQuery.tableDnD.oldY; // update the old value jQuery.tableDnD.oldY = y; // update the style to show we're dragging if (config.onDragClass) { dragObj.addClass(config.onDragClass); } else { dragObj.css(config.onDragStyle); } // If we're over a row then move the dragged row to there so that the user sees the // effect dynamically var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y); if (currentRow) { // TODO worry about what happens when there are multiple TBODIES if (movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } } } return false; }, /** We're only worried about the y position really, because we can only move rows up and down */ findDropTargetRow: function(draggedRow, y) { var rows = jQuery.tableDnD.currentTable.rows; for (var i=0; i<rows.length; i++) { var row = rows[i]; var rowY = this.getPosition(row).y; var rowHeight = parseInt(row.offsetHeight)/2; if (row.offsetHeight == 0) { rowY = this.getPosition(row.firstChild).y; rowHeight = parseInt(row.firstChild.offsetHeight)/2; } // Because we always have to insert before, we need to offset the height a bit if ((y > rowY - rowHeight) && (y < (rowY + rowHeight + rowHeight))) { // that's the row we're over // If it's the same as the current row, ignore it if (row == draggedRow) {return null;} var config = jQuery.tableDnD.currentTable.tableDnDConfig; if (config.onAllowDrop) { if (config.onAllowDrop(draggedRow, row)) { return row; } else { return null; } } else { // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic) var nodrop = jQuery(row).hasClass("nodrop"); if (! nodrop) { return row; } else { return null; } } return row; } } return null; }, mouseup: function(e) { if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) { var droppedRow = jQuery.tableDnD.dragObject; var config = jQuery.tableDnD.currentTable.tableDnDConfig; // If we have a dragObject, then we need to release it, // The row will already have been moved to the right place so we just reset stuff if (config.onDragClass) { jQuery(droppedRow).removeClass(config.onDragClass); } else { jQuery(droppedRow).css(config.onDropStyle); } jQuery.tableDnD.dragObject = null; if (config.onDrop) { // Call the onDrop method if there is one config.onDrop(jQuery.tableDnD.currentTable, droppedRow); } jQuery.tableDnD.currentTable = null; // let go of the table too } }, serialize: function() { if (jQuery.tableDnD.currentTable) { return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable); } else { return "Error: No Table id set, you need to set an id on your table and every row"; } }, serializeTable: function(table) { var result = ""; var tableId = table.id; var rows = table.rows; for (var i=0; i<rows.length; i++) { if (result.length > 0) result += "&"; var rowId = rows[i].id; if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) { rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0]; } result += tableId + '[]=' + rowId; } return result; }, serializeTables: function() { var result = ""; this.each(function() { // this is now bound to each matching table result += jQuery.tableDnD.serializeTable(this); }); return result; } } jQuery.fn.extend( { tableDnD : jQuery.tableDnD.build, tableDnDUpdate : jQuery.tableDnD.updateTables, tableDnDSerialize: jQuery.tableDnD.serializeTables } );
JavaScript
jQuery(function(){ //hover states on the static widgets jQuery('#dialog_link, ul#icons li').hover( function() { jQuery(this).addClass('ui-state-hover'); }, function() { jQuery(this).removeClass('ui-state-hover'); } ); }); /* initialize datepicker */ jQuery(function(){ // Datepicker jQuery('.wppb_datepicker').datepicker({ inline: true, changeMonth: true, changeYear: true }); });
JavaScript
function wppb_insertAtCursor(myField,value) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = value; } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + value + myField.value.substring(endPos, myField.value.length); } else { myField.value += value; } } function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function wppb_replaceSelection (input, replaceString) { if (input.setSelectionRange) { var selectionStart = input.selectionStart; var selectionEnd = input.selectionEnd; input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd); if (selectionStart != selectionEnd){ setSelectionRange(input, selectionStart, selectionStart + replaceString.length); }else{ setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length); } }else if (document.selection) { var range = document.selection.createRange(); if (range.parentElement() == input) { var isCollapsed = range.text == ''; range.text = replaceString; if (!isCollapsed) { range.moveStart('character', -replaceString.length); range.select(); } } } } // We are going to catch the TAB key so that we can use it, Hooray! function wppb_catchTab(item,e){ if(navigator.userAgent.match("Gecko")){ c=e.which; }else{ c=e.keyCode; } if(c==9){ wppb_replaceSelection(item,String.fromCharCode(9)); setTimeout("document.getElementById('"+item.id+"').focus();",0); return false; } }
JavaScript
/** * * Delay * * Creates a way to delay events * Dependencies: jQuery * */ /* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ (function ($) { $.fn.delay = function(time,func){ return this.each(function(){ setTimeout(func,time); }); }; })(jQuery); /** * * Center AJAX * * Creates a way to center the AJAX message * Dependencies: jQuery * */ (function ($) { $.fn.ajaxMessage = function(html){ if (html) { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()}); } else { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()}); } }; })(jQuery); /** * * Style File * * Creates a way to cover file input with a better styled version * Dependencies: jQuery * */ (function ($) { styleFile = { init: function () { $('input.file').each(function(){ var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />'; $(this).wrap('<div class="file_wrap" />'); $(this).addClass('file').css('opacity', 0); //set to invisible $(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton)); $(this).bind('change', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); $(this).bind('mouseout', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); }); } }; $(document).ready(function () { styleFile.init() }) })(jQuery); /** * * Style Select * * Replace Select text * Dependencies: jQuery * */ (function ($) { styleSelect = { init: function () { $('.select_wrapper').each(function () { $(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>'); }); $('.select').live('change', function () { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); $('.select').bind($.browser.msie ? 'click' : 'change', function(event) { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); } }; $(document).ready(function () { styleSelect.init() }) })(jQuery); /** * * Activate Tabs * * Tab style UI toggle * Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs * */ (function ($) { activateTabs = { init: function () { // Activate $("#options_tabs").tabs(); // Append Toggle Button $('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>'); // Toggle Tabs $('.toggle_tabs').toggle(function() { $("#options_tabs").tabs('destroy'); $(this).addClass('off'); }, function() { $("#options_tabs").tabs(); $(this).removeClass('off'); }); } }; $(document).ready(function () { activateTabs.init() }) })(jQuery); /** * * Upload Option * * Allows window.send_to_editor to function properly using a private post_id * Dependencies: jQuery, Media Upload, Thickbox * */ (function ($) { uploadOption = { init: function () { var formfield, formID, btnContent = true; // On Click $('.upload_button').live("click", function () { formfield = $(this).prev('input').attr('name'); formID = $(this).attr('rel'); tb_show('', 'media-upload.php?post_id='+formID+'&type=image&amp;TB_iframe=1'); return false; }); window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html) { if (formfield) { itemurl = $(html).attr('href'); var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi; var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi; var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi; var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi; if (itemurl.match(image)) { btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>'; } else { btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>'; } $('#' + formfield).val(itemurl); $('#' + formfield).next().next('div').slideDown().html(btnContent); tb_remove(); } else { window.original_send_to_editor(html); } } } }; $(document).ready(function () { uploadOption.init() }) })(jQuery); /** * * Inline Edit Options * * Creates & Updates Options via Ajax * Dependencies: jQuery * */ (function ($) { inlineEditOption = { init: function () { var c = this, d = $("tr.inline-edit-option"); $('.save-options', '#the-theme-options').live("click", function () { inlineEditOption.save_options(this); return false; }); $("a.edit-inline").live("click", function (event) { if ($("a.edit-inline").hasClass('disable')) { event.preventDefault(); return false; } else { inlineEditOption.edit(this); return false; } }); $("a.save").live("click", function () { if ($("a.save").hasClass('add-save')) { inlineEditOption.addSave(this); return false; } else { inlineEditOption.editSave(this); return false; } }); $("a.cancel").live("click", function () { if ($("a.cancel").hasClass('undo-add')) { inlineEditOption.undoAdd(); return false; } else { inlineEditOption.revert(); return false; } }); $("a.add-option").live("click", function (event) { if ($(this).hasClass('disable')) { event.preventDefault(); return false; } else { $.post( ajaxurl, { action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() }, function (response) { c = parseInt(response) + 1; inlineEditOption.add(c); } ); return false; } }); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); $('.delete-inline').live("click", function (event) { if ($("a.delete-inline").hasClass('disable')) { event.preventDefault(); return false; } else { var agree = confirm("Are you sure you want to delete this input?"); if (agree) { inlineEditOption.remove(this); return false; } else { return false; } } }); // Fade out message div if ($('.ajax-message').hasClass('show')) { $('.ajax-message').ajaxMessage(); } // Remove Uploaded Image $('.remove').live('click', function(event) { $(this).hide(); $(this).parents().prev().prev('.upload').attr('value', ''); $(this).parents('.screenshot').slideUp(); }); }, save_options: function (e) { var d = { action: "profile_builder_array_save" }; b = $(':input', '#the-theme-options').serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r != -1) { $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Theme Options were saved</div>'); $(".option-tree-slider-body").hide(); $('.option-tree-slider .edit').removeClass('down'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>Theme Options could not be saved</div>'); } }); return false; }, remove: function (b) { var c = true; // Set ID c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); d = { action: "profile_builder_delete", id: c, _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (r) { if (r) { r=$.trim(r); if (r == 'removed') { $("#option-" + c).remove(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input deleted.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, add: function (c) { var e = this, addRow, editRow = true, temp_select; e.revert(); // Clone the blank main row addRow = $('#inline-add').clone(true); addRow = $(addRow).attr('id', 'option-'+c); // Clone the blank edit row editRow = $('#inline-edit').clone(true); $('a.cancel', editRow).addClass('undo-add'); $('a.save', editRow).addClass('add-save'); $('a.edit-inline').addClass('disable'); $('a.delete-inline').addClass('disable'); $('a.add-option').addClass('disable'); // Set Colspan to 6 $('td', editRow).attr('colspan', 6); // Add Row $("#framework-settings tr:last").after(addRow); // Add Row and hide $(addRow).hide().after(editRow); $('.item-data', addRow).attr('id', 'inline_'+c); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); $('.item_title', '#edit-'+c).focus(); // Item MetaKey $('.item_metaName', editRow).attr('value', 'custom_field_'+c); //internal id $('.internal_id', editRow).attr('value', c); $('.select').each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).hide(); } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative3').hide(); $('.alternative').hide(); $('.regular').show(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); $('.option-required', '#edit-'+c).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /* avatar */ }else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); $('.option-required', '#edit-'+c).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else { $('.alternative3').hide(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).hide(); $('.option-required', '#edit-'+c).show(); } } }); // Scroll $('html, body').animate({ scrollTop: 2000 }, 500); return false; }, undoAdd: function (b) { var e = this, c = true; e.revert(); c = $("#framework-settings tr:last").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); $("a.edit-inline").removeClass('disable'); $("a.delete-inline").removeClass('disable'); $("a.add-option").removeClass('disable'); $("#option-" + c).remove(); return false; }, addSave: function (e) { var d, b, c, f, g, itemMN; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemMN) { itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_add", id: e, item_metaName: itemMN, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (jQuery.trim(r) == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input added.</div>'); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, edit: function (b) { var e = this, c, editRow, rowData, item_title, itemMN, item_type, item_desc, item_options = true, temp_select, item_required; e.revert(); c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); // Clone the blank row editRow = $('#inline-edit').clone(true); $('td', editRow).attr('colspan', 6); $("#option-" + c).hide().after(editRow); // First Option Settings if ("#option-" + c == '#option-1') { $('.option').hide(); $('.option-title').show().css({"paddingBottom":"1px"}); //$('.option-title', editRow).html('<strong>Title:</strong> The title of the item.<br/>First item must be a heading.'); $('.option-internal_id', editRow).show(); } // Populate the option data rowData = $('#inline_' + c); // Item Title item_title = $('.item_title', rowData).text(); $('.item_title', editRow).attr('value', item_title); // Item MetaKey item_metaName = $('.item_metaName', rowData).text(); $('.item_metaName', editRow).attr('value', 'custom_field_'+c); // Item MetaNames itemMN = $('.item_metaName', rowData).text(); $('.item_metaName', editRow).attr('value', itemMN); // Internal ID internal_id = $('.internal_id', rowData).text(); $('.internal_id', editRow).attr('value', c); // Item Type item_type = $('.item_type', rowData).text(); $('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true); var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text(); $('.select_wrapper span', editRow).text(temp_item_type); // Item Description item_desc = $('.item_desc', rowData).text(); $('.item_desc', editRow).attr('value', item_desc); // Avatar size item_avatar = $('.item_avatar', rowData).text(); $('.item_avatar', editRow).attr('value', item_avatar); // Hidden field value item_hiddenField = $('.item_hiddenField', rowData).text(); $('.item_hiddenField', editRow).attr('value', item_hiddenField); // Item Options item_options = $('.item_options', rowData).text(); $('.item_options', editRow).attr('value', item_options); //Item Required checkbox item_required = $('.item_required', rowData).text(); if(item_required == "yes") { $('.item_required', editRow).attr('checked', 'checked'); } $('.select', editRow).each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /*avatar */ } else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); } else { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.alternative3').hide(); $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.alternative3').hide(); $('.regular').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* input */ }else if (temp_select == 'Input'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Maximum Character Length:</strong> Enter a value for the maxlength attribute(optional).'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-required', editRow).show(); /* end input */ /*avatar */ } else if (temp_select == 'Avatar'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end avatar */ /*upload */ } else if (temp_select == 'Upload'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Allowed Extensions:</strong> Specify the extension(s) you want to limit for upload(optional).<br/>Example: .ext1,.ext2,.ext3'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); /* end upload */ /* agree to terms */ }else if (temp_select == 'Checkbox ("I agree to terms and conditions")'){ $('.alternative3').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); /* agree to terms end */ } /* hidden input*/ else if (temp_select == 'Input (Hidden)'){ $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Value:</strong> Enter the value for the hidden input field. This can be overwritten for each user individually by a user with administrator rights.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).hide(); /* end hidden input */ } else { if (temp_select == 'Textarea') { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.alternative3').hide(); $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); $('.option-internal_id', editRow).show(); } else { $('.alternative3').hide(); $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); $('.option-internal_id', editRow).show(); $('.option-required', editRow).show(); } } }); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); // Scroll var target = $('#edit-'+c); if (c > 1) { var top = target.offset().top; $('html,body').animate({scrollTop: top}, 500); return false; } return false; }, editSave: function (e) { var d, b, c, f, g, itemMN; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemMN = $.trim($("input.item_metaName", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemMN) { itemMN = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_edit", id: e, item_metaName: itemMN, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (jQuery.trim(r) == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input Saved.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, afterSave: function (e) { var x, y, z, n, m, o, p, q, r = true, t, itemMN; x = $("#edit-" + e); y = $("#option-" + e); z = $("#inline_" + e); $('.option').show(); $('a.cancel', x).removeClass('undo-add'); $('a.save', x).removeClass('add-save'); $("a.add-option").removeClass('disable'); $('a.edit-inline').removeClass('disable'); $('a.delete-inline').removeClass('disable'); if (n = $("input.item_title", x).val()) { if ($("select.item_type", x).val() != 'heading') { $(y).removeClass('col-heading'); $('.col-title', y).attr('colspan', 1); $(".col-type", y).show(); $(".col-metaName", y).show(); itemMN = $("input.item_metaName", x).val(); if (itemMN == '') itemMN = n; itemMN = itemMN.replace(" ","_"); $(".col-metaName", y).text(itemMN); $(".col-internal_id", y).show(); $(".col-internal_id", y).text(e); $(".col-item_required", y).show(); t = $("input.item_required", x).attr('checked'); if (t == 'checked'){ $(".col-item_required", y).text('Yes'); $('.item_required', z).text('yes'); } else{ $(".col-item_required", y).text('No'); $('.item_required', z).text('no'); } $(".col-title", y).text('- ' + n); } else { $(y).addClass('col-heading'); $('.col-title', y).attr('colspan', 5); $(".col-internal_id", y).hide(); $(".col-type", y).hide(); $(".col-metaName", y).hide(); $(".col-item_required", y).hide(); $(".col-title", y).text(n); } $(".item_title", z).text(n); } if (m = $.trim($("input.item_metaName", x).val().toLowerCase()).replace(/(\s+)/g,'_')) { $(".col-key", y).text(m); $(".item_metaName", z).text(m); } else { m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_'); $(".col-key", y).text(m); $(".item_metaName", z).text(m); } if (o = $("select.item_type option:selected", x).val()) { $(".col-type", y).text(o); $(".item_type", z).text(o); } if (p = $("textarea.item_desc", x).val()) { $(".item_desc", z).text(p); } if (r = $("input.item_options", x).val()) { $(".item_options", z).text(r); } }, revert: function () { var b, n, m, o, p, q, r = true; if (b = $(".inline-editor").attr("id")) { $('#'+ b).remove(); b = b.substr(b.lastIndexOf("-") + 1); $('.option').show(); $("#option-" + b).show(); } return false; } }; $(document).ready(function () { inlineEditOption.init(); }) })(jQuery);
JavaScript
/* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ /** * TableDnD plug-in for JQuery, allows you to drag and drop table rows * You can set up various options to control how the system will work * Copyright (c) Denis Howlett <denish@isocra.com> * Licensed like jQuery, see http://docs.jquery.com/License. * * Configuration options: * * onDragStyle * This is the style that is assigned to the row during drag. There are limitations to the styles that can be * associated with a row (such as you can't assign a border--well you can, but it won't be * displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as * a map (as used in the jQuery css(...) function). * onDropStyle * This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations * to what you can do. Also this replaces the original style, so again consider using onDragClass which * is simply added and then removed on drop. * onDragClass * This class is added for the duration of the drag and then removed when the row is dropped. It is more * flexible than using onDragStyle since it can be inherited by the row cells and other content. The default * is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your * stylesheet. * onDrop * Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table * and the row that was dropped. You can work out the new order of the rows by using * table.rows. * onDragStart * Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the * table and the row which the user has started to drag. * onAllowDrop * Pass a function that will be called as a row is over another row. If the function returns true, allow * dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under * the cursor. It returns a boolean: true allows the drop, false doesn't allow it. * scrollAmount * This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the * window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2, * FF3 beta * dragHandle * This is the name of a class that you assign to one or more cells in each row that is draggable. If you * specify this class, then you are responsible for setting cursor: move in the CSS and only these cells * will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where * the whole row is draggable. * * Other ways to control behaviour: * * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows * that you don't want to be draggable. * * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have * an ID as must all the rows. * * Other methods: * * $("...").tableDnDUpdate() * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells). * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again. * The table maintains the original configuration (so you don't have to specify it again). * * $("...").tableDnDSerialize() * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be * called from anywhere and isn't dependent on the currentTable being set up correctly before calling * * Known problems: * - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0 * * Version 0.2: 2008-02-20 First public version * Version 0.3: 2008-02-07 Added onDragStart option * Made the scroll amount configurable (default is 5 as before) * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes * Added onAllowDrop to control dropping * Fixed a bug which meant that you couldn't set the scroll amount in both directions * Added serialize method * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row * draggable * Improved the serialize method to use a default (and settable) regular expression. * Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table */ jQuery.tableDnD = { /** Keep hold of the current table being dragged */ currentTable : null, /** Keep hold of the current drag object if any */ dragObject: null, /** The current mouse offset */ mouseOffset: null, /** Remember the old value of Y so that we don't do too much processing */ oldY: 0, /** Actually build the structure */ build: function(options) { // Set up the defaults if any this.each(function() { // This is bound to each matching table, set up the defaults and override with user options this.tableDnDConfig = jQuery.extend({ onDragStyle: null, onDropStyle: null, // Add in the default class for whileDragging onDragClass: "tDnD_whileDrag", onDrop: null, onDragStart: null, scrollAmount: 5, serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs serializeParamName: null, // If you want to specify another parameter name instead of the table ID dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable }, options || {}); // Now make the rows draggable jQuery.tableDnD.makeDraggable(this); }); // Now we need to capture the mouse up and mouse move event // We can use bind so that we don't interfere with other event handlers jQuery(document) .bind('mousemove', jQuery.tableDnD.mousemove) .bind('mouseup', jQuery.tableDnD.mouseup); // Don't break the chain return this; }, /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */ makeDraggable: function(table) { var config = table.tableDnDConfig; if (table.tableDnDConfig.dragHandle) { // We only need to add the event to the specified cells var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table); cells.each(function() { // The cell is bound to "this" jQuery(this).mousedown(function(ev) { jQuery.tableDnD.dragObject = this.parentNode; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; }); }) } else { // For backwards compatibility, we add the event to the whole row var rows = jQuery("tr", table); // get all the rows as a wrapped set rows.each(function() { // Iterate through each row, the row is bound to "this" var row = jQuery(this); if (! row.hasClass("nodrag")) { row.mousedown(function(ev) { if (ev.target.tagName == "TD") { jQuery.tableDnD.dragObject = this; jQuery.tableDnD.currentTable = table; jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev); if (config.onDragStart) { // Call the onDrop method if there is one config.onDragStart(table, this); } return false; } }).css("cursor", "move"); // Store the tableDnD object } }); } }, updateTables: function() { this.each(function() { // this is now bound to each matching table if (this.tableDnDConfig) { jQuery.tableDnD.makeDraggable(this); } }) }, /** Get the mouse coordinates from the event (allowing for browser differences) */ mouseCoords: function(ev){ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; }, /** Given a target element and a mouse event, get the mouse offset from that element. To do this we need the element's position and the mouse position */ getMouseOffset: function(target, ev) { ev = ev || window.event; var docPos = this.getPosition(target); var mousePos = this.mouseCoords(ev); return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y}; }, /** Get the position of an element by going up the DOM tree and adding up all the offsets */ getPosition: function(e){ var left = 0; var top = 0; /** Safari fix -- thanks to Luis Chato for this! */ if (e.offsetHeight == 0) { /** Safari 2 doesn't correctly grab the offsetTop of a table row this is detailed here: http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/ the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild. note that firefox will return a text node as a first child, so designing a more thorough solution may need to take that into account, for now this seems to work in firefox, safari, ie */ e = e.firstChild; // a table cell } while (e.offsetParent){ left += e.offsetLeft; top += e.offsetTop; e = e.offsetParent; } left += e.offsetLeft; top += e.offsetTop; return {x:left, y:top}; }, mousemove: function(ev) { if (jQuery.tableDnD.dragObject == null) { return; } var dragObj = jQuery(jQuery.tableDnD.dragObject); var config = jQuery.tableDnD.currentTable.tableDnDConfig; var mousePos = jQuery.tableDnD.mouseCoords(ev); var y = mousePos.y - jQuery.tableDnD.mouseOffset.y; //auto scroll the window var yOffset = window.pageYOffset; if (document.all) { // Windows version //yOffset=document.body.scrollTop; if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') { yOffset = document.documentElement.scrollTop; } else if (typeof document.body != 'undefined') { yOffset=document.body.scrollTop; } } if (mousePos.y-yOffset < config.scrollAmount) { window.scrollBy(0, -config.scrollAmount); } else { var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight; if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) { window.scrollBy(0, config.scrollAmount); } } if (y != jQuery.tableDnD.oldY) { // work out if we're going up or down... var movingDown = y > jQuery.tableDnD.oldY; // update the old value jQuery.tableDnD.oldY = y; // update the style to show we're dragging if (config.onDragClass) { dragObj.addClass(config.onDragClass); } else { dragObj.css(config.onDragStyle); } // If we're over a row then move the dragged row to there so that the user sees the // effect dynamically var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y); if (currentRow) { // TODO worry about what happens when there are multiple TBODIES if (movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling); } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) { jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow); } } } return false; }, /** We're only worried about the y position really, because we can only move rows up and down */ findDropTargetRow: function(draggedRow, y) { var rows = jQuery.tableDnD.currentTable.rows; for (var i=0; i<rows.length; i++) { var row = rows[i]; var rowY = this.getPosition(row).y; var rowHeight = parseInt(row.offsetHeight)/2; if (row.offsetHeight == 0) { rowY = this.getPosition(row.firstChild).y; rowHeight = parseInt(row.firstChild.offsetHeight)/2; } // Because we always have to insert before, we need to offset the height a bit if ((y > rowY - rowHeight) && (y < (rowY + rowHeight + rowHeight))) { // that's the row we're over // If it's the same as the current row, ignore it if (row == draggedRow) {return null;} var config = jQuery.tableDnD.currentTable.tableDnDConfig; if (config.onAllowDrop) { if (config.onAllowDrop(draggedRow, row)) { return row; } else { return null; } } else { // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic) var nodrop = jQuery(row).hasClass("nodrop"); if (! nodrop) { return row; } else { return null; } } return row; } } return null; }, mouseup: function(e) { if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) { var droppedRow = jQuery.tableDnD.dragObject; var config = jQuery.tableDnD.currentTable.tableDnDConfig; // If we have a dragObject, then we need to release it, // The row will already have been moved to the right place so we just reset stuff if (config.onDragClass) { jQuery(droppedRow).removeClass(config.onDragClass); } else { jQuery(droppedRow).css(config.onDropStyle); } jQuery.tableDnD.dragObject = null; if (config.onDrop) { // Call the onDrop method if there is one config.onDrop(jQuery.tableDnD.currentTable, droppedRow); } jQuery.tableDnD.currentTable = null; // let go of the table too } }, serialize: function() { if (jQuery.tableDnD.currentTable) { return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable); } else { return "Error: No Table id set, you need to set an id on your table and every row"; } }, serializeTable: function(table) { var result = ""; var tableId = table.id; var rows = table.rows; for (var i=0; i<rows.length; i++) { if (result.length > 0) result += "&"; var rowId = rows[i].id; if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) { rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0]; } result += tableId + '[]=' + rowId; } return result; }, serializeTables: function() { var result = ""; this.each(function() { // this is now bound to each matching table result += jQuery.tableDnD.serializeTable(this); }); return result; } } jQuery.fn.extend( { tableDnD : jQuery.tableDnD.build, tableDnDUpdate : jQuery.tableDnD.updateTables, tableDnDSerialize: jQuery.tableDnD.serializeTables } );
JavaScript
/** * * Delay * * Creates a way to delay events * Dependencies: jQuery * */ /* Original Plugin Name: OptionTree Original Plugin URI: http://wp.envato.com Original Author: Derek Herman Original Author URI: http://valendesigns.com */ (function ($) { $.fn.delay = function(time,func){ return this.each(function(){ setTimeout(func,time); }); }; })(jQuery); /** * * Center AJAX * * Creates a way to center the AJAX message * Dependencies: jQuery * */ (function ($) { $.fn.ajaxMessage = function(html){ if (html) { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').html(html).delay(3000, function(){$('.ajax-message').fadeOut()}); } else { return $(this).animate({"top":( $(window).height() - $(this).height() ) / 2 - 200 + $(window).scrollTop() + "px"},100).fadeIn('fast').delay(3000, function(){$('.ajax-message').fadeOut()}); } }; })(jQuery); /** * * Style File * * Creates a way to cover file input with a better styled version * Dependencies: jQuery * */ (function ($) { styleFile = { init: function () { $('input.file').each(function(){ var uploadbutton = '<input class="upload_file_button" type="button" value="Upload" />'; $(this).wrap('<div class="file_wrap" />'); $(this).addClass('file').css('opacity', 0); //set to invisible $(this).parent().append($('<div class="fake_file" />').append($('<input type="text" class="upload" />').attr('id',$(this).attr('id')+'_file')).append(uploadbutton)); $(this).bind('change', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); $(this).bind('mouseout', function() { $('#'+$(this).attr('id')+'_file').val($(this).val());; }); }); } }; $(document).ready(function () { styleFile.init() }) })(jQuery); /** * * Style Select * * Replace Select text * Dependencies: jQuery * */ (function ($) { styleSelect = { init: function () { $('.select_wrapper').each(function () { $(this).prepend('<span>' + $(this).find('.select option:selected').text() + '</span>'); }); $('.select').live('change', function () { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); $('.select').bind($.browser.msie ? 'click' : 'change', function(event) { $(this).prev('span').replaceWith('<span>' + $(this).find('option:selected').text() + '</span>'); }); } }; $(document).ready(function () { styleSelect.init() }) })(jQuery); /** * * Activate Tabs * * Tab style UI toggle * Dependencies: jQuery, jQuery UI Core, jQuery UI Tabs * */ (function ($) { activateTabs = { init: function () { // Activate $("#options_tabs").tabs(); // Append Toggle Button $('.top-info').append('<a href="" class="toggle_tabs">Tabs</a>'); // Toggle Tabs $('.toggle_tabs').toggle(function() { $("#options_tabs").tabs('destroy'); $(this).addClass('off'); }, function() { $("#options_tabs").tabs(); $(this).removeClass('off'); }); } }; $(document).ready(function () { activateTabs.init() }) })(jQuery); /** * * Upload Option * * Allows window.send_to_editor to function properly using a private post_id * Dependencies: jQuery, Media Upload, Thickbox * */ (function ($) { uploadOption = { init: function () { var formfield, formID, btnContent = true; // On Click $('.upload_button').live("click", function () { formfield = $(this).prev('input').attr('name'); formID = $(this).attr('rel'); tb_show('', 'media-upload.php?post_id='+formID+'&type=image&amp;TB_iframe=1'); return false; }); window.original_send_to_editor = window.send_to_editor; window.send_to_editor = function(html) { if (formfield) { itemurl = $(html).attr('href'); var image = /(^.*\.jpg|jpeg|png|gif|ico*)/gi; var document = /(^.*\.pdf|doc|docx|ppt|pptx|odt*)/gi; var audio = /(^.*\.mp3|m4a|ogg|wav*)/gi; var video = /(^.*\.mp4|m4v|mov|wmv|avi|mpg|ogv|3gp|3g2*)/gi; if (itemurl.match(image)) { btnContent = '<img src="'+itemurl+'" alt="" /><a href="" class="remove">Remove Image</a>'; } else { btnContent = '<div class="no_image">'+html+'<a href="" class="remove">Remove</a></div>'; } $('#' + formfield).val(itemurl); $('#' + formfield).next().next('div').slideDown().html(btnContent); tb_remove(); } else { window.original_send_to_editor(html); } } } }; $(document).ready(function () { uploadOption.init() }) })(jQuery); /** * * Inline Edit Options * * Creates & Updates Options via Ajax * Dependencies: jQuery * */ (function ($) { inlineEditOption = { init: function () { var c = this, d = $("tr.inline-edit-option"); $('.save-options', '#the-theme-options').live("click", function () { inlineEditOption.save_options(this); return false; }); $("a.edit-inline").live("click", function (event) { if ($("a.edit-inline").hasClass('disable')) { event.preventDefault(); return false; } else { inlineEditOption.edit(this); return false; } }); $("a.save").live("click", function () { if ($("a.save").hasClass('add-save')) { inlineEditOption.addSave(this); return false; } else { inlineEditOption.editSave(this); return false; } }); $("a.cancel").live("click", function () { if ($("a.cancel").hasClass('undo-add')) { inlineEditOption.undoAdd(); return false; } else { inlineEditOption.revert(); return false; } }); $("a.add-option").live("click", function (event) { if ($(this).hasClass('disable')) { event.preventDefault(); return false; } else { $.post( ajaxurl, { action:'profile_builder_next_id', _ajax_nonce: $("#_ajax_nonce").val() }, function (response) { c = parseInt(response) + 1; inlineEditOption.add(c); } ); return false; } }); $('.delete-inline').live("click", function (event) { if ($("a.delete-inline").hasClass('disable')) { event.preventDefault(); return false; } else { var agree = confirm("Are you sure you want to delete this input?"); if (agree) { inlineEditOption.remove(this); return false; } else { return false; } } }); // Fade out message div if ($('.ajax-message').hasClass('show')) { $('.ajax-message').ajaxMessage(); } // Remove Uploaded Image $('.remove').live('click', function(event) { $(this).hide(); $(this).parents().prev().prev('.upload').attr('value', ''); $(this).parents('.screenshot').slideUp(); }); }, save_options: function (e) { var d = { action: "profile_builder_array_save" }; b = $(':input', '#the-theme-options').serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r != -1) { $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Theme Options were saved</div>'); $(".option-tree-slider-body").hide(); $('.option-tree-slider .edit').removeClass('down'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>Theme Options could not be saved</div>'); } }); return false; }, remove: function (b) { var c = true; // Set ID c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); d = { action: "profile_builder_delete", id: c, _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (r) { if (r) { if (r == 'removed') { $("#option-" + c).remove(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input deleted.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, add: function (c) { var e = this, addRow, editRow = true, temp_select; e.revert(); // Clone the blank main row addRow = $('#inline-add').clone(true); addRow = $(addRow).attr('id', 'option-'+c); // Clone the blank edit row editRow = $('#inline-edit').clone(true); $('a.cancel', editRow).addClass('undo-add'); $('a.save', editRow).addClass('add-save'); $('a.edit-inline').addClass('disable'); $('a.delete-inline').addClass('disable'); $('a.add-option').addClass('disable'); // Set Colspan to 5 $('td', editRow).attr('colspan', 5); // Add Row $("#framework-settings tr:last").after(addRow); // Add Row and hide $(addRow).hide().after(editRow); $('.item-data', addRow).attr('id', 'inline_'+c); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); $('.item_title', '#edit-'+c).focus(); $('.select').each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', '#edit-'+c).hide(); $('.option-options', '#edit-'+c).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.regular').show(); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); /* avatar */ }else if (temp_select == 'Avatar'){ $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /* end avatar */ } else { if (temp_select == 'Textarea') { $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).show(); } else { $('.option-desc', '#edit-'+c).show(); $('.option-options', '#edit-'+c).hide(); } } }); // Scroll $('html, body').animate({ scrollTop: 2000 }, 500); return false; }, undoAdd: function (b) { var e = this, c = true; e.revert(); c = $("#framework-settings tr:last").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); $("a.edit-inline").removeClass('disable'); $("a.delete-inline").removeClass('disable'); $("a.add-option").removeClass('disable'); $("#option-" + c).remove(); return false; }, addSave: function (e) { var d, b, c, f, g, itemId; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemId) { itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_add", id: e, item_id: itemId, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (r == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Input added.</div>'); $('#framework-settings').tableDnD({ onDragClass: "dragging", onDrop: function(table, row) { d = { action: "profile_builder_sort", id: $.tableDnD.serialize(), _ajax_nonce: $("#_ajax_nonce").val() }; $.post(ajaxurl, d, function (response) { }, "html"); } }); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, edit: function (b) { var e = this, c, editRow, rowData, item_title, item_id, item_type, item_desc, item_options = true, temp_select; e.revert(); c = $(b).parents("tr:first").attr('id'); c = c.substr(c.lastIndexOf("-") + 1); // Clone the blank row editRow = $('#inline-edit').clone(true); $('td', editRow).attr('colspan', 5); $("#option-" + c).hide().after(editRow); // First Option Settings if ("#option-" + c == '#option-1') { $('.option').hide(); $('.option-title').show().css({"paddingBottom":"1px"}); $('.description', editRow).html('First item must be a heading.'); } // Populate the option data rowData = $('#inline_' + c); // Item Title item_title = $('.item_title', rowData).text(); $('.item_title', editRow).attr('value', item_title); // Item ID item_id = $('.item_id', rowData).text(); $('.item_id', editRow).attr('value', item_id); // Item Type item_type = $('.item_type', rowData).text(); $('select[name=item_type] option[value='+item_type+']', editRow).attr('selected', true); var temp_item_type = $('select[name=item_type] option[value='+item_type+']', editRow).text(); $('.select_wrapper span', editRow).text(temp_item_type); // Item Description item_desc = $('.item_desc', rowData).text(); $('.item_desc', editRow).attr('value', item_desc); // Avatar size item_avatar = $('.item_avatar', rowData).text(); $('.item_avatar', editRow).attr('value', item_avatar); // Item Options item_options = $('.item_options', rowData).text(); $('.item_options', editRow).attr('value', item_options); $('.select', editRow).each(function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /*avatar */ } else if (temp_select == 'Avatar'){ $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /* end avatar */ } else { if (temp_select == 'Textarea') { $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else { $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); } } }); $('.select').live('change', function () { temp_select = $(this).prev('span').text(); if (temp_select == 'Heading') { $('.option-desc', editRow).hide(); $('.option-options', editRow).hide(); } else if ( temp_select == 'Checkbox' || temp_select == 'Radio' || temp_select == 'Select' ) { $('.alternative').hide(); $('.regular').show(); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /*avatar */ } else if (temp_select == 'Avatar'){ $('.regular').hide(); $('.alternative').show().html('<strong>Avatar Size:</strong> Enter a pair of values (between 20 and 200), separated (only) by a comma in the following format: width,height. If you only specify one number, the avatar will be square.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); /* end avatar */ } else { if (temp_select == 'Textarea') { $('.regular').hide(); $('.alternative').show().html('<strong>Row Count:</strong> Enter a numeric value for the number of rows in your textarea.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else if ( temp_select == 'Custom Post' || temp_select == 'Custom Posts' ) { $('.regular').hide(); $('.alternative').show().html('<strong>Post Type:</strong> Enter your custom post_type.'); $('.option-desc', editRow).show(); $('.option-options', editRow).show(); } else { $('.option-desc', editRow).show(); $('.option-options', editRow).hide(); } } }); // Show The Editor $(editRow).attr('id', 'edit-'+c).addClass('inline-editor').show(); // Scroll var target = $('#edit-'+c); if (c > 1) { var top = target.offset().top; $('html,body').animate({scrollTop: top}, 500); return false; } return false; }, editSave: function (e) { var d, b, c, f, g, itemId; e = $("tr.inline-editor").attr("id"); e = e.substr(e.lastIndexOf("-") + 1); f = $("#edit-" + e); g = $("#inline_" + e); itemId = $.trim($("input.item_id", f).val().toLowerCase()).replace(/(\s+)/g,'_'); if (!itemId) { itemId = $.trim($("input.item_title", f).val().toLowerCase()).replace(/(\s+)/g,'_'); } d = { action: "profile_builder_edit", id: e, item_id: itemId, item_title: $("input.item_title", f).val(), item_desc: $("textarea.item_desc", f).val(), item_type: $("select.item_type", f).val(), item_options: $("input.item_options", f).val() }; b = $("#edit-" + e + " :input").serialize(); d = b + "&" + $.param(d); $.post(ajaxurl, d, function (r) { if (r) { if (r == 'updated') { inlineEditOption.afterSave(e); $("#edit-" + e).remove(); $("#option-" + e).show(); $('.ajax-message').ajaxMessage('<div class="message"><span>&nbsp;</span>Option Saved.</div>'); } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } } else { $('.ajax-message').ajaxMessage('<div class="message warning"><span>&nbsp;</span>'+r+'</div>'); } }); return false; }, afterSave: function (e) { var x, y, z, n, m, o, p, q, r = true; x = $("#edit-" + e); y = $("#option-" + e); z = $("#inline_" + e); $('.option').show(); $('a.cancel', x).removeClass('undo-add'); $('a.save', x).removeClass('add-save'); $("a.add-option").removeClass('disable'); $('a.edit-inline').removeClass('disable'); $('a.delete-inline').removeClass('disable'); if (n = $("input.item_title", x).val()) { if ($("select.item_type", x).val() != 'heading') { $(y).removeClass('col-heading'); $('.col-title', y).attr('colspan', 1); $(".col-key", y).show(); $(".col-type", y).show(); $(".col-title", y).text('- ' + n); } else { $(y).addClass('col-heading'); $('.col-title', y).attr('colspan', 3); $(".col-key", y).hide(); $(".col-type", y).hide(); $(".col-title", y).text(n); } $(".item_title", z).text(n); } if (m = $.trim($("input.item_id", x).val().toLowerCase()).replace(/(\s+)/g,'_')) { $(".col-key", y).text(m); $(".item_id", z).text(m); } else { m = $.trim($("input.item_title", x).val().toLowerCase()).replace(/(\s+)/g,'_'); $(".col-key", y).text(m); $(".item_id", z).text(m); } if (o = $("select.item_type option:selected", x).val()) { $(".col-type", y).text(o); $(".item_type", z).text(o); } if (p = $("textarea.item_desc", x).val()) { $(".item_desc", z).text(p); } if (r = $("input.item_options", x).val()) { $(".item_options", z).text(r); } }, revert: function () { var b, n, m, o, p, q, r = true; if (b = $(".inline-editor").attr("id")) { $('#'+ b).remove(); b = b.substr(b.lastIndexOf("-") + 1); $('.option').show(); $("#option-" + b).show(); } return false; } }; $(document).ready(function () { inlineEditOption.init(); }) })(jQuery);
JavaScript
function wppb_display_page_select( value ) { if ( value == 'yes' ) jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).show(); else jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).hide(); } jQuery(function() { if ( ( jQuery( '#framework_wrap #content .wppb_general_settings2' ).val() == 'yes' ) || ( jQuery( '#framework_wrap #content #wppb_general_settings_hidden' ).val() == 'multisite' ) ) jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).show(); else jQuery ( '#framework_wrap #content #general_settings_registration_page_div' ).hide(); });
JavaScript
jQuery( document ).ready( function( $ ) { // Don't ever cache ajax requests $.ajaxSetup( { 'cache' : false } ); // Remove the loading class when ajax requests complete $( document ).ajaxComplete( function() { $( '.hmbkp-ajax-loading' ).removeClass( 'hmbkp-ajax-loading' ).removeAttr( 'disabled' ); } ); $( document ).on( 'click', '.hmbkp-colorbox-close', function() { $.colorbox.close(); location.reload(); } ); // Setup the tabs $( '.hmbkp-tabs' ).tabs(); // Set the first tab to be active if ( ! $( '.subsubsub a.current' ).size() ) $( '.subsubsub li:first a').addClass( 'current' ); // Initialize colorbox $( '.colorbox' ).colorbox( { 'initialWidth' : '320px', 'initialHeight' : '100px', 'transition' : 'elastic', 'scrolling' : false, 'innerWidth' : '320px', 'maxHeight' : '85%', // 85% Takes into account the WP Admin bar. 'escKey' : false, 'overlayClose' : false, 'onLoad' : function() { $( '#cboxClose' ).remove(); }, 'onComplete' : function() { $( '.hmbkp-tabs' ).tabs(); if ( $( ".hmbkp-form p.submit:contains('" + hmbkp.update + "')" ).size() ) { $( '<button type="button" class="button-secondary hmbkp-colorbox-close">' + hmbkp.cancel + '</button>' ).appendTo( '.hmbkp-form p.submit' ); } $( '.recurring-setting' ).hide(); hmbkpToggleScheduleFields( $('select#hmbkp_schedule_recurrence_type').val() ); $( document ).on( 'change', 'select#hmbkp_schedule_recurrence_type', function() { hmbkpToggleScheduleFields( $( this ).val() ); } ); $.colorbox.resize(); } } ); // Resize the colorbox when switching tabs $( document).on( 'click', '.ui-tabs-anchor', function( e ) { $.colorbox.resize(); } ); // Show delete confirm message for delete schedule $( document ).on( 'click', '.hmbkp-schedule-actions .delete-action', function( e ) { if ( ! confirm( hmbkp.delete_schedule ) ) e.preventDefault(); } ); // Show delete confirm message for delete backup $( document ).on( 'click', '.hmbkp_manage_backups_row .delete-action', function( e ) { if ( ! confirm( hmbkp.delete_backup ) ) e.preventDefault(); } ); // Show delete confirm message for remove exclude rule $( document ).on( 'click', '.hmbkp-edit-schedule-excludes-form .delete-action', function( e ) { if ( ! confirm( hmbkp.remove_exclude_rule ) ) e.preventDefault(); } ); // Preview exclude rule $( document ).on( 'click', '.hmbkp_preview_exclude_rule', function() { if ( ! $( '.hmbkp_add_exclude_rule input' ).val() ) { $( '.hmbkp_add_exclude_rule ul' ).remove(); $( '.hmbkp_add_exclude_rule p' ).remove(); return; } $( this ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' ); $.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_file_list', 'hmbkp_schedule_excludes' : $( '.hmbkp_add_exclude_rule input' ).val(), 'hmbkp_schedule_id' : $( '[name="hmbkp_schedule_id"]' ).val() }, function( data ) { $( '.hmbkp_add_exclude_rule ul' ).remove(); $( '.hmbkp_add_exclude_rule p' ).remove(); if ( data.indexOf( 'hmbkp_file_list' ) != -1 ) $( '.hmbkp_add_exclude_rule' ).append( data ); else $( '.hmbkp_add_exclude_rule' ).append( '<p>There was an error previewing the exclude rule.</p>' ); $( '.hmbkp-edit-schedule-excludes-form' ).addClass( 'hmbkp-exclude-preview-open' ); $.colorbox.resize(); } ) } ); // Fire the preview button when the enter key is pressed in the preview input $( document ).on( 'keypress', '.hmbkp_add_exclude_rule input', function( e ) { if ( ! $( '.hmbkp_add_exclude_rule input' ).val() ) return true; var code = ( e.keyCode ? e.keyCode : e.which ); if ( code != 13 ) return true; $( '.hmbkp_preview_exclude_rule' ).click(); e.preventDefault(); } ); // Cancel add exclude rule $( document ).on( 'click', '.hmbkp_cancel_save_exclude_rule, .hmbkp-edit-schedule-excludes-form .submit button', function() { $( '.hmbkp_add_exclude_rule ul' ).remove(); $( '.hmbkp_add_exclude_rule p' ).remove(); $( '.hmbkp-edit-schedule-excludes-form' ).removeClass( 'hmbkp-exclude-preview-open' ); $.colorbox.resize(); } ); // Add exclude rule $( document ).on( 'click', '.hmbkp_save_exclude_rule', function() { $( this ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' ); $.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_add_exclude_rule', 'hmbkp_exclude_rule' : $( '.hmbkp_add_exclude_rule input' ).val(), 'hmbkp_schedule_id' : $( '[name="hmbkp_schedule_id"]' ).val() }, function( data ) { $( '.hmbkp-edit-schedule-excludes-form' ).replaceWith( data ); $( '.hmbkp-edit-schedule-excludes-form' ).show(); $( '.hmbkp-tabs' ).tabs(); $.colorbox.resize(); } ); } ); // Remove exclude rule $( document ).on( 'click', '.hmbkp-edit-schedule-excludes-form td a', function( e ) { $( this ).addClass( 'hmbkp-ajax-loading' ).text( '' ).attr( 'disabled', 'disabled' ); $.colorbox.resize(); e.preventDefault(); $.get( ajaxurl, { 'action' : 'hmbkp_delete_exclude_rule', 'hmbkp_exclude_rule' : $( this ).closest( 'td' ).attr( 'data-hmbkp-exclude-rule' ), 'hmbkp_schedule_id' : $( '[name="hmbkp_schedule_id"]' ).val() }, function( data ) { $( '.hmbkp-edit-schedule-excludes-form' ).replaceWith( data ); $( '.hmbkp-edit-schedule-excludes-form' ).show(); $( '.hmbkp-tabs' ).tabs(); $.colorbox.resize(); } ); } ); // Edit schedule form submit $( document ).on( 'submit', 'form.hmbkp-form', function( e ) { var $isDestinationSettingsForm = $( this ).find( 'button[type="submit"]' ).hasClass( "dest-settings-save" ); var isNewSchedule = $( this ).closest( 'form' ).attr( 'data-schedule-action' ) == 'add' ? true : false; var scheduleId = $( this ).closest( 'form' ).find( '[name="hmbkp_schedule_id"]' ).val(); // Only continue if we have a schedule id if ( typeof( scheduleId ) == 'undefined' ) return; // Warn that backups will be deleted if max backups has been set to less than the number of backups currently stored if ( ! isNewSchedule && Number( $( 'input[name="hmbkp_schedule_max_backups"]' ).val() ) < Number( $( '.hmbkp_manage_backups_row' ).size() ) && ! confirm( hmbkp.remove_old_backups ) ) return false; $( this ).find( 'button[type="submit"]' ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' ); $( '.hmbkp-error span' ).remove(); $( '.hmbkp-error' ).removeClass( 'hmbkp-error' ); e.preventDefault(); $.get( ajaxurl + '?' + $( this ).serialize(), { 'action' : 'hmbkp_edit_schedule_submit' }, function( data ) { if ( ( data.success === true ) && ( $isDestinationSettingsForm === false ) ) { $.colorbox.close(); // Reload the page so we see changes if ( isNewSchedule ) location.replace( '//' + location.host + location.pathname + '?page=' + hmbkp.page_slug + '&hmbkp_schedule_id=' + scheduleId ); else location.reload(); } else if( data.success === true ) { // nothing for now } else { // Get the errors json string var errors = data.data; // Loop through the errors $.each( errors, function( key, value ) { var selector = key.replace(/(:|\.|\[|\])/g,'\\$1'); // Focus the first field that errored if ( typeof( hmbkp_focused ) == 'undefined' ) { $( '#' + selector ).focus(); hmbkp_focused = true; } // Add an error class to all fields with errors $( 'label[for=' + selector + ']' ).addClass( 'hmbkp-error' ); $( '#' + selector ).next( 'span' ).remove(); // Add the error message $( '#' + selector ).after( '<span class="hmbkp-error">' + value + '</span>' ); } ); } } ); } ); // Test the cron response using ajax $.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_cron_test' }, function( data ) { if ( data != 1 ) { $( '.wrap > h2' ).after( data ); } } ); // Calculate the estimated backup size if ( $( '.hmbkp-schedule-sentence .calculating' ).size() ) { $.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_calculate', 'hmbkp_schedule_id' : $( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ) }, function( data ) { if ( data.indexOf( 'title' ) != -1 ) $( '.hmbkp-schedule-sentence' ).replaceWith( data ); // Fail silently for now else $( '.calculating' ).remove(); } ).error( function() { // Fail silently for now $( '.calculating' ).remove(); } ); } if ( $( '.hmbkp-schedule-sentence.hmbkp-running' ).size() ) hmbkpRedirectOnBackupComplete( $( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ), true ); // Run a backup $( document ).on( 'click', '.hmbkp-run', function( e ) { $( this ).closest( '.hmbkp-schedule-sentence' ).addClass( 'hmbkp-running' ); $( '.hmbkp-error' ).removeClass( 'hmbkp-error' ); scheduleId = $( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ); ajaxRequest = $.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_run_schedule', 'hmbkp_schedule_id' : scheduleId } ).done( function( data ) { hmbkpCatchResponseAndOfferToEmail( data ); // Redirect back on error } ).fail( function( jqXHR, textStatus ) { hmbkpCatchResponseAndOfferToEmail( jqXHR.responseText ); } ); setTimeout( function() { hmbkpRedirectOnBackupComplete( scheduleId, false ) }, 1000 ); e.preventDefault(); } ); } ); function hmbkpToggleScheduleFields( recurrence ){ recurrence = typeof recurrence !== 'undefined' ? recurrence : 'manually'; var settingFields = jQuery( '.recurring-setting'); var scheduleSettingFields = jQuery( '#schedule-start'); var twiceDailyNote = jQuery( 'p.twice-js' ); switch( recurrence ) { case 'manually': settingFields.hide(); break; case 'hmbkp_hourly' : // fall through case 'hmbkp_daily' : settingFields.hide(); scheduleSettingFields.show(); twiceDailyNote.hide(); break; case 'hmbkp_twicedaily' : settingFields.hide(); scheduleSettingFields.show(); twiceDailyNote.show(); break; case 'hmbkp_weekly' : // fall through case 'hmbkp_fortnightly' : settingFields.hide(); jQuery( '#start-day' ).show(); scheduleSettingFields.show(); twiceDailyNote.hide(); break; case 'hmbkp_monthly' : settingFields.hide(); scheduleSettingFields.show(); jQuery( '#start-date' ).show(); twiceDailyNote.hide(); break; } jQuery.colorbox.resize(); } function hmbkpCatchResponseAndOfferToEmail( data ) { // Backup Succeeded if ( ! data || data == 0 ) location.reload( true ); // The backup failed, show the error and offer to have it emailed back else { jQuery( '.hmbkp-schedule-sentence.hmbkp-running' ).removeClass( 'hmbkp-running' ).addClass( 'hmbkp-error' ); jQuery.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_backup_error', 'hmbkp_error' : data }, function( data ) { if ( ! data || data == 0 ) return; jQuery.colorbox( { 'innerWidth' : "320px", 'maxHeight' : "100%", 'html' : data, 'overlayClose' : false, 'escKey' : false, 'onLoad' : function() { jQuery( '#cboxClose' ).remove(); jQuery.colorbox.resize(); } } ); } ); } jQuery( document ).one( 'click', '.hmbkp_send_error_via_email', function( e ) { e.preventDefault(); jQuery( this ).addClass( 'hmbkp-ajax-loading' ).attr( 'disabled', 'disabled' ); jQuery.post( ajaxurl, { 'nonce' : hmbkp.nonce, 'action' : 'hmbkp_email_error', 'hmbkp_error' : data }, function( data ) { jQuery.colorbox.close(); } ) } ); } function hmbkpRedirectOnBackupComplete( schedule_id, redirect ) { jQuery.post( ajaxurl, { 'nonce':hmbkp.nonce, 'action' : 'hmbkp_is_in_progress', 'hmbkp_schedule_id' : jQuery( '[data-hmbkp-schedule-id]' ).attr( 'data-hmbkp-schedule-id' ) }, function( data ) { if ( data == 0 && redirect === true && ! jQuery( '.hmbkp-error' ).size() ) { location.reload( true ); } else { if ( data != 0 ) { redirect = true; jQuery( '.hmbkp-status' ).remove(); jQuery( '.hmbkp-schedule-actions' ).replaceWith( data ); } setTimeout( function() { hmbkpRedirectOnBackupComplete( schedule_id, redirect ); }, 5000 ); } } ); }
JavaScript
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title, description, and background color changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' === to ) { $( '.site-title, .site-title a, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.site-title, .site-title a, .site-description' ).css( { 'clip': 'auto', 'color': to, 'position': 'relative' } ); } } ); } ); // Hook into background color/image change and adjust body class value as needed. wp.customize( 'background_color', function( value ) { value.bind( function( to ) { var body = $( 'body' ); if ( ( '#ffffff' == to || '#fff' == to ) && 'none' == body.css( 'background-image' ) ) body.addClass( 'custom-background-white' ); else if ( '' == to && 'none' == body.css( 'background-image' ) ) body.addClass( 'custom-background-empty' ); else body.removeClass( 'custom-background-empty custom-background-white' ); } ); } ); wp.customize( 'background_image', function( value ) { value.bind( function( to ) { var body = $( 'body' ); if ( '' != to ) body.removeClass( 'custom-background-empty custom-background-white' ); else if ( 'rgb(255, 255, 255)' == body.css( 'background-color' ) ) body.addClass( 'custom-background-white' ); else if ( 'rgb(230, 230, 230)' == body.css( 'background-color' ) && '' == _wpCustomizeSettings.values.background_color ) body.addClass( 'custom-background-empty' ); } ); } ); } )( jQuery );
JavaScript
/** * Handles toggling the navigation menu for small screens and * accessibility for submenu items. */ ( function() { var nav = document.getElementById( 'site-navigation' ), button, menu; if ( ! nav ) { return; } button = nav.getElementsByTagName( 'h3' )[0]; menu = nav.getElementsByTagName( 'ul' )[0]; if ( ! button ) { return; } // Hide button if menu is missing or empty. if ( ! menu || ! menu.childNodes.length ) { button.style.display = 'none'; return; } button.onclick = function() { if ( -1 === menu.className.indexOf( 'nav-menu' ) ) { menu.className = 'nav-menu'; } if ( -1 !== button.className.indexOf( 'toggled-on' ) ) { button.className = button.className.replace( ' toggled-on', '' ); menu.className = menu.className.replace( ' toggled-on', '' ); } else { button.className += ' toggled-on'; menu.className += ' toggled-on'; } }; } )(); // Better focus for hidden submenu items for accessibility. ( function( $ ) { $( '.main-navigation' ).find( 'a' ).on( 'focus.twentytwelve blur.twentytwelve', function() { $( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' ); } ); } )( jQuery );
JavaScript
/** * Theme functions file * * Contains handlers for navigation, accessibility, header sizing * footer widgets and Featured Content slider * */ ( function( $ ) { var body = $( 'body' ), _window = $( window ); // Enable menu toggle for small screens. ( function() { var nav = $( '#primary-navigation' ), button, menu; if ( ! nav ) { return; } button = nav.find( '.menu-toggle' ); if ( ! button ) { return; } // Hide button if menu is missing or empty. menu = nav.find( '.nav-menu' ); if ( ! menu || ! menu.children().length ) { button.hide(); return; } $( '.menu-toggle' ).on( 'click.twentyfourteen', function() { nav.toggleClass( 'toggled-on' ); } ); } )(); /* * Makes "skip to content" link work correctly in IE9 and Chrome for better * accessibility. * * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/ */ _window.on( 'hashchange.twentyfourteen', function() { var element = document.getElementById( location.hash.substring( 1 ) ); if ( element ) { if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) { element.tabIndex = -1; } element.focus(); // Repositions the window on jump-to-anchor to account for header height. window.scrollBy( 0, -80 ); } } ); $( function() { // Search toggle. $( '.search-toggle' ).on( 'click.twentyfourteen', function( event ) { var that = $( this ), wrapper = $( '.search-box-wrapper' ); that.toggleClass( 'active' ); wrapper.toggleClass( 'hide' ); if ( that.is( '.active' ) || $( '.search-toggle .screen-reader-text' )[0] === event.target ) { wrapper.find( '.search-field' ).focus(); } } ); /* * Fixed header for large screen. * If the header becomes more than 48px tall, unfix the header. * * The callback on the scroll event is only added if there is a header * image and we are not on mobile. */ if ( _window.width() > 781 ) { var mastheadHeight = $( '#masthead' ).height(), toolbarOffset, mastheadOffset; if ( mastheadHeight > 48 ) { body.removeClass( 'masthead-fixed' ); } if ( body.is( '.header-image' ) ) { toolbarOffset = body.is( '.admin-bar' ) ? $( '#wpadminbar' ).height() : 0; mastheadOffset = $( '#masthead' ).offset().top - toolbarOffset; _window.on( 'scroll.twentyfourteen', function() { if ( ( window.scrollY > mastheadOffset ) && ( mastheadHeight < 49 ) ) { body.addClass( 'masthead-fixed' ); } else { body.removeClass( 'masthead-fixed' ); } } ); } } // Focus styles for menus. $( '.primary-navigation, .secondary-navigation' ).find( 'a' ).on( 'focus.twentyfourteen blur.twentyfourteen', function() { $( this ).parents().toggleClass( 'focus' ); } ); } ); _window.load( function() { // Arrange footer widgets vertically. if ( $.isFunction( $.fn.masonry ) ) { $( '#footer-sidebar' ).masonry( { itemSelector: '.widget', columnWidth: function( containerWidth ) { return containerWidth / 4; }, gutterWidth: 0, isResizable: true, isRTL: $( 'body' ).is( '.rtl' ) } ); } // Initialize Featured Content slider. if ( body.is( '.slider' ) ) { $( '.featured-content' ).featuredslider( { selector: '.featured-content-inner > article', controlsContainer: '.featured-content' } ); } } ); } )( jQuery );
JavaScript
/** * Twenty Fourteen keyboard support for image navigation. */ ( function( $ ) { $( document ).on( 'keydown.twentyfourteen', function( e ) { var url = false; // Left arrow key code. if ( e.which === 37 ) { url = $( '.previous-image a' ).attr( 'href' ); // Right arrow key code. } else if ( e.which === 39 ) { url = $( '.entry-attachment a' ).attr( 'href' ); } if ( url && ( !$( 'textarea, input' ).is( ':focus' ) ) ) { window.location = url; } } ); } )( jQuery );
JavaScript
/* * Twenty Fourteen Featured Content Slider * * Adapted from FlexSlider v2.2.0, copyright 2012 WooThemes * @link http://www.woothemes.com/flexslider/ */ /* global DocumentTouch:true,setImmediate:true,featuredSliderDefaults:true,MSGesture:true */ ( function( $ ) { // FeaturedSlider: object instance. $.featuredslider = function( el, options ) { var slider = $( el ), msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, touch = ( ( 'ontouchstart' in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch ), // MSFT specific. eventType = 'click touchend MSPointerUp', watchedEvent = '', watchedEventClearTimer, methods = {}, namespace; // Make variables public. slider.vars = $.extend( {}, $.featuredslider.defaults, options ); namespace = slider.vars.namespace, // Store a reference to the slider object. $.data( el, 'featuredslider', slider ); // Private slider methods. methods = { init: function() { slider.animating = false; slider.currentSlide = 0; slider.animatingTo = slider.currentSlide; slider.atEnd = ( slider.currentSlide === 0 || slider.currentSlide === slider.last ); slider.containerSelector = slider.vars.selector.substr( 0, slider.vars.selector.search( ' ' ) ); slider.slides = $( slider.vars.selector, slider ); slider.container = $( slider.containerSelector, slider ); slider.count = slider.slides.length; slider.prop = 'marginLeft'; slider.isRtl = $( 'body' ).hasClass( 'rtl' ); slider.args = {}; // TOUCH slider.transitions = ( function() { var obj = document.createElement( 'div' ), props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'], i; for ( i in props ) { if ( obj.style[ props[i] ] !== undefined ) { slider.pfx = props[i].replace( 'Perspective', '' ).toLowerCase(); slider.prop = '-' + slider.pfx + '-transform'; return true; } } return false; }() ); // CONTROLSCONTAINER if ( slider.vars.controlsContainer !== '' ) { slider.controlsContainer = $( slider.vars.controlsContainer ).length > 0 && $( slider.vars.controlsContainer ); } slider.doMath(); // INIT slider.setup( 'init' ); // CONTROLNAV methods.controlNav.setup(); // DIRECTIONNAV methods.directionNav.setup(); // KEYBOARD if ( $( slider.containerSelector ).length === 1 ) { $( document ).bind( 'keyup', function( event ) { var keycode = event.keyCode, target = false; if ( ! slider.animating && ( keycode === 39 || keycode === 37 ) ) { if ( keycode === 39 ) { target = slider.getTarget( 'next' ); } else if ( keycode === 37 ) { target = slider.getTarget( 'prev' ); } slider.featureAnimate( target ); } } ); } // TOUCH if ( touch ) { methods.touch(); } $( window ).bind( 'resize orientationchange focus', methods.resize ); slider.find( 'img' ).attr( 'draggable', 'false' ); }, controlNav: { setup: function() { methods.controlNav.setupPaging(); }, setupPaging: function() { var type = 'control-paging', j = 1, item, slide, i; slider.controlNavScaffold = $( '<ol class="' + namespace + 'control-nav ' + namespace + type + '"></ol>' ); if ( slider.pagingCount > 1 ) { for ( i = 0; i < slider.pagingCount; i++ ) { slide = slider.slides.eq( i ); item = '<a>' + j + '</a>'; slider.controlNavScaffold.append( '<li>' + item + '</li>' ); j++; } } // CONTROLSCONTAINER ( slider.controlsContainer ) ? $( slider.controlsContainer ).append( slider.controlNavScaffold ) : slider.append( slider.controlNavScaffold ); methods.controlNav.set(); methods.controlNav.active(); slider.controlNavScaffold.delegate( 'a, img', eventType, function( event ) { event.preventDefault(); if ( watchedEvent === '' || watchedEvent === event.type ) { var $this = $( this ), target = slider.controlNav.index( $this ); if ( ! $this.hasClass( namespace + 'active' ) ) { slider.direction = ( target > slider.currentSlide ) ? 'next' : 'prev'; slider.featureAnimate( target ); } } // Set up flags to prevent event duplication. if ( watchedEvent === '' ) { watchedEvent = event.type; } methods.setToClearWatchedEvent(); } ); }, set: function() { var selector = 'a'; slider.controlNav = $( '.' + namespace + 'control-nav li ' + selector, ( slider.controlsContainer ) ? slider.controlsContainer : slider ); }, active: function() { slider.controlNav.removeClass( namespace + 'active' ).eq( slider.animatingTo ).addClass( namespace + 'active' ); }, update: function( action, pos ) { if ( slider.pagingCount > 1 && action === 'add' ) { slider.controlNavScaffold.append( $( '<li><a>' + slider.count + '</a></li>' ) ); } else if ( slider.pagingCount === 1 ) { slider.controlNavScaffold.find( 'li' ).remove(); } else { slider.controlNav.eq( pos ).closest( 'li' ).remove(); } methods.controlNav.set(); ( slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length ) ? slider.update( pos, action ) : methods.controlNav.active(); } }, directionNav: { setup: function() { var directionNavScaffold = $( '<ul class="' + namespace + 'direction-nav"><li><a class="' + namespace + 'prev" href="#">' + slider.vars.prevText + '</a></li><li><a class="' + namespace + 'next" href="#">' + slider.vars.nextText + '</a></li></ul>' ); // CONTROLSCONTAINER if ( slider.controlsContainer ) { $( slider.controlsContainer ).append( directionNavScaffold ); slider.directionNav = $( '.' + namespace + 'direction-nav li a', slider.controlsContainer ); } else { slider.append( directionNavScaffold ); slider.directionNav = $( '.' + namespace + 'direction-nav li a', slider ); } methods.directionNav.update(); slider.directionNav.bind( eventType, function( event ) { event.preventDefault(); var target; if ( watchedEvent === '' || watchedEvent === event.type ) { target = ( $( this ).hasClass( namespace + 'next' ) ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' ); slider.featureAnimate( target ); } // Set up flags to prevent event duplication. if ( watchedEvent === '' ) { watchedEvent = event.type; } methods.setToClearWatchedEvent(); } ); }, update: function() { var disabledClass = namespace + 'disabled'; if ( slider.pagingCount === 1 ) { slider.directionNav.addClass( disabledClass ).attr( 'tabindex', '-1' ); } else { slider.directionNav.removeClass( disabledClass ).removeAttr( 'tabindex' ); } } }, touch: function() { var startX, startY, offset, cwidth, dx, startT, scrolling = false, localX = 0, localY = 0, accDx = 0; if ( ! msGesture ) { el.addEventListener( 'touchstart', onTouchStart, false ); } else { el.style.msTouchAction = 'none'; el._gesture = new MSGesture(); // MSFT specific. el._gesture.target = el; el.addEventListener( 'MSPointerDown', onMSPointerDown, false ); el._slider = slider; el.addEventListener( 'MSGestureChange', onMSGestureChange, false ); el.addEventListener( 'MSGestureEnd', onMSGestureEnd, false ); } function onTouchStart( e ) { if ( slider.animating ) { e.preventDefault(); } else if ( ( window.navigator.msPointerEnabled ) || e.touches.length === 1 ) { cwidth = slider.w; startT = Number( new Date() ); // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; offset = ( slider.currentSlide + slider.cloneOffset ) * cwidth; if ( slider.animatingTo === slider.last && slider.direction !== 'next' ) { offset = 0; } startX = localX; startY = localY; el.addEventListener( 'touchmove', onTouchMove, false ); el.addEventListener( 'touchend', onTouchEnd, false ); } } function onTouchMove( e ) { // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; dx = startX - localX; scrolling = Math.abs( dx ) < Math.abs( localY - startY ); if ( ! scrolling ) { e.preventDefault(); if ( slider.transitions ) { slider.setProps( offset + dx, 'setTouch' ); } } } function onTouchEnd() { // Finish the touch by undoing the touch session. el.removeEventListener( 'touchmove', onTouchMove, false ); if ( slider.animatingTo === slider.currentSlide && ! scrolling && dx !== null ) { var updateDx = dx, target = ( updateDx > 0 ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' ); slider.featureAnimate( target ); } el.removeEventListener( 'touchend', onTouchEnd, false ); startX = null; startY = null; dx = null; offset = null; } function onMSPointerDown( e ) { e.stopPropagation(); if ( slider.animating ) { e.preventDefault(); } else { el._gesture.addPointer( e.pointerId ); accDx = 0; cwidth = slider.w; startT = Number( new Date() ); offset = ( slider.currentSlide + slider.cloneOffset ) * cwidth; if ( slider.animatingTo === slider.last && slider.direction !== 'next' ) { offset = 0; } } } function onMSGestureChange( e ) { e.stopPropagation(); var slider = e.target._slider, transX, transY; if ( ! slider ) { return; } transX = -e.translationX, transY = -e.translationY; // Accumulate translations. accDx = accDx + transX; dx = accDx; scrolling = Math.abs( accDx ) < Math.abs( -transY ); if ( e.detail === e.MSGESTURE_FLAG_INERTIA ) { setImmediate( function () { // MSFT specific. el._gesture.stop(); } ); return; } if ( ! scrolling || Number( new Date() ) - startT > 500 ) { e.preventDefault(); if ( slider.transitions ) { slider.setProps( offset + dx, 'setTouch' ); } } } function onMSGestureEnd( e ) { e.stopPropagation(); var slider = e.target._slider, updateDx, target; if ( ! slider ) { return; } if ( slider.animatingTo === slider.currentSlide && ! scrolling && dx !== null ) { updateDx = dx, target = ( updateDx > 0 ) ? slider.getTarget( 'next' ) : slider.getTarget( 'prev' ); slider.featureAnimate( target ); } startX = null; startY = null; dx = null; offset = null; accDx = 0; } }, resize: function() { if ( ! slider.animating && slider.is( ':visible' ) ) { slider.doMath(); // SMOOTH HEIGHT methods.smoothHeight(); slider.newSlides.width( slider.computedW ); slider.setProps( slider.computedW, 'setTotal' ); } }, smoothHeight: function( dur ) { var $obj = slider.viewport; ( dur ) ? $obj.animate( { 'height': slider.slides.eq( slider.animatingTo ).height() }, dur ) : $obj.height( slider.slides.eq( slider.animatingTo ).height() ); }, setToClearWatchedEvent: function() { clearTimeout( watchedEventClearTimer ); watchedEventClearTimer = setTimeout( function() { watchedEvent = ''; }, 3000 ); } }; // Public methods. slider.featureAnimate = function( target ) { if ( target !== slider.currentSlide ) { slider.direction = ( target > slider.currentSlide ) ? 'next' : 'prev'; } if ( ! slider.animating && slider.is( ':visible' ) ) { slider.animating = true; slider.animatingTo = target; // CONTROLNAV methods.controlNav.active(); slider.slides.removeClass( namespace + 'active-slide' ).eq( target ).addClass( namespace + 'active-slide' ); slider.atEnd = target === 0 || target === slider.last; // DIRECTIONNAV methods.directionNav.update(); var dimension = slider.computedW, slideString; if ( slider.currentSlide === 0 && target === slider.count - 1 && slider.direction !== 'next' ) { slideString = 0; } else if ( slider.currentSlide === slider.last && target === 0 && slider.direction !== 'prev' ) { slideString = ( slider.count + 1 ) * dimension; } else { slideString = ( target + slider.cloneOffset ) * dimension; } slider.setProps( slideString, '', slider.vars.animationSpeed ); if ( slider.transitions ) { if ( ! slider.atEnd ) { slider.animating = false; slider.currentSlide = slider.animatingTo; } slider.container.unbind( 'webkitTransitionEnd transitionend' ); slider.container.bind( 'webkitTransitionEnd transitionend', function() { slider.wrapup( dimension ); } ); } else { slider.container.animate( slider.args, slider.vars.animationSpeed, 'swing', function() { slider.wrapup( dimension ); } ); } // SMOOTH HEIGHT methods.smoothHeight( slider.vars.animationSpeed ); } }; slider.wrapup = function( dimension ) { if ( slider.currentSlide === 0 && slider.animatingTo === slider.last ) { slider.setProps( dimension, 'jumpEnd' ); } else if ( slider.currentSlide === slider.last && slider.animatingTo === 0 ) { slider.setProps( dimension, 'jumpStart' ); } slider.animating = false; slider.currentSlide = slider.animatingTo; }; slider.getTarget = function( dir ) { slider.direction = dir; // Swap for RTL. if ( slider.isRtl ) { dir = 'next' === dir ? 'prev' : 'next'; } if ( dir === 'next' ) { return ( slider.currentSlide === slider.last ) ? 0 : slider.currentSlide + 1; } else { return ( slider.currentSlide === 0 ) ? slider.last : slider.currentSlide - 1; } }; slider.setProps = function( pos, special, dur ) { var target = ( function() { var posCalc = ( function() { switch ( special ) { case 'setTotal': return ( slider.currentSlide + slider.cloneOffset ) * pos; case 'setTouch': return pos; case 'jumpEnd': return slider.count * pos; case 'jumpStart': return pos; default: return pos; } }() ); return ( posCalc * -1 ) + 'px'; }() ); if ( slider.transitions ) { target = 'translate3d(' + target + ',0,0 )'; dur = ( dur !== undefined ) ? ( dur / 1000 ) + 's' : '0s'; slider.container.css( '-' + slider.pfx + '-transition-duration', dur ); } slider.args[slider.prop] = target; if ( slider.transitions || dur === undefined ) { slider.container.css( slider.args ); } }; slider.setup = function( type ) { var sliderOffset; if ( type === 'init' ) { slider.viewport = $( '<div class="' + namespace + 'viewport"></div>' ).css( { 'overflow': 'hidden', 'position': 'relative' } ).appendTo( slider ).append( slider.container ); slider.cloneCount = 0; slider.cloneOffset = 0; } slider.cloneCount = 2; slider.cloneOffset = 1; // Clear out old clones. if ( type !== 'init' ) { slider.container.find( '.clone' ).remove(); } slider.container.append( slider.slides.first().clone().addClass( 'clone' ).attr( 'aria-hidden', 'true' ) ).prepend( slider.slides.last().clone().addClass( 'clone' ).attr( 'aria-hidden', 'true' ) ); slider.newSlides = $( slider.vars.selector, slider ); sliderOffset = slider.currentSlide + slider.cloneOffset; slider.container.width( ( slider.count + slider.cloneCount ) * 200 + '%' ); slider.setProps( sliderOffset * slider.computedW, 'init' ); setTimeout( function() { slider.doMath(); slider.newSlides.css( { 'width': slider.computedW, 'float': 'left', 'display': 'block' } ); // SMOOTH HEIGHT methods.smoothHeight(); }, ( type === 'init' ) ? 100 : 0 ); slider.slides.removeClass( namespace + 'active-slide' ).eq( slider.currentSlide ).addClass( namespace + 'active-slide' ); }; slider.doMath = function() { var slide = slider.slides.first(); slider.w = ( slider.viewport===undefined ) ? slider.width() : slider.viewport.width(); slider.h = slide.height(); slider.boxPadding = slide.outerWidth() - slide.width(); slider.itemW = slider.w; slider.pagingCount = slider.count; slider.last = slider.count - 1; slider.computedW = slider.itemW - slider.boxPadding; }; slider.update = function( pos, action ) { slider.doMath(); // Update currentSlide and slider.animatingTo if necessary. if ( pos < slider.currentSlide ) { slider.currentSlide += 1; } else if ( pos <= slider.currentSlide && pos !== 0 ) { slider.currentSlide -= 1; } slider.animatingTo = slider.currentSlide; // Update controlNav. if ( action === 'add' || slider.pagingCount > slider.controlNav.length ) { methods.controlNav.update( 'add' ); } else if ( action === 'remove' || slider.pagingCount < slider.controlNav.length ) { if ( slider.currentSlide > slider.last ) { slider.currentSlide -= 1; slider.animatingTo -= 1; } methods.controlNav.update( 'remove', slider.last ); } // Update directionNav. methods.directionNav.update(); }; // FeaturedSlider: initialize. methods.init(); }; // Default settings. $.featuredslider.defaults = { namespace: 'slider-', // String: prefix string attached to the class of every element generated by the plugin. selector: '.slides > li', // String: selector, must match a simple pattern. animationSpeed: 600, // Integer: Set the speed of animations, in milliseconds. controlsContainer: '', // jQuery Object/Selector: container navigation to append elements. // Text labels. prevText: featuredSliderDefaults.prevText, // String: Set the text for the "previous" directionNav item. nextText: featuredSliderDefaults.nextText // String: Set the text for the "next" directionNav item. }; // FeaturedSlider: plugin function. $.fn.featuredslider = function( options ) { if ( options === undefined ) { options = {}; } if ( typeof options === 'object' ) { return this.each( function() { var $this = $( this ), selector = ( options.selector ) ? options.selector : '.slides > li', $slides = $this.find( selector ); if ( $slides.length === 1 || $slides.length === 0 ) { $slides.fadeIn( 400 ); } else if ( $this.data( 'featuredslider' ) === undefined ) { new $.featuredslider( this, options ); } } ); } }; } )( jQuery );
JavaScript
/** * Twenty Fourteen Featured Content admin behavior: add a tag suggestion * when changing the tag. */ /* global ajaxurl:true */ jQuery( document ).ready( function( $ ) { $( '#customize-control-featured-content-tag-name input' ).suggest( ajaxurl + '?action=ajax-tag-search&tax=post_tag', { delay: 500, minchars: 2 } ); });
JavaScript
/** * Twenty Fourteen Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color. wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' === to ) { $( '.site-title, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.site-title, .site-description' ).css( { 'clip': 'auto', 'position': 'static' } ); $( '.site-title a' ).css( { 'color': to } ); } } ); } ); } )( jQuery );
JavaScript
$(function() { $("<div id='tweet'>adsa</div>").appendTo("#tweeter").lastTwitterMessage('chriscoyier'); });
JavaScript
$(function() { $("<div id='tweet'></div>").hide().appendTo("#footer") .lastTwitterMessage('chriscoyier'); });
JavaScript
$( function($){ $.fn.lastTwitterMessage = function(username){ var $base = this; if(!username || username == "") return this; var url = "http://twitter.com/statuses/user_timeline.json?callback=?"; $.getJSON(url,{count:10,screen_name:username }, function(data){ if(data && data.length >= 1){ try{ var item = null; for(var i = 0; i < data.length; i++){ if(/^@/i.test(data[i].text)) continue; item = data[i]; break; } if(!item) return; var $tweet = $("<p>aa</p> ").text(item.text); $tweet.html( $tweet.html().replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi, '<a href="$1">$1</a>') .replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>') .replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>') ) $tweet.append(" &nbsp;<a href='http://twitter.com/" + username + "'>(&#8734;)</a>&nbsp; ").wrapInner("<span>"); $base.empty().append($tweet).show(); } catch(e) { }; }; }); return this; // Don't break the chain }; });
JavaScript
/*! * imagesLoaded PACKAGED v3.1.8 * JavaScript is all like "You images are done yet or what?" * MIT License */ /*! * EventEmitter v4.2.6 - git.io/ee * Oliver Caldwell * MIT license * @preserve */ (function () { /** * Class for managing events. * Can be extended to provide event functionality in other classes. * * @class EventEmitter Manages event registering and emitting. */ function EventEmitter() {} // Shortcuts to improve speed and size var proto = EventEmitter.prototype; var exports = this; var originalGlobalValue = exports.EventEmitter; /** * Finds the index of the listener for the event in it's storage array. * * @param {Function[]} listeners Array of listeners to search through. * @param {Function} listener Method to look for. * @return {Number} Index of the specified listener, -1 if not found * @api private */ function indexOfListener(listeners, listener) { var i = listeners.length; while (i--) { if (listeners[i].listener === listener) { return i; } } return -1; } /** * Alias a method while keeping the context correct, to allow for overwriting of target method. * * @param {String} name The name of the target method. * @return {Function} The aliased method * @api private */ function alias(name) { return function aliasClosure() { return this[name].apply(this, arguments); }; } /** * Returns the listener array for the specified event. * Will initialise the event object and listener arrays if required. * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. * Each property in the object response is an array of listener functions. * * @param {String|RegExp} evt Name of the event to return the listeners from. * @return {Function[]|Object} All listener functions for the event. */ proto.getListeners = function getListeners(evt) { var events = this._getEvents(); var response; var key; // Return a concatenated array of all matching events if // the selector is a regular expression. if (typeof evt === 'object') { response = {}; for (key in events) { if (events.hasOwnProperty(key) && evt.test(key)) { response[key] = events[key]; } } } else { response = events[evt] || (events[evt] = []); } return response; }; /** * Takes a list of listener objects and flattens it into a list of listener functions. * * @param {Object[]} listeners Raw listener objects. * @return {Function[]} Just the listener functions. */ proto.flattenListeners = function flattenListeners(listeners) { var flatListeners = []; var i; for (i = 0; i < listeners.length; i += 1) { flatListeners.push(listeners[i].listener); } return flatListeners; }; /** * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. * * @param {String|RegExp} evt Name of the event to return the listeners from. * @return {Object} All listener functions for an event in an object. */ proto.getListenersAsObject = function getListenersAsObject(evt) { var listeners = this.getListeners(evt); var response; if (listeners instanceof Array) { response = {}; response[evt] = listeners; } return response || listeners; }; /** * Adds a listener function to the specified event. * The listener will not be added if it is a duplicate. * If the listener returns true then it will be removed after it is called. * If you pass a regular expression as the event name then the listener will be added to all events that match it. * * @param {String|RegExp} evt Name of the event to attach the listener to. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. * @return {Object} Current instance of EventEmitter for chaining. */ proto.addListener = function addListener(evt, listener) { var listeners = this.getListenersAsObject(evt); var listenerIsWrapped = typeof listener === 'object'; var key; for (key in listeners) { if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) { listeners[key].push(listenerIsWrapped ? listener : { listener: listener, once: false }); } } return this; }; /** * Alias of addListener */ proto.on = alias('addListener'); /** * Semi-alias of addListener. It will add a listener that will be * automatically removed after it's first execution. * * @param {String|RegExp} evt Name of the event to attach the listener to. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. * @return {Object} Current instance of EventEmitter for chaining. */ proto.addOnceListener = function addOnceListener(evt, listener) { return this.addListener(evt, { listener: listener, once: true }); }; /** * Alias of addOnceListener. */ proto.once = alias('addOnceListener'); /** * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. * You need to tell it what event names should be matched by a regex. * * @param {String} evt Name of the event to create. * @return {Object} Current instance of EventEmitter for chaining. */ proto.defineEvent = function defineEvent(evt) { this.getListeners(evt); return this; }; /** * Uses defineEvent to define multiple events. * * @param {String[]} evts An array of event names to define. * @return {Object} Current instance of EventEmitter for chaining. */ proto.defineEvents = function defineEvents(evts) { for (var i = 0; i < evts.length; i += 1) { this.defineEvent(evts[i]); } return this; }; /** * Removes a listener function from the specified event. * When passed a regular expression as the event name, it will remove the listener from all events that match it. * * @param {String|RegExp} evt Name of the event to remove the listener from. * @param {Function} listener Method to remove from the event. * @return {Object} Current instance of EventEmitter for chaining. */ proto.removeListener = function removeListener(evt, listener) { var listeners = this.getListenersAsObject(evt); var index; var key; for (key in listeners) { if (listeners.hasOwnProperty(key)) { index = indexOfListener(listeners[key], listener); if (index !== -1) { listeners[key].splice(index, 1); } } } return this; }; /** * Alias of removeListener */ proto.off = alias('removeListener'); /** * Adds listeners in bulk using the manipulateListeners method. * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. * You can also pass it a regular expression to add the array of listeners to all events that match it. * Yeah, this function does quite a bit. That's probably a bad thing. * * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. * @param {Function[]} [listeners] An optional array of listener functions to add. * @return {Object} Current instance of EventEmitter for chaining. */ proto.addListeners = function addListeners(evt, listeners) { // Pass through to manipulateListeners return this.manipulateListeners(false, evt, listeners); }; /** * Removes listeners in bulk using the manipulateListeners method. * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. * You can also pass it an event name and an array of listeners to be removed. * You can also pass it a regular expression to remove the listeners from all events that match it. * * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. * @param {Function[]} [listeners] An optional array of listener functions to remove. * @return {Object} Current instance of EventEmitter for chaining. */ proto.removeListeners = function removeListeners(evt, listeners) { // Pass through to manipulateListeners return this.manipulateListeners(true, evt, listeners); }; /** * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. * The first argument will determine if the listeners are removed (true) or added (false). * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. * You can also pass it an event name and an array of listeners to be added/removed. * You can also pass it a regular expression to manipulate the listeners of all events that match it. * * @param {Boolean} remove True if you want to remove listeners, false if you want to add. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. * @param {Function[]} [listeners] An optional array of listener functions to add/remove. * @return {Object} Current instance of EventEmitter for chaining. */ proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) { var i; var value; var single = remove ? this.removeListener : this.addListener; var multiple = remove ? this.removeListeners : this.addListeners; // If evt is an object then pass each of it's properties to this method if (typeof evt === 'object' && !(evt instanceof RegExp)) { for (i in evt) { if (evt.hasOwnProperty(i) && (value = evt[i])) { // Pass the single listener straight through to the singular method if (typeof value === 'function') { single.call(this, i, value); } else { // Otherwise pass back to the multiple function multiple.call(this, i, value); } } } } else { // So evt must be a string // And listeners must be an array of listeners // Loop over it and pass each one to the multiple method i = listeners.length; while (i--) { single.call(this, evt, listeners[i]); } } return this; }; /** * Removes all listeners from a specified event. * If you do not specify an event then all listeners will be removed. * That means every event will be emptied. * You can also pass a regex to remove all events that match it. * * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. * @return {Object} Current instance of EventEmitter for chaining. */ proto.removeEvent = function removeEvent(evt) { var type = typeof evt; var events = this._getEvents(); var key; // Remove different things depending on the state of evt if (type === 'string') { // Remove all listeners for the specified event delete events[evt]; } else if (type === 'object') { // Remove all events matching the regex. for (key in events) { if (events.hasOwnProperty(key) && evt.test(key)) { delete events[key]; } } } else { // Remove all listeners in all events delete this._events; } return this; }; /** * Alias of removeEvent. * * Added to mirror the node API. */ proto.removeAllListeners = alias('removeEvent'); /** * Emits an event of your choice. * When emitted, every listener attached to that event will be executed. * If you pass the optional argument array then those arguments will be passed to every listener upon execution. * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. * So they will not arrive within the array on the other side, they will be separate. * You can also pass a regular expression to emit to all events that match it. * * @param {String|RegExp} evt Name of the event to emit and execute listeners for. * @param {Array} [args] Optional array of arguments to be passed to each listener. * @return {Object} Current instance of EventEmitter for chaining. */ proto.emitEvent = function emitEvent(evt, args) { var listeners = this.getListenersAsObject(evt); var listener; var i; var key; var response; for (key in listeners) { if (listeners.hasOwnProperty(key)) { i = listeners[key].length; while (i--) { // If the listener returns true then it shall be removed from the event // The function is executed either with a basic call or an apply if there is an args array listener = listeners[key][i]; if (listener.once === true) { this.removeListener(evt, listener.listener); } response = listener.listener.apply(this, args || []); if (response === this._getOnceReturnValue()) { this.removeListener(evt, listener.listener); } } } } return this; }; /** * Alias of emitEvent */ proto.trigger = alias('emitEvent'); /** * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. * * @param {String|RegExp} evt Name of the event to emit and execute listeners for. * @param {...*} Optional additional arguments to be passed to each listener. * @return {Object} Current instance of EventEmitter for chaining. */ proto.emit = function emit(evt) { var args = Array.prototype.slice.call(arguments, 1); return this.emitEvent(evt, args); }; /** * Sets the current value to check against when executing listeners. If a * listeners return value matches the one set here then it will be removed * after execution. This value defaults to true. * * @param {*} value The new value to check for when executing listeners. * @return {Object} Current instance of EventEmitter for chaining. */ proto.setOnceReturnValue = function setOnceReturnValue(value) { this._onceReturnValue = value; return this; }; /** * Fetches the current value to check against when executing listeners. If * the listeners return value matches this one then it should be removed * automatically. It will return true by default. * * @return {*|Boolean} The current value to check for or the default, true. * @api private */ proto._getOnceReturnValue = function _getOnceReturnValue() { if (this.hasOwnProperty('_onceReturnValue')) { return this._onceReturnValue; } else { return true; } }; /** * Fetches the events object and creates one if required. * * @return {Object} The events storage object. * @api private */ proto._getEvents = function _getEvents() { return this._events || (this._events = {}); }; /** * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version. * * @return {Function} Non conflicting EventEmitter class. */ EventEmitter.noConflict = function noConflict() { exports.EventEmitter = originalGlobalValue; return EventEmitter; }; // Expose the class either via AMD, CommonJS or the global object if (typeof define === 'function' && define.amd) { define('eventEmitter/EventEmitter',[],function () { return EventEmitter; }); } else if (typeof module === 'object' && module.exports){ module.exports = EventEmitter; } else { this.EventEmitter = EventEmitter; } }.call(this)); /*! * eventie v1.0.4 * event binding helper * eventie.bind( elem, 'click', myFn ) * eventie.unbind( elem, 'click', myFn ) */ /*jshint browser: true, undef: true, unused: true */ /*global define: false */ ( function( window ) { var docElem = document.documentElement; var bind = function() {}; function getIEEvent( obj ) { var event = window.event; // add event.target event.target = event.target || event.srcElement || obj; return event; } if ( docElem.addEventListener ) { bind = function( obj, type, fn ) { obj.addEventListener( type, fn, false ); }; } else if ( docElem.attachEvent ) { bind = function( obj, type, fn ) { obj[ type + fn ] = fn.handleEvent ? function() { var event = getIEEvent( obj ); fn.handleEvent.call( fn, event ); } : function() { var event = getIEEvent( obj ); fn.call( obj, event ); }; obj.attachEvent( "on" + type, obj[ type + fn ] ); }; } var unbind = function() {}; if ( docElem.removeEventListener ) { unbind = function( obj, type, fn ) { obj.removeEventListener( type, fn, false ); }; } else if ( docElem.detachEvent ) { unbind = function( obj, type, fn ) { obj.detachEvent( "on" + type, obj[ type + fn ] ); try { delete obj[ type + fn ]; } catch ( err ) { // can't delete window object properties obj[ type + fn ] = undefined; } }; } var eventie = { bind: bind, unbind: unbind }; // transport if ( typeof define === 'function' && define.amd ) { // AMD define( 'eventie/eventie',eventie ); } else { // browser global window.eventie = eventie; } })( this ); /*! * imagesLoaded v3.1.8 * JavaScript is all like "You images are done yet or what?" * MIT License */ ( function( window, factory ) { // universal module definition /*global define: false, module: false, require: false */ if ( typeof define === 'function' && define.amd ) { // AMD define( [ 'eventEmitter/EventEmitter', 'eventie/eventie' ], function( EventEmitter, eventie ) { return factory( window, EventEmitter, eventie ); }); } else if ( typeof exports === 'object' ) { // CommonJS module.exports = factory( window, require('wolfy87-eventemitter'), require('eventie') ); } else { // browser global window.imagesLoaded = factory( window, window.EventEmitter, window.eventie ); } })( window, // -------------------------- factory -------------------------- // function factory( window, EventEmitter, eventie ) { var $ = window.jQuery; var console = window.console; var hasConsole = typeof console !== 'undefined'; // -------------------------- helpers -------------------------- // // extend objects function extend( a, b ) { for ( var prop in b ) { a[ prop ] = b[ prop ]; } return a; } var objToString = Object.prototype.toString; function isArray( obj ) { return objToString.call( obj ) === '[object Array]'; } // turn element or nodeList into an array function makeArray( obj ) { var ary = []; if ( isArray( obj ) ) { // use object if already an array ary = obj; } else if ( typeof obj.length === 'number' ) { // convert nodeList to array for ( var i=0, len = obj.length; i < len; i++ ) { ary.push( obj[i] ); } } else { // array of single index ary.push( obj ); } return ary; } // -------------------------- imagesLoaded -------------------------- // /** * @param {Array, Element, NodeList, String} elem * @param {Object or Function} options - if function, use as callback * @param {Function} onAlways - callback function */ function ImagesLoaded( elem, options, onAlways ) { // coerce ImagesLoaded() without new, to be new ImagesLoaded() if ( !( this instanceof ImagesLoaded ) ) { return new ImagesLoaded( elem, options ); } // use elem as selector string if ( typeof elem === 'string' ) { elem = document.querySelectorAll( elem ); } this.elements = makeArray( elem ); this.options = extend( {}, this.options ); if ( typeof options === 'function' ) { onAlways = options; } else { extend( this.options, options ); } if ( onAlways ) { this.on( 'always', onAlways ); } this.getImages(); if ( $ ) { // add jQuery Deferred object this.jqDeferred = new $.Deferred(); } // HACK check async to allow time to bind listeners var _this = this; setTimeout( function() { _this.check(); }); } ImagesLoaded.prototype = new EventEmitter(); ImagesLoaded.prototype.options = {}; ImagesLoaded.prototype.getImages = function() { this.images = []; // filter & find items if we have an item selector for ( var i=0, len = this.elements.length; i < len; i++ ) { var elem = this.elements[i]; // filter siblings if ( elem.nodeName === 'IMG' ) { this.addImage( elem ); } // find children // no non-element nodes, #143 var nodeType = elem.nodeType; if ( !nodeType || !( nodeType === 1 || nodeType === 9 || nodeType === 11 ) ) { continue; } var childElems = elem.querySelectorAll('img'); // concat childElems to filterFound array for ( var j=0, jLen = childElems.length; j < jLen; j++ ) { var img = childElems[j]; this.addImage( img ); } } }; /** * @param {Image} img */ ImagesLoaded.prototype.addImage = function( img ) { var loadingImage = new LoadingImage( img ); this.images.push( loadingImage ); }; ImagesLoaded.prototype.check = function() { var _this = this; var checkedCount = 0; var length = this.images.length; this.hasAnyBroken = false; // complete if no images if ( !length ) { this.complete(); return; } function onConfirm( image, message ) { if ( _this.options.debug && hasConsole ) { console.log( 'confirm', image, message ); } _this.progress( image ); checkedCount++; if ( checkedCount === length ) { _this.complete(); } return true; // bind once } for ( var i=0; i < length; i++ ) { var loadingImage = this.images[i]; loadingImage.on( 'confirm', onConfirm ); loadingImage.check(); } }; ImagesLoaded.prototype.progress = function( image ) { this.hasAnyBroken = this.hasAnyBroken || !image.isLoaded; // HACK - Chrome triggers event before object properties have changed. #83 var _this = this; setTimeout( function() { _this.emit( 'progress', _this, image ); if ( _this.jqDeferred && _this.jqDeferred.notify ) { _this.jqDeferred.notify( _this, image ); } }); }; ImagesLoaded.prototype.complete = function() { var eventName = this.hasAnyBroken ? 'fail' : 'done'; this.isComplete = true; var _this = this; // HACK - another setTimeout so that confirm happens after progress setTimeout( function() { _this.emit( eventName, _this ); _this.emit( 'always', _this ); if ( _this.jqDeferred ) { var jqMethod = _this.hasAnyBroken ? 'reject' : 'resolve'; _this.jqDeferred[ jqMethod ]( _this ); } }); }; // -------------------------- jquery -------------------------- // if ( $ ) { $.fn.imagesLoaded = function( options, callback ) { var instance = new ImagesLoaded( this, options, callback ); return instance.jqDeferred.promise( $(this) ); }; } // -------------------------- -------------------------- // function LoadingImage( img ) { this.img = img; } LoadingImage.prototype = new EventEmitter(); LoadingImage.prototype.check = function() { // first check cached any previous images that have same src var resource = cache[ this.img.src ] || new Resource( this.img.src ); if ( resource.isConfirmed ) { this.confirm( resource.isLoaded, 'cached was confirmed' ); return; } // If complete is true and browser supports natural sizes, // try to check for image status manually. if ( this.img.complete && this.img.naturalWidth !== undefined ) { // report based on naturalWidth this.confirm( this.img.naturalWidth !== 0, 'naturalWidth' ); return; } // If none of the checks above matched, simulate loading on detached element. var _this = this; resource.on( 'confirm', function( resrc, message ) { _this.confirm( resrc.isLoaded, message ); return true; }); resource.check(); }; LoadingImage.prototype.confirm = function( isLoaded, message ) { this.isLoaded = isLoaded; this.emit( 'confirm', this, message ); }; // -------------------------- Resource -------------------------- // // Resource checks each src, only once // separate class from LoadingImage to prevent memory leaks. See #115 var cache = {}; function Resource( src ) { this.src = src; // add to cache cache[ src ] = this; } Resource.prototype = new EventEmitter(); Resource.prototype.check = function() { // only trigger checking once if ( this.isChecked ) { return; } // simulate loading on detached element var proxyImage = new Image(); eventie.bind( proxyImage, 'load', this ); eventie.bind( proxyImage, 'error', this ); proxyImage.src = this.src; // set flag this.isChecked = true; }; // ----- events ----- // // trigger specified handler for event type Resource.prototype.handleEvent = function( event ) { var method = 'on' + event.type; if ( this[ method ] ) { this[ method ]( event ); } }; Resource.prototype.onload = function( event ) { this.confirm( true, 'onload' ); this.unbindProxyEvents( event ); }; Resource.prototype.onerror = function( event ) { this.confirm( false, 'onerror' ); this.unbindProxyEvents( event ); }; // ----- confirm ----- // Resource.prototype.confirm = function( isLoaded, message ) { this.isConfirmed = true; this.isLoaded = isLoaded; this.emit( 'confirm', this, message ); }; Resource.prototype.unbindProxyEvents = function( event ) { eventie.unbind( event.target, 'load', this ); eventie.unbind( event.target, 'error', this ); }; // ----- ----- // return ImagesLoaded; });
JavaScript
/** * This file adds some LIVE to the Theme Customizer live preview. To leverage * this, set your custom settings to 'postMessage' and then add your handling * here. Your javascript should grab settings from customizer controls, and * then make any necessary changes to the page using jQuery. */ ( function( $ ) { //Update site accent color in real time... wp.customize( 'accent_color', function( value ) { value.bind( function( newval ) { $('.post-title a:hover').css('color', newval ); $('.main-menu .current-menu-item:before').css('color', newval ); $('.main-menu .current_page_item:before').css('color', newval ); $('.post-content blockquote:before').css('color', newval ); } ); } ); } )( jQuery );
JavaScript
jQuery(document).ready(function($) { //Masonry blocks $blocks = $(".posts"); $blocks.imagesLoaded(function(){ $blocks.masonry({ itemSelector: '.post-container' }); // Fade blocks in after images are ready (prevents jumping and re-rendering) $(".post-container").fadeIn(); }); $(document).ready( function() { setTimeout( function() { $blocks.masonry(); }, 500); }); $(window).resize(function () { $blocks.masonry(); }); // Toggle navigation $(".nav-toggle").on("click", function(){ $(this).toggleClass("active"); $(".mobile-navigation").slideToggle(); }); // Hide mobile-menu > 1000 $(window).resize(function() { if ($(window).width() > 1000) { $(".nav-toggle").removeClass("active"); $(".mobile-navigation").hide(); } }); // Load Flexslider $(".flexslider").flexslider({ animation: "slide", controlNav: false, smoothHeight: true, start: $blocks.masonry(), }); // resize videos after container var vidSelector = ".post iframe, .post object, .post video, .widget-content iframe, .widget-content object, .widget-content iframe"; var resizeVideo = function(sSel) { $( sSel ).each(function() { var $video = $(this), $container = $video.parent(), iTargetWidth = $container.width(); if ( !$video.attr("data-origwidth") ) { $video.attr("data-origwidth", $video.attr("width")); $video.attr("data-origheight", $video.attr("height")); } var ratio = iTargetWidth / $video.attr("data-origwidth"); $video.css("width", iTargetWidth + "px"); $video.css("height", ( $video.attr("data-origheight") * ratio ) + "px"); }); }; resizeVideo(vidSelector); $(window).resize(function() { resizeVideo(vidSelector); }); // When Jetpack Infinite scroll posts have loaded $( document.body ).on( 'post-load', function () { var $container = $('.posts'); $container.masonry( 'reloadItems' ); $blocks.imagesLoaded(function(){ $blocks.masonry({ itemSelector: '.post-container' }); // Fade blocks in after images are ready (prevents jumping and re-rendering) $(".post-container").fadeIn(); }); // Rerun video resizing resizeVideo(vidSelector); $container.masonry( 'reloadItems' ); // Load Flexslider $(".flexslider").flexslider({ animation: "slide", controlNav: false, prevText: "Previous", nextText: "Next", smoothHeight: true }); $(document).ready( function() { setTimeout( function() { $blocks.masonry(); }, 500); }); }); });
JavaScript
jQuery(window).load(function() { /* Navigation */ jQuery('#submenu ul.sfmenu').superfish({ delay: 500, // 0.1 second delay on mouseout animation: { opacity:'show',height:'show'}, // fade-in and slide-down animation dropShadows: true // disable drop shadows }); /* Hover block */ jQuery('.portfolio-box').hover(function(){ jQuery(this).find('div').animate({opacity:'1'},{queue:false,duration:500}); }, function(){ jQuery(this).find('div').animate({opacity:'0'},{queue:false,duration:500}); }); /* equal column */ var biggestHeight = 0; //check each of them jQuery('.equal_height').each(function(){ //if the height of the current element is //bigger then the current biggestHeight value if(jQuery(this).height() > biggestHeight){ //update the biggestHeight with the //height of the current elements biggestHeight = jQuery(this).height(); } }); //when checking for biggestHeight is done set that //height to all the elements jQuery('.equal_height').height(biggestHeight); });
JavaScript
jQuery(document).ready(function () { // Установка реального цвета с учётом прозрачности function setIColor(fake_i, color, opacity) { var id = fake_i.attr("id"); var name = id.substring(5); jQuery('#' + name).val(color); jQuery('#' + name + '_opacity').val(opacity); } function setColorPicker() { jQuery("input.color-picker").css({"height": "auto", "padding-top": "7px", "padding-right": "7px", "padding-bottom": "7px"}); jQuery("input.color-picker").minicolors({ 'control': "wheel", 'defaultValue': "#FFFFFF", 'changeDelay': 25, 'inline': false, 'position': "bottom left", 'letterCase': "lowercase", 'theme': "bootstrap", 'opacity': true, 'change': function(hex, opacity) { var color = hex; if (opacity != 1) color = jQuery(this).minicolors('rgbaString'); setIColor(jQuery(this), color, opacity); }, 'hide': function() { var opacity = jQuery(this).minicolors('opacity'); var color = jQuery(this).val(); if (opacity != 1) color = jQuery(this).minicolors('rgbaString'); setIColor(jQuery(this), color, opacity); } }); jQuery(".minicolors").css({"width": "100%"}); jQuery(".minicolors-swatch").css({"top": "4px"}); } // + Выставляем opacity // + Запоняем скрытые поля из знач по умолчанию jQuery("input[type=hidden]").each(function() { var id = jQuery(this).attr('id'); // Запоняем скрытые поля из знач по умолчанию if (typeof(id) != 'undefined' && id.substring(10) != 'opacity' && jQuery("#fake_" + id.substring(0, 9)).length > 0) { if (jQuery(this).val() == '') jQuery(this).val( jQuery("#fake_" + id.substring(0, 9)).val() ); } if (typeof(id) == 'undefined' || id.substring(10) != 'opacity' || jQuery("#fake_" + id.substring(0, 9)).length <= 0) return; jQuery("#fake_" + id.substring(0, 9)).attr('data-opacity', jQuery(this).val()); }); setColorPicker(); });
JavaScript
/** * Custom scripts needed for the colorpicker, image button selectors, * and navigation tabs. */ jQuery(document).ready(function($) { // Loads the color pickers $('.of-color').wpColorPicker(); // Image Options $('.of-radio-img-img').click(function(){ $(this).parent().parent().find('.of-radio-img-img').removeClass('of-radio-img-selected'); $(this).addClass('of-radio-img-selected'); }); $('.of-radio-img-label').hide(); $('.of-radio-img-img').show(); $('.of-radio-img-radio').hide(); // Loads tabbed sections if they exist if ( $('.nav-tab-wrapper').length > 0 ) { options_framework_tabs(); } function options_framework_tabs() { // Hides all the .group sections to start $('.group').hide(); // Find if a selected tab is saved in localStorage var active_tab = ''; if ( typeof(localStorage) != 'undefined' ) { active_tab = localStorage.getItem("active_tab"); } // If active tab is saved and exists, load it's .group if (active_tab != '' && $(active_tab).length ) { $(active_tab).fadeIn(); $(active_tab + '-tab').addClass('nav-tab-active'); } else { $('.group:first').fadeIn(); $('.nav-tab-wrapper a:first').addClass('nav-tab-active'); } // Bind tabs clicks $('.nav-tab-wrapper a').click(function(evt) { evt.preventDefault(); // Remove active class from all tabs $('.nav-tab-wrapper a').removeClass('nav-tab-active'); $(this).addClass('nav-tab-active').blur(); var group = $(this).attr('href'); if (typeof(localStorage) != 'undefined' ) { localStorage.setItem("active_tab", $(this).attr('href') ); } $('.group').hide(); $(group).fadeIn(); // Editor height sometimes needs adjustment when unhidden $('.wp-editor-wrap').each(function() { var editor_iframe = $(this).find('iframe'); if ( editor_iframe.height() < 30 ) { editor_iframe.css({'height':'auto'}); } }); }); } });
JavaScript
jQuery(document).ready(function($){ var optionsframework_upload; var optionsframework_selector; function optionsframework_add_file(event, selector) { var upload = $(".uploaded-file"), frame; var $el = $(this); optionsframework_selector = selector; event.preventDefault(); // If the media frame already exists, reopen it. if ( optionsframework_upload ) { optionsframework_upload.open(); } else { // Create the media frame. optionsframework_upload = wp.media.frames.optionsframework_upload = wp.media({ // Set the title of the modal. title: $el.data('choose'), // Customize the submit button. button: { // Set the text of the button. text: $el.data('update'), // Tell the button not to close the modal, since we're // going to refresh the page when the image is selected. close: false } }); // When an image is selected, run a callback. optionsframework_upload.on( 'select', function() { // Grab the selected attachment. var attachment = optionsframework_upload.state().get('selection').first(); optionsframework_upload.close(); optionsframework_selector.find('.upload').val(attachment.attributes.url); if ( attachment.attributes.type == 'image' ) { optionsframework_selector.find('.screenshot').empty().hide().append('<img src="' + attachment.attributes.url + '"><a class="remove-image">Remove</a>').slideDown('fast'); } optionsframework_selector.find('.upload-button').unbind().addClass('remove-file').removeClass('upload-button').val(optionsframework_l10n.remove); optionsframework_selector.find('.of-background-properties').slideDown(); optionsframework_selector.find('.remove-image, .remove-file').on('click', function() { optionsframework_remove_file( $(this).parents('.section') ); }); }); } // Finally, open the modal. optionsframework_upload.open(); } function optionsframework_remove_file(selector) { selector.find('.remove-image').hide(); selector.find('.upload').val(''); selector.find('.of-background-properties').hide(); selector.find('.screenshot').slideUp(); selector.find('.remove-file').unbind().addClass('upload-button').removeClass('remove-file').val(optionsframework_l10n.upload); // We don't display the upload button if .upload-notice is present // This means the user doesn't have the WordPress 3.5 Media Library Support if ( $('.section-upload .upload-notice').length > 0 ) { $('.upload-button').remove(); } selector.find('.upload-button').on('click', function(event) { optionsframework_add_file(event, $(this).parents('.section')); }); } $('.remove-image, .remove-file').on('click', function() { optionsframework_remove_file( $(this).parents('.section') ); }); $('.upload-button').click( function( event ) { optionsframework_add_file(event, $(this).parents('.section')); }); });
JavaScript
jQuery(window).load(function() { /* Navigation */ jQuery('#submenu ul.sfmenu').superfish({ delay: 500, // 0.1 second delay on mouseout animation: { opacity:'show',height:'show'}, // fade-in and slide-down animation dropShadows: true // disable drop shadows }); /* Hover block */ jQuery('.portfolio-box').hover(function(){ jQuery(this).find('div').animate({opacity:'1'},{queue:false,duration:500}); }, function(){ jQuery(this).find('div').animate({opacity:'0'},{queue:false,duration:500}); }); /* equal column */ var biggestHeight = 0; //check each of them jQuery('.equal_height').each(function(){ //if the height of the current element is //bigger then the current biggestHeight value if(jQuery(this).height() > biggestHeight){ //update the biggestHeight with the //height of the current elements biggestHeight = jQuery(this).height(); } }); //when checking for biggestHeight is done set that //height to all the elements jQuery('.equal_height').height(biggestHeight); //cài css cho iframe them album/anh jQuery(".toggle_button").click(function() { if(jQuery("#secondary").is(":visible")) { jQuery("#secondary").hide("slow"); jQuery("#toggle_icon").css({'transition-duration': '0.5s','-webkit-transform' : 'rotate(90deg)', '-moz-transform' : 'rotate(90deg)', '-ms-transform' : 'rotate(90deg)', 'transform' : 'rotate(90deg)'}); var r=jQuery("iframe").width()+100; if (r>1300) jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'50px' }); else jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition':'margin-left 0.5s','margin-left':'150px' }); } else { jQuery("#secondary").show("slow"); jQuery("#toggle_icon").css({'transition-duration': '0.5s','-webkit-transform' : 'rotate(0deg)', '-moz-transform' : 'rotate(0deg)', '-ms-transform' : 'rotate(0deg)', 'transform' : 'rotate(0deg)'}); jQuery("#primary").css({'transition-duration': '0.5s','-webkit-transition': 'margin-left 0.5s','margin-left':'255px' }); } }); }); jQuery(document).ready(function(){ //tao doi tuong websocket // var wsUri = "ws://localhost:9070/server.php"; // wsocket = new WebSocket(wsUri); //khi ket noi duoc mo //khi nhan dc message tu sever // wsocket.onmessage = function(ev) { // var msg = JSON.parse(ev.data); //chuyen chuoi JSON thanh doi tuong JSON // var type = msg.notification_type; //kieu message // var counter=msg.counter; // if(type == 'like') //neu la message cua user // { // jQuery('.comment_counter').css({opacity: 0}); // jQuery('.comment_counter').text(counter); // jQuery('.comment_counter').css({top: '-10px'}); // jQuery('.comment_counter').animate({top: '-2px', opacity: 1}); // } // if(type == 'comment') //neu la message cua he thong // { // jQuery('.like_counter').css({opacity: 0}); // jQuery('.like_counter').text(counter); // jQuery('.like_counter').css({top: '-10px'}); // jQuery('.like_counter').animate({top: '-2px', opacity: 1}); // } // if(type == 'image') //neu la message cua he thong // { // jQuery('.image_counter').css({opacity: 0}); // jQuery('.image_counter').text(counter); // jQuery('.image_counter').css({top: '-10px'}); // jQuery('.image_counter').animate({top: '-2px', opacity: 1}); // } // if(type == 'message') //neu la message cua he thong // { // jQuery('.image_counter').css({opacity: 0}); // jQuery('.image_counter').text(counter); // jQuery('.image_counter').css({top: '-10px'}); // jQuery('.image_counter').animate({top: '-2px', opacity: 1}); // } // }; });
JavaScript
jQuery(document).ready(function () { // Установка реального цвета с учётом прозрачности function setIColor(fake_i, color, opacity) { var id = fake_i.attr("id"); var name = id.substring(5); jQuery('#' + name).val(color); jQuery('#' + name + '_opacity').val(opacity); } function setColorPicker() { jQuery("input.color-picker").css({"height": "auto", "padding-top": "7px", "padding-right": "7px", "padding-bottom": "7px"}); jQuery("input.color-picker").minicolors({ 'control': "wheel", 'defaultValue': "#FFFFFF", 'changeDelay': 25, 'inline': false, 'position': "bottom left", 'letterCase': "lowercase", 'theme': "bootstrap", 'opacity': true, 'change': function(hex, opacity) { var color = hex; if (opacity != 1) color = jQuery(this).minicolors('rgbaString'); setIColor(jQuery(this), color, opacity); }, 'hide': function() { var opacity = jQuery(this).minicolors('opacity'); var color = jQuery(this).val(); if (opacity != 1) color = jQuery(this).minicolors('rgbaString'); setIColor(jQuery(this), color, opacity); } }); jQuery(".minicolors").css({"width": "100%"}); jQuery(".minicolors-swatch").css({"top": "4px"}); } // + Выставляем opacity // + Запоняем скрытые поля из знач по умолчанию jQuery("input[type=hidden]").each(function() { var id = jQuery(this).attr('id'); // Запоняем скрытые поля из знач по умолчанию if (typeof(id) != 'undefined' && id.substring(10) != 'opacity' && jQuery("#fake_" + id.substring(0, 9)).length > 0) { if (jQuery(this).val() == '') jQuery(this).val( jQuery("#fake_" + id.substring(0, 9)).val() ); } if (typeof(id) == 'undefined' || id.substring(10) != 'opacity' || jQuery("#fake_" + id.substring(0, 9)).length <= 0) return; jQuery("#fake_" + id.substring(0, 9)).attr('data-opacity', jQuery(this).val()); }); setColorPicker(); });
JavaScript
/** * Custom scripts needed for the colorpicker, image button selectors, * and navigation tabs. */ jQuery(document).ready(function($) { // Loads the color pickers $('.of-color').wpColorPicker(); // Image Options $('.of-radio-img-img').click(function(){ $(this).parent().parent().find('.of-radio-img-img').removeClass('of-radio-img-selected'); $(this).addClass('of-radio-img-selected'); }); $('.of-radio-img-label').hide(); $('.of-radio-img-img').show(); $('.of-radio-img-radio').hide(); // Loads tabbed sections if they exist if ( $('.nav-tab-wrapper').length > 0 ) { options_framework_tabs(); } function options_framework_tabs() { // Hides all the .group sections to start $('.group').hide(); // Find if a selected tab is saved in localStorage var active_tab = ''; if ( typeof(localStorage) != 'undefined' ) { active_tab = localStorage.getItem("active_tab"); } // If active tab is saved and exists, load it's .group if (active_tab != '' && $(active_tab).length ) { $(active_tab).fadeIn(); $(active_tab + '-tab').addClass('nav-tab-active'); } else { $('.group:first').fadeIn(); $('.nav-tab-wrapper a:first').addClass('nav-tab-active'); } // Bind tabs clicks $('.nav-tab-wrapper a').click(function(evt) { evt.preventDefault(); // Remove active class from all tabs $('.nav-tab-wrapper a').removeClass('nav-tab-active'); $(this).addClass('nav-tab-active').blur(); var group = $(this).attr('href'); if (typeof(localStorage) != 'undefined' ) { localStorage.setItem("active_tab", $(this).attr('href') ); } $('.group').hide(); $(group).fadeIn(); // Editor height sometimes needs adjustment when unhidden $('.wp-editor-wrap').each(function() { var editor_iframe = $(this).find('iframe'); if ( editor_iframe.height() < 30 ) { editor_iframe.css({'height':'auto'}); } }); }); } });
JavaScript
jQuery(document).ready(function($){ var optionsframework_upload; var optionsframework_selector; function optionsframework_add_file(event, selector) { var upload = $(".uploaded-file"), frame; var $el = $(this); optionsframework_selector = selector; event.preventDefault(); // If the media frame already exists, reopen it. if ( optionsframework_upload ) { optionsframework_upload.open(); } else { // Create the media frame. optionsframework_upload = wp.media.frames.optionsframework_upload = wp.media({ // Set the title of the modal. title: $el.data('choose'), // Customize the submit button. button: { // Set the text of the button. text: $el.data('update'), // Tell the button not to close the modal, since we're // going to refresh the page when the image is selected. close: false } }); // When an image is selected, run a callback. optionsframework_upload.on( 'select', function() { // Grab the selected attachment. var attachment = optionsframework_upload.state().get('selection').first(); optionsframework_upload.close(); optionsframework_selector.find('.upload').val(attachment.attributes.url); if ( attachment.attributes.type == 'image' ) { optionsframework_selector.find('.screenshot').empty().hide().append('<img src="' + attachment.attributes.url + '"><a class="remove-image">Remove</a>').slideDown('fast'); } optionsframework_selector.find('.upload-button').unbind().addClass('remove-file').removeClass('upload-button').val(optionsframework_l10n.remove); optionsframework_selector.find('.of-background-properties').slideDown(); optionsframework_selector.find('.remove-image, .remove-file').on('click', function() { optionsframework_remove_file( $(this).parents('.section') ); }); }); } // Finally, open the modal. optionsframework_upload.open(); } function optionsframework_remove_file(selector) { selector.find('.remove-image').hide(); selector.find('.upload').val(''); selector.find('.of-background-properties').hide(); selector.find('.screenshot').slideUp(); selector.find('.remove-file').unbind().addClass('upload-button').removeClass('remove-file').val(optionsframework_l10n.upload); // We don't display the upload button if .upload-notice is present // This means the user doesn't have the WordPress 3.5 Media Library Support if ( $('.section-upload .upload-notice').length > 0 ) { $('.upload-button').remove(); } selector.find('.upload-button').on('click', function(event) { optionsframework_add_file(event, $(this).parents('.section')); }); } $('.remove-image, .remove-file').on('click', function() { optionsframework_remove_file( $(this).parents('.section') ); }); $('.upload-button').click( function( event ) { optionsframework_add_file(event, $(this).parents('.section')); }); });
JavaScript
/** * Functionality specific to Twenty Thirteen. * * Provides helper functions to enhance the theme experience. */ ( function( $ ) { var body = $( 'body' ), _window = $( window ); /** * Adds a top margin to the footer if the sidebar widget area is higher * than the rest of the page, to help the footer always visually clear * the sidebar. */ $( function() { if ( body.is( '.sidebar' ) ) { var sidebar = $( '#secondary .widget-area' ), secondary = ( 0 === sidebar.length ) ? -40 : sidebar.height(), margin = $( '#tertiary .widget-area' ).height() - $( '#content' ).height() - secondary; if ( margin > 0 && _window.innerWidth() > 999 ) { $( '#colophon' ).css( 'margin-top', margin + 'px' ); } } } ); /** * Enables menu toggle for small screens. */ ( function() { var nav = $( '#site-navigation' ), button, menu; if ( ! nav ) { return; } button = nav.find( '.menu-toggle' ); if ( ! button ) { return; } // Hide button if menu is missing or empty. menu = nav.find( '.nav-menu' ); if ( ! menu || ! menu.children().length ) { button.hide(); return; } button.on( 'click.twentythirteen', function() { nav.toggleClass( 'toggled-on' ); } ); // Better focus for hidden submenu items for accessibility. menu.find( 'a' ).on( 'focus.twentythirteen blur.twentythirteen', function() { $( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' ); } ); } )(); /** * Makes "skip to content" link work correctly in IE9 and Chrome for better * accessibility. * * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/ */ _window.on( 'hashchange.twentythirteen', function() { var element = document.getElementById( location.hash.substring( 1 ) ); if ( element ) { if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) { element.tabIndex = -1; } element.focus(); } } ); /** * Arranges footer widgets vertically. */ if ( $.isFunction( $.fn.masonry ) ) { var columnWidth = body.is( '.sidebar' ) ? 228 : 245; $( '#secondary .widget-area' ).masonry( { itemSelector: '.widget', columnWidth: columnWidth, gutterWidth: 20, isRTL: body.is( '.rtl' ) } ); } } )( jQuery );
JavaScript
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title and description changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title' ).text( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).text( to ); } ); } ); // Header text color. wp.customize( 'header_textcolor', function( value ) { value.bind( function( to ) { if ( 'blank' == to ) { if ( 'remove-header' == _wpCustomizeSettings.values.header_image ) $( '.home-link' ).css( 'min-height', '0' ); $( '.site-title, .site-description' ).css( { 'clip': 'rect(1px, 1px, 1px, 1px)', 'position': 'absolute' } ); } else { $( '.home-link' ).css( 'min-height', '230px' ); $( '.site-title, .site-description' ).css( { 'clip': 'auto', 'color': to, 'position': 'relative' } ); } } ); } ); } )( jQuery );
JavaScript
/** * AJAX Upload ( http://valums.com/ajax-upload/ ) * Copyright (c) Andrew Valums * Licensed under the MIT license */ (function () { /** * Attaches event to a dom element. * @param {Element} el * @param type event name * @param fn callback This refers to the passed element */ function addEvent(el, type, fn){ if (el.addEventListener) { el.addEventListener(type, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + type, function(){ fn.call(el); }); } else { throw new Error('not supported or DOM not loaded'); } } /** * Attaches resize event to a window, limiting * number of event fired. Fires only when encounteres * delay of 100 after series of events. * * Some browsers fire event multiple times when resizing * http://www.quirksmode.org/dom/events/resize.html * * @param fn callback This refers to the passed element */ function addResizeEvent(fn){ var timeout; addEvent(window, 'resize', function(){ if (timeout){ clearTimeout(timeout); } timeout = setTimeout(fn, 100); }); } // Needs more testing, will be rewriten for next version // getOffset function copied from jQuery lib (http://jquery.com/) if (document.documentElement.getBoundingClientRect){ // Get Offset using getBoundingClientRect // http://ejohn.org/blog/getboundingclientrect-is-awesome/ var getOffset = function(el){ var box = el.getBoundingClientRect(); var doc = el.ownerDocument; var body = doc.body; var docElem = doc.documentElement; // for ie var clientTop = docElem.clientTop || body.clientTop || 0; var clientLeft = docElem.clientLeft || body.clientLeft || 0; // In Internet Explorer 7 getBoundingClientRect property is treated as physical, // while others are logical. Make all logical, like in IE8. var zoom = 1; if (body.getBoundingClientRect) { var bound = body.getBoundingClientRect(); zoom = (bound.right - bound.left) / body.clientWidth; } if (zoom > 1) { clientTop = 0; clientLeft = 0; } var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft; return { top: top, left: left }; }; } else { // Get offset adding all offsets var getOffset = function(el){ var top = 0, left = 0; do { top += el.offsetTop || 0; left += el.offsetLeft || 0; el = el.offsetParent; } while (el); return { left: left, top: top }; }; } /** * Returns left, top, right and bottom properties describing the border-box, * in pixels, with the top-left relative to the body * @param {Element} el * @return {Object} Contains left, top, right,bottom */ function getBox(el){ var left, right, top, bottom; var offset = getOffset(el); left = offset.left; top = offset.top; right = left + el.offsetWidth; bottom = top + el.offsetHeight; return { left: left, right: right, top: top, bottom: bottom }; } /** * Helper that takes object literal * and add all properties to element.style * @param {Element} el * @param {Object} styles */ function addStyles(el, styles){ for (var name in styles) { if (styles.hasOwnProperty(name)) { el.style[name] = styles[name]; } } } /** * Function places an absolutely positioned * element on top of the specified element * copying position and dimentions. * @param {Element} from * @param {Element} to */ function copyLayout(from, to){ var box = getBox(from); addStyles(to, { position: 'absolute', left : box.left + 'px', top : box.top + 'px', width : from.offsetWidth + 'px', height : from.offsetHeight + 'px' }); } /** * Creates and returns element from html chunk * Uses innerHTML to create an element */ var toElement = (function(){ var div = document.createElement('div'); return function(html){ div.innerHTML = html; var el = div.firstChild; return div.removeChild(el); }; })(); /** * Function generates unique id * @return unique id */ var getUID = (function(){ var id = 0; return function(){ return 'ValumsAjaxUpload' + id++; }; })(); /** * Get file name from path * @param {String} file path to file * @return filename */ function fileFromPath(file){ return file.replace(/.*(\/|\\)/, ""); } /** * Get file extension lowercase * @param {String} file name * @return file extenstion */ function getExt(file){ return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : ''; } function hasClass(el, name){ var re = new RegExp('\\b' + name + '\\b'); return re.test(el.className); } function addClass(el, name){ if ( ! hasClass(el, name)){ el.className += ' ' + name; } } function removeClass(el, name){ var re = new RegExp('\\b' + name + '\\b'); el.className = el.className.replace(re, ''); } function removeNode(el){ el.parentNode.removeChild(el); } /** * Easy styling and uploading * @constructor * @param button An element you want convert to * upload button. Tested dimentions up to 500x500px * @param {Object} options See defaults below. */ window.AjaxUpload = function(button, options){ this._settings = { // Location of the server-side upload script action: 'upload.php', // File upload name name: 'userfile', // Select & upload multiple files at once FF3.6+, Chrome 4+ multiple: false, // Additional data to send data: {}, // Submit file as soon as it's selected autoSubmit: true, // The type of data that you're expecting back from the server. // html and xml are detected automatically. // Only useful when you are using json data as a response. // Set to "json" in that case. responseType: false, // Class applied to button when mouse is hovered hoverClass: 'hover', // Class applied to button when button is focused focusClass: 'focus', // Class applied to button when AU is disabled disabledClass: 'disabled', // When user selects a file, useful with autoSubmit disabled // You can return false to cancel upload onChange: function(file, extension){ }, // Callback to fire before file is uploaded // You can return false to cancel upload onSubmit: function(file, extension){ }, // Fired when file upload is completed // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE! onComplete: function(file, response){ } }; // Merge the users options with our defaults for (var i in options) { if (options.hasOwnProperty(i)){ this._settings[i] = options[i]; } } // button isn't necessary a dom element if (button.jquery){ // jQuery object was passed button = button[0]; } else if (typeof button == "string") { if (/^#.*/.test(button)){ // If jQuery user passes #elementId don't break it button = button.slice(1); } button = document.getElementById(button); } if ( ! button || button.nodeType !== 1){ throw new Error("Please make sure that you're passing a valid element"); } if ( button.nodeName.toUpperCase() == 'A'){ // disable link addEvent(button, 'click', function(e){ if (e && e.preventDefault){ e.preventDefault(); } else if (window.event){ window.event.returnValue = false; } }); } // DOM element this._button = button; // DOM element this._input = null; // If disabled clicking on button won't do anything this._disabled = false; // if the button was disabled before refresh if will remain // disabled in FireFox, let's fix it this.enable(); this._rerouteClicks(); }; // assigning methods to our class AjaxUpload.prototype = { setData: function(data){ this._settings.data = data; }, disable: function(){ addClass(this._button, this._settings.disabledClass); this._disabled = true; var nodeName = this._button.nodeName.toUpperCase(); if (nodeName == 'INPUT' || nodeName == 'BUTTON'){ this._button.setAttribute('disabled', 'disabled'); } // hide input if (this._input){ if (this._input.parentNode) { // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it // has display none when user selects a file this._input.parentNode.style.visibility = 'hidden'; } } }, enable: function(){ removeClass(this._button, this._settings.disabledClass); this._button.removeAttribute('disabled'); this._disabled = false; }, /** * Creates invisible file input * that will hover above the button * <div><input type='file' /></div> */ _createInput: function(){ var self = this; var input = document.createElement("input"); input.setAttribute('type', 'file'); input.setAttribute('name', this._settings.name); if(this._settings.multiple) input.setAttribute('multiple', 'multiple'); addStyles(input, { 'position' : 'absolute', // in Opera only 'browse' button // is clickable and it is located at // the right side of the input 'right' : 0, 'margin' : 0, 'padding' : 0, 'fontSize' : '480px', // in Firefox if font-family is set to // 'inherit' the input doesn't work 'fontFamily' : 'sans-serif', 'cursor' : 'pointer' }); var div = document.createElement("div"); addStyles(div, { 'display' : 'block', 'position' : 'absolute', 'overflow' : 'hidden', 'margin' : 0, 'padding' : 0, 'opacity' : 0, // Make sure browse button is in the right side // in Internet Explorer 'direction' : 'ltr', //Max zIndex supported by Opera 9.0-9.2 'zIndex': 2147483583 }); // Make sure that element opacity exists. // Otherwise use IE filter if ( div.style.opacity !== "0") { if (typeof(div.filters) == 'undefined'){ throw new Error('Opacity not supported by the browser'); } div.style.filter = "alpha(opacity=0)"; } addEvent(input, 'change', function(){ if ( ! input || input.value === ''){ return; } // Get filename from input, required // as some browsers have path instead of it var file = fileFromPath(input.value); if (false === self._settings.onChange.call(self, file, getExt(file))){ self._clearInput(); return; } // Submit form when value is changed if (self._settings.autoSubmit) { self.submit(); } }); addEvent(input, 'mouseover', function(){ addClass(self._button, self._settings.hoverClass); }); addEvent(input, 'mouseout', function(){ removeClass(self._button, self._settings.hoverClass); removeClass(self._button, self._settings.focusClass); if (input.parentNode) { // We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it // has display none when user selects a file input.parentNode.style.visibility = 'hidden'; } }); addEvent(input, 'focus', function(){ addClass(self._button, self._settings.focusClass); }); addEvent(input, 'blur', function(){ removeClass(self._button, self._settings.focusClass); }); div.appendChild(input); document.body.appendChild(div); this._input = input; }, _clearInput : function(){ if (!this._input){ return; } // this._input.value = ''; Doesn't work in IE6 removeNode(this._input.parentNode); this._input = null; this._createInput(); removeClass(this._button, this._settings.hoverClass); removeClass(this._button, this._settings.focusClass); }, /** * Function makes sure that when user clicks upload button, * the this._input is clicked instead */ _rerouteClicks: function(){ var self = this; // IE will later display 'access denied' error // if you use using self._input.click() // other browsers just ignore click() addEvent(self._button, 'mouseover', function(){ if (self._disabled){ return; } if ( ! self._input){ self._createInput(); } var div = self._input.parentNode; copyLayout(self._button, div); div.style.visibility = 'visible'; }); // commented because we now hide input on mouseleave /** * When the window is resized the elements * can be misaligned if button position depends * on window size */ //addResizeEvent(function(){ // if (self._input){ // copyLayout(self._button, self._input.parentNode); // } //}); }, /** * Creates iframe with unique name * @return {Element} iframe */ _createIframe: function(){ // We can't use getTime, because it sometimes return // same value in safari :( var id = getUID(); // We can't use following code as the name attribute // won't be properly registered in IE6, and new window // on form submit will open // var iframe = document.createElement('iframe'); // iframe.setAttribute('name', id); var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />'); // src="javascript:false; was added // because it possibly removes ie6 prompt // "This page contains both secure and nonsecure items" // Anyway, it doesn't do any harm. iframe.setAttribute('id', id); iframe.style.display = 'none'; document.body.appendChild(iframe); return iframe; }, /** * Creates form, that will be submitted to iframe * @param {Element} iframe Where to submit * @return {Element} form */ _createForm: function(iframe){ var settings = this._settings; // We can't use the following code in IE6 // var form = document.createElement('form'); // form.setAttribute('method', 'post'); // form.setAttribute('enctype', 'multipart/form-data'); // Because in this case file won't be attached to request var form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.setAttribute('action', settings.action); form.setAttribute('target', iframe.name); form.style.display = 'none'; document.body.appendChild(form); // Create hidden input element for each data key for (var prop in settings.data) { if (settings.data.hasOwnProperty(prop)){ var el = document.createElement("input"); el.setAttribute('type', 'hidden'); el.setAttribute('name', prop); el.setAttribute('value', settings.data[prop]); form.appendChild(el); } } return form; }, /** * Gets response from iframe and fires onComplete event when ready * @param iframe * @param file Filename to use in onComplete callback */ _getResponse : function(iframe, file){ // getting response var toDeleteFlag = false, self = this, settings = this._settings; addEvent(iframe, 'load', function(){ if (// For Safari iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" || // For FF, IE iframe.src == "javascript:'<html></html>';"){ // First time around, do not delete. // We reload to blank page, so that reloading main page // does not re-submit the post. if (toDeleteFlag) { // Fix busy state in FF3 setTimeout(function(){ removeNode(iframe); }, 0); } return; } var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00 if (doc.readyState && doc.readyState != 'complete') { // Opera fires load event multiple times // Even when the DOM is not ready yet // this fix should not affect other browsers return; } // fixing Opera 9.64 if (doc.body && doc.body.innerHTML == "false") { // In Opera 9.64 event was fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec return; } var response; if (doc.XMLDocument) { // response is a xml document Internet Explorer property response = doc.XMLDocument; } else if (doc.body){ // response is html document or plain text response = doc.body.innerHTML; if (settings.responseType && settings.responseType.toLowerCase() == 'json') { // If the document was sent as 'application/javascript' or // 'text/javascript', then the browser wraps the text in a <pre> // tag and performs html encoding on the contents. In this case, // we need to pull the original text content from the text node's // nodeValue property to retrieve the unmangled content. // Note that IE6 only understands text/html if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') { doc.normalize(); response = doc.body.firstChild.firstChild.nodeValue; } if (response) { response = eval("(" + response + ")"); } else { response = {}; } } } else { // response is a xml document response = doc; } settings.onComplete.call(self, file, response); // Reload blank page, so that reloading main page // does not re-submit the post. Also, remember to // delete the frame toDeleteFlag = true; // Fix IE mixed content issue iframe.src = "javascript:'<html></html>';"; }); }, /** * Upload file contained in this._input */ submit: function(){ var self = this, settings = this._settings; if ( ! this._input || this._input.value === ''){ return; } var file = fileFromPath(this._input.value); // user returned false to cancel upload if (false === settings.onSubmit.call(this, file, getExt(file))){ this._clearInput(); return; } // sending request var iframe = this._createIframe(); var form = this._createForm(iframe); // assuming following structure // div -> input type='file' removeNode(this._input.parentNode); removeClass(self._button, self._settings.hoverClass); removeClass(self._button, self._settings.focusClass); form.appendChild(this._input); form.submit(); // request set, clean up removeNode(form); form = null; removeNode(this._input); this._input = null; // Get response from iframe and fire onComplete event when ready this._getResponse(iframe, file); // get ready for next request this._createInput(); } }; })();
JavaScript
/** * * Color picker * Author: Stefan Petre www.eyecon.ro * * Dependencies: jQuery * */ (function ($) { var ColorPicker = function () { var ids = {}, inAction, charMin = 65, visible, tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>', defaults = { eventName: 'click', onShow: function () {}, onBeforeShow: function(){}, onHide: function () {}, onChange: function () {}, onSubmit: function () {}, color: 'ff0000', livePreview: true, flat: false }, fillRGBFields = function (hsb, cal) { var rgb = HSBToRGB(hsb); $(cal).data('colorpicker').fields .eq(1).val(rgb.r).end() .eq(2).val(rgb.g).end() .eq(3).val(rgb.b).end(); }, fillHSBFields = function (hsb, cal) { $(cal).data('colorpicker').fields .eq(4).val(hsb.h).end() .eq(5).val(hsb.s).end() .eq(6).val(hsb.b).end(); }, fillHexFields = function (hsb, cal) { $(cal).data('colorpicker').fields .eq(0).val(HSBToHex(hsb)).end(); }, setSelector = function (hsb, cal) { $(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100})); $(cal).data('colorpicker').selectorIndic.css({ left: parseInt(150 * hsb.s/100, 10), top: parseInt(150 * (100-hsb.b)/100, 10) }); }, setHue = function (hsb, cal) { $(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10)); }, setCurrentColor = function (hsb, cal) { $(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb)); }, setNewColor = function (hsb, cal) { $(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb)); }, keyDown = function (ev) { var pressedKey = ev.charCode || ev.keyCode || -1; if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) { return false; } var cal = $(this).parent().parent(); if (cal.data('colorpicker').livePreview === true) { change.apply(this); } }, change = function (ev) { var cal = $(this).parent().parent(), col; if (this.parentNode.className.indexOf('_hex') > 0) { cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value)); } else if (this.parentNode.className.indexOf('_hsb') > 0) { cal.data('colorpicker').color = col = fixHSB({ h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10), s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10), b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10) }); } else { cal.data('colorpicker').color = col = RGBToHSB(fixRGB({ r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10), g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10), b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10) })); } if (ev) { fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); } setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]); }, blur = function (ev) { var cal = $(this).parent().parent(); cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus') }, focus = function () { charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65; $(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus'); $(this).parent().addClass('colorpicker_focus'); }, downIncrement = function (ev) { var field = $(this).parent().find('input').focus(); var current = { el: $(this).parent().addClass('colorpicker_slider'), max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255), y: ev.pageY, field: field, val: parseInt(field.val(), 10), preview: $(this).parent().parent().data('colorpicker').livePreview }; $(document).bind('mouseup', current, upIncrement); $(document).bind('mousemove', current, moveIncrement); }, moveIncrement = function (ev) { ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10)))); if (ev.data.preview) { change.apply(ev.data.field.get(0), [true]); } return false; }, upIncrement = function (ev) { change.apply(ev.data.field.get(0), [true]); ev.data.el.removeClass('colorpicker_slider').find('input').focus(); $(document).unbind('mouseup', upIncrement); $(document).unbind('mousemove', moveIncrement); return false; }, downHue = function (ev) { var current = { cal: $(this).parent(), y: $(this).offset().top }; current.preview = current.cal.data('colorpicker').livePreview; $(document).bind('mouseup', current, upHue); $(document).bind('mousemove', current, moveHue); }, moveHue = function (ev) { change.apply( ev.data.cal.data('colorpicker') .fields .eq(4) .val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10)) .get(0), [ev.data.preview] ); return false; }, upHue = function (ev) { fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); $(document).unbind('mouseup', upHue); $(document).unbind('mousemove', moveHue); return false; }, downSelector = function (ev) { var current = { cal: $(this).parent(), pos: $(this).offset() }; current.preview = current.cal.data('colorpicker').livePreview; $(document).bind('mouseup', current, upSelector); $(document).bind('mousemove', current, moveSelector); }, moveSelector = function (ev) { change.apply( ev.data.cal.data('colorpicker') .fields .eq(6) .val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10)) .end() .eq(5) .val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10)) .get(0), [ev.data.preview] ); return false; }, upSelector = function (ev) { fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); $(document).unbind('mouseup', upSelector); $(document).unbind('mousemove', moveSelector); return false; }, enterSubmit = function (ev) { $(this).addClass('colorpicker_focus'); }, leaveSubmit = function (ev) { $(this).removeClass('colorpicker_focus'); }, clickSubmit = function (ev) { var cal = $(this).parent(); var col = cal.data('colorpicker').color; cal.data('colorpicker').origColor = col; setCurrentColor(col, cal.get(0)); cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col)); cal.hide(); }, show = function (ev) { var cal = $('#' + $(this).data('colorpickerId')); cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]); var pos = $(this).offset(); var viewPort = getViewport(); var top = pos.top + this.offsetHeight; var left = pos.left; if (top + 176 > viewPort.t + viewPort.h) { top -= this.offsetHeight + 176; } else { top += 5; } if (left + 356 > viewPort.l + viewPort.w) { left -= 356; } cal.css({left: left + 'px', top: top + 'px'}); if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) { cal.show(); } $(document).bind('mousedown', {cal: cal}, hide); return false; }, hide = function (ev) { if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) { if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) { ev.data.cal.hide(); } $(document).unbind('mousedown', hide); } }, isChildOf = function(parentEl, el, container) { if (parentEl == el) { return true; } if (parentEl.contains) { return parentEl.contains(el); } if ( parentEl.compareDocumentPosition ) { return !!(parentEl.compareDocumentPosition(el) & 16); } var prEl = el.parentNode; while(prEl && prEl != container) { if (prEl == parentEl) return true; prEl = prEl.parentNode; } return false; }, getViewport = function () { var m = document.compatMode == 'CSS1Compat'; return { l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft), t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop), w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth), h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight) }; }, fixHSB = function (hsb) { return { h: Math.min(360, Math.max(0, hsb.h)), s: Math.min(100, Math.max(0, hsb.s)), b: Math.min(100, Math.max(0, hsb.b)) }; }, fixRGB = function (rgb) { return { r: Math.min(255, Math.max(0, rgb.r)), g: Math.min(255, Math.max(0, rgb.g)), b: Math.min(255, Math.max(0, rgb.b)) }; }, fixHex = function (hex) { var len = 6 - hex.length; if (len > 0) { var o = []; for (var i=0; i<len; i++) { o.push('0'); } o.push(hex); hex = o.join(''); } return hex; }, HexToRGB = function (hex) { var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)}; }, HexToHSB = function (hex) { return RGBToHSB(HexToRGB(hex)); }, RGBToHSB = function (rgb) { var hsb = {}; hsb.b = Math.max(Math.max(rgb.r,rgb.g),rgb.b); hsb.s = (hsb.b <= 0) ? 0 : Math.round(100*(hsb.b - Math.min(Math.min(rgb.r,rgb.g),rgb.b))/hsb.b); hsb.b = Math.round((hsb.b /255)*100); if((rgb.r==rgb.g) && (rgb.g==rgb.b)) hsb.h = 0; else if(rgb.r>=rgb.g && rgb.g>=rgb.b) hsb.h = 60*(rgb.g-rgb.b)/(rgb.r-rgb.b); else if(rgb.g>=rgb.r && rgb.r>=rgb.b) hsb.h = 60 + 60*(rgb.g-rgb.r)/(rgb.g-rgb.b); else if(rgb.g>=rgb.b && rgb.b>=rgb.r) hsb.h = 120 + 60*(rgb.b-rgb.r)/(rgb.g-rgb.r); else if(rgb.b>=rgb.g && rgb.g>=rgb.r) hsb.h = 180 + 60*(rgb.b-rgb.g)/(rgb.b-rgb.r); else if(rgb.b>=rgb.r && rgb.r>=rgb.g) hsb.h = 240 + 60*(rgb.r-rgb.g)/(rgb.b-rgb.g); else if(rgb.r>=rgb.b && rgb.b>=rgb.g) hsb.h = 300 + 60*(rgb.r-rgb.b)/(rgb.r-rgb.g); else hsb.h = 0; hsb.h = Math.round(hsb.h); return hsb; }, HSBToRGB = function (hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s*255/100); var v = Math.round(hsb.b*255/100); if(s == 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255-s)*v/255; var t3 = (t1-t2)*(h%60)/60; if(h==360) h = 0; if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3} else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3} else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3} else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3} else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3} else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3} else {rgb.r=0; rgb.g=0; rgb.b=0} } return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)}; }, RGBToHex = function (rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function (nr, val) { if (val.length == 1) { hex[nr] = '0' + val; } }); return hex.join(''); }, HSBToHex = function (hsb) { return RGBToHex(HSBToRGB(hsb)); }; return { init: function (options) { options = $.extend({}, defaults, options||{}); if (typeof options.color == 'string') { options.color = HexToHSB(options.color); } else if (options.color.r != undefined && options.color.g != undefined && options.color.b != undefined) { options.color = RGBToHSB(options.color); } else if (options.color.h != undefined && options.color.s != undefined && options.color.b != undefined) { options.color = fixHSB(options.color); } else { return this; } options.origColor = options.color; return this.each(function () { if (!$(this).data('colorpickerId')) { var id = 'collorpicker_' + parseInt(Math.random() * 1000); $(this).data('colorpickerId', id); var cal = $(tpl).attr('id', id); if (options.flat) { cal.appendTo(this).show(); } else { cal.appendTo(document.body); } options.fields = cal .find('input') .bind('keydown', keyDown) .bind('change', change) .bind('blur', blur) .bind('focus', focus); cal.find('span').bind('mousedown', downIncrement); options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector); options.selectorIndic = options.selector.find('div div'); options.hue = cal.find('div.colorpicker_hue div'); cal.find('div.colorpicker_hue').bind('mousedown', downHue); options.newColor = cal.find('div.colorpicker_new_color'); options.currentColor = cal.find('div.colorpicker_current_color'); cal.data('colorpicker', options); cal.find('div.colorpicker_submit') .bind('mouseenter', enterSubmit) .bind('mouseleave', leaveSubmit) .bind('click', clickSubmit); fillRGBFields(options.color, cal.get(0)); fillHSBFields(options.color, cal.get(0)); fillHexFields(options.color, cal.get(0)); setHue(options.color, cal.get(0)); setSelector(options.color, cal.get(0)); setCurrentColor(options.color, cal.get(0)); setNewColor(options.color, cal.get(0)); if (options.flat) { cal.css({ position: 'relative', display: 'block' }); } else { $(this).bind(options.eventName, show); } } }); }, showPicker: function() { return this.each( function () { if ($(this).data('colorpickerId')) { show.apply(this); } }); }, hidePicker: function() { return this.each( function () { if ($(this).data('colorpickerId')) { $('#' + $(this).data('colorpickerId')).hide(); } }); }, setColor: function(col) { if (typeof col == 'string') { col = HexToHSB(col); } else if (col.r != undefined && col.g != undefined && col.b != undefined) { col = RGBToHSB(col); } else if (col.h != undefined && col.s != undefined && col.b != undefined) { col = fixHSB(col); } else { return this; } return this.each(function(){ if ($(this).data('colorpickerId')) { var cal = $('#' + $(this).data('colorpickerId')); cal.data('colorpicker').color = col; cal.data('colorpicker').origColor = col; fillRGBFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); setHue(col, cal.get(0)); setSelector(col, cal.get(0)); setCurrentColor(col, cal.get(0)); setNewColor(col, cal.get(0)); } }); } }; }(); $.fn.extend({ ColorPicker: ColorPicker.init, ColorPickerHide: ColorPicker.hide, ColorPickerShow: ColorPicker.show, ColorPickerSetColor: ColorPicker.setColor }); })(jQuery)
JavaScript
/// <reference path="../../../lib/jquery-1.2.6.js" /> /* Masked Input plugin for jQuery Copyright (c) 2007-2009 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.2.2 (03/09/2009 22:39:06) */ (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]" } }; $.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.focus(); 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]); var tests = input.data("tests"); return $.map(input.data("buffer"), function(c, i) { return tests[i] ? c : null; }).join(''); } 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.each(function() { var input = $(this); var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c }); var ignore = false; //Variable for ignoring control keys var focusText = input.val(); input.data("buffer", buffer).data("tests", tests); function seekNext(pos) { while (++pos <= len && !tests[pos]); return pos; }; function shiftL(pos) { while (!tests[pos] && --pos >= 0); for (var i = pos; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; var j = seekNext(i); if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; } else break; } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, pos)); }; 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 pos = $(this).caret(); var k = e.keyCode; ignore = (k < 16 || (k > 16 && k < 32) || (k > 32 && k < 41)); //delete selection before proceeding if ((pos.begin - pos.end) != 0 && (!ignore || k == 8 || k == 46)) clearBuffer(pos.begin, pos.end); //backspace, delete, and escape get special treatment if (k == 8 || k == 46 || (iPhone && k == 127)) {//backspace/delete shiftL(pos.begin + (k == 46 ? 0 : -1)); return false; } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); return false; } }; function keypressEvent(e) { if (ignore) { ignore = false; //Fixes Mac FF bug on backspace return (e.keyCode == 8) ? false : null; } e = e || window.event; var k = e.charCode || e.keyCode || e.which; var pos = $(this).caret(); if (e.ctrlKey || e.altKey || e.metaKey) {//Ignore return true; } else if ((k >= 32 && k <= 125) || k > 186) {//typeable characters 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); $(this).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[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); }; if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData("buffer") .removeData("tests"); }) .bind("focus.mask", function() { focusText = input.val(); var pos = checkVal(); writeBuffer(); setTimeout(function() { if (pos == mask.length) input.caret(0, pos); else input.caret(pos); }, 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
/** * jQuery Masonry v2.0.110927 * A dynamic layout plugin for jQuery * The flip-side of CSS Floats * http://masonry.desandro.com * * Licensed under the MIT license. * Copyright 2011 David DeSandro */ (function( window, $, undefined ){ /* * smartresize: debounced resize event for jQuery * * latest version and complete README available on Github: * https://github.com/louisremi/jquery.smartresize.js * * Copyright 2011 @louis_remi * Licensed under the MIT license. */ var $event = $.event, resizeTimeout; $event.special.smartresize = { setup: function() { $(this).bind( "resize", $event.special.smartresize.handler ); }, teardown: function() { $(this).unbind( "resize", $event.special.smartresize.handler ); }, handler: function( event, execAsap ) { // Save the context var context = this, args = arguments; // set correct event type event.type = "smartresize"; if ( resizeTimeout ) { clearTimeout( resizeTimeout ); } resizeTimeout = setTimeout(function() { jQuery.event.handle.apply( context, args ); }, execAsap === "execAsap"? 0 : 100 ); } }; $.fn.smartresize = function( fn ) { return fn ? this.bind( "smartresize", fn ) : this.trigger( "smartresize", ["execAsap"] ); }; // ========================= Masonry =============================== // our "Widget" object constructor $.Mason = function( options, element ){ this.element = $( element ); this._create( options ); this._init(); }; // styles of container element we want to keep track of var masonryContainerStyles = [ 'position', 'height' ]; $.Mason.settings = { isResizable: true, isAnimated: false, animationOptions: { queue: false, duration: 500 }, gutterWidth: 0, isRTL: false, isFitWidth: false }; $.Mason.prototype = { _filterFindBricks: function( $elems ) { var selector = this.options.itemSelector; // if there is a selector // filter/find appropriate item elements return !selector ? $elems : $elems.filter( selector ).add( $elems.find( selector ) ); }, _getBricks: function( $elems ) { var $bricks = this._filterFindBricks( $elems ) .css({ position: 'absolute' }) .addClass('masonry-brick'); return $bricks; }, // sets up widget _create : function( options ) { this.options = $.extend( true, {}, $.Mason.settings, options ); this.styleQueue = []; // need to get bricks this.reloadItems(); // get original styles in case we re-apply them in .destroy() var elemStyle = this.element[0].style; this.originalStyle = {}; for ( var i=0, len = masonryContainerStyles.length; i < len; i++ ) { var prop = masonryContainerStyles[i]; this.originalStyle[ prop ] = elemStyle[ prop ] || ''; } this.element.css({ position : 'relative' }); this.horizontalDirection = this.options.isRTL ? 'right' : 'left'; this.offset = {}; // get top left position of where the bricks should be var $cursor = $( document.createElement('div') ); this.element.prepend( $cursor ); this.offset.y = Math.round( $cursor.position().top ); // get horizontal offset if ( !this.options.isRTL ) { this.offset.x = Math.round( $cursor.position().left ); } else { $cursor.css({ 'float': 'right', display: 'inline-block'}); this.offset.x = Math.round( this.element.outerWidth() - $cursor.position().left ); } $cursor.remove(); // add masonry class first time around var instance = this; setTimeout( function() { instance.element.addClass('masonry'); }, 0 ); // bind resize method if ( this.options.isResizable ) { $(window).bind( 'smartresize.masonry', function() { instance.resize(); }); } }, // _init fires when instance is first created // and when instance is triggered again -> $el.masonry(); _init : function( callback ) { this._getColumns('masonry'); this._reLayout( callback ); }, option: function( key, value ){ // set options AFTER initialization: // signature: $('#foo').bar({ cool:false }); if ( $.isPlainObject( key ) ){ this.options = $.extend(true, this.options, key); } }, // ====================== General Layout ====================== // used on collection of atoms (should be filtered, and sorted before ) // accepts atoms-to-be-laid-out to start with layout : function( $bricks, callback ) { // layout logic var $brick, colSpan, groupCount, groupY, groupColY, j; for (var i=0, len = $bricks.length; i < len; i++) { $brick = $( $bricks[i] ); //how many columns does this brick span colSpan = Math.ceil( $brick.outerWidth(true) / this.columnWidth ); colSpan = Math.min( colSpan, this.cols ); if ( colSpan === 1 ) { // if brick spans only one column, just like singleMode this._placeBrick( $brick, this.colYs ); } else { // brick spans more than one column // how many different places could this brick fit horizontally groupCount = this.cols + 1 - colSpan; groupY = []; // for each group potential horizontal position for ( j=0; j < groupCount; j++ ) { // make an array of colY values for that one group groupColY = this.colYs.slice( j, j+colSpan ); // and get the max value of the array groupY[j] = Math.max.apply( Math, groupColY ); } this._placeBrick( $brick, groupY ); } } // set the size of the container var containerSize = {}; containerSize.height = Math.max.apply( Math, this.colYs ) - this.offset.y; if ( this.options.isFitWidth ) { var unusedCols = 0, i = this.cols; // count unused columns while ( --i ) { if ( this.colYs[i] !== this.offset.y ) { break; } unusedCols++; } // fit container to columns that have been used; containerSize.width = (this.cols - unusedCols) * this.columnWidth - this.options.gutterWidth; } this.styleQueue.push({ $el: this.element, style: containerSize }); // are we animating the layout arrangement? // use plugin-ish syntax for css or animate var styleFn = !this.isLaidOut ? 'css' : ( this.options.isAnimated ? 'animate' : 'css' ), animOpts = this.options.animationOptions; // process styleQueue var obj; for (i=0, len = this.styleQueue.length; i < len; i++) { obj = this.styleQueue[i]; obj.$el[ styleFn ]( obj.style, animOpts ); } // clear out queue for next time this.styleQueue = []; // provide $elems as context for the callback if ( callback ) { callback.call( $bricks ); } this.isLaidOut = true; }, // calculates number of columns // i.e. this.columnWidth = 200 _getColumns : function() { var container = this.options.isFitWidth ? this.element.parent() : this.element, containerWidth = container.width(); this.columnWidth = this.options.columnWidth || // or use the size of the first item this.$bricks.outerWidth(true) || // if there's no items, use size of container containerWidth; this.columnWidth += this.options.gutterWidth; this.cols = Math.floor( ( containerWidth + this.options.gutterWidth ) / this.columnWidth ); this.cols = Math.max( this.cols, 1 ); }, _placeBrick : function( $brick, setY ) { // get the minimum Y value from the columns var minimumY = Math.min.apply( Math, setY ), shortCol = 0; // Find index of short column, the first from the left for (var i=0, len = setY.length; i < len; i++) { if ( setY[i] === minimumY ) { shortCol = i; break; } } // position the brick var position = { top : minimumY }; // position.left or position.right position[ this.horizontalDirection ] = this.columnWidth * shortCol + this.offset.x; this.styleQueue.push({ $el: $brick, style: position }); // apply setHeight to necessary columns var setHeight = minimumY + $brick.outerHeight(true), setSpan = this.cols + 1 - len; for ( i=0; i < setSpan; i++ ) { this.colYs[ shortCol + i ] = setHeight; } }, resize : function() { var prevColCount = this.cols; // get updated colCount this._getColumns('masonry'); if ( this.cols !== prevColCount ) { // if column count has changed, trigger new layout this._reLayout(); } }, _reLayout : function( callback ) { // reset columns var i = this.cols; this.colYs = []; while (i--) { this.colYs.push( this.offset.y ); } // apply layout logic to all bricks this.layout( this.$bricks, callback ); }, // ====================== Convenience methods ====================== // goes through all children again and gets bricks in proper order reloadItems : function() { this.$bricks = this._getBricks( this.element.children() ); }, reload : function( callback ) { this.reloadItems(); this._init( callback ); }, // convienence method for working with Infinite Scroll appended : function( $content, isAnimatedFromBottom, callback ) { if ( isAnimatedFromBottom ) { // set new stuff to the bottom this._filterFindBricks( $content ).css({ top: this.element.height() }); var instance = this; setTimeout( function(){ instance._appended( $content, callback ); }, 1 ); } else { this._appended( $content, callback ); } }, _appended : function( $content, callback ) { var $newBricks = this._getBricks( $content ); // add new bricks to brick pool this.$bricks = this.$bricks.add( $newBricks ); this.layout( $newBricks, callback ); }, // removes elements from Masonry widget remove : function( $content ) { this.$bricks = this.$bricks.not( $content ); $content.remove(); }, // destroys widget, returns elements and container back (close) to original style destroy : function() { this.$bricks .removeClass('masonry-brick') .each(function(){ this.style.position = ''; this.style.top = ''; this.style.left = ''; }); // re-apply saved container styles var elemStyle = this.element[0].style; for ( var i=0, len = masonryContainerStyles.length; i < len; i++ ) { var prop = masonryContainerStyles[i]; elemStyle[ prop ] = this.originalStyle[ prop ]; } this.element .unbind('.masonry') .removeClass('masonry') .removeData('masonry'); $(window).unbind('.masonry'); } }; // ======================= imagesLoaded Plugin =============================== /*! * jQuery imagesLoaded plugin v1.0.3 * http://github.com/desandro/imagesloaded * * MIT License. by Paul Irish et al. */ // $('#my-container').imagesLoaded(myFunction) // or // $('img').imagesLoaded(myFunction) // execute a callback when all images have loaded. // needed because .load() doesn't work on cached images // callback function gets image collection as argument // `this` is the container $.fn.imagesLoaded = function( callback ) { var $this = this, $images = $this.find('img').add( $this.filter('img') ), len = $images.length, blank = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=='; function triggerCallback() { callback.call( $this, $images ); } function imgLoaded() { if ( --len <= 0 && this.src !== blank ){ setTimeout( triggerCallback ); $images.unbind( 'load error', imgLoaded ); } } if ( !len ) { triggerCallback(); } $images.bind( 'load error', imgLoaded ).each( function() { // cached images don't fire load sometimes, so we reset src. if (this.complete || this.complete === undefined){ var src = this.src; // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f // data uri bypasses webkit log warning (thx doug jones) this.src = blank; this.src = src; } }); return $this; }; // helper function for logging errors // $.error breaks jQuery chaining var logError = function( message ) { if ( this.console ) { console.error( message ); } }; // ======================= Plugin bridge =============================== // leverages data method to either create or return $.Mason constructor // A bit from jQuery UI // https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js // A bit from jcarousel // https://github.com/jsor/jcarousel/blob/master/lib/jquery.jcarousel.js $.fn.masonry = function( options ) { if ( typeof options === 'string' ) { // call method var args = Array.prototype.slice.call( arguments, 1 ); this.each(function(){ var instance = $.data( this, 'masonry' ); if ( !instance ) { logError( "cannot call methods on masonry prior to initialization; " + "attempted to call method '" + options + "'" ); return; } if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) { logError( "no such method '" + options + "' for masonry instance" ); return; } // apply method instance[ options ].apply( instance, args ); }); } else { this.each(function() { var instance = $.data( this, 'masonry' ); if ( instance ) { // apply options & init instance.option( options || {} ); instance._init(); } else { // initialize new instance $.data( this, 'masonry', new $.Mason( options, this ) ); } }); } return this; }; })( window, jQuery );
JavaScript
var elixir = require('laravel-elixir'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Less | file for our application, as well as publishing vendor resources. | */ elixir(function(mix) { mix.less('app.less'); });
JavaScript
// Improvements/bug-fixes since book publication. // // Use of the 'backgroundColor' property has been replaced with // 'background' because it works exactly the same way when used // with a color, and is therefore shorter and faster. // // In Initialize() the mouse is also captured by the onscroll // event (and by the onmousewheel event for IE), so that using // a mouse scroll wheel is also captured. // // The O() function now handles certain object cases better. // // In the function CleanupString() the spacestosingle option // has been improved to work with all whitespace. // // For Opera & Chrome: The FieldPrompt() function forces the width // of the input to the current width to prevent these browsers // changing the width as they switch between normal and italic // text. // // The Ajax functions had a spurious ID argument left in from // earlier versions, which is now removed. // // Amended TextType() to use Html not .innerText for IE // // Added OnDOMReady() function - much faster than window.onload function O(id, property, value) { if (id instanceof Array) { var tmp = [] for (var j = 0 ; j < id.length ; ++j) tmp.push(O(id[j], property, value)) return tmp } if (typeof property != UNDEF && typeof value != UNDEF) { if (typeof value == 'string') value = "'" + value + "'" if (typeof id == 'object') return eval(id.property = value) else return eval("O('" + id + "')." + property + " = " + value) } if (typeof id == 'object') return id else { try { return document.getElementById(id) } catch(e) { alert('PJ - Unknown ID: ' + id) } } } function S(id, property, value) { if (id instanceof Array) { var tmp = [] for (var j = 0 ; j < id.length ; ++j) tmp.push(S(id[j], property, value)) return tmp } if (typeof property != UNDEF && typeof value != UNDEF) { try { return O(id).style[property] = value } catch(e) { alert('PJ - Unknown ID: ' + id) } } else if (typeof id == 'object') return id.style else { try { return O(id).style } catch(e) { alert('PJ - Unknown ID: ' + id) } } } function Initialize() { MOUSE_DOWN = false MOUSE_IN = true MOUSE_X = 0 MOUSE_Y = 0 SCROLL_X = 0 SCROLL_Y = 0 KEY_PRESS = '' ZINDEX = 1000 CHAIN_CALLS = [] INTERVAL = 30 UNDEF = 'undefined' HID = 'hidden' VIS = 'visible' ABS = 'absolute' FIX = 'fixed' REL = 'relative' STA = 'static' INH = 'inherit' TP = 'top' BM = 'bottom' LT = 'left' RT = 'right' if (document.all) BROWSER = 'IE' else if (window.opera) BROWSER = 'Opera' else if (NavCheck('Chrome')) BROWSER = 'Chrome' else if (NavCheck('iPod')) BROWSER = 'iPod' else if (NavCheck('iPhone')) BROWSER = 'iPhone' else if (NavCheck('iPad')) BROWSER = 'iPad' else if (NavCheck('Android')) BROWSER = 'Android' else if (NavCheck('Safari')) BROWSER = 'Safari' else if (NavCheck('Gecko')) BROWSER = 'Firefox' else BROWSER = 'UNKNOWN' document.onmousemove = CaptureMouse document.onscroll = CaptureMouse document.onmousewheel = CaptureMouse document.onkeydown = CaptureKeyboard document.onkeypress = CaptureKeyboard document.onmouseout = function() { MOUSE_IN = false } document.onmouseover = function() { MOUSE_IN = true } document.onmouseup = function() { MOUSE_DOWN = false } document.onmousedown = function() { MOUSE_DOWN = true } function NavCheck(check) { return navigator.userAgent.indexOf(check) != -1 } } function CaptureMouse(e) { if (BROWSER == 'IE') { SCROLL_X = document.documentElement.scrollLeft SCROLL_Y = document.documentElement.scrollTop MOUSE_X = window.event.clientX + SCROLL_X MOUSE_Y = window.event.clientY + SCROLL_Y } else { SCROLL_X = window.pageXOffset SCROLL_Y = window.pageYOffset MOUSE_X = e.pageX MOUSE_Y = e.pageY } return true } function CaptureKeyboard(e) { if (BROWSER == 'IE') { KEY_PRESS = FromKeyCode(window.event.keyCode) if (KEY_PRESS > 0) KEY_PRESS = String.fromCharCode(KEY_PRESS) } else { if (e.charCode) KEY_PRESS = String.fromCharCode(e.charCode) else if (e.keyCode) KEY_PRESS = FromKeyCode(e.keyCode) } return true } function FromKeyCode(c) { switch (c) { case 8: return 'Backspace' case 9: return 'Tab' case 12: return 'Center' case 13: return 'Enter' case 16: return 'Shift' case 17: return 'Control' case 18: return 'Alt' case 19: return 'Pause' case 20: return 'Capslock' case 27: return 'Esc' case 33: return 'PgUp' case 34: return 'PgDn' case 35: return 'End' case 36: return 'Home' case 37: return 'left' case 38: return 'Up' case 39: return 'Right' case 40: return 'Down' case 45: return 'Ins' case 46: return 'Del' case 91: return 'Windows' case 93: return 'Menu' case 144: return 'Numlock' } return c } function GetLastKey() { var k = KEY_PRESS KEY_PRESS = '' return k } function PreventAction(id, type, onoff) { if (type == 'drag' || type == 'both') { if (onoff == true) { if (typeof O(id).ondragstart != UNDEF) O(id).ondragstart = function() { return false } else O(id).onmousedown = function() { return false } } else { if (typeof O(id).ondragstart != UNDEF) O(id).ondragstart = '' else O(id).onmousedown = '' } } if (type == 'select' || type == 'both') { if (onoff == true) { if (typeof O(id).onselectstart != UNDEF) O(id).onselectstart = function() { return false } else if (typeof S(id).MozUserSelect != UNDEF) S(id).MozUserSelect = 'none' else O(id).onmousedown = function() { return false } } else { if (typeof O(id).onselectstart != UNDEF) O(id).onselectstart = '' else if (typeof S(id).MozUserSelect != UNDEF) S(id).MozUserSelect = 'text' else O(id).onmousedown = '' } } } function NoPx(value) { return value.replace(/px/, '') * 1 } function Px(value) { return value + 'px' } function X(id) { var obj = O(id) var offset = obj.offsetLeft if (obj.offsetParent) while(obj = obj.offsetParent) offset += obj.offsetLeft return offset } function Y(id) { var obj = O(id) var offset = obj.offsetTop if (obj.offsetParent) while(obj = obj.offsetParent) offset += obj.offsetTop return offset } function W(id) { var width = O(id).offsetWidth + NoPx(S(id).marginLeft) + NoPx(S(id).marginRight) var bord = NoPx(S(id).borderLeftWidth) + NoPx(S(id).borderRightWidth) if (bord > 0) width -= bord else if (O(id).border) width -= O(id).border * 2 return width } function H(id) { var height = O(id).offsetHeight + NoPx(S(id).marginTop) + NoPx(S(id).marginBottom) var bord = NoPx(S(id).borderTopWidth) + NoPx(S(id).borderBottomWidth) if (bord > 0) height -= bord else if(O(id).border) height -= O(id).border * 2 return height } function Html(id, value) { if (typeof value != UNDEF) O(id).innerHTML = value return O(id).innerHTML } function SaveState(id) { O(id).Save_left = S(id).left O(id).Save_top = S(id).top O(id).Save_visibility = S(id).visibility O(id).Save_color = S(id).color O(id).Save_background = S(id).background O(id).Save_display = S(id).display O(id).Save_opacity = S(id).opacity O(id).Save_MozOpacity = S(id).MozOpacity O(id).Save_KhtmlOpacity = S(id).KhtmlOpacity O(id).Save_filter = S(id).filter O(id).Save_zIndex = S(id).zIndex } function RestoreState(id) { S(id).left = O(id).Save_left S(id).top = O(id).Save_top S(id).visibility = O(id).Save_visibility S(id).color = O(id).Save_color S(id).background = O(id).Save_background S(id).display = O(id).Save_display S(id).opacity = O(id).Save_opacity S(id).MozOpacity = O(id).Save_MozOpacity S(id).KhtmlOpacity = O(id).Save_KhtmlOpacity S(id).filter = O(id).Save_filter S(id).zIndex = O(id).Save_zIndex } function InsVars() { var tmp = arguments[0] for (var j = 1 ; j < arguments.length ; ++j) tmp = tmp.replace(new RegExp('#' + j, 'g'), arguments[j]) return tmp } function StrRepeat(str, num) { var tmp = '' for (var j = 0 ; j < num ; ++j) tmp += str return tmp } function HexDec(n) { return(parseInt(n, 16)) } function DecHex(n) { return (n < 16 ? '0' : '') + n.toString(16) } function ResizeWidth(id, width) { S(id, 'overflow', HID) S(id, 'width', Px(width)) } function ResizeHeight(id, height) { S(id, 'overflow', HID) S(id, 'height', Px(height)) } function Resize(id, width, height) { ResizeWidth(id, width) ResizeHeight(id, height) } function Position(id, type) { S(id, 'position', type) } function GoTo(id, x, y) { S(id, 'left', Px(x)) S(id, 'top', Px(y)) } function Locate(id, type, x, y) { Position(id, type) GoTo(id, x, y) } function GetWindowWidth() { var de = document.documentElement if (BROWSER != 'IE') { var barwidth = de.scrollHeight > de.clientHeight ? 17 : 0 return window.innerWidth - barwidth } return de.clientWidth || document.body.clientWidth } function GetWindowHeight() { var de = document.documentElement if (BROWSER != 'IE') { var barwidth = de.scrollWidth > de.clientWidth ? 17 : 0 return window.innerHeight - barwidth } return de.clientHeight || document.body.clientHeight } function GoToEdge(id, where, percent) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) GoToEdge(id[j], where, percent) return } var width = GetWindowWidth() - W(id) var height = GetWindowHeight() - H(id) var amount = percent / 100 switch(where) { case TP: var x = width * amount var y = 0 break case BM: var x = width * amount var y = height break case LT: var x = 0 var y = height * amount break case RT: var x = width var y = height * amount } GoTo(id, x, y) } function CenterX(id) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) CenterX(id[j]) return } S(id).left = Px(Math.round((GetWindowWidth() - W(id))) / 2 + SCROLL_X) } function CenterY(id) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) CenterY(id[j]) return } S(id).top = Px(Math.round((GetWindowHeight() - H(id))) / 2 + SCROLL_Y) } function Center(id) { CenterX(id) CenterY(id) } function Invisible(id) { S(id, 'visibility', HID) } function Visible(id) { S(id, 'visibility', VIS) } function VisibilityToggle(id) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) VisibilityToggle(id[j]) return } S(id).visibility = (S(id).visibility == HID) ? VIS : HID } function Opacity(id, percent) { S(id, 'opacity', percent / 100) S(id, 'MozOpacity', percent / 100) S(id, 'KhtmlOpacity', percent / 100) S(id, 'filter', InsVars("alpha(opacity = '#1')", percent)) } function Fade(id, start, end, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Fade(id[j], start, end, msecs, interruptible, CB) return } var stepval = Math.abs(start - end) / (msecs / INTERVAL) if (O(id).FA_Flag) { if (!O(id).FA_Int) return clearInterval(O(id).FA_IID) O(id).FA_Start = O(id).FA_Level } else { O(id).FA_Start = start O(id).FA_Level = start } O(id).FA_Flag = true O(id).FA_End = end O(id).FA_Int = interruptible O(id).FA_Step = end > O(id).FA_Start ? stepval : -stepval O(id).Fadeout = end < O(id).FA_Start ? true : false O(id).FA_IID = setInterval(DoFade, INTERVAL) function DoFade() { O(id).FA_Level += O(id).FA_Step if (O(id).FA_Level >= Math.max(O(id).FA_Start, O(id).FA_End) || O(id).FA_Level <= Math.min(O(id).FA_Start, O(id).FA_End)) { O(id).FA_Level = O(id).FA_End O(id).FA_Flag = false clearInterval(O(id).FA_IID) if (typeof CB != UNDEF) eval(CB) } Opacity(id, O(id).FA_Level) } } function FadeOut(id, msecs, interruptible, CB) { Fade(id, 100, 0, msecs, interruptible, CB) } function FadeIn(id, msecs, interruptible, CB) { Fade(id, 0, 100, msecs, interruptible, CB) } function FadeToggle(id, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) FadeToggle(id[j], msecs, interruptible, CB) return } if (O(id).Fadeout) FadeIn( id, msecs, interruptible, CB) else FadeOut(id, msecs, interruptible, CB) } function FadeBetween(id1, id2, msecs, interruptible, CB) { FadeOut(id1, msecs, interruptible, CB) FadeIn( id2, msecs, interruptible, CB) } function Hide(id, CB) { S(id, 'display', 'none') O(id, 'HI_Flag', true) if (typeof CB != UNDEF) eval(CB) } function Show(id, CB) { S(id, 'display', 'block') O(id, 'HI_Flag', false) } function HideToggle(id, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) HideToggle(id[j], CB) return } if (S(id).display != 'none') Hide(id, CB) else Show(id, CB) } function Slide(id, frx, fry, tox, toy, msecs, interruptible, CB) { if (O(id).SL_Flag) { if (!O(id).SL_Int) return else clearInterval(O(id).SL_IID) var len1 = Distance(tox - frx, toy - fry) frx = X(id) fry = Y(id) var len2 = Distance(tox - frx, toy - fry) msecs *= len2 / len1 } var stepx = (tox - frx) / (msecs / INTERVAL) var stepy = (toy - fry) / (msecs / INTERVAL) var count = 0 O(id).SL_Int = interruptible O(id).SL_Flag = true O(id).SL_IID = setInterval(DoSlide, INTERVAL) function Distance(x, y) { x = Math.max(1, x) y = Math.max(1, y) return Math.round(Math.sqrt(Math.abs(x * x) + Math.abs(y * y))) } function DoSlide() { GoTo(id, frx + stepx * count, fry + stepy * count) if (count++ >= (msecs / INTERVAL)) { O(id).SL_Flag = false GoTo(id, tox, toy) clearInterval(O(id).SL_IID) if (typeof CB != UNDEF) eval(CB) } } } function SlideBetween(id1, id2, msecs, interruptible, CB) { if (O(id1).SL_Flag || O(id2).SL_Flag) { if (!O(id1).SL_Int || !O(id2).SL_Int) return var t1 = O(id1).SB_X var t2 = O(id1).SB_Y O(id1).SB_X = O(id2).SB_X O(id1).SB_Y = O(id2).SB_Y O(id2).SB_X = t1 O(id2).SB_Y = t2 } else { O(id1).SB_X = X(id1) O(id1).SB_Y = Y(id1) O(id2).SB_X = X(id2) O(id2).SB_Y = Y(id2) } var x1 = O(id1).SB_X var y1 = O(id1).SB_Y var x2 = O(id2).SB_X var y2 = O(id2).SB_Y Slide(id1, x1, y1, x2, y2, msecs, interruptible, CB) Slide(id2, x2, y2, x1, y1, msecs, interruptible, CB) } function Deflate(id, w, h, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Deflate(id[j], w, h, msecs, interruptible, CB) return } if (!w) ResizeWidth( id, W(id)) if (!h) ResizeHeight(id, H(id)) if (O(id).DF_Flag) { if (!O(id).DF_Int) return else clearInterval(O(id).DF_IID) } else { if (w) O(id).DF_OldW = W(id) if (h) O(id).DF_OldH = H(id) O(id).DF_Count = msecs / INTERVAL } var stepw = O(id).DF_OldW / (msecs / INTERVAL) var steph = O(id).DF_OldH / (msecs / INTERVAL) S(id).overflow = HID O(id).Deflated = true O(id).DF_Flag = true O(id).DF_Int = interruptible O(id).DF_IID = setInterval(DoDeflate, INTERVAL) function DoDeflate() { if (w) ResizeWidth( id, stepw * O(id).DF_Count) if (h) ResizeHeight(id, steph * O(id).DF_Count) if (O(id).DF_Count-- < 1) { O(id).DF_Flag = false if (w) ResizeWidth( id, 0) if (h) ResizeHeight(id, 0) clearInterval(O(id).DF_IID) if (typeof CB != UNDEF) eval(CB) } } } function Reflate(id, w, h, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Reflate(id[j], w, h, msecs, interruptible, CB) return } if (!O(id).Deflated) return else if (O(id).DF_Flag) { if (!O(id).DF_Int) return else clearInterval(O(id).DF_IID) } else O(id).DF_Count = 0 var stepw = O(id).DF_OldW / (msecs / INTERVAL) var steph = O(id).DF_OldH / (msecs / INTERVAL) O(id).DF_Flag = true O(id).Deflated = false O(id).DF_Int = interruptible O(id).DF_IID = setInterval(DoReflate, INTERVAL) function DoReflate() { if (w) ResizeWidth( id, stepw * O(id).DF_Count) if (h) ResizeHeight(id, steph * O(id).DF_Count) if (O(id).DF_Count++ >= msecs / INTERVAL) { O(id).DF_Flag = false if (w) ResizeWidth( id, O(id).DF_OldW) if (h) ResizeHeight(id, O(id).DF_OldH) clearInterval(O(id).DF_IID) if (typeof CB != UNDEF) eval(CB) } } } function DeflateToggle(id, w, h, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) DeflateToggle(id[j], w, h, msecs, interruptible, CB) return } if (O(id).Deflated) Reflate(id, w, h, msecs, interruptible, CB) else Deflate(id, w, h, msecs, interruptible, CB) } function DeflateBetween(id1, id2, w, h, msecs, interruptible, CB) { Deflate(id1, w, h, msecs, interruptible, CB) Reflate(id2, w, h, msecs, interruptible, CB) } function Zoom(id, w, h, fromw, fromh, tow, toh, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Zoom(id[j], w, h, fromw, fromh, tow, toh, msecs, pad, interruptible, CB) return } if (typeof O(id).ZO_X == UNDEF) { O(id).ZO_X = X(id) O(id).ZO_Y = Y(id) } if (!O(id).ZO_Flag) { O(id).ZO_W = Math.max(fromw, tow) O(id).ZO_H = Math.max(fromh, toh) O(id).ZO_Count = 0 } else { if (!O(id).ZO_Int) return else clearInterval(O(id).ZO_IID) O(id).ZO_Count = (msecs / INTERVAL) - O(id).ZO_Count } var maxw = Math.max(fromw, tow) var maxh = Math.max(fromh, toh) var stepw = (tow - fromw) / (msecs / INTERVAL) var steph = (toh - fromh) / (msecs / INTERVAL) S(id).overflow = HID O(id).ZO_Flag = true O(id).ZO_Int = interruptible O(id).ZO_IID = setInterval(DoZoom, INTERVAL) function DoZoom() { if (w) O(id).ZO_W = Math.round(fromw + stepw * O(id).ZO_Count) if (h) O(id).ZO_H = Math.round(fromh + steph * O(id).ZO_Count) Resize(id, O(id).ZO_W, O(id).ZO_H) var midx = O(id).ZO_X + Math.round((maxw - O(id).ZO_W) / 2) var midy = O(id).ZO_Y + Math.round((maxh - O(id).ZO_H) / 2) if (pad > 0) ZoomPad(Math.max(fromw, tow), Math.max(fromh, toh), O(id).ZO_W, O(id).ZO_H) else if (pad != -1) GoTo(id, midx, midy) if (O(id).DB_Parent) GoToEdge(O(id).DB_Parent, O(id).DB_Where, 50) if (++O(id).ZO_Count >= (msecs / INTERVAL)) { var endx = O(id).ZO_X + Math.round((maxw - tow) / 2) var endy = O(id).ZO_Y + Math.round((maxh - toh) / 2) O(id).ZO_Flag = false Resize(id, tow, toh) clearInterval(O(id).ZO_IID) if (pad > 0) ZoomPad(fromw, fromh, tow, toh) else if (pad != -1) GoTo(id, endx, endy) if (O(id).DB_Parent) GoToEdge(O(id).DB_Parent, O(id).DB_Where, 50) if (typeof CB != UNDEF) eval(CB) } function ZoomPad(frw, frh, padw, padh) { var left = Math.max(0, frw - Math.round(padw)) / 2 var right = left var top = Math.max(0, frh - Math.round(padh)) / 2 var bottom = top if (left != Math.floor(left)) { left = Math.floor(left) right = left + 1 } if (top != Math.floor(top)) { top = Math.floor(top) bottom = top + 1 } S(id).paddingLeft = Px(left) S(id).paddingRight = Px(right) S(id).paddingTop = Px(top) S(id).paddingBottom = Px(bottom) } } } function ZoomDown(id, w, h, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ZoomDown(id[j], w, h, msecs, pad, interruptible, CB) return } if (O(id).ZO_Flag && !O(id).ZO_Int) return else if (!O(id).ZO_OldW) { O(id).ZO_OldW = W(id) O(id).ZO_OldH = H(id) O(id).ZO_X = X(id) O(id).ZO_Y = Y(id) } O(id).Zoomdown = true GoTo(id, O(id).ZO_X, O(id).ZO_Y) Zoom(id, w, h, O(id).ZO_OldW, O(id).ZO_OldH, 0, 0, msecs, pad, interruptible, CB) } function ZoomRestore(id, w, h, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ZoomRestore(id[j], w, h, msecs, pad, interruptible, CB) return } if ((O(id).ZO_Flag && !O(id).ZO_Int) || !O(id).Zoomdown) return O(id).Zoomdown = false Zoom(id, w, h, 0, 0, O(id).ZO_OldW, O(id).ZO_OldH, msecs, pad, interruptible, CB) } function ZoomToggle(id, w, h, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ZoomToggle(id[j], w, h, msecs, pad, interruptible, CB) return } if (O(id).ZO_Flag && !O(id).ZO_Int) return if (!O(id).Zoomdown) ZoomDown(id, w, h, msecs, pad, interruptible, CB) else ZoomRestore(id, w, h, msecs, pad, interruptible, CB) } function Chain(calls) { for (var j = calls.length ; j >= 0 ; --j) if (calls[j]) CHAIN_CALLS.push(calls[j]) NextInChain() } function NextInChain() { if (CHAIN_CALLS.length) CallBack(CHAIN_CALLS.pop()) } function CallBack(expr) { var insert = expr.lastIndexOf(')') var left = expr.substr(0, insert) var right = expr.substr(insert) var middle = "'NextInChain()'" if (expr.substr(insert - 1, 1) != '(') middle = ', ' + middle eval(left + middle + right) } function ChainThis(expr) { eval(expr) NextInChain() } function Repeat(number, calls) { var temp = calls for (var j = 1 ; j < number ; ++j) calls = calls.concat(temp) Chain(calls) } function While(expr, calls) { if (eval(expr)) { var temp = '' for (var j = 0 ; j < calls.length ; ++j) temp += '"' + calls[j].replace(/"/g, '\\\"') + '",' temp = temp.substr(0, temp.length -1) calls.push(InsVars("While('#1', Array(#2))", expr, temp)) Chain(calls) } } function Pause(wait) { setTimeout("NextInChain()", wait) } function WaitKey() { GetLastKey() setTimeout(DoWaitKey, INTERVAL) function DoWaitKey() { if (KEY_PRESS != '') NextInChain() else setTimeout(DoWaitKey, INTERVAL) } } function Flip(id1, id2, w, h, msecs, pad) { if (O(id1).ZO_Flag || O(id2).ZO_Flag) return var swap = "ChainThis('VisibilityToggle(\"#1\")')" var fast = "ZoomToggle('#1', #2, #3, 1, #4, 0)" var slow = "ZoomToggle('#1', #2, #3, #4, #5, 0)" Chain(Array( InsVars(slow, id1, w, h, msecs / 2, pad), InsVars(fast, id2, w, h, pad), InsVars(swap, id2 ), InsVars(slow, id2, w, h, msecs / 2, pad), InsVars(swap, id1 ), InsVars(fast, id1, w, h, pad) )) } function HoverSlide(id, where, offset, showing, msecs) { var w = GetWindowWidth() - W(id) var h = GetWindowHeight() - H(id) var o = offset[0] != '%' ? 0 : offset.substr(1) / 100 if (where == LT || where == RT) { var t = W(id) - showing var u = Math.min(t, msecs / INTERVAL) var x = where == LT ? -t : w + t var y = o ? h * o : offset var s = t / u } else { var t = H(id) - showing var u = Math.min(t, msecs / INTERVAL) var x = o ? w * o : offset var y = where == TP ? -t : h + t var s = t / u } GoTo(id, x, y) O(id).HS_X = x O(id).HS_Y = y O(id).onmouseover = SlideIn O(id).onmouseout = SlideOut function SlideIn() { if (O(id).HS_IID) clearInterval(O(id).HS_IID) O(id).HS_IID = setInterval(DoSlideIn, INTERVAL) function DoSlideIn() { var ox = O(id).HS_X var oy = O(id).HS_Y if (where == TP && oy < 0) oy = Math.min(0, oy + s) else if (where == BM && oy > h) oy = Math.max(h, oy - s) else if (where == LT && ox < 0) ox = Math.min(0, ox + s) else if (where == RT && ox > w) ox = Math.max(w, ox - s) else clearInterval(O(id).HS_IID) GoTo(id, ox, oy) O(id).HS_X = ox O(id).HS_Y = oy } } function SlideOut() { if (O(id).HS_IID) clearInterval(O(id).HS_IID) O(id).HS_IID = setInterval(DoSlideOut, INTERVAL) function DoSlideOut() { var ox = O(id).HS_X var oy = O(id).HS_Y if (where == TP && oy > y) oy = Math.max(y, oy - s) else if (where == BM && oy < y) oy = Math.min(y, oy + s) else if (where == LT && ox > x) ox = Math.max(x, ox - s) else if (where == RT && ox < x) ox = Math.max(x, ox + s) else clearInterval(O(id).HS_IID) GoTo(id, ox, oy) O(id).HS_X = ox O(id).HS_Y = oy } } } function HoverSlideMenu(ids, where, offset, showing, gap, msecs) { var len = ids.length var total = gap * (len - 1) var start = (offset[0] != '%') ? 0 : offset.substr(1) / 100 var a = [] var jump = 0 if (where == TP || where == BM) { for (var j = 0 ; j < len ; ++j) { a[j] = W(ids[j]) total += a[j] } start = start ? (GetWindowWidth() - total) * start : offset * 1 } else { for (var j = 0 ; j < len ; ++j) { a[j] = H(ids[j]) total += a[j] } start = start ? (GetWindowHeight() - total) * start : offset * 1 } for (var j = 0 ; j < len ; ++j) { HoverSlide(ids[j], where, start + jump, showing, msecs) jump += a[j] + gap } } function PopDown(id, type, w, h, msecs, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PopDown(id[j], type, w, h, msecs, interruptible) return } if (type == 'fade') { FadeOut(id, msecs, interruptible, InsVars("Hide('#1')", id)) } else if (type == 'inflate') { Deflate(id, w, h, msecs, interruptible, InsVars("Hide('#1')", id)) } else if (type == 'zoom') { ZoomDown(id, w, h, msecs, 1, interruptible, InsVars("Hide('#1')", id)) } else if (type == 'instant') Hide(id) O(id).PO_IsUp = false } function PopUp(id, type, w, h, msecs, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PopUp(id[j], type, w, h, msecs, interruptible) return } Show(id) if (type == 'fade') FadeIn(id, msecs, interruptible) else if (type == 'inflate') Reflate(id, w, h, msecs, interruptible) else if (type == 'zoom') ZoomRestore(id, w, h, msecs, 1, interruptible) O(id).PO_IsUp = true } function PopToggle(id, type, w, h, msecs, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PopToggle(id[j], type, w, h, msecs, interruptible) return } if (typeof O(id).PO_IsUp == UNDEF) O(id).PO_IsUp = true if (O(id).PO_IsUp) PopDown(id, type, w, h, msecs, interruptible) else PopUp(id, type, w, h, msecs, interruptible) } function FoldingMenu(headings, contents, action, type, multi, w, h, msecs1, msecs2, interruptible) { PopDown(contents.slice(1), type, w, h, 1, 0) O(contents[0]).PO_IsUp = true for (var j = 0 ; j < headings.length ; ++j) { O(headings[j]).FO_C = contents[j] S(headings[j]).cursor = 'pointer' if (action == 'hover') O(headings[j]).onmouseover = DoFoldingMenu else O(headings[j]).onclick = DoFoldingMenu } function DoFoldingMenu() { if (multi) PopToggle(this.FO_C, type, w, h, msecs1, interruptible) else { for (j = 0 ; j < headings.length ; ++j) if (O(O(headings[j]).FO_C).PO_IsUp && O(headings[j]) != this) PopDown(O(headings[j]).FO_C, type, w, h, msecs1, interruptible) if (!O(this.FO_C).PO_IsUp) PopUp(this.FO_C, type, w, h, msecs2, interruptible) } } } function ContextMenu(id, contents, type, w, h, msecs) { Locate(contents, ABS, -10000, -10000) PopDown(contents, type, 1, 1, 1, 0) O(id).oncontextmenu = ContextUp function ContextUp() { if (O(contents).PO_IsUp || O(contents).FA_Flag || O(contents).DF_Flag) return false var x = MOUSE_X var y = MOUSE_Y GoTo(contents, x, y) PopUp(contents, type, w, h, msecs, 1) S(contents).zIndex = ZINDEX + 1 O(id).Context_IID = setInterval(ContextDown, INTERVAL) return false function ContextDown() { if (MOUSE_X < x || MOUSE_X > (x + W(contents)) || MOUSE_Y < y || MOUSE_Y > (y + H(contents))) { PopDown(contents, type, w, h, msecs, 1) clearInterval(O(id).Context_IID) O(contents).PO_IsUp = false } } } } function DockBar(id, items, where, increase, msecs) { Position(id, FIX) for (var j = 0 ; j < items.length ; ++j) { if (where == TP || where == BM) S(items[j]).verticalAlign = where else O(items[j]).align = where var oldw = W(items[j]) var oldh = H(items[j]) S(items[j]).cursor = 'pointer' O(items[j]).DB_Parent = id O(items[j]).DB_Where = where O(items[j]).DB_OldW = oldw O(items[j]).DB_OldH = oldh O(items[j]).DB_NewW = Math.round(oldw + oldw * increase / 100) O(items[j]).DB_NewH = Math.round(oldh + oldh * increase / 100) O(items[j]).onmouseover = DockUp O(items[j]).onmouseout = DockDown } GoToEdge(id, where, 50) function DockUp() { Zoom(this, 1, 1, O(this).DB_OldW, O(this).DB_OldH, O(this).DB_NewW, O(this).DB_NewH, msecs, 0, 1) } function DockDown() { Zoom(this, 1, 1, O(this).DB_NewW, O(this).DB_NewH, O(this).DB_OldW, O(this).DB_OldH, msecs, 0, 1) } } function RollOver(ro1, ro2) { if (ro1 instanceof Array) { for (var j = 0 ; j < id.length ; ++j) RollOver(ro1[j], ro2[j]) return } var a = Array(ro1, ro2) var w = W(ro1) + 1 var h = H(ro1) + 1 var x = X(ro1) var y = Y(ro1) Hide(ro2) Locate(a, REL, 0, 0) O(ro1).onmouseover = DoRoll function DoRoll() { HideToggle(a) var iid = setInterval(RollCheck, INTERVAL) function RollCheck() { if (MOUSE_X < x || MOUSE_X > x + w || MOUSE_Y < y || MOUSE_Y > y + h) { HideToggle(a) clearInterval(iid) } } } } function Breadcrumbs(spacer) { var parts = self.location.href.split('?')[0].split('/') var crumbs = Array(parts[0] + '//') for (var j = 2 ; j < parts.length ; ++j) { if (parts[j] == '') crumbs[0] += '/' else crumbs.push(parts[j]) } var title = document.title ? document.title : parts[j - 1] var url = crumbs[0] + crumbs[1] var display = InsVars("<a href='#1'>Home</a>", url) if (typeof spacer == UNDEF) gap = ' ' for (j = 2 ; j < crumbs.length - 1 ; ++j) { url += '/' + crumbs[j] display += spacer + InsVars("<a href='#1'>#2</a>", url, crumbs[j]) } return display + spacer + title } function BrowserWindow(id, headerid, closeid, x, y, bounds, type, w, h, msecs, interruptible) { GoTo(id, x, y) PopUp(id, type, w, h, msecs, interruptible) var browserw = GetWindowWidth() var browserh = GetWindowHeight() var borderw = NoPx(S(id).borderLeftWidth) + NoPx(S(id).borderRightWidth) var borderh = NoPx(S(id).borderTopWidth) + NoPx(S(id).borderBottomWidth) var popupw = W(id) var popuph = H(id) S(closeid).cursor = 'pointer' O(id).onclick = BWToFront O(closeid).onclick = BWCloseWindow O(headerid).onmousedown = BWMove PreventAction(headerid, 'select', true) PreventAction(closeid, 'select', true) function BWToFront() { S(id).zIndex = ++ZINDEX } function BWCloseWindow() { PopDown(id, type, w, h, msecs, interruptible) } function BWMove() { BWToFront() S(headerid).cursor = 'move' var xoffset = MOUSE_X - X(id) var yoffset = MOUSE_Y - Y(id) var iid = setInterval(DoBWMove, 10) function DoBWMove() { var x = MOUSE_X - xoffset var y = MOUSE_Y - yoffset if (bounds) { var r = browserw - popupw - borderw + SCROLL_X var b = browserh - popuph - borderh + SCROLL_Y x = Math.max(0, Math.min(x, r)) y = Math.max(0, Math.min(y, b)) } if (MOUSE_X < 0 || MOUSE_X > (browserw + SCROLL_X) || MOUSE_Y < 0 || MOUSE_Y > (browserh + SCROLL_Y) || !MOUSE_DOWN || !MOUSE_IN) { clearInterval(iid) S(headerid).cursor = 'default' } GoTo(id, x, y) } } } function TextScroll(id, dir, number, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextScroll(id[j], dir, number, msecs) return } if (O(id).TS_Flag) return else O(id).TS_Flag = true var copy = Html(id) var len = copy.length var freq = Math.round(msecs / len) var ctr1 = 0 var ctr2 = 0 var iid = setInterval(DoTextScroll, freq) function DoTextScroll() { if (dir == LT) copy = copy.substr(1) + copy[0] else copy = copy[len - 1] + copy.substr(0, len - 1) if (O(id).innerText) O(id).innerText = copy else O(id).textContent = copy if (++ctr1 == len) { ctr1 = 0 if (++ctr2 == number) { O(id).TS_Flag = false clearInterval(iid) } } } } function TextType(id, number, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextType(id[j], number, msecs) return } if (O(id).TT_Flag) return else O(id).TT_Flag = true var html = Html(id) Html(id, '') Show(id) var len = html.length var freq = Math.round(msecs / len) var ctr1 = 0 var ctr2 = 0 var iid = setInterval(DoTextType, freq) function DoTextType() { var str = html.substr(0, ctr1) + '_' if (ctr1++ == len) { ctr1 = 0 if (++ctr2 == number) { O(id).TT_Flag = false clearInterval(iid) str = str.substr(0, len) } } if (O(id).innerText) O(id).innerText = str else Html(id, str) } } function MatrixToText(id, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) MatrixToText(id[j], msecs) return } if (O(id).MT_Flag) return else O(id).MT_Flag = true var html = Html(id) Html(id, '') Show(id) var len = html.length var freq = Math.round(msecs / INTERVAL) var matrix = '' var count = 0 var chars = 'ABCDEFGHIHJKLMOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789' for (var j = 0 ; j < len ; ++j) { if (html[j] == '\n' || html[j] == ' ') matrix += html[j] else matrix += chars[Math.floor(Math.random() * chars.length)] } if (O(id).innerText) O(id).innerText = matrix else O(id).textContent = matrix var iid = setInterval(DoMatrixToText, freq) function DoMatrixToText() { for (j = 0 ; j < len / 20 ; ++j) { var k = Math.floor(Math.random() * len) matrix = matrix.substr(0, k) + html[k] + matrix.substr(k + 1) } if (O(id).innerText) O(id).innerText = matrix else O(id).textContent = matrix if (++count == INTERVAL) { O(id).MT_Flag = false Html(id, html) clearInterval(iid) } } } function TextToMatrix(id, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextToMatrix(id[j], msecs) return } if (O(id).TM_Flag) return else O(id).TM_Flag = true var text = Html(id) Html(id, '') Show(id) var len = text.length var freq = Math.round(msecs / INTERVAL) var count = 0 var chars = 'ABCDEFGHIHJKLMOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789' var iid = setInterval(DoTextToMatrix, freq) function DoTextToMatrix() { for (var j = 0 ; j < len / 20 ; ++j) { var k = Math.floor(Math.random() * len) var l = Math.floor(Math.random() * chars.length) if (text[k] != '\n' && text[k] != '\r' && text[k] != ' ') text = text.substr(0, k) + chars[l] + text.substr(k + 1) } if (O(id).innerText) O(id).innerText = text else O(id).textContent = text if (++count == INTERVAL) { O(id).TM_Flag = false clearInterval(iid) } } } function ColorFade(id, color1, color2, what, msecs, number, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ColorFade(id[j], color1, color2, what, msecs, number) return } if (O(id)['CF_Flag' + what]) { if (!O(id)['CF_Int' + what]) return else clearInterval(O(id)['CF_IID' + what]) } else O(id)['CF_Flag' + what] = true if (color1[0] == '#') color1 = color1.substr(1) if (color2[0] == '#') color2 = color2.substr(1) var step = Math.round(msecs / INTERVAL) var index = 0 var count = 0 var direc = 1 var cols = [] var steps = [] for (var j = 0 ; j < 3 ; ++j) { var tmp = HexDec(color2.substr(j * 2, 2)) cols[j] = HexDec(color1.substr(j * 2, 2)) steps[j] = (tmp - cols[j]) / step } if (what == 'text') var prop = 'color' else var prop = 'background' O(id)['CF_Int' + what] = interruptible O(id)['CF_IID' + what] = setInterval(DoColorFade, INTERVAL) function DoColorFade() { var temp ='#' for (var j = 0 ; j < 3 ; ++j) temp += DecHex(ZeroToFF(cols[j] + index * steps[j])) S(id)[prop] = temp if ((index += direc) > step || index < 0) { direc = -direc if (++count == number) { O(id)['CF_Flag' + what] = false clearInterval(O(id)['CF_IID' + what]) } } function ZeroToFF(num) { return Math.round(Math.min(255, Math.max(0, num))) } } } function FlyIn(id, x, y, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) FlyIn(id[j], x, y, msecs) return } if (O(id).FI_Flag) return else O(id).FI_Flag = true var tox = X(id) var toy = Y(id) var fromx = tox + x var fromy = toy + y var xstep = x / (msecs / INTERVAL) var ystep = y / (msecs / INTERVAL) var count = 0 Position(id, ABS) var iid = setInterval(DoFlyIn, INTERVAL) function DoFlyIn() { GoTo(id, fromx - xstep * count, fromy - ystep * count) if (count++ >= msecs / INTERVAL) { O(id).FI_Flag = false GoTo(id, tox, toy) clearInterval(iid) } } } function TextRipple(id, number, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextRipple(id[j], number, msecs) return } if (O(id).TR_Flag) return else O(id).TR_Flag = true var html = Html(id) var len = html.length var freq = msecs / len var ctr1 = 0 var ctr2 = 0 var iid = setInterval(DoTextRipple, freq) function DoTextRipple() { var temp = html.substr(0, ctr1) for (var j = 0 ; j < 7 ; ++j) temp += InsVars("<font size='+#1'>#2</font>", 4 - Math.abs(j - 3), html.substr(ctr1 + j, 1)) Html(id, temp + html.substr(ctr1 + j)) if (++ctr1 == len) { ctr1 = 0 if (++ctr2 == number) { if (O(id).innerText) O(id).innerText = html else O(id).textContent = html O(id).TR_Flag = false clearInterval(iid) } } } } function Lightbox(id, col1, col2, opacity, msecs) { S(id).cursor = 'pointer' if (!O('LB_DIV')) { var newdiv = document.createElement('div') newdiv.setAttribute('id', 'LB_DIV') document.body.appendChild(newdiv) } S(document.body).overflow = HID Hide(Array(id, 'LB_DIV')) Locate('LB_DIV', ABS, 0, 0) Resize('LB_DIV', GetWindowWidth(), GetWindowHeight()) S('LB_DIV').zIndex = ZINDEX Opacity(id, 0) Position(id, ABS) S(id).zIndex = ++ZINDEX Show(Array(id, 'LB_DIV')) Center(id) Fade('LB_DIV', 0, opacity, msecs) FadeIn(id, msecs, 0) ColorFade('LB_DIV', col1, col2, 'back', msecs, 1) O(id).onclick = DismissLB function DismissLB() { Fade('LB_DIV', opacity, 0, msecs) ColorFade('LB_DIV', col2, col1, 'back', msecs, 1) Chain(Array( InsVars("FadeOut(Array('#1', 'LB_DIV'), #2, 0)", id, msecs), InsVars("Hide(Array('#1', 'LB_DIV'))", id), "S(document.body, 'overflow', 'auto')" )) } } function Slideshow(id, images, msecs, wait) { var len = images.length O(id).SS_Stop = (wait == 'stop') ? true : false if (!O(id).SS_Stop && !O(id).SS_Flag) { if (!O('SS_IMG1')) { var newimg = document.createElement('img') newimg.setAttribute('id', 'SS_IMG1') O(id).appendChild(newimg) newimg = document.createElement('img') newimg.setAttribute('id', 'SS_IMG2') O(id).appendChild(newimg) Locate('SS_IMG2', ABS, 0, 0) } var index = 0 O('SS_IMG1').src = images[0] O(id).SS_Flag = true Opacity('SS_IMG2', 0) FadeIn('SS_IMG1', msecs, 0) setTimeout(DoSlideshow, msecs + wait) } function DoSlideshow() { O('SS_IMG1').src = images[index] Opacity('SS_IMG1', 100) Opacity('SS_IMG2', 0) index = ++index % len O('SS_IMG2').src = images[index] var next = InsVars("O('SS_IMG1').src = '#1'", images[(index + 1) % len]) FadeBetween('SS_IMG1', 'SS_IMG2', msecs, 0, next) if (!O(id).SS_Stop) setTimeout(DoSlideshow, msecs + wait) else O(id).SS_Flag = false } } function Billboard(id, objects, random, msecs, wait) { var len = objects.length if (!O(id).BB_Ready) { var h = 0 O(id).BB_Index = 0 O(id).BB_Ready = true FadeOut(objects.slice(1), 1, 0) for (j = 1 ; j < len ; ++j) { h -= H(O(objects[j-1])) Locate(O(objects[j]), REL, 0, h) } } O(id).BB_Stop = (wait == 'stop') ? true : false if (!O(id).BB_Stop && !O(id).BB_Flag) O(id).BB_IID = setTimeout(DoBillboard, msecs + wait) function DoBillboard() { O(id).BB_Flag = true if (O(id).BB_Stop) { O(id).BB_Flag = false clearTimeout(O(id).BB_IID) return } else FadeOut(objects[O(id).BB_Index], msecs, 0) if (random) { var rand = O(id).BB_Index while (rand == O(id).BB_Index ) rand = Math.floor(Math.random() * len) O(id).BB_Index = rand } else O(id).BB_Index = ++O(id).BB_Index % len FadeIn(objects[O(id).BB_Index ], msecs, 0) clearTimeout(O(id).BB_IID) O(id).BB_IID = setTimeout(DoBillboard, msecs + wait) } } function GoogleChart(id, title, tcolor, tsize, type, bwidth, labels, legends, colors, bgfill, width, height, data) { var types = { 'line' : 'lc', 'vbar' : 'bvg', 'hbar' : 'bhg', 'gometer' : 'gom', 'pie' : 'p', 'pie3d' : 'p3', 'venn' : 'v', 'radar' : 'r' } if (typeof type == UNDEF) type = 'pie' var t1 = escape(title) var t2 = types[type] var tail = 'chtt=' + t1 + '&cht=' + t2 + '&chs=' + width + 'x' + height + '&chbh=' + bwidth + '&chxt=x,y' + '&chd=t:' + data if (tcolor && tsize) tail += '&chts=' + tcolor + ',' + tsize if (labels) tail += '&chl=' + labels if (legends) tail += '&chdl=' + legends if (colors) tail += '&chco=' + colors if (bgfill) tail += '&chf=bg,s,' + bgfill Html(id, "<img src='http://chart.apis.google.com/chart?" + tail + "' />") } function PlaySound(id, file, loop) { Resize(id, 0, 0) Locate(id, ABS, 0, 0) if (loop == 'stop') Html(id, '') else Html(id, InsVars("<embed src='#1' hidden='true' " + "autostart='true' loop='#2' />", file, loop)) } function EmbedYouTube(video, width, height, hq, full, auto) { if (hq) hq = '&ap=%2526fmt%3D18' else hq = '' if (width && !height) height = width * 0.7500 if (!width && height) width = height * 1.3333 if (!width) width = 425 if (!height) height = 324 var temp = InsVars("<object width='#1' height='#2'>" + "<param name='movie' value='http://www.youtube.com/v/" + "#3&amp;fs=1&amp;autoplay=#4#5'>", width, height, video, auto, hq) temp += InsVars("</param><param name='allowFullScreen' " + "value='#1'></param><param name='allowscriptaccess' " + "value='always'></param>", full) temp += InsVars("<embed src='http://www.youtube.com" + "/v/#1&amp;fs=1&amp;autoplay=#2#3' type='application/" + "x-shockwave-flash' allowscriptaccess='always' " + "allowfullscreen='true'", video, auto, hq) temp += InsVars("width='#1' height='#2'></embed></object>", width, height) return temp } function PulsateOnMouseover(id, op1, op2, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PulsateOnMouseover(id[j], op1, op2, msecs) return } var finish = false var iid Opacity(id, op1) O(id).FA_Level = op1 O(id).onmouseover = PulsateOn O(id).onmouseout = function() { finish = true } function PulsateOn() { var faded = false finish = false if (iid) clearInterval(iid) iid = setInterval(DoPulsate, INTERVAL) function DoPulsate() { if (!faded && O(id).FA_Level == op1) { if (finish) clearInterval(iid) else { Fade(id, op1, op2, msecs / 2, 0) faded = true } } else if (!O(id).FA_Flag) { Fade(id, op2, op1, msecs / 2, 0) faded = false } } } } function ProcessCookie(action, name, value, seconds, path, domain, secure) { if (action == 'save') { var date = new Date() date.setTime(parseInt(date.getTime() + seconds * 1000)) var expires = seconds ? '; expires=' + date.toGMTString() : '' path = path ? '; path=' + path : '' domain = domain ? '; domain=' + domain : '' secure = secure ? '; secure=' + secure : '' document.cookie = name + '=' + escape(value) + expires + path } else if (action == 'read') { if (!document.cookie.length) return false else { var start = document.cookie.indexOf(name + '=') if (start == -1) return false else { start += name.length + 1 var end = document.cookie.indexOf(';', start) end = (end == -1) ? document.cookie.length : end return unescape(document.cookie.substring(start, end)) } } } else if (action == 'erase') ProcessCookie('save', name, '', -60) } function CreateAjaxObject(callback, force) { try { var ajax = new XMLHttpRequest() } catch(e1) { try { ajax = new ActiveXObject("Msxml2.XMLHTTP") } catch(e2) { try { ajax = new ActiveXObject("Microsoft.XMLHTTP") } catch(e3) { ajax = false } } } if (ajax) ajax.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200 && this.responseText != null) callback.call(this.responseText) } return ajax } function GetAjaxRequest(callback, url, args) { var nocache = '&nocache=' + Math.random() * 1000000 var ajax = new CreateAjaxObject(callback) if (!ajax) return false ajax.open('GET', url + '?' + args + nocache, true) ajax.send(null) return true } function PostAjaxRequest(callback, url, args) { var contenttype = 'application/x-www-form-urlencoded' var ajax = new CreateAjaxObject(callback) if (!ajax) return false ajax.open('POST', url, true) ajax.setRequestHeader('Content-type', contenttype) ajax.setRequestHeader('Content-length', args.length) ajax.setRequestHeader('Connection', 'close') ajax.send(args) return true } function FrameBust(message) { if (top != self) { if (message) { if (confirm(message)) top.location.replace(self.location.href) } else top.location.replace(self.location.href) } } function ProtectEmail() { var a = '' for (var j=0 ; j < arguments.length ; ++j) a += arguments[j] return "<a hr" + "ef" + "='mai" + "lt" + "o:" + a + "'>" + a + "</a>" } function FieldPrompt(id, prompt, inputcolor, promptcolor, promptstyle) { inputcolor = inputcolor ? inputcolor : '#000000' promptcolor = promptcolor ? promptcolor : '#888888' promptstyle = promptstyle ? promptstyle : 'italic' if (BROWSER == 'Opera' || BROWSER == 'Chrome') ResizeWidth(id, W(id)) FP_On() O(id).onfocus = FP_Off O(id).onblur = FP_On function FP_Off() { if (O(id).value == prompt) { O(id).FP_Empty = true O(id).value = '' S(id).fontStyle = '' S(id).color = inputcolor } else O(id).FP_Empty = false } function FP_On() { if (O(id).value == '' || O(id).value == prompt) { O(id).FP_Empty = true O(id).value = prompt S(id).fontStyle = promptstyle S(id).color = promptcolor } else O(id).FP_Empty = false } } function ResizeTextarea(id, min, max) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ResizeTextarea(id[j], min, max) return } min = min ? min : 0 max = max ? max : 10 O(id).onmouseup = DoResizeTextarea O(id).onkeyup = DoResizeTextarea function DoResizeTextarea() { while (O(id).scrollHeight > O(id).clientHeight && O(id).rows < max) ++O(id).rows while (O(id).scrollHeight < O(id).clientHeight && O(id).rows > min) --O(id).rows } } function ValidateEmail(email) { var at = email.indexOf('@') if (at == -1 || /[^\w\-\.\@\_\+]/.test(email)) return false var left = email.substr(0, at) var right = email.substr(at + 1) var llen = left.length var rlen = right.length if (llen < 1 || llen > 64 || rlen < 4 || rlen > 254 || right.indexOf('.') == -1) return false return true } function ValidatePassword(pass, min, max, upper, lower, dig, punct) { var len = pass.length var valid = true if (len < min || len > max) valid = false else if (upper && !/[A-Z]/.test(pass)) valid = false else if (lower && !/[a-z]/.test(pass)) valid = false else if (dig && !/[0-9]/.test(pass)) valid = false else if (punct && !/[^a-zA-Z0-9]/.test(pass)) valid = false return valid } function CleanupString(string, allspaces, alldigs, alltext, allpunct, uptolow, lowtoup, spacestosingle) { if (allspaces) string = string.replace(/[\s]/g, '') if (alldigs) string = string.replace(/[\d]/g, '') if (alltext) string = string.replace(/[a-zA-Z]/g, '') if (allpunct) string = string.replace(/[^\sa-zA-Z0-9]/g, '') if (uptolow) string = string.toLowerCase() if (lowtoup) string = string.toUpperCase() if (spacestosingle) string = string.replace(/[\s]+/g, ' ') return string } function ValidateCreditCard(number, month, year) { number += '' month += '' year += '' number = CleanupString(number, true, false, true, true) month = CleanupString(month, true, false, true, true) year = CleanupString(year, true, false, true, true) var left = number.substr(0, 4) var cclen = number.length var chksum = 0 if (left >= 3000 && left <= 3059 || left >= 3600 && left <= 3699 || left >= 3800 && left <= 3889) { // Diners Club if (cclen != 14) return false } else if (left >= 3088 && left <= 3094 || left >= 3096 && left <= 3102 || left >= 3112 && left <= 3120 || left >= 3158 && left <= 3159 || left >= 3337 && left <= 3349 || left >= 3528 && left <= 3589) { // JCB if (cclen != 16) return false } else if (left >= 3400 && left <= 3499 || left >= 3700 && left <= 3799) { // American Express if (cclen != 15) return false } else if (left >= 3890 && left <= 3899) { // Carte Blanche if (cclen != 14) return false } else if (left >= 4000 && left <= 4999) { // Visa if (cclen != 13 && cclen != 16) return false } else if (left >= 5100 && left <= 5599) { // MasterCard if (cclen != 16) return false } else if (left == 5610) { // Australian BankCard if (cclen != 16) return false } else if (left == 6011) { // Discover if (cclen != 16) return false } else return false // Unrecognized Card for (var j = 1 - (cclen % 2) ; j < cclen ; j += 2) if (j < cclen) chksum += number[j] * 1 for (j = cclen % 2 ; j < cclen ; j += 2) { if (j < cclen) { d = number[j] * 2 chksum += d < 10 ? d : d - 9 } } if (chksum % 10 != 0) return false var date = new Date() date.setTime(date.getTime()) if (year.length == 4) year = year.substr(2, 2) if (year > 50) return false else if (year < (date.getFullYear() - 2000)) return false else if ((date.getMonth() + 1 ) > month) return false else return true } function RollingCopyright(start) { var date = new Date() date = date.getFullYear() return '© ' + start + "-" + date } function Alert(value) { var divs = Array('ALERT_DIV', 'SHADOW_DIV') var warn = "<font color=red size=6 style='vertical-align:middle;'>" + "Δ</font> " var ok = "<center><input id='ALERT_OK' type='submit' /></center>" var mess = warn + value + '<br /><br />' + ok var html = "<div id='ALERT_TITLE'></div>" + "<div id='ALERT_MESSAGE'></div>" if (!O('ALERT_DIV')) { var newdiv = document.createElement('div') newdiv.setAttribute('id', 'SHADOW_DIV') document.body.appendChild(newdiv) newdiv = document.createElement('div') newdiv.setAttribute('id', 'ALERT_DIV') document.body.appendChild(newdiv) Position(divs, ABS) Resize('ALERT_DIV', 350, 140) Resize('SHADOW_DIV', 354, 146) Center('ALERT_DIV') GoTo('SHADOW_DIV', X('ALERT_DIV') + 4, Y('ALERT_DIV') + 6) Opacity('SHADOW_DIV', 50) } AlertHide() Html('ALERT_DIV', html) Resize('ALERT_TITLE', 350, 22) Resize('ALERT_MESSAGE', 330, 98) Html('ALERT_TITLE', 'Message from the webpage') Html('ALERT_MESSAGE', mess) S('ALERT_TITLE').background = '#acc5e0' S('ALERT_TITLE').fontFamily = 'Arial' S('ALERT_TITLE').paddingTop = '2px' S('ALERT_TITLE').textAlign = 'center' S('ALERT_TITLE').fontSize = '14px' S('ALERT_MESSAGE').fontFamily = 'Arial' S('ALERT_MESSAGE').fontSize = '12px' S('ALERT_MESSAGE').padding = '10px' S('ALERT_MESSAGE').overflow = 'auto' S('ALERT_DIV').background = '#f0f0f0' S('ALERT_DIV').border = 'solid #444444 1px' S('SHADOW_DIV').background = '#444444' O('ALERT_OK').value = ' OK ' O('ALERT_OK').onclick = AlertHide Visible(divs) function AlertHide() { Invisible(divs) } } function ReplaceAlert() { window.alert = Alert } function ToolTip(id, tip, font, size, textc, backc, bordc, bstyle, bwidth, msecs, timeout) { var tt = 'TT_' + O(id).id if (!O(tt)) { var newdiv = document.createElement('div') newdiv.setAttribute('id', tt) document.body.appendChild(newdiv) Opacity(tt, 0) Position(tt, ABS) font = font ? font : 'Arial' size = size ? size : 'small' textc = textc ? textc : '#884444' backc = backc ? backc : '#ffff88' bordc = bordc ? bordc : '#aaaaaa' bstyle = bstyle ? bstyle : 'dotted' bwidth = bwidth ? bwidth : 1 msecs = msecs ? msecs : 250 S(tt).fontFamily = font S(tt).fontSize = size S(tt).padding = '3px 5px 3px 5px' S(tt).color = textc S(tt).background = backc S(tt).borderColor = bordc S(tt).borderStyle = bstyle S(tt).borderWidth = Px(bwidth) Html(tt, tip) } O(id).onmouseover = DoToolTip O(id).onmouseout = ToolTipHide O(tt).Hidden = false function DoToolTip() { GoTo(tt, MOUSE_X + 15, MOUSE_Y + 15) O(tt).zIndex = ZINDEX + 1 FadeIn(tt, msecs) O(tt).Hidden = false if (timeout) { if (O(tt).IID) clearTimeout(O(tt).IID) O(tt).IID = setTimeout(ToolTipHide, timeout) } } function ToolTipHide() { if (!O(tt).Hidden) { FadeOut(tt, msecs) O(tt).Hidden = true } } } function CursorTrail(image, length, state) { var w = GetWindowWidth() var h = GetWindowHeight() var c = 'CT_' if (!state) return clearInterval(CT_IID) if (!O('TT_0')) { for (var j = 0 ; j < 10 ; ++j) { var newimg = document.createElement('img') newimg.setAttribute('id', c + j) document.body.appendChild(newimg) Position(newimg, ABS) Opacity(newimg, (j + 1) * 9) newimg.src = image O(c + j).X = -9999 O(c + j).Y = -9999 } } CT_IID = setInterval(DoCurTrail, length) function DoCurTrail() { for (var j = 0 ; j < 10 ; ++j) { GoTo(c + j, O(c + j).X + 2, O(c + j).Y + 2) S(c + j).zIndex = ZINDEX + 1 if (O(c + j).X == MOUSE_X && O(c + j).Y == MOUSE_Y) Hide(c + j) else Show(c + j) if (j > 0) { O(c + (j - 1)).X = O(c + j).X O(c + (j - 1)).Y = O(c + j).Y } } O(c + 9).X = MOUSE_X < (w - 12) ? MOUSE_X : -9999 O(c + 9).Y = MOUSE_Y < (h - 20) ? MOUSE_Y : -9999 } } function TouchEnable(state) { var db = document.body if (state) { var iid = null var flag = false PreventAction(db, 'both', true) db.onmousedown = StartTE db.onmouseup = StopTE } else { PreventAction(db, 'both', false) db.onmousedown = '' db.onmouseup = '' return } function StartTE(e) { if (!flag) { var oldmousex = MOUSE_X var oldmousey = MOUSE_Y var tempmousex = MOUSE_X var tempmousey = MOUSE_Y flag = true iid = setInterval(DoTE, 10) } return false function DoTE() { if (MOUSE_DOWN && MOUSE_IN) { if (MOUSE_X != tempmousex || MOUSE_Y != tempmousey) { tempmousex = MOUSE_X tempmousey = MOUSE_Y window.scrollBy(oldmousex - MOUSE_X, oldmousey - MOUSE_Y) } } else StopTE() } } function StopTE() { flag = false clearInterval(iid) } } // Based on a function by Ryan Morr at: // http://ryanmorr.com/archives/ondomready-no-browser-sniffing // // Use this in place of window.onload to start your code much more // quickly than waiting for window.onload, which only triggers after // all contents such as images are also loaded - whereas this code // triggers as soon as the DOM is complete and in a useable state. // // Example: // // OnDOMReady(function() // { // // Your code goes here... // }) function OnDOMReady(func) { var timer = setInterval(onChange, 5) var ready = false if(document.addEventListener) document.addEventListener( "DOMContentLoaded", onChange, false) document.onreadystatechange = window.onload = onChange function onChange(e) { if(e && e.type == "DOMContentLoaded") { fireDOMReady() } else if(e && e.type == "load") { fireDOMReady() } else if(document.readyState) { if((/loaded|complete/).test(document.readyState)) { fireDOMReady() } else if(!!document.documentElement.doScroll) { try { ready || document.documentElement.doScroll('left') } catch(e) { return } fireDOMReady(); } } } function fireDOMReady() { if(!ready) { ready = true func.call() if(document.removeEventListener) document.removeEventListener( "DOMContentLoaded", onChange, false) clearInterval(timer) document.onreadystatechange = window.onload = timer = null } } }
JavaScript
/************************************/ /* PC.js: Version 1.0 */ /* From Plug-in CSS, by Robin Nixon */ /* McGraw-Hill 2011 */ /* */ /* Plug-ins 58-100: Dynamic classes */ /* and Superclasses */ /************************************/ Initialize() OnDOMReady(function() { var gfurl = 'http://fonts.googleapis.com/css?family=' var wheight = GetWindowHeight() var tags = document.getElementsByTagName("*") var numtags = tags.length var font = '' var elems = [] var gfonts = [] var cites = [] var refers = [] var sclasses = [] var gfindex = 0 var cindex = 0 var demand = false var index, index2, thistag, regex, oldclassname loadsclasses(sclasses) for (index = 0 ; index < numtags ; ++ index) { thistag = tags[index] var tagname = thistag.tagName.toLowerCase() var tagtype = (thistag.type) ? thistag.type.toLowerCase() : '' var classname = thistag.className.toLowerCase() var cnamecopy = classname var origcname = thistag.className var repeat = true /**********************/ /* Chapter 8: Objects */ /**********************/ /* 58: nojs and onlyjs classes */ if (classname.search(/\bnojs\b/, 0) != -1) Hide(thistag) if (classname.search(/\bonlyjs\b/, 0) != -1) Show(thistag) /* 59: middle class */ if (classname.search(/\bmiddle\b/, 0) != -1) { S(thistag).marginTop = S(thistag).marginBottom = Px((H(thistag.parentNode) - H(thistag)) / 2) } /* 60: center class */ if (classname.search(/\bcenter\b/, 0) != -1) { S(thistag).marginLeft = S(thistag).marginRight = Px((W(thistag.parentNode) - W(thistag)) / 2) } /* 61: top class */ if (classname.search(/\btop\b/, 0) != -1) { S(thistag).marginTop = '0px'; S(thistag).marginBottom = Px(H(thistag.parentNode) -H(thistag)) } /* 62: bottom class */ if (classname.search(/\bbottom\b/, 0) != -1) { S(thistag).marginTop = Px(H(thistag.parentNode) -H(thistag)) S(thistag).marginBottom = '0px'; } /* 63: left class */ if (classname.search(/\bleft\b/, 0) != -1) { S(thistag).marginLeft = '0px'; S(thistag).marginRight = Px(W(thistag.parentNode) - W(thistag)) } /* 64: right class */ if (classname.search(/\bright\b/, 0) != -1) { S(thistag).marginLeft = Px(W(thistag.parentNode) - W(thistag)) S(thistag).marginRight = '0px'; } /* 65: ondemand class */ if (classname.search(/\bondemand\b/, 0) != -1 && tagname == 'img') { if (Y(thistag) > (SCROLL_Y + wheight)) { elems[index] = thistag.alt demand = true Opacity(thistag, 0) } else thistag.src = thistag.alt } /* 66: fadein class */ if (classname.search(/\bfadein\b/, 0) != -1) { cnamecopy.replace(/fadein\[([^\]]*)\]/, function() { Opacity(thistag, 0); FadeIn(thistag, arguments[1]) } ) } /* 67: fadeout class */ if (classname.search(/\bfadeout\b/, 0) != -1) { cnamecopy.replace(/fadeout\[([^\]]*)\]/, function() { FadeOut(thistag, arguments[1]) } ) } /* 68: resizeta class */ if (classname.search(/\bresizeta\b/, 0) != -1 && tagname == 'textarea') { cnamecopy.replace(/resizeta\[([^\|]*)\|([^\]]*)\]/, function() { ResizeTextarea(thistag, arguments[1], arguments[2]) } ) } /* 69: rotate class */ if (classname.search(/\brotate\b/, 0) != -1) { cnamecopy.replace(/rotate\[([^\]]*)\]/, function() { var r = arguments[1] S(thistag).MozTransform = 'rotate(' + r + 'deg)' S(thistag).WebkitTransform = 'rotate(' + r + 'deg)' S(thistag).OTransform = 'rotate(' + r + 'deg)' S(thistag).transform = 'rotate(' + r + 'deg)' if (typeof S(thistag).filter != UNDEF) { var rad = r * (Math.PI * 2 / 360) var cosrad = Math.cos(rad) var sinrad = Math.sin(rad) var w = W(thistag) var h = H(thistag) var filter = 'progid:DXImageTransform.Microsoft.' + 'Matrix(M11=' + cosrad + ', M12=' + -sinrad + ', M21=' + sinrad + ', M22=' + cosrad + ", SizingMethod='auto expand')" S(thistag).filter = filter Locate(thistag, REL, -((W(thistag) - w) / 2), -((H(thistag) - h) / 2)) } } ) } /* 70: w class */ if (classname.search(/\bw\b/, 0) != -1) { cnamecopy.replace(/w\[([^\]]*)\]/, function() { S(thistag).width = Px(arguments[1]) } ) } /* 71: h class */ if (classname.search(/\bh\b/, 0) != -1) { cnamecopy.replace(/h\[([^\]]*)\]/, function() { S(thistag).height = Px(arguments[1]) } ) } /* 72: x class */ if (classname.search(/\bx\b/, 0) != -1) { cnamecopy.replace(/x\[([^\]]*)\]/, function() { S(thistag).left = Px(arguments[1]) } ) } /* 73: y class */ if (classname.search(/\by\b/, 0) != -1) { cnamecopy.replace(/y\[([^\]]*)\]/, function() { S(thistag).top = Px(arguments[1]) } ) } /* 74: color class */ if (classname.search(/\bcolor\b/, 0) != -1) { cnamecopy.replace(/color\[([^\]]*)\]/, function() { S(thistag).color = arguments[1] } ) } /* 75: bcolor class */ if (classname.search(/\bbcolor\b/, 0) != -1) { cnamecopy.replace(/bcolor\[([^\]]*)\]/, function() { S(thistag).backgroundColor = arguments[1] } ) } /**********************************/ /* Chapter 9: Text and Typography */ /**********************************/ /* 76: typetext class */ if (classname.search(/\btypetext\b/, 0) != -1) { cnamecopy.replace(/typetext\[([^\]]*)\]/, function() { TextType(thistag, 1, arguments[1]) } ) } /* 77: digitsonly class */ if (classname.search(/\bdigitsonly\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 0, 1, 1) } } /* 78: textonly class */ if (classname.search(/\btextonly\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 1, 0, 1) } } /* 79: nospaces class */ if (classname.search(/\bnospaces\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 1) } } /* 80: nopunct class */ if (classname.search(/\bnopunct\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 0, 0, 1) } } /* 81: minwhitespace class */ if (classname.search(/\bminwhitespace\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 0, 0, 0, 0, 0, 1) } } /* 82: gfont class */ if (classname.search(/\bgfont\b/, 0) != -1) { cnamecopy.replace(/gfont\[([^\]]*)\]/, function() { switch(arguments[1]) { case 'cantarell' : font = 'Cantarell'; break case 'cardo' : font = 'Cardo'; break case 'crimson' : font = 'Crimson Text'; break case 'droidsans' : font = 'Droid Sans'; break case 'droidsansm' : font = 'Droid Sans Mono'; break case 'droidserif' : font = 'Droid Serif'; break case 'imfell' : font = 'IM Fell English'; break case 'inconsolata': font = 'Inconsolata'; break case 'josefin' : font = 'Josefin Sans Std Light'; break case 'lobster' : font = 'Lobster'; break case 'molengo' : font = 'Molengo'; break case 'neuton' : font = 'Neuton'; break case 'nobile' : font = 'Nobile'; break case 'oflsorts' : font = 'OFL Sorts Mill Goudy TT';break case 'oldstandard': font = 'Old Standard TT'; break case 'reenie' : font = 'Reenie Beanie'; break case 'tangerine' : font = 'Tangerine'; break case 'vollkorn' : font = 'Vollkorn'; break case 'yanone' : font = 'Yanone Kaffeesatz'; break } if (!window[font]) { window[font] = true gfonts[gfindex++] = font } S(thistag).fontFamily = font } ) } /* 83: textmiddle class */ if (classname.search(/\btextmiddle\b/, 0) != -1) { S(thistag).lineHeight = Px(H(thistag)) } /* 84: textglow class */ if (classname.search(/\btextglow\b/, 0) != -1) { cnamecopy.replace(/textglow\[([^\|]*)\|([^\|]*)\|([^\]]*)\]/, function() { ColorFade(thistag, arguments[1], arguments[2], 'text', arguments[3]) } ) } /* 85: backglow class */ if (classname.search(/\bbackglow\b/, 0) != -1) { cnamecopy.replace(/backglow\[([^\|]*)\|([^\|]*)\|([^\]]*)\]/, function() { ColorFade(thistag, arguments[1], arguments[2], '', arguments[3]) } ) } /**************************/ /* Chapter 10: Navigation */ /**************************/ /* 86: placeholder class */ if (classname.search(/\bplaceholder\b/, 0) != -1 && tagname == 'input') { origcname.replace(/placeholder\[([^\]]*)\]/, function() { if (thistag.placeholder == '' || typeof thistag.placeholder == UNDEF) FieldPrompt(thistag, arguments[1]) } ) } /* 87: autofocus class */ if (classname.search(/\bautofocus\b/, 0) != -1 && tagname == 'input' || tagname == 'select' || tagname == 'textarea' || tagname == 'button') { if (tagtype != 'hidden') thistag.focus() } /* 88: cite class */ if (classname.search(/\bcite\b/, 0) != -1) { origcname.replace(/cite\[([^\]]*)\]/, function() { cites[cindex++] = arguments[1] S(thistag).verticalAlign = 'super' S(thistag).textDecoration = 'none' S(thistag).fontSize = '50%' Html(thistag, Html(thistag) + InsVars("<a href='#cite#1'>[#1]</a>", cindex)) } ) } /* 89: ref class */ if (classname.search(/\bref\b/, 0) != -1) { cnamecopy.replace(/ref\[([^\|]*)\|([^\]]*)\]/, function() { var a1 = arguments[1] var a2 = arguments[2] if (typeof refers[a1] == UNDEF) { refers[a1] = Array() refers[a1]['count'] = 1 refers[a1][a2] = 1 } else if (typeof refers[a1][a2] == UNDEF) refers[a1][a2] = ++refers[a1]['count'] Html(thistag, refers[a1][a2]) } ) } /* 90: nocopy class */ if (classname.search(/\bnocopy\b/, 0) != -1) { PreventAction(thistag, 'both', true) } /****************************************/ /* Chapter 11: Incorporating JavaScript */ /****************************************/ /* 91: embedjs class */ if (classname.search(/\bembedjs\b/, 0) != -1) { Html(thistag, Html(thistag).replace(/\[\[([^\]]*)\]\]/g, function() { arguments[1] = arguments[1].replace(/</g, '<') arguments[1] = arguments[1].replace(/>/g, '>') try { return eval(arguments[1]) } catch(e) { return "<span class='red'>[" + e + "]</span>" } } )) } /* 92: if class */ if (classname.search(/\bif\b/, 0) != -1) { origcname.replace(/(if|IF)\[([^\]]*)\]/, function() { if (!eval(arguments[2])) Html(thistag, '<!-- ' + Html(thistag) + ' -->') } ) } /* 93: ifnot class */ if (classname.search(/\bifnot\b/, 0) != -1) { origcname.replace(/(ifnot|IFNOT)\[([^\]]*)\]/, function() { if (eval(arguments[2])) Html(thistag, '<!-- ' + Html(thistag) + ' -->') } ) } /****************************/ /* Chapter 12: Superclasses */ /****************************/ // Load in superclasses from meta tags if (thistag.tagName == 'META' && thistag.httpEquiv.toUpperCase() == 'SCLASS') sclasses[thistag.name] = thistag.content // Apply superclasses while (repeat) { oldclassname = thistag.className for (index2 in sclasses) { regex = new RegExp('\\b' + index2 + '\\b', 'g') thistag.className = thistag.className.replace(regex, sclasses[index2]) } if (thistag.className != oldclassname) repeat = true else repeat = false } } // Import Google Fonts Stylesheets for (index = 0 ; index < gfindex ; ++index) { var newcss = document.createElement('link') newcss.setAttribute('href', gfurl + escape(gfonts[index])) newcss.setAttribute('rel', 'stylesheet') newcss.setAttribute('type', 'text/css') document.getElementsByTagName('head')[0].appendChild(newcss) } if (gfindex && window.opera) setTimeout(function()// Required by Opera { document.body.style += "" }, 1) // to redraw browser // Add citations to 'citations' object if (cindex > 0) { var html = '<ol>' for (index = 0 ; index < cindex ; ++index) html += InsVars('<a name=cite#1></a><li>#2</li>', index + 1, cites[index]) // Check that 'citations' exists before inserting HTML if (typeof O('citations') != UNDEF) Html('citations', html + '</ol>') } // If there are unloaded images outside the current view if (demand) setTimeout(DoOnDemand, 10) // Perform on demand image loading function DoOnDemand() { demand = false for (index = 0 ; index < numtags ; ++index) { thistag = tags[index] if (elems[index]) { demand = true if (Y(thistag) < (SCROLL_Y + wheight)) { thistag.onload = function() { FadeIn(this, 500) } thistag.src = elems[index] elems[index] = '' } } } // repeat if there are still any unloaded images if (demand) setTimeout(DoOnDemand, 10) } }) function loadsclasses(sclasses) { /* 94 - 100: Superclasses */ sclasses['clickable'] = 'nooutline pointer' sclasses['rssbutton'] = 'carrot1 carrot2_a smallestround b white ' + 'yellow_h smallbutton clickable' sclasses['border'] = 'bwidth1 bsolid bblack' sclasses['abstopleft'] = 'absolute totop toleft' sclasses['rollover'] = 'trans00 trans10_h' sclasses['rollover_h'] = 'abstopleft trans10 trans00_h' sclasses['vtab'] = 'leftpadding10 leftpadding40_h ' + 'rightpadding5 b transitionallfast_l' sclasses['htab'] = 'absolute center toppadding20_h b ' + 'transitionallfast_l' } /************************************************************************ You can add more classes to your HTML using meta tags, like this... <meta http-equiv='sclass' name='clickable' content='nooutline pointer' /> which replicates one of the superclasses built into this script. You can override it, or add more superclasses with new names and values. You can also add them to this file using the syntax shown above. ************************************************************************/
JavaScript
// JavaScript Document // 꼭 필요한 HTML5 그리고 HTML5 API #pubple p.71 // pro jquery 제이쿼리 완벽마스터 #apress/길벗 p.284 // 접근성을 유지하며 팝업창 뛰우기 // <a href=' ' class='popup' data-height=100 data-width=200 data-winName='kongji' >공지사항</a> $(function() { $('a.popup' ).click(function(e) { e.preventDefault(); var href = $(this).attr('href'); var height = $(this).attr('data-height'); var widht = $(this).attr('data-width') || $(this).getAttribute('data-width') || $(this).data('width') || this.dataset.width; var winName = $(this).attr('data-winName'); var popup = window.open(href, winName, 'height=' + height + ', width=' + width); }); }); // 전화번호 정규식 function phone_format(num) { var regExp = /(^02.{0}|^01.{1}|[0|1|6|7|8|9]{3})([0-9]+)([0-9]{4})/; return num.replace(regExp, "$1-$2-$3"); } alert(phone_format('01011112222')); // 010-1111-2222 alert(phone_format('022223333')); // 다양한 테스트 필요
JavaScript
if(typeof Object.create!=="function"){ Object.create=function(o){ function F(){ }; F.prototype=o; return new F(); }; } var ua={toString:function(){ return navigator.userAgent; },test:function(s){ return this.toString().toLowerCase().indexOf(s.toLowerCase())>-1; }}; ua.version=(ua.toString().toLowerCase().match(/[\s\S]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1]; ua.webkit=ua.test("webkit"); ua.gecko=ua.test("gecko")&&!ua.webkit; ua.opera=ua.test("opera"); ua.ie=ua.test("msie")&&!ua.opera; ua.ie6=ua.ie&&document.compatMode&&typeof document.documentElement.style.maxHeight==="undefined"; ua.ie7=ua.ie&&document.documentElement&&typeof document.documentElement.style.maxHeight!=="undefined"&&typeof XDomainRequest==="undefined"; ua.ie8=ua.ie&&typeof XDomainRequest!=="undefined"; var domReady=function(){ var _1=[]; var _2=function(){ if(!arguments.callee.done){ arguments.callee.done=true; for(var i=0;i<_1.length;i++){ _1[i](); } } }; if(document.addEventListener){ document.addEventListener("DOMContentLoaded",_2,false); } if(ua.ie){ (function(){ try{ document.documentElement.doScroll("left"); } catch(e){ setTimeout(arguments.callee,50); return; } _2(); })(); document.onreadystatechange=function(){ if(document.readyState==="complete"){ document.onreadystatechange=null; _2(); } }; } if(ua.webkit&&document.readyState){ (function(){ if(document.readyState!=="loading"){ _2(); }else{ setTimeout(arguments.callee,10); } })(); } window.onload=_2; return function(fn){ if(typeof fn==="function"){ _1[_1.length]=fn; } return fn; }; }(); var cssHelper=function(){ var _3={BLOCKS:/[^\s{][^{]*\{(?:[^{}]*\{[^{}]*\}[^{}]*|[^{}]*)*\}/g,BLOCKS_INSIDE:/[^\s{][^{]*\{[^{}]*\}/g,DECLARATIONS:/[a-zA-Z\-]+[^;]*:[^;]+;/g,RELATIVE_URLS:/url\(['"]?([^\/\)'"][^:\)'"]+)['"]?\)/g,REDUNDANT_COMPONENTS:/(?:\/\*([^*\\\\]|\*(?!\/))+\*\/|@import[^;]+;)/g,REDUNDANT_WHITESPACE:/\s*(,|:|;|\{|\})\s*/g,MORE_WHITESPACE:/\s{2,}/g,FINAL_SEMICOLONS:/;\}/g,NOT_WHITESPACE:/\S+/g}; var _4,_5=false; var _6=[]; var _7=function(fn){ if(typeof fn==="function"){ _6[_6.length]=fn; } }; var _8=function(){ for(var i=0;i<_6.length;i++){ _6[i](_4); } }; var _9={}; var _a=function(n,v){ if(_9[n]){ var _b=_9[n].listeners; if(_b){ for(var i=0;i<_b.length;i++){ _b[i](v); } } } }; var _c=function(_d,_e,_f){ if(ua.ie&&!window.XMLHttpRequest){ window.XMLHttpRequest=function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }; } if(!XMLHttpRequest){ return ""; } var r=new XMLHttpRequest(); try{ r.open("get",_d,true); r.setRequestHeader("X_REQUESTED_WITH","XMLHttpRequest"); } catch(e){ _f(); return; } var _10=false; setTimeout(function(){ _10=true; },5000); document.documentElement.style.cursor="progress"; r.onreadystatechange=function(){ if(r.readyState===4&&!_10){ if(!r.status&&location.protocol==="file:"||(r.status>=200&&r.status<300)||r.status===304||navigator.userAgent.indexOf("Safari")>-1&&typeof r.status==="undefined"){ _e(r.responseText); }else{ _f(); } document.documentElement.style.cursor=""; r=null; } }; r.send(""); }; var _11=function(_12){ _12=_12.replace(_3.REDUNDANT_COMPONENTS,""); _12=_12.replace(_3.REDUNDANT_WHITESPACE,"$1"); _12=_12.replace(_3.MORE_WHITESPACE," "); _12=_12.replace(_3.FINAL_SEMICOLONS,"}"); return _12; }; var _13={mediaQueryList:function(s){ var o={}; var idx=s.indexOf("{"); var lt=s.substring(0,idx); s=s.substring(idx+1,s.length-1); var mqs=[],rs=[]; var qts=lt.toLowerCase().substring(7).split(","); for(var i=0;i<qts.length;i++){ mqs[mqs.length]=_13.mediaQuery(qts[i],o); } var rts=s.match(_3.BLOCKS_INSIDE); if(rts!==null){ for(i=0;i<rts.length;i++){ rs[rs.length]=_13.rule(rts[i],o); } } o.getMediaQueries=function(){ return mqs; }; o.getRules=function(){ return rs; }; o.getListText=function(){ return lt; }; o.getCssText=function(){ return s; }; return o; },mediaQuery:function(s,mql){ s=s||""; var not=false,_14; var exp=[]; var _15=true; var _16=s.match(_3.NOT_WHITESPACE); for(var i=0;i<_16.length;i++){ var _17=_16[i]; if(!_14&&(_17==="not"||_17==="only")){ if(_17==="not"){ not=true; } }else{ if(!_14){ _14=_17; }else{ if(_17.charAt(0)==="("){ var _18=_17.substring(1,_17.length-1).split(":"); exp[exp.length]={mediaFeature:_18[0],value:_18[1]||null}; } } } } return {getList:function(){ return mql||null; },getValid:function(){ return _15; },getNot:function(){ return not; },getMediaType:function(){ return _14; },getExpressions:function(){ return exp; }}; },rule:function(s,mql){ var o={}; var idx=s.indexOf("{"); var st=s.substring(0,idx); var ss=st.split(","); var ds=[]; var dts=s.substring(idx+1,s.length-1).split(";"); for(var i=0;i<dts.length;i++){ ds[ds.length]=_13.declaration(dts[i],o); } o.getMediaQueryList=function(){ return mql||null; }; o.getSelectors=function(){ return ss; }; o.getSelectorText=function(){ return st; }; o.getDeclarations=function(){ return ds; }; o.getPropertyValue=function(n){ for(var i=0;i<ds.length;i++){ if(ds[i].getProperty()===n){ return ds[i].getValue(); } } return null; }; return o; },declaration:function(s,r){ var idx=s.indexOf(":"); var p=s.substring(0,idx); var v=s.substring(idx+1); return {getRule:function(){ return r||null; },getProperty:function(){ return p; },getValue:function(){ return v; }}; }}; var _19=function(el){ if(typeof el.cssHelperText!=="string"){ return; } var o={mediaQueryLists:[],rules:[],selectors:{},declarations:[],properties:{}}; var _1a=o.mediaQueryLists; var ors=o.rules; var _1b=el.cssHelperText.match(_3.BLOCKS); if(_1b!==null){ for(var i=0;i<_1b.length;i++){ if(_1b[i].substring(0,7)==="@media "){ _1a[_1a.length]=_13.mediaQueryList(_1b[i]); ors=o.rules=ors.concat(_1a[_1a.length-1].getRules()); }else{ ors[ors.length]=_13.rule(_1b[i]); } } } var oss=o.selectors; var _1c=function(r){ var ss=r.getSelectors(); for(var i=0;i<ss.length;i++){ var n=ss[i]; if(!oss[n]){ oss[n]=[]; } oss[n][oss[n].length]=r; } }; for(i=0;i<ors.length;i++){ _1c(ors[i]); } var ods=o.declarations; for(i=0;i<ors.length;i++){ ods=o.declarations=ods.concat(ors[i].getDeclarations()); } var ops=o.properties; for(i=0;i<ods.length;i++){ var n=ods[i].getProperty(); if(!ops[n]){ ops[n]=[]; } ops[n][ops[n].length]=ods[i]; } el.cssHelperParsed=o; _4[_4.length]=el; return o; }; var _1d=function(el,s){ el.cssHelperText=_11(s||el.innerHTML); return _19(el); }; var _1e=function(){ _5=true; _4=[]; var _1f=[]; var _20=function(){ for(var i=0;i<_1f.length;i++){ _19(_1f[i]); } var _21=document.getElementsByTagName("style"); for(i=0;i<_21.length;i++){ _1d(_21[i]); } _5=false; _8(); }; var _22=document.getElementsByTagName("link"); for(var i=0;i<_22.length;i++){ var _23=_22[i]; if(_23.getAttribute("rel").indexOf("style")>-1&&_23.href&&_23.href.length!==0&&!_23.disabled){ _1f[_1f.length]=_23; } } if(_1f.length>0){ var c=0; var _24=function(){ c++; if(c===_1f.length){ _20(); } }; var _25=function(_26){ var _27=_26.href; _c(_27,function(_28){ _28=_11(_28).replace(_3.RELATIVE_URLS,"url("+_27.substring(0,_27.lastIndexOf("/"))+"/$1)"); _26.cssHelperText=_28; _24(); },_24); }; for(i=0;i<_1f.length;i++){ _25(_1f[i]); } }else{ _20(); } }; var _29={mediaQueryLists:"array",rules:"array",selectors:"object",declarations:"array",properties:"object"}; var _2a={mediaQueryLists:null,rules:null,selectors:null,declarations:null,properties:null}; var _2b=function(_2c,v){ if(_2a[_2c]!==null){ if(_29[_2c]==="array"){ return (_2a[_2c]=_2a[_2c].concat(v)); }else{ var c=_2a[_2c]; for(var n in v){ if(v.hasOwnProperty(n)){ if(!c[n]){ c[n]=v[n]; }else{ c[n]=c[n].concat(v[n]); } } } return c; } } }; var _2d=function(_2e){ _2a[_2e]=(_29[_2e]==="array")?[]:{}; for(var i=0;i<_4.length;i++){ _2b(_2e,_4[i].cssHelperParsed[_2e]); } return _2a[_2e]; }; domReady(function(){ var els=document.body.getElementsByTagName("*"); for(var i=0;i<els.length;i++){ els[i].checkedByCssHelper=true; } if(document.implementation.hasFeature("MutationEvents","2.0")||window.MutationEvent){ document.body.addEventListener("DOMNodeInserted",function(e){ var el=e.target; if(el.nodeType===1){ _a("DOMElementInserted",el); el.checkedByCssHelper=true; } },false); }else{ setInterval(function(){ var els=document.body.getElementsByTagName("*"); for(var i=0;i<els.length;i++){ if(!els[i].checkedByCssHelper){ _a("DOMElementInserted",els[i]); els[i].checkedByCssHelper=true; } } },1000); } }); var _2f=function(d){ if(typeof window.innerWidth!="undefined"){ return window["inner"+d]; }else{ if(typeof document.documentElement!="undefined"&&typeof document.documentElement.clientWidth!="undefined"&&document.documentElement.clientWidth!=0){ return document.documentElement["client"+d]; } } }; return {addStyle:function(s,_30){ var el=document.createElement("style"); el.setAttribute("type","text/css"); document.getElementsByTagName("head")[0].appendChild(el); if(el.styleSheet){ el.styleSheet.cssText=s; }else{ el.appendChild(document.createTextNode(s)); } el.addedWithCssHelper=true; if(typeof _30==="undefined"||_30===true){ cssHelper.parsed(function(_31){ var o=_1d(el,s); for(var n in o){ if(o.hasOwnProperty(n)){ _2b(n,o[n]); } } _a("newStyleParsed",el); }); }else{ el.parsingDisallowed=true; } return el; },removeStyle:function(el){ return el.parentNode.removeChild(el); },parsed:function(fn){ if(_5){ _7(fn); }else{ if(typeof _4!=="undefined"){ if(typeof fn==="function"){ fn(_4); } }else{ _7(fn); _1e(); } } },mediaQueryLists:function(fn){ cssHelper.parsed(function(_32){ fn(_2a.mediaQueryLists||_2d("mediaQueryLists")); }); },rules:function(fn){ cssHelper.parsed(function(_33){ fn(_2a.rules||_2d("rules")); }); },selectors:function(fn){ cssHelper.parsed(function(_34){ fn(_2a.selectors||_2d("selectors")); }); },declarations:function(fn){ cssHelper.parsed(function(_35){ fn(_2a.declarations||_2d("declarations")); }); },properties:function(fn){ cssHelper.parsed(function(_36){ fn(_2a.properties||_2d("properties")); }); },broadcast:_a,addListener:function(n,fn){ if(typeof fn==="function"){ if(!_9[n]){ _9[n]={listeners:[]}; } _9[n].listeners[_9[n].listeners.length]=fn; } },removeListener:function(n,fn){ if(typeof fn==="function"&&_9[n]){ var ls=_9[n].listeners; for(var i=0;i<ls.length;i++){ if(ls[i]===fn){ ls.splice(i,1); i-=1; } } } },getViewportWidth:function(){ return _2f("Width"); },getViewportHeight:function(){ return _2f("Height"); }}; }(); domReady(function enableCssMediaQueries(){ var _37; var _38={LENGTH_UNIT:/[0-9]+(em|ex|px|in|cm|mm|pt|pc)$/,RESOLUTION_UNIT:/[0-9]+(dpi|dpcm)$/,ASPECT_RATIO:/^[0-9]+\/[0-9]+$/,ABSOLUTE_VALUE:/^[0-9]*(\.[0-9]+)*$/}; var _39=[]; var _3a=function(){ var id="css3-mediaqueries-test"; var el=document.createElement("div"); el.id=id; var _3b=cssHelper.addStyle("@media all and (width) { #"+id+" { width: 1px !important; } }",false); document.body.appendChild(el); var ret=el.offsetWidth===1; _3b.parentNode.removeChild(_3b); el.parentNode.removeChild(el); _3a=function(){ return ret; }; return ret; }; var _3c=function(){ _37=document.createElement("div"); _37.style.cssText="position:absolute;top:-9999em;left:-9999em;"+"margin:0;border:none;padding:0;width:1em;font-size:1em;"; document.body.appendChild(_37); if(_37.offsetWidth!==16){ _37.style.fontSize=16/_37.offsetWidth+"em"; } _37.style.width=""; }; var _3d=function(_3e){ _37.style.width=_3e; var _3f=_37.offsetWidth; _37.style.width=""; return _3f; }; var _40=function(_41,_42){ var l=_41.length; var min=(_41.substring(0,4)==="min-"); var max=(!min&&_41.substring(0,4)==="max-"); if(_42!==null){ var _43; var _44; if(_38.LENGTH_UNIT.exec(_42)){ _43="length"; _44=_3d(_42); }else{ if(_38.RESOLUTION_UNIT.exec(_42)){ _43="resolution"; _44=parseInt(_42,10); var _45=_42.substring((_44+"").length); }else{ if(_38.ASPECT_RATIO.exec(_42)){ _43="aspect-ratio"; _44=_42.split("/"); }else{ if(_38.ABSOLUTE_VALUE){ _43="absolute"; _44=_42; }else{ _43="unknown"; } } } } } var _46,_47; if("device-width"===_41.substring(l-12,l)){ _46=screen.width; if(_42!==null){ if(_43==="length"){ return ((min&&_46>=_44)||(max&&_46<_44)||(!min&&!max&&_46===_44)); }else{ return false; } }else{ return _46>0; } }else{ if("device-height"===_41.substring(l-13,l)){ _47=screen.height; if(_42!==null){ if(_43==="length"){ return ((min&&_47>=_44)||(max&&_47<_44)||(!min&&!max&&_47===_44)); }else{ return false; } }else{ return _47>0; } }else{ if("width"===_41.substring(l-5,l)){ _46=document.documentElement.clientWidth||document.body.clientWidth; if(_42!==null){ if(_43==="length"){ return ((min&&_46>=_44)||(max&&_46<_44)||(!min&&!max&&_46===_44)); }else{ return false; } }else{ return _46>0; } }else{ if("height"===_41.substring(l-6,l)){ _47=document.documentElement.clientHeight||document.body.clientHeight; if(_42!==null){ if(_43==="length"){ return ((min&&_47>=_44)||(max&&_47<_44)||(!min&&!max&&_47===_44)); }else{ return false; } }else{ return _47>0; } }else{ if("device-aspect-ratio"===_41.substring(l-19,l)){ return _43==="aspect-ratio"&&screen.width*_44[1]===screen.height*_44[0]; }else{ if("color-index"===_41.substring(l-11,l)){ var _48=Math.pow(2,screen.colorDepth); if(_42!==null){ if(_43==="absolute"){ return ((min&&_48>=_44)||(max&&_48<_44)||(!min&&!max&&_48===_44)); }else{ return false; } }else{ return _48>0; } }else{ if("color"===_41.substring(l-5,l)){ var _49=screen.colorDepth; if(_42!==null){ if(_43==="absolute"){ return ((min&&_49>=_44)||(max&&_49<_44)||(!min&&!max&&_49===_44)); }else{ return false; } }else{ return _49>0; } }else{ if("resolution"===_41.substring(l-10,l)){ var res; if(_45==="dpcm"){ res=_3d("1cm"); }else{ res=_3d("1in"); } if(_42!==null){ if(_43==="resolution"){ return ((min&&res>=_44)||(max&&res<_44)||(!min&&!max&&res===_44)); }else{ return false; } }else{ return res>0; } }else{ return false; } } } } } } } } }; var _4a=function(mq){ var _4b=mq.getValid(); var _4c=mq.getExpressions(); var l=_4c.length; if(l>0){ for(var i=0;i<l&&_4b;i++){ _4b=_40(_4c[i].mediaFeature,_4c[i].value); } var not=mq.getNot(); return (_4b&&!not||not&&!_4b); } }; var _4d=function(mql){ var mqs=mql.getMediaQueries(); var t={}; for(var i=0;i<mqs.length;i++){ if(_4a(mqs[i])){ t[mqs[i].getMediaType()]=true; } } var s=[],c=0; for(var n in t){ if(t.hasOwnProperty(n)){ if(c>0){ s[c++]=","; } s[c++]=n; } } if(s.length>0){ _39[_39.length]=cssHelper.addStyle("@media "+s.join("")+"{"+mql.getCssText()+"}",false); } }; var _4e=function(_4f){ for(var i=0;i<_4f.length;i++){ _4d(_4f[i]); } if(ua.ie){ document.documentElement.style.display="block"; setTimeout(function(){ document.documentElement.style.display=""; },0); setTimeout(function(){ cssHelper.broadcast("cssMediaQueriesTested"); },100); }else{ cssHelper.broadcast("cssMediaQueriesTested"); } }; var _50=function(){ for(var i=0;i<_39.length;i++){ cssHelper.removeStyle(_39[i]); } _39=[]; cssHelper.mediaQueryLists(_4e); }; var _51=0; var _52=function(){ var _53=cssHelper.getViewportWidth(); var _54=cssHelper.getViewportHeight(); if(ua.ie){ var el=document.createElement("div"); el.style.position="absolute"; el.style.top="-9999em"; el.style.overflow="scroll"; document.body.appendChild(el); _51=el.offsetWidth-el.clientWidth; document.body.removeChild(el); } var _55; var _56=function(){ var vpw=cssHelper.getViewportWidth(); var vph=cssHelper.getViewportHeight(); if(Math.abs(vpw-_53)>_51||Math.abs(vph-_54)>_51){ _53=vpw; _54=vph; clearTimeout(_55); _55=setTimeout(function(){ if(!_3a()){ _50(); }else{ cssHelper.broadcast("cssMediaQueriesTested"); } },500); } }; window.onresize=function(){ var x=window.onresize||function(){ }; return function(){ x(); _56(); }; }(); }; var _57=document.documentElement; _57.style.marginLeft="-32767px"; setTimeout(function(){ _57.style.marginTop=""; },20000); return function(){ if(!_3a()){ cssHelper.addListener("newStyleParsed",function(el){ _4e(el.cssHelperParsed.mediaQueryLists); }); cssHelper.addListener("cssMediaQueriesTested",function(){ if(ua.ie){ _57.style.width="1px"; } setTimeout(function(){ _57.style.width=""; _57.style.marginLeft=""; },0); cssHelper.removeListener("cssMediaQueriesTested",arguments.callee); }); _3c(); _50(); }else{ _57.style.marginLeft=""; } _52(); }; }()); try{ document.execCommand("BackgroundImageCache",false,true); } catch(e){ }
JavaScript
// JavaScript Document // ### googleAnalystics ### var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-36372185-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
JavaScript
// JavaScript Document // var storage_support = window.sessionStorage || window.localStorage; // // // // var isSupport = { // #### html5 관련 // 꼭 필요한 HTML5 그리고 HTML5 API #pubple p.247, p.262 webDB: function() { var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB; if(window.openDatabase) { return webSQL; } else if(indexedDB) { return indexedDB; } return false; }, postMessage: function() { if(typeof window.postMessage == 'undefined') { return false; } return true; }, autofocus: function() { var element = document.createElement('input'); return 'autofocus' in element; }, placeholder: function() { var element = document.createElement('input'); return 'placeholder' in element; } // 직접체크 /* window.applicationCache window.jQuery // #### dom 관련 /* querySelector: function() { var dom = document.querySelector('body') && document.querySelectorAll('p'); return dom?????? } getElementById getElementsByTagName getElementsByName getElementsByClassName */ } // jQurey 지원 필수 $(function() { // 꼭 필요한 HTML5 그리고 HTML5 API #pubple p.89 if(!isSupport.autofocus()) { $('input[autofocus = autofocus]').focus(); } // 꼭 필요한 HTML5 그리고 HTML5 API #pubple p.90 # if(!isSupport.placeholder()) { $('[placeholder]').textPlaceholder(); } }); // placeholder플러그인 : http://sbcoba.tistory.com/17 (function($) { $.fn.textPlaceholder = function() { return this.each(function() { var that = this; var placeholder = that.getAttribute('placeholder'); if (!placeholder) return; var $input = $(that); $input.attr('placeholder', ''); var $placeholderDiv = $('<div/>') .text(placeholder) .addClass('text-placeholder') .css({'position' : 'absolute', 'top':$input.position().top, 'left':$input.position().left}) .height($input.height()) .width($input.width()) .appendTo($input.parent()); $placeholderDiv.click(function() { $input.focus(); }); $input.focus(function() { $placeholderDiv.hide(); }); $input.blur(function() { if ($(this).val()==''){ $placeholderDiv.show(); } }); }); // END OF return this.each } })(jQuery);
JavaScript
// jQueryFallback.js /** * 폼검증 * 열혈강의 자바스크립트 #프리렉 p.280 * 1차 cdn 이용 실패시 즉시 적용 할 수 있도록 * 바로 뒤에서 지원여부 체크한뒤 2차 cdn경로, 최종으로 웹경로를 위치 시킨다. * <script>window.jQuery || document.write("<script src='사이트내 jquery가 위치한 경로'>\x3C/script>")</script> */ // jQueryFallback // todo: 1.서비스 할 홈 페이지 경로를 환경에 맞게 조정하세요. if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js' type='text/javascript'%3E%3C/script%3E")); } else if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='http://code.jquery.com/jquery-1.8.3.min.js' type='text/javascript'%3E%3C/script%3E")); } else if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'%3E%3C/script%3E")); } else if (typeof jQuery == 'undefined') { document.write(unescape("%3Cscript src='http://localhost/oop/common/js/jQuery.1.7.2.js' type='text/javascript'%3E%3C/script%3E")); }
JavaScript
// JavaScript Document // 가비아 모마일 리다이렉트 v 1.22 evt.add('body', 'load', 'checkScreen'); var mdomain = "http://m.printer79.com"; // 모바일용 도메인 설정 function checkScreen() { var vref = document.referrer; var vfrom="", qstring=""; // Daum, Nate등은 레퍼가 없는 상태로 넘어오기때문에 레퍼가 있는 경우에만 체크 if (vref) { if (vref.indexOf('?')!=-1) { qstring = vref.substring(vref.indexOf('?'), vref.length); // QueryString 은 그대로 전달 } var vuri = parseURI(vref); // 동일 host에서 넘어오는 경우 리다이렉트 시키지 않는다. if (vuri.host == document.domain) return; } // pc 파라미터가 활성화 된경우 PC버전 링크로 인식, 리다이렉트 시키지 않는다. vfrom = checkURI('pc'); // 안드로이드 계열 디바이스 세로 width 의 기기별 차이로 인해 480에서 640으로 변경 if (screen.width <= 640 && !vfrom) { // 해상도가 640 이하 모바일 디바이스로 분류, 레퍼없고 pc 파라미터 없으면 모바일로 접속 window.location.replace(mdomain+qstring); } else { // 해상도가 640을 초과하면 일반 웹접속으로 분류(아무 작업 없이 현재 접속 유지) } // // 단, 아이패드등의 태블릿등으로 접속한 경우 PC웹 또는 모바일 중 어느곳으로 // 접속시킬지 정책에 따라 다름. // } function checkURI(name, ref) { name = name.replace(/[\[]/,"\[").replace(/[\]]/,"\]"); var regexS = "[\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( ref ? ref : window.location.href ); if( results == null ) return ""; else return results[1]; } function parseURI (str) { var o= parseURI.options,m=o.parser[o.strictMode ? "strict" : "loose"].exec(str),uri={},i=14; while (i--) uri[o.key[i]] = m[i] || ""; uri[o.q.name] = {}; uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { if ($1) uri[o.q.name][$1] = $2; }); return uri; }; parseURI.options = { strictMode: false, key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], q: {name:"queryKey",parser: /(?:^|&)([^&=]*)=?([^&]*)/g}, parser: {strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose : /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } }; /* // ### checkMobile ### // todo: mobile에서 pc 포맷 형태로 이동할 수 있는 버튼을 만들것 // mobile > pc 모드로 이동 function isMobile() { if(document.referrer.substring(0,22) == "http://m.printer79.com" || document.referrer.substring(0,41) == "http://www.printer79.com/mobile/index.php") { location.href = "http://www.printer79.com"; } // pc > mobile 모드로 이동 ( viewport 설정 ) if(window.innerWidth && window.innerWidth <= 960) { var my_agent = navigator.userAgent.toLowerCase(); var mobile = ['android', 'iphone', 'ipod', 'blackberry', 'bada', 'iemobile', 'windows ce', 'lg', 'mot', 'samsung', 'sonyericsson','windows phone', 'nokia', 'webos', 'opera mini', 'opera mobi']; for (var word in mobile) { if (my_agent.match(mobile[word]) != null) { location.href = "http://www.printer79.com/mobile/index.php"; break; } } for (var i=0, len=mobile.length; i<len; i++) { if (my_agent.indexOf(mobile[i]) >= 0) { location.href = "http://m.printer79.com/index.php"; break; } } } } /**/ function addFavorite() { // <a href="javascript:addFavorite();">즐겨찾기에 추가</a> var url="http://www.printer79.com"; var title="프린터친구"; if(document.all) // IE { window.external.AddFavorite(url, title); } else if(window.sidebar) // FF { window.sidebar.addPanel(title, url, ""); } else if(window.opera && window.print) // OP { var elem = document.createElement('a'); elem.setAttribute('href', url); elem.setAttribute('title', title); elem.setAttribute('rel', 'sidebar'); elem.click(); } else { alert("이용하시는 웹 브라우저는 기능이 지원되지 않습니다.\n\nCtrl+D 키를 누르시면 즐겨찾기에 추가하실 수 있습니다."); return true; } } function setStartpage(obj) { // <a href="javascript:setStartpage(document.body);">시작페이지로</a> var url="http://www.printer79.com"; obj.style.behavior = 'url(#default#homepage)'; obj.setHomePage(url); } /* <input type="button" value="시작페이지로" onclick="this.style.behavior = 'url(#default#homepage)';this.setHomePage('http://www.printer79.com/');" /> <a herf="#" onMouseOver="this.style.cursor='hand';" onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.printer79.com');">시작페이지로</a> */
JavaScript
/* selectivizr v1.0.2 - (c) Keith Clark, freely distributable under the terms of the MIT license. selectivizr.com */ /* Notes about this source ----------------------- * The #DEBUG_START and #DEBUG_END comments are used to mark blocks of code that will be removed prior to building a final release version (using a pre-compression script) References: ----------- * CSS Syntax : http://www.w3.org/TR/2003/WD-css3-syntax-20030813/#style * Selectors : http://www.w3.org/TR/css3-selectors/#selectors * IE Compatability : http://msdn.microsoft.com/en-us/library/cc351024(VS.85).aspx * W3C Selector Tests : http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/html/tests/ */ (function(win) { // If browser isn't IE, then stop execution! This handles the script // being loaded by non IE browsers because the developer didn't use // conditional comments. if (/*@cc_on!@*/true) return; // =========================== Init Objects ============================ var doc = document; var root = doc.documentElement; var xhr = getXHRObject(); var ieVersion = /MSIE (\d+)/.exec(navigator.userAgent)[1]; // If were not in standards mode, IE is too old / new or we can't create // an XMLHttpRequest object then we should get out now. if (doc.compatMode != 'CSS1Compat' || ieVersion<6 || ieVersion>8 || !xhr) { return; } // ========================= Common Objects ============================ // Compatiable selector engines in order of CSS3 support. Note: '*' is // a placholder for the object key name. (basically, crude compression) var selectorEngines = { "NW" : "*.Dom.select", "MooTools" : "$$", "DOMAssistant" : "*.$", "Prototype" : "$$", "YAHOO" : "*.util.Selector.query", "Sizzle" : "*", "jQuery" : "*", "dojo" : "*.query" }; var selectorMethod; var enabledWatchers = []; // array of :enabled/:disabled elements to poll var ie6PatchID = 0; // used to solve ie6's multiple class bug var patchIE6MultipleClasses = true; // if true adds class bloat to ie6 var namespace = "slvzr"; // Stylesheet parsing regexp's var RE_COMMENT = /(\/\*[^*]*\*+([^\/][^*]*\*+)*\/)\s*/g; var RE_IMPORT = /@import\s*(?:(?:(?:url\(\s*(['"]?)(.*)\1)\s*\))|(?:(['"])(.*)\3))[^;]*;/g; var RE_ASSET_URL = /\burl\(\s*(["']?)(?!data:)([^"')]+)\1\s*\)/g; var RE_PSEUDO_STRUCTURAL = /^:(empty|(first|last|only|nth(-last)?)-(child|of-type))$/; var RE_PSEUDO_ELEMENTS = /:(:first-(?:line|letter))/g; var RE_SELECTOR_GROUP = /(^|})\s*([^\{]*?[\[:][^{]+)/g; var RE_SELECTOR_PARSE = /([ +~>])|(:[a-z-]+(?:\(.*?\)+)?)|(\[.*?\])/g; var RE_LIBRARY_INCOMPATIBLE_PSEUDOS = /(:not\()?:(hover|enabled|disabled|focus|checked|target|active|visited|first-line|first-letter)\)?/g; var RE_PATCH_CLASS_NAME_REPLACE = /[^\w-]/g; // HTML UI element regexp's var RE_INPUT_ELEMENTS = /^(INPUT|SELECT|TEXTAREA|BUTTON)$/; var RE_INPUT_CHECKABLE_TYPES = /^(checkbox|radio)$/; // Broken attribute selector implementations (IE7/8 native [^=""], [$=""] and [*=""]) var BROKEN_ATTR_IMPLEMENTATIONS = ieVersion>6 ? /[\$\^*]=(['"])\1/ : null; // Whitespace normalization regexp's var RE_TIDY_TRAILING_WHITESPACE = /([(\[+~])\s+/g; var RE_TIDY_LEADING_WHITESPACE = /\s+([)\]+~])/g; var RE_TIDY_CONSECUTIVE_WHITESPACE = /\s+/g; var RE_TIDY_TRIM_WHITESPACE = /^\s*((?:[\S\s]*\S)?)\s*$/; // String constants var EMPTY_STRING = ""; var SPACE_STRING = " "; var PLACEHOLDER_STRING = "$1"; // =========================== Patching ================================ // --[ patchStyleSheet() ]---------------------------------------------- // Scans the passed cssText for selectors that require emulation and // creates one or more patches for each matched selector. function patchStyleSheet( cssText ) { return cssText.replace(RE_PSEUDO_ELEMENTS, PLACEHOLDER_STRING). replace(RE_SELECTOR_GROUP, function(m, prefix, selectorText) { var selectorGroups = selectorText.split(","); for (var c = 0, cs = selectorGroups.length; c < cs; c++) { var selector = normalizeSelectorWhitespace(selectorGroups[c]) + SPACE_STRING; var patches = []; selectorGroups[c] = selector.replace(RE_SELECTOR_PARSE, function(match, combinator, pseudo, attribute, index) { if (combinator) { if (patches.length>0) { applyPatches( selector.substring(0, index), patches ); patches = []; } return combinator; } else { var patch = (pseudo) ? patchPseudoClass( pseudo ) : patchAttribute( attribute ); if (patch) { patches.push(patch); return "." + patch.className; } return match; } } ); } return prefix + selectorGroups.join(","); }); }; // --[ patchAttribute() ]----------------------------------------------- // returns a patch for an attribute selector. function patchAttribute( attr ) { return (!BROKEN_ATTR_IMPLEMENTATIONS || BROKEN_ATTR_IMPLEMENTATIONS.test(attr)) ? { className: createClassName(attr), applyClass: true } : null; }; // --[ patchPseudoClass() ]--------------------------------------------- // returns a patch for a pseudo-class function patchPseudoClass( pseudo ) { var applyClass = true; var className = createClassName(pseudo.slice(1)); var isNegated = pseudo.substring(0, 5) == ":not("; var activateEventName; var deactivateEventName; // if negated, remove :not() if (isNegated) { pseudo = pseudo.slice(5, -1); } // bracket contents are irrelevant - remove them var bracketIndex = pseudo.indexOf("(") if (bracketIndex > -1) { pseudo = pseudo.substring(0, bracketIndex); } // check we're still dealing with a pseudo-class if (pseudo.charAt(0) == ":") { switch (pseudo.slice(1)) { case "root": applyClass = function(e) { return isNegated ? e != root : e == root; } break; case "target": // :target is only supported in IE8 if (ieVersion == 8) { applyClass = function(e) { var handler = function() { var hash = location.hash; var hashID = hash.slice(1); return isNegated ? (hash == EMPTY_STRING || e.id != hashID) : (hash != EMPTY_STRING && e.id == hashID); }; addEvent( win, "hashchange", function() { toggleElementClass(e, className, handler()); }) return handler(); } break; } return false; case "checked": applyClass = function(e) { if (RE_INPUT_CHECKABLE_TYPES.test(e.type)) { addEvent( e, "propertychange", function() { if (event.propertyName == "checked") { toggleElementClass( e, className, e.checked !== isNegated ); } }) } return e.checked !== isNegated; } break; case "disabled": isNegated = !isNegated; case "enabled": applyClass = function(e) { if (RE_INPUT_ELEMENTS.test(e.tagName)) { addEvent( e, "propertychange", function() { if (event.propertyName == "$disabled") { toggleElementClass( e, className, e.$disabled === isNegated ); } }); enabledWatchers.push(e); e.$disabled = e.disabled; return e.disabled === isNegated; } return pseudo == ":enabled" ? isNegated : !isNegated; } break; case "focus": activateEventName = "focus"; deactivateEventName = "blur"; case "hover": if (!activateEventName) { activateEventName = "mouseenter"; deactivateEventName = "mouseleave"; } applyClass = function(e) { addEvent( e, isNegated ? deactivateEventName : activateEventName, function() { toggleElementClass( e, className, true ); }) addEvent( e, isNegated ? activateEventName : deactivateEventName, function() { toggleElementClass( e, className, false ); }) return isNegated; } break; // everything else default: // If we don't support this pseudo-class don't create // a patch for it if (!RE_PSEUDO_STRUCTURAL.test(pseudo)) { return false; } break; } } return { className: className, applyClass: applyClass }; }; // --[ applyPatches() ]------------------------------------------------- // uses the passed selector text to find DOM nodes and patch them function applyPatches(selectorText, patches) { var elms; // Although some selector libraries can find :checked :enabled etc. // we need to find all elements that could have that state because // it can be changed by the user. var domSelectorText = selectorText.replace(RE_LIBRARY_INCOMPATIBLE_PSEUDOS, EMPTY_STRING); // If the dom selector equates to an empty string or ends with // whitespace then we need to append a universal selector (*) to it. if (domSelectorText == EMPTY_STRING || domSelectorText.charAt(domSelectorText.length - 1) == SPACE_STRING) { domSelectorText += "*"; } // Ensure we catch errors from the selector library try { elms = selectorMethod( domSelectorText ); } catch (ex) { // #DEBUG_START log( "Selector '" + selectorText + "' threw exception '" + ex + "'" ); // #DEBUG_END } if (elms) { for (var d = 0, dl = elms.length; d < dl; d++) { var elm = elms[d]; var cssClasses = elm.className; for (var f = 0, fl = patches.length; f < fl; f++) { var patch = patches[f]; if (!hasPatch(elm, patch)) { if (patch.applyClass && (patch.applyClass === true || patch.applyClass(elm) === true)) { cssClasses = toggleClass(cssClasses, patch.className, true ); } } } elm.className = cssClasses; } } }; // --[ hasPatch() ]----------------------------------------------------- // checks for the exsistence of a patch on an element function hasPatch( elm, patch ) { return new RegExp("(^|\\s)" + patch.className + "(\\s|$)").test(elm.className); }; // =========================== Utility ================================= function createClassName( className ) { return namespace + "-" + ((ieVersion == 6 && patchIE6MultipleClasses) ? ie6PatchID++ : className.replace(RE_PATCH_CLASS_NAME_REPLACE, function(a) { return a.charCodeAt(0) })); }; // --[ log() ]---------------------------------------------------------- // #DEBUG_START function log( message ) { if (win.console) { win.console.log(message); } }; // #DEBUG_END // --[ trim() ]--------------------------------------------------------- // removes leading, trailing whitespace from a string function trim( text ) { return text.replace(RE_TIDY_TRIM_WHITESPACE, PLACEHOLDER_STRING); }; // --[ normalizeWhitespace() ]------------------------------------------ // removes leading, trailing and consecutive whitespace from a string function normalizeWhitespace( text ) { return trim(text).replace(RE_TIDY_CONSECUTIVE_WHITESPACE, SPACE_STRING); }; // --[ normalizeSelectorWhitespace() ]---------------------------------- // tidies whitespace around selector brackets and combinators function normalizeSelectorWhitespace( selectorText ) { return normalizeWhitespace(selectorText. replace(RE_TIDY_TRAILING_WHITESPACE, PLACEHOLDER_STRING). replace(RE_TIDY_LEADING_WHITESPACE, PLACEHOLDER_STRING) ); }; // --[ toggleElementClass() ]------------------------------------------- // toggles a single className on an element function toggleElementClass( elm, className, on ) { var oldClassName = elm.className; var newClassName = toggleClass(oldClassName, className, on); if (newClassName != oldClassName) { elm.className = newClassName; elm.parentNode.className += EMPTY_STRING; } }; // --[ toggleClass() ]-------------------------------------------------- // adds / removes a className from a string of classNames. Used to // manage multiple class changes without forcing a DOM redraw function toggleClass( classList, className, on ) { var re = RegExp("(^|\\s)" + className + "(\\s|$)"); var classExists = re.test(classList); if (on) { return classExists ? classList : classList + SPACE_STRING + className; } else { return classExists ? trim(classList.replace(re, PLACEHOLDER_STRING)) : classList; } }; // --[ addEvent() ]----------------------------------------------------- function addEvent(elm, eventName, eventHandler) { elm.attachEvent("on" + eventName, eventHandler); }; // --[ getXHRObject() ]------------------------------------------------- function getXHRObject() { if (win.XMLHttpRequest) { return new XMLHttpRequest; } try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) { return null; } }; // --[ loadStyleSheet() ]----------------------------------------------- function loadStyleSheet( url ) { xhr.open("GET", url, false); xhr.send(); return (xhr.status==200) ? xhr.responseText : EMPTY_STRING; }; // --[ resolveUrl() ]--------------------------------------------------- // Converts a URL fragment to a fully qualified URL using the specified // context URL. Returns null if same-origin policy is broken function resolveUrl( url, contextUrl ) { function getProtocolAndHost( url ) { return url.substring(0, url.indexOf("/", 8)); }; // absolute path if (/^https?:\/\//i.test(url)) { return getProtocolAndHost(contextUrl) == getProtocolAndHost(url) ? url : null; } // root-relative path if (url.charAt(0)=="/") { return getProtocolAndHost(contextUrl) + url; } // relative path var contextUrlPath = contextUrl.split(/[?#]/)[0]; // ignore query string in the contextUrl if (url.charAt(0) != "?" && contextUrlPath.charAt(contextUrlPath.length - 1) != "/") { contextUrlPath = contextUrlPath.substring(0, contextUrlPath.lastIndexOf("/") + 1); } return contextUrlPath + url; }; // --[ parseStyleSheet() ]---------------------------------------------- // Downloads the stylesheet specified by the URL, removes it's comments // and recursivly replaces @import rules with their contents, ultimately // returning the full cssText. function parseStyleSheet( url ) { if (url) { return loadStyleSheet(url).replace(RE_COMMENT, EMPTY_STRING). replace(RE_IMPORT, function( match, quoteChar, importUrl, quoteChar2, importUrl2 ) { return parseStyleSheet(resolveUrl(importUrl || importUrl2, url)); }). replace(RE_ASSET_URL, function( match, quoteChar, assetUrl ) { quoteChar = quoteChar || EMPTY_STRING; return " url(" + quoteChar + resolveUrl(assetUrl, url) + quoteChar + ") "; }); } return EMPTY_STRING; }; // --[ init() ]--------------------------------------------------------- function init() { // honour the <base> tag var url, stylesheet; var baseTags = doc.getElementsByTagName("BASE"); var baseUrl = (baseTags.length > 0) ? baseTags[0].href : doc.location.href; /* Note: This code prevents IE from freezing / crashing when using @font-face .eot files but it modifies the <head> tag and could trigger the IE stylesheet limit. It will also cause FOUC issues. If you choose to use it, make sure you comment out the for loop directly below this comment. var head = doc.getElementsByTagName("head")[0]; for (var c=doc.styleSheets.length-1; c>=0; c--) { stylesheet = doc.styleSheets[c] head.appendChild(doc.createElement("style")) var patchedStylesheet = doc.styleSheets[doc.styleSheets.length-1]; if (stylesheet.href != EMPTY_STRING) { url = resolveUrl(stylesheet.href, baseUrl) if (url) { patchedStylesheet.cssText = patchStyleSheet( parseStyleSheet( url ) ) stylesheet.disabled = true setTimeout( function () { stylesheet.owningElement.parentNode.removeChild(stylesheet.owningElement) }) } } } */ for (var c = 0; c < doc.styleSheets.length; c++) { stylesheet = doc.styleSheets[c] if (stylesheet.href != EMPTY_STRING) { url = resolveUrl(stylesheet.href, baseUrl); if (url) { stylesheet.cssText = patchStyleSheet( parseStyleSheet( url ) ); } } } // :enabled & :disabled polling script (since we can't hook // onpropertychange event when an element is disabled) if (enabledWatchers.length > 0) { setInterval( function() { for (var c = 0, cl = enabledWatchers.length; c < cl; c++) { var e = enabledWatchers[c]; if (e.disabled !== e.$disabled) { if (e.disabled) { e.disabled = false; e.$disabled = true; e.disabled = true; } else { e.$disabled = e.disabled; } } } },250) } }; // Bind selectivizr to the ContentLoaded event. ContentLoaded(win, function() { // Determine the "best fit" selector engine for (var engine in selectorEngines) { var members, member, context = win; if (win[engine]) { members = selectorEngines[engine].replace("*", engine).split("."); while ((member = members.shift()) && (context = context[member])) {} if (typeof context == "function") { selectorMethod = context; init(); return; } } } }); /*! * ContentLoaded.js by Diego Perini, modified for IE<9 only (to save space) * * Author: Diego Perini (diego.perini at gmail.com) * Summary: cross-browser wrapper for DOMContentLoaded * Updated: 20101020 * License: MIT * Version: 1.2 * * URL: * http://javascript.nwbox.com/ContentLoaded/ * http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE * */ // @w window reference // @f function reference function ContentLoaded(win, fn) { var done = false, top = true, init = function(e) { if (e.type == "readystatechange" && doc.readyState != "complete") return; (e.type == "load" ? win : doc).detachEvent("on" + e.type, init, false); if (!done && (done = true)) fn.call(win, e.type || e); }, poll = function() { try { root.doScroll("left"); } catch(e) { setTimeout(poll, 50); return; } init('poll'); }; if (doc.readyState == "complete") fn.call(win, EMPTY_STRING); else { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch(e) { } if (top) poll(); } addEvent(doc,"readystatechange", init); addEvent(win,"load", init); } }; })(this);
JavaScript
/* json2.js 2012-10-08 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 '&nbsp;'), 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, regexp: true */ /*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 (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; 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) { if (typeof rep[i] === 'string') { k = rep[i]; 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.prototype.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.prototype.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
// Improvements/bug-fixes since book publication. // // Use of the 'backgroundColor' property has been replaced with // 'background' because it works exactly the same way when used // with a color, and is therefore shorter and faster. // // In Initialize() the mouse is also captured by the onscroll // event (and by the onmousewheel event for IE), so that using // a mouse scroll wheel is also captured. // // The O() function now handles certain object cases better. // // In the function CleanupString() the spacestosingle option // has been improved to work with all whitespace. // // For Opera & Chrome: The FieldPrompt() function forces the width // of the input to the current width to prevent these browsers // changing the width as they switch between normal and italic // text. // // The Ajax functions had a spurious ID argument left in from // earlier versions, which is now removed. // // Amended TextType() to use Html not .innerText for IE // // Added OnDOMReady() function - much faster than window.onload function O(id, property, value) { if (id instanceof Array) { var tmp = [] for (var j = 0 ; j < id.length ; ++j) tmp.push(O(id[j], property, value)) return tmp } if (typeof property != UNDEF && typeof value != UNDEF) { if (typeof value == 'string') value = "'" + value + "'" if (typeof id == 'object') return eval(id.property = value) else return eval("O('" + id + "')." + property + " = " + value) } if (typeof id == 'object') return id else { try { return document.getElementById(id) } catch(e) { alert('PJ - Unknown ID: ' + id) } } } function S(id, property, value) { if (id instanceof Array) { var tmp = [] for (var j = 0 ; j < id.length ; ++j) tmp.push(S(id[j], property, value)) return tmp } if (typeof property != UNDEF && typeof value != UNDEF) { try { return O(id).style[property] = value } catch(e) { alert('PJ - Unknown ID: ' + id) } } else if (typeof id == 'object') return id.style else { try { return O(id).style } catch(e) { alert('PJ - Unknown ID: ' + id) } } } function Initialize() { MOUSE_DOWN = false MOUSE_IN = true MOUSE_X = 0 MOUSE_Y = 0 SCROLL_X = 0 SCROLL_Y = 0 KEY_PRESS = '' ZINDEX = 1000 CHAIN_CALLS = [] INTERVAL = 30 UNDEF = 'undefined' HID = 'hidden' VIS = 'visible' ABS = 'absolute' FIX = 'fixed' REL = 'relative' STA = 'static' INH = 'inherit' TP = 'top' BM = 'bottom' LT = 'left' RT = 'right' if (document.all) BROWSER = 'IE' else if (window.opera) BROWSER = 'Opera' else if (NavCheck('Chrome')) BROWSER = 'Chrome' else if (NavCheck('iPod')) BROWSER = 'iPod' else if (NavCheck('iPhone')) BROWSER = 'iPhone' else if (NavCheck('iPad')) BROWSER = 'iPad' else if (NavCheck('Android')) BROWSER = 'Android' else if (NavCheck('Safari')) BROWSER = 'Safari' else if (NavCheck('Gecko')) BROWSER = 'Firefox' else BROWSER = 'UNKNOWN' document.onmousemove = CaptureMouse document.onscroll = CaptureMouse document.onmousewheel = CaptureMouse document.onkeydown = CaptureKeyboard document.onkeypress = CaptureKeyboard document.onmouseout = function() { MOUSE_IN = false } document.onmouseover = function() { MOUSE_IN = true } document.onmouseup = function() { MOUSE_DOWN = false } document.onmousedown = function() { MOUSE_DOWN = true } function NavCheck(check) { return navigator.userAgent.indexOf(check) != -1 } } function CaptureMouse(e) { if (BROWSER == 'IE') { SCROLL_X = document.documentElement.scrollLeft SCROLL_Y = document.documentElement.scrollTop MOUSE_X = window.event.clientX + SCROLL_X MOUSE_Y = window.event.clientY + SCROLL_Y } else { SCROLL_X = window.pageXOffset SCROLL_Y = window.pageYOffset MOUSE_X = e.pageX MOUSE_Y = e.pageY } return true } function CaptureKeyboard(e) { if (BROWSER == 'IE') { KEY_PRESS = FromKeyCode(window.event.keyCode) if (KEY_PRESS > 0) KEY_PRESS = String.fromCharCode(KEY_PRESS) } else { if (e.charCode) KEY_PRESS = String.fromCharCode(e.charCode) else if (e.keyCode) KEY_PRESS = FromKeyCode(e.keyCode) } return true } function FromKeyCode(c) { switch (c) { case 8: return 'Backspace' case 9: return 'Tab' case 12: return 'Center' case 13: return 'Enter' case 16: return 'Shift' case 17: return 'Control' case 18: return 'Alt' case 19: return 'Pause' case 20: return 'Capslock' case 27: return 'Esc' case 33: return 'PgUp' case 34: return 'PgDn' case 35: return 'End' case 36: return 'Home' case 37: return 'left' case 38: return 'Up' case 39: return 'Right' case 40: return 'Down' case 45: return 'Ins' case 46: return 'Del' case 91: return 'Windows' case 93: return 'Menu' case 144: return 'Numlock' } return c } function GetLastKey() { var k = KEY_PRESS KEY_PRESS = '' return k } function PreventAction(id, type, onoff) { if (type == 'drag' || type == 'both') { if (onoff == true) { if (typeof O(id).ondragstart != UNDEF) O(id).ondragstart = function() { return false } else O(id).onmousedown = function() { return false } } else { if (typeof O(id).ondragstart != UNDEF) O(id).ondragstart = '' else O(id).onmousedown = '' } } if (type == 'select' || type == 'both') { if (onoff == true) { if (typeof O(id).onselectstart != UNDEF) O(id).onselectstart = function() { return false } else if (typeof S(id).MozUserSelect != UNDEF) S(id).MozUserSelect = 'none' else O(id).onmousedown = function() { return false } } else { if (typeof O(id).onselectstart != UNDEF) O(id).onselectstart = '' else if (typeof S(id).MozUserSelect != UNDEF) S(id).MozUserSelect = 'text' else O(id).onmousedown = '' } } } function NoPx(value) { return value.replace(/px/, '') * 1 } function Px(value) { return value + 'px' } function X(id) { var obj = O(id) var offset = obj.offsetLeft if (obj.offsetParent) while(obj = obj.offsetParent) offset += obj.offsetLeft return offset } function Y(id) { var obj = O(id) var offset = obj.offsetTop if (obj.offsetParent) while(obj = obj.offsetParent) offset += obj.offsetTop return offset } function W(id) { var width = O(id).offsetWidth + NoPx(S(id).marginLeft) + NoPx(S(id).marginRight) var bord = NoPx(S(id).borderLeftWidth) + NoPx(S(id).borderRightWidth) if (bord > 0) width -= bord else if (O(id).border) width -= O(id).border * 2 return width } function H(id) { var height = O(id).offsetHeight + NoPx(S(id).marginTop) + NoPx(S(id).marginBottom) var bord = NoPx(S(id).borderTopWidth) + NoPx(S(id).borderBottomWidth) if (bord > 0) height -= bord else if(O(id).border) height -= O(id).border * 2 return height } function Html(id, value) { if (typeof value != UNDEF) O(id).innerHTML = value return O(id).innerHTML } function SaveState(id) { O(id).Save_left = S(id).left O(id).Save_top = S(id).top O(id).Save_visibility = S(id).visibility O(id).Save_color = S(id).color O(id).Save_background = S(id).background O(id).Save_display = S(id).display O(id).Save_opacity = S(id).opacity O(id).Save_MozOpacity = S(id).MozOpacity O(id).Save_KhtmlOpacity = S(id).KhtmlOpacity O(id).Save_filter = S(id).filter O(id).Save_zIndex = S(id).zIndex } function RestoreState(id) { S(id).left = O(id).Save_left S(id).top = O(id).Save_top S(id).visibility = O(id).Save_visibility S(id).color = O(id).Save_color S(id).background = O(id).Save_background S(id).display = O(id).Save_display S(id).opacity = O(id).Save_opacity S(id).MozOpacity = O(id).Save_MozOpacity S(id).KhtmlOpacity = O(id).Save_KhtmlOpacity S(id).filter = O(id).Save_filter S(id).zIndex = O(id).Save_zIndex } function InsVars() { var tmp = arguments[0] for (var j = 1 ; j < arguments.length ; ++j) tmp = tmp.replace(new RegExp('#' + j, 'g'), arguments[j]) return tmp } function StrRepeat(str, num) { var tmp = '' for (var j = 0 ; j < num ; ++j) tmp += str return tmp } function HexDec(n) { return(parseInt(n, 16)) } function DecHex(n) { return (n < 16 ? '0' : '') + n.toString(16) } function ResizeWidth(id, width) { S(id, 'overflow', HID) S(id, 'width', Px(width)) } function ResizeHeight(id, height) { S(id, 'overflow', HID) S(id, 'height', Px(height)) } function Resize(id, width, height) { ResizeWidth(id, width) ResizeHeight(id, height) } function Position(id, type) { S(id, 'position', type) } function GoTo(id, x, y) { S(id, 'left', Px(x)) S(id, 'top', Px(y)) } function Locate(id, type, x, y) { Position(id, type) GoTo(id, x, y) } function GetWindowWidth() { var de = document.documentElement if (BROWSER != 'IE') { var barwidth = de.scrollHeight > de.clientHeight ? 17 : 0 return window.innerWidth - barwidth } return de.clientWidth || document.body.clientWidth } function GetWindowHeight() { var de = document.documentElement if (BROWSER != 'IE') { var barwidth = de.scrollWidth > de.clientWidth ? 17 : 0 return window.innerHeight - barwidth } return de.clientHeight || document.body.clientHeight } function GoToEdge(id, where, percent) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) GoToEdge(id[j], where, percent) return } var width = GetWindowWidth() - W(id) var height = GetWindowHeight() - H(id) var amount = percent / 100 switch(where) { case TP: var x = width * amount var y = 0 break case BM: var x = width * amount var y = height break case LT: var x = 0 var y = height * amount break case RT: var x = width var y = height * amount } GoTo(id, x, y) } function CenterX(id) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) CenterX(id[j]) return } S(id).left = Px(Math.round((GetWindowWidth() - W(id))) / 2 + SCROLL_X) } function CenterY(id) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) CenterY(id[j]) return } S(id).top = Px(Math.round((GetWindowHeight() - H(id))) / 2 + SCROLL_Y) } function Center(id) { CenterX(id) CenterY(id) } function Invisible(id) { S(id, 'visibility', HID) } function Visible(id) { S(id, 'visibility', VIS) } function VisibilityToggle(id) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) VisibilityToggle(id[j]) return } S(id).visibility = (S(id).visibility == HID) ? VIS : HID } function Opacity(id, percent) { S(id, 'opacity', percent / 100) S(id, 'MozOpacity', percent / 100) S(id, 'KhtmlOpacity', percent / 100) S(id, 'filter', InsVars("alpha(opacity = '#1')", percent)) } function Fade(id, start, end, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Fade(id[j], start, end, msecs, interruptible, CB) return } var stepval = Math.abs(start - end) / (msecs / INTERVAL) if (O(id).FA_Flag) { if (!O(id).FA_Int) return clearInterval(O(id).FA_IID) O(id).FA_Start = O(id).FA_Level } else { O(id).FA_Start = start O(id).FA_Level = start } O(id).FA_Flag = true O(id).FA_End = end O(id).FA_Int = interruptible O(id).FA_Step = end > O(id).FA_Start ? stepval : -stepval O(id).Fadeout = end < O(id).FA_Start ? true : false O(id).FA_IID = setInterval(DoFade, INTERVAL) function DoFade() { O(id).FA_Level += O(id).FA_Step if (O(id).FA_Level >= Math.max(O(id).FA_Start, O(id).FA_End) || O(id).FA_Level <= Math.min(O(id).FA_Start, O(id).FA_End)) { O(id).FA_Level = O(id).FA_End O(id).FA_Flag = false clearInterval(O(id).FA_IID) if (typeof CB != UNDEF) eval(CB) } Opacity(id, O(id).FA_Level) } } function FadeOut(id, msecs, interruptible, CB) { Fade(id, 100, 0, msecs, interruptible, CB) } function FadeIn(id, msecs, interruptible, CB) { Fade(id, 0, 100, msecs, interruptible, CB) } function FadeToggle(id, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) FadeToggle(id[j], msecs, interruptible, CB) return } if (O(id).Fadeout) FadeIn( id, msecs, interruptible, CB) else FadeOut(id, msecs, interruptible, CB) } function FadeBetween(id1, id2, msecs, interruptible, CB) { FadeOut(id1, msecs, interruptible, CB) FadeIn( id2, msecs, interruptible, CB) } function Hide(id, CB) { S(id, 'display', 'none') O(id, 'HI_Flag', true) if (typeof CB != UNDEF) eval(CB) } function Show(id, CB) { S(id, 'display', 'block') O(id, 'HI_Flag', false) } function HideToggle(id, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) HideToggle(id[j], CB) return } if (S(id).display != 'none') Hide(id, CB) else Show(id, CB) } function Slide(id, frx, fry, tox, toy, msecs, interruptible, CB) { if (O(id).SL_Flag) { if (!O(id).SL_Int) return else clearInterval(O(id).SL_IID) var len1 = Distance(tox - frx, toy - fry) frx = X(id) fry = Y(id) var len2 = Distance(tox - frx, toy - fry) msecs *= len2 / len1 } var stepx = (tox - frx) / (msecs / INTERVAL) var stepy = (toy - fry) / (msecs / INTERVAL) var count = 0 O(id).SL_Int = interruptible O(id).SL_Flag = true O(id).SL_IID = setInterval(DoSlide, INTERVAL) function Distance(x, y) { x = Math.max(1, x) y = Math.max(1, y) return Math.round(Math.sqrt(Math.abs(x * x) + Math.abs(y * y))) } function DoSlide() { GoTo(id, frx + stepx * count, fry + stepy * count) if (count++ >= (msecs / INTERVAL)) { O(id).SL_Flag = false GoTo(id, tox, toy) clearInterval(O(id).SL_IID) if (typeof CB != UNDEF) eval(CB) } } } function SlideBetween(id1, id2, msecs, interruptible, CB) { if (O(id1).SL_Flag || O(id2).SL_Flag) { if (!O(id1).SL_Int || !O(id2).SL_Int) return var t1 = O(id1).SB_X var t2 = O(id1).SB_Y O(id1).SB_X = O(id2).SB_X O(id1).SB_Y = O(id2).SB_Y O(id2).SB_X = t1 O(id2).SB_Y = t2 } else { O(id1).SB_X = X(id1) O(id1).SB_Y = Y(id1) O(id2).SB_X = X(id2) O(id2).SB_Y = Y(id2) } var x1 = O(id1).SB_X var y1 = O(id1).SB_Y var x2 = O(id2).SB_X var y2 = O(id2).SB_Y Slide(id1, x1, y1, x2, y2, msecs, interruptible, CB) Slide(id2, x2, y2, x1, y1, msecs, interruptible, CB) } function Deflate(id, w, h, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Deflate(id[j], w, h, msecs, interruptible, CB) return } if (!w) ResizeWidth( id, W(id)) if (!h) ResizeHeight(id, H(id)) if (O(id).DF_Flag) { if (!O(id).DF_Int) return else clearInterval(O(id).DF_IID) } else { if (w) O(id).DF_OldW = W(id) if (h) O(id).DF_OldH = H(id) O(id).DF_Count = msecs / INTERVAL } var stepw = O(id).DF_OldW / (msecs / INTERVAL) var steph = O(id).DF_OldH / (msecs / INTERVAL) S(id).overflow = HID O(id).Deflated = true O(id).DF_Flag = true O(id).DF_Int = interruptible O(id).DF_IID = setInterval(DoDeflate, INTERVAL) function DoDeflate() { if (w) ResizeWidth( id, stepw * O(id).DF_Count) if (h) ResizeHeight(id, steph * O(id).DF_Count) if (O(id).DF_Count-- < 1) { O(id).DF_Flag = false if (w) ResizeWidth( id, 0) if (h) ResizeHeight(id, 0) clearInterval(O(id).DF_IID) if (typeof CB != UNDEF) eval(CB) } } } function Reflate(id, w, h, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Reflate(id[j], w, h, msecs, interruptible, CB) return } if (!O(id).Deflated) return else if (O(id).DF_Flag) { if (!O(id).DF_Int) return else clearInterval(O(id).DF_IID) } else O(id).DF_Count = 0 var stepw = O(id).DF_OldW / (msecs / INTERVAL) var steph = O(id).DF_OldH / (msecs / INTERVAL) O(id).DF_Flag = true O(id).Deflated = false O(id).DF_Int = interruptible O(id).DF_IID = setInterval(DoReflate, INTERVAL) function DoReflate() { if (w) ResizeWidth( id, stepw * O(id).DF_Count) if (h) ResizeHeight(id, steph * O(id).DF_Count) if (O(id).DF_Count++ >= msecs / INTERVAL) { O(id).DF_Flag = false if (w) ResizeWidth( id, O(id).DF_OldW) if (h) ResizeHeight(id, O(id).DF_OldH) clearInterval(O(id).DF_IID) if (typeof CB != UNDEF) eval(CB) } } } function DeflateToggle(id, w, h, msecs, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) DeflateToggle(id[j], w, h, msecs, interruptible, CB) return } if (O(id).Deflated) Reflate(id, w, h, msecs, interruptible, CB) else Deflate(id, w, h, msecs, interruptible, CB) } function DeflateBetween(id1, id2, w, h, msecs, interruptible, CB) { Deflate(id1, w, h, msecs, interruptible, CB) Reflate(id2, w, h, msecs, interruptible, CB) } function Zoom(id, w, h, fromw, fromh, tow, toh, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) Zoom(id[j], w, h, fromw, fromh, tow, toh, msecs, pad, interruptible, CB) return } if (typeof O(id).ZO_X == UNDEF) { O(id).ZO_X = X(id) O(id).ZO_Y = Y(id) } if (!O(id).ZO_Flag) { O(id).ZO_W = Math.max(fromw, tow) O(id).ZO_H = Math.max(fromh, toh) O(id).ZO_Count = 0 } else { if (!O(id).ZO_Int) return else clearInterval(O(id).ZO_IID) O(id).ZO_Count = (msecs / INTERVAL) - O(id).ZO_Count } var maxw = Math.max(fromw, tow) var maxh = Math.max(fromh, toh) var stepw = (tow - fromw) / (msecs / INTERVAL) var steph = (toh - fromh) / (msecs / INTERVAL) S(id).overflow = HID O(id).ZO_Flag = true O(id).ZO_Int = interruptible O(id).ZO_IID = setInterval(DoZoom, INTERVAL) function DoZoom() { if (w) O(id).ZO_W = Math.round(fromw + stepw * O(id).ZO_Count) if (h) O(id).ZO_H = Math.round(fromh + steph * O(id).ZO_Count) Resize(id, O(id).ZO_W, O(id).ZO_H) var midx = O(id).ZO_X + Math.round((maxw - O(id).ZO_W) / 2) var midy = O(id).ZO_Y + Math.round((maxh - O(id).ZO_H) / 2) if (pad > 0) ZoomPad(Math.max(fromw, tow), Math.max(fromh, toh), O(id).ZO_W, O(id).ZO_H) else if (pad != -1) GoTo(id, midx, midy) if (O(id).DB_Parent) GoToEdge(O(id).DB_Parent, O(id).DB_Where, 50) if (++O(id).ZO_Count >= (msecs / INTERVAL)) { var endx = O(id).ZO_X + Math.round((maxw - tow) / 2) var endy = O(id).ZO_Y + Math.round((maxh - toh) / 2) O(id).ZO_Flag = false Resize(id, tow, toh) clearInterval(O(id).ZO_IID) if (pad > 0) ZoomPad(fromw, fromh, tow, toh) else if (pad != -1) GoTo(id, endx, endy) if (O(id).DB_Parent) GoToEdge(O(id).DB_Parent, O(id).DB_Where, 50) if (typeof CB != UNDEF) eval(CB) } function ZoomPad(frw, frh, padw, padh) { var left = Math.max(0, frw - Math.round(padw)) / 2 var right = left var top = Math.max(0, frh - Math.round(padh)) / 2 var bottom = top if (left != Math.floor(left)) { left = Math.floor(left) right = left + 1 } if (top != Math.floor(top)) { top = Math.floor(top) bottom = top + 1 } S(id).paddingLeft = Px(left) S(id).paddingRight = Px(right) S(id).paddingTop = Px(top) S(id).paddingBottom = Px(bottom) } } } function ZoomDown(id, w, h, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ZoomDown(id[j], w, h, msecs, pad, interruptible, CB) return } if (O(id).ZO_Flag && !O(id).ZO_Int) return else if (!O(id).ZO_OldW) { O(id).ZO_OldW = W(id) O(id).ZO_OldH = H(id) O(id).ZO_X = X(id) O(id).ZO_Y = Y(id) } O(id).Zoomdown = true GoTo(id, O(id).ZO_X, O(id).ZO_Y) Zoom(id, w, h, O(id).ZO_OldW, O(id).ZO_OldH, 0, 0, msecs, pad, interruptible, CB) } function ZoomRestore(id, w, h, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ZoomRestore(id[j], w, h, msecs, pad, interruptible, CB) return } if ((O(id).ZO_Flag && !O(id).ZO_Int) || !O(id).Zoomdown) return O(id).Zoomdown = false Zoom(id, w, h, 0, 0, O(id).ZO_OldW, O(id).ZO_OldH, msecs, pad, interruptible, CB) } function ZoomToggle(id, w, h, msecs, pad, interruptible, CB) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ZoomToggle(id[j], w, h, msecs, pad, interruptible, CB) return } if (O(id).ZO_Flag && !O(id).ZO_Int) return if (!O(id).Zoomdown) ZoomDown(id, w, h, msecs, pad, interruptible, CB) else ZoomRestore(id, w, h, msecs, pad, interruptible, CB) } function Chain(calls) { for (var j = calls.length ; j >= 0 ; --j) if (calls[j]) CHAIN_CALLS.push(calls[j]) NextInChain() } function NextInChain() { if (CHAIN_CALLS.length) CallBack(CHAIN_CALLS.pop()) } function CallBack(expr) { var insert = expr.lastIndexOf(')') var left = expr.substr(0, insert) var right = expr.substr(insert) var middle = "'NextInChain()'" if (expr.substr(insert - 1, 1) != '(') middle = ', ' + middle eval(left + middle + right) } function ChainThis(expr) { eval(expr) NextInChain() } function Repeat(number, calls) { var temp = calls for (var j = 1 ; j < number ; ++j) calls = calls.concat(temp) Chain(calls) } function While(expr, calls) { if (eval(expr)) { var temp = '' for (var j = 0 ; j < calls.length ; ++j) temp += '"' + calls[j].replace(/"/g, '\\\"') + '",' temp = temp.substr(0, temp.length -1) calls.push(InsVars("While('#1', Array(#2))", expr, temp)) Chain(calls) } } function Pause(wait) { setTimeout("NextInChain()", wait) } function WaitKey() { GetLastKey() setTimeout(DoWaitKey, INTERVAL) function DoWaitKey() { if (KEY_PRESS != '') NextInChain() else setTimeout(DoWaitKey, INTERVAL) } } function Flip(id1, id2, w, h, msecs, pad) { if (O(id1).ZO_Flag || O(id2).ZO_Flag) return var swap = "ChainThis('VisibilityToggle(\"#1\")')" var fast = "ZoomToggle('#1', #2, #3, 1, #4, 0)" var slow = "ZoomToggle('#1', #2, #3, #4, #5, 0)" Chain(Array( InsVars(slow, id1, w, h, msecs / 2, pad), InsVars(fast, id2, w, h, pad), InsVars(swap, id2 ), InsVars(slow, id2, w, h, msecs / 2, pad), InsVars(swap, id1 ), InsVars(fast, id1, w, h, pad) )) } function HoverSlide(id, where, offset, showing, msecs) { var w = GetWindowWidth() - W(id) var h = GetWindowHeight() - H(id) var o = offset[0] != '%' ? 0 : offset.substr(1) / 100 if (where == LT || where == RT) { var t = W(id) - showing var u = Math.min(t, msecs / INTERVAL) var x = where == LT ? -t : w + t var y = o ? h * o : offset var s = t / u } else { var t = H(id) - showing var u = Math.min(t, msecs / INTERVAL) var x = o ? w * o : offset var y = where == TP ? -t : h + t var s = t / u } GoTo(id, x, y) O(id).HS_X = x O(id).HS_Y = y O(id).onmouseover = SlideIn O(id).onmouseout = SlideOut function SlideIn() { if (O(id).HS_IID) clearInterval(O(id).HS_IID) O(id).HS_IID = setInterval(DoSlideIn, INTERVAL) function DoSlideIn() { var ox = O(id).HS_X var oy = O(id).HS_Y if (where == TP && oy < 0) oy = Math.min(0, oy + s) else if (where == BM && oy > h) oy = Math.max(h, oy - s) else if (where == LT && ox < 0) ox = Math.min(0, ox + s) else if (where == RT && ox > w) ox = Math.max(w, ox - s) else clearInterval(O(id).HS_IID) GoTo(id, ox, oy) O(id).HS_X = ox O(id).HS_Y = oy } } function SlideOut() { if (O(id).HS_IID) clearInterval(O(id).HS_IID) O(id).HS_IID = setInterval(DoSlideOut, INTERVAL) function DoSlideOut() { var ox = O(id).HS_X var oy = O(id).HS_Y if (where == TP && oy > y) oy = Math.max(y, oy - s) else if (where == BM && oy < y) oy = Math.min(y, oy + s) else if (where == LT && ox > x) ox = Math.max(x, ox - s) else if (where == RT && ox < x) ox = Math.max(x, ox + s) else clearInterval(O(id).HS_IID) GoTo(id, ox, oy) O(id).HS_X = ox O(id).HS_Y = oy } } } function HoverSlideMenu(ids, where, offset, showing, gap, msecs) { var len = ids.length var total = gap * (len - 1) var start = (offset[0] != '%') ? 0 : offset.substr(1) / 100 var a = [] var jump = 0 if (where == TP || where == BM) { for (var j = 0 ; j < len ; ++j) { a[j] = W(ids[j]) total += a[j] } start = start ? (GetWindowWidth() - total) * start : offset * 1 } else { for (var j = 0 ; j < len ; ++j) { a[j] = H(ids[j]) total += a[j] } start = start ? (GetWindowHeight() - total) * start : offset * 1 } for (var j = 0 ; j < len ; ++j) { HoverSlide(ids[j], where, start + jump, showing, msecs) jump += a[j] + gap } } function PopDown(id, type, w, h, msecs, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PopDown(id[j], type, w, h, msecs, interruptible) return } if (type == 'fade') { FadeOut(id, msecs, interruptible, InsVars("Hide('#1')", id)) } else if (type == 'inflate') { Deflate(id, w, h, msecs, interruptible, InsVars("Hide('#1')", id)) } else if (type == 'zoom') { ZoomDown(id, w, h, msecs, 1, interruptible, InsVars("Hide('#1')", id)) } else if (type == 'instant') Hide(id) O(id).PO_IsUp = false } function PopUp(id, type, w, h, msecs, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PopUp(id[j], type, w, h, msecs, interruptible) return } Show(id) if (type == 'fade') FadeIn(id, msecs, interruptible) else if (type == 'inflate') Reflate(id, w, h, msecs, interruptible) else if (type == 'zoom') ZoomRestore(id, w, h, msecs, 1, interruptible) O(id).PO_IsUp = true } function PopToggle(id, type, w, h, msecs, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PopToggle(id[j], type, w, h, msecs, interruptible) return } if (typeof O(id).PO_IsUp == UNDEF) O(id).PO_IsUp = true if (O(id).PO_IsUp) PopDown(id, type, w, h, msecs, interruptible) else PopUp(id, type, w, h, msecs, interruptible) } function FoldingMenu(headings, contents, action, type, multi, w, h, msecs1, msecs2, interruptible) { PopDown(contents.slice(1), type, w, h, 1, 0) O(contents[0]).PO_IsUp = true for (var j = 0 ; j < headings.length ; ++j) { O(headings[j]).FO_C = contents[j] S(headings[j]).cursor = 'pointer' if (action == 'hover') O(headings[j]).onmouseover = DoFoldingMenu else O(headings[j]).onclick = DoFoldingMenu } function DoFoldingMenu() { if (multi) PopToggle(this.FO_C, type, w, h, msecs1, interruptible) else { for (j = 0 ; j < headings.length ; ++j) if (O(O(headings[j]).FO_C).PO_IsUp && O(headings[j]) != this) PopDown(O(headings[j]).FO_C, type, w, h, msecs1, interruptible) if (!O(this.FO_C).PO_IsUp) PopUp(this.FO_C, type, w, h, msecs2, interruptible) } } } function ContextMenu(id, contents, type, w, h, msecs) { Locate(contents, ABS, -10000, -10000) PopDown(contents, type, 1, 1, 1, 0) O(id).oncontextmenu = ContextUp function ContextUp() { if (O(contents).PO_IsUp || O(contents).FA_Flag || O(contents).DF_Flag) return false var x = MOUSE_X var y = MOUSE_Y GoTo(contents, x, y) PopUp(contents, type, w, h, msecs, 1) S(contents).zIndex = ZINDEX + 1 O(id).Context_IID = setInterval(ContextDown, INTERVAL) return false function ContextDown() { if (MOUSE_X < x || MOUSE_X > (x + W(contents)) || MOUSE_Y < y || MOUSE_Y > (y + H(contents))) { PopDown(contents, type, w, h, msecs, 1) clearInterval(O(id).Context_IID) O(contents).PO_IsUp = false } } } } function DockBar(id, items, where, increase, msecs) { Position(id, FIX) for (var j = 0 ; j < items.length ; ++j) { if (where == TP || where == BM) S(items[j]).verticalAlign = where else O(items[j]).align = where var oldw = W(items[j]) var oldh = H(items[j]) S(items[j]).cursor = 'pointer' O(items[j]).DB_Parent = id O(items[j]).DB_Where = where O(items[j]).DB_OldW = oldw O(items[j]).DB_OldH = oldh O(items[j]).DB_NewW = Math.round(oldw + oldw * increase / 100) O(items[j]).DB_NewH = Math.round(oldh + oldh * increase / 100) O(items[j]).onmouseover = DockUp O(items[j]).onmouseout = DockDown } GoToEdge(id, where, 50) function DockUp() { Zoom(this, 1, 1, O(this).DB_OldW, O(this).DB_OldH, O(this).DB_NewW, O(this).DB_NewH, msecs, 0, 1) } function DockDown() { Zoom(this, 1, 1, O(this).DB_NewW, O(this).DB_NewH, O(this).DB_OldW, O(this).DB_OldH, msecs, 0, 1) } } function RollOver(ro1, ro2) { if (ro1 instanceof Array) { for (var j = 0 ; j < id.length ; ++j) RollOver(ro1[j], ro2[j]) return } var a = Array(ro1, ro2) var w = W(ro1) + 1 var h = H(ro1) + 1 var x = X(ro1) var y = Y(ro1) Hide(ro2) Locate(a, REL, 0, 0) O(ro1).onmouseover = DoRoll function DoRoll() { HideToggle(a) var iid = setInterval(RollCheck, INTERVAL) function RollCheck() { if (MOUSE_X < x || MOUSE_X > x + w || MOUSE_Y < y || MOUSE_Y > y + h) { HideToggle(a) clearInterval(iid) } } } } function Breadcrumbs(spacer) { var parts = self.location.href.split('?')[0].split('/') var crumbs = Array(parts[0] + '//') for (var j = 2 ; j < parts.length ; ++j) { if (parts[j] == '') crumbs[0] += '/' else crumbs.push(parts[j]) } var title = document.title ? document.title : parts[j - 1] var url = crumbs[0] + crumbs[1] var display = InsVars("<a href='#1'>Home</a>", url) if (typeof spacer == UNDEF) gap = ' ' for (j = 2 ; j < crumbs.length - 1 ; ++j) { url += '/' + crumbs[j] display += spacer + InsVars("<a href='#1'>#2</a>", url, crumbs[j]) } return display + spacer + title } function BrowserWindow(id, headerid, closeid, x, y, bounds, type, w, h, msecs, interruptible) { GoTo(id, x, y) PopUp(id, type, w, h, msecs, interruptible) var browserw = GetWindowWidth() var browserh = GetWindowHeight() var borderw = NoPx(S(id).borderLeftWidth) + NoPx(S(id).borderRightWidth) var borderh = NoPx(S(id).borderTopWidth) + NoPx(S(id).borderBottomWidth) var popupw = W(id) var popuph = H(id) S(closeid).cursor = 'pointer' O(id).onclick = BWToFront O(closeid).onclick = BWCloseWindow O(headerid).onmousedown = BWMove PreventAction(headerid, 'select', true) PreventAction(closeid, 'select', true) function BWToFront() { S(id).zIndex = ++ZINDEX } function BWCloseWindow() { PopDown(id, type, w, h, msecs, interruptible) } function BWMove() { BWToFront() S(headerid).cursor = 'move' var xoffset = MOUSE_X - X(id) var yoffset = MOUSE_Y - Y(id) var iid = setInterval(DoBWMove, 10) function DoBWMove() { var x = MOUSE_X - xoffset var y = MOUSE_Y - yoffset if (bounds) { var r = browserw - popupw - borderw + SCROLL_X var b = browserh - popuph - borderh + SCROLL_Y x = Math.max(0, Math.min(x, r)) y = Math.max(0, Math.min(y, b)) } if (MOUSE_X < 0 || MOUSE_X > (browserw + SCROLL_X) || MOUSE_Y < 0 || MOUSE_Y > (browserh + SCROLL_Y) || !MOUSE_DOWN || !MOUSE_IN) { clearInterval(iid) S(headerid).cursor = 'default' } GoTo(id, x, y) } } } function TextScroll(id, dir, number, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextScroll(id[j], dir, number, msecs) return } if (O(id).TS_Flag) return else O(id).TS_Flag = true var copy = Html(id) var len = copy.length var freq = Math.round(msecs / len) var ctr1 = 0 var ctr2 = 0 var iid = setInterval(DoTextScroll, freq) function DoTextScroll() { if (dir == LT) copy = copy.substr(1) + copy[0] else copy = copy[len - 1] + copy.substr(0, len - 1) if (O(id).innerText) O(id).innerText = copy else O(id).textContent = copy if (++ctr1 == len) { ctr1 = 0 if (++ctr2 == number) { O(id).TS_Flag = false clearInterval(iid) } } } } function TextType(id, number, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextType(id[j], number, msecs) return } if (O(id).TT_Flag) return else O(id).TT_Flag = true var html = Html(id) Html(id, '') Show(id) var len = html.length var freq = Math.round(msecs / len) var ctr1 = 0 var ctr2 = 0 var iid = setInterval(DoTextType, freq) function DoTextType() { var str = html.substr(0, ctr1) + '_' if (ctr1++ == len) { ctr1 = 0 if (++ctr2 == number) { O(id).TT_Flag = false clearInterval(iid) str = str.substr(0, len) } } if (O(id).innerText) O(id).innerText = str else Html(id, str) } } function MatrixToText(id, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) MatrixToText(id[j], msecs) return } if (O(id).MT_Flag) return else O(id).MT_Flag = true var html = Html(id) Html(id, '') Show(id) var len = html.length var freq = Math.round(msecs / INTERVAL) var matrix = '' var count = 0 var chars = 'ABCDEFGHIHJKLMOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789' for (var j = 0 ; j < len ; ++j) { if (html[j] == '\n' || html[j] == ' ') matrix += html[j] else matrix += chars[Math.floor(Math.random() * chars.length)] } if (O(id).innerText) O(id).innerText = matrix else O(id).textContent = matrix var iid = setInterval(DoMatrixToText, freq) function DoMatrixToText() { for (j = 0 ; j < len / 20 ; ++j) { var k = Math.floor(Math.random() * len) matrix = matrix.substr(0, k) + html[k] + matrix.substr(k + 1) } if (O(id).innerText) O(id).innerText = matrix else O(id).textContent = matrix if (++count == INTERVAL) { O(id).MT_Flag = false Html(id, html) clearInterval(iid) } } } function TextToMatrix(id, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextToMatrix(id[j], msecs) return } if (O(id).TM_Flag) return else O(id).TM_Flag = true var text = Html(id) Html(id, '') Show(id) var len = text.length var freq = Math.round(msecs / INTERVAL) var count = 0 var chars = 'ABCDEFGHIHJKLMOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789' var iid = setInterval(DoTextToMatrix, freq) function DoTextToMatrix() { for (var j = 0 ; j < len / 20 ; ++j) { var k = Math.floor(Math.random() * len) var l = Math.floor(Math.random() * chars.length) if (text[k] != '\n' && text[k] != '\r' && text[k] != ' ') text = text.substr(0, k) + chars[l] + text.substr(k + 1) } if (O(id).innerText) O(id).innerText = text else O(id).textContent = text if (++count == INTERVAL) { O(id).TM_Flag = false clearInterval(iid) } } } function ColorFade(id, color1, color2, what, msecs, number, interruptible) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ColorFade(id[j], color1, color2, what, msecs, number) return } if (O(id)['CF_Flag' + what]) { if (!O(id)['CF_Int' + what]) return else clearInterval(O(id)['CF_IID' + what]) } else O(id)['CF_Flag' + what] = true if (color1[0] == '#') color1 = color1.substr(1) if (color2[0] == '#') color2 = color2.substr(1) var step = Math.round(msecs / INTERVAL) var index = 0 var count = 0 var direc = 1 var cols = [] var steps = [] for (var j = 0 ; j < 3 ; ++j) { var tmp = HexDec(color2.substr(j * 2, 2)) cols[j] = HexDec(color1.substr(j * 2, 2)) steps[j] = (tmp - cols[j]) / step } if (what == 'text') var prop = 'color' else var prop = 'background' O(id)['CF_Int' + what] = interruptible O(id)['CF_IID' + what] = setInterval(DoColorFade, INTERVAL) function DoColorFade() { var temp ='#' for (var j = 0 ; j < 3 ; ++j) temp += DecHex(ZeroToFF(cols[j] + index * steps[j])) S(id)[prop] = temp if ((index += direc) > step || index < 0) { direc = -direc if (++count == number) { O(id)['CF_Flag' + what] = false clearInterval(O(id)['CF_IID' + what]) } } function ZeroToFF(num) { return Math.round(Math.min(255, Math.max(0, num))) } } } function FlyIn(id, x, y, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) FlyIn(id[j], x, y, msecs) return } if (O(id).FI_Flag) return else O(id).FI_Flag = true var tox = X(id) var toy = Y(id) var fromx = tox + x var fromy = toy + y var xstep = x / (msecs / INTERVAL) var ystep = y / (msecs / INTERVAL) var count = 0 Position(id, ABS) var iid = setInterval(DoFlyIn, INTERVAL) function DoFlyIn() { GoTo(id, fromx - xstep * count, fromy - ystep * count) if (count++ >= msecs / INTERVAL) { O(id).FI_Flag = false GoTo(id, tox, toy) clearInterval(iid) } } } function TextRipple(id, number, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) TextRipple(id[j], number, msecs) return } if (O(id).TR_Flag) return else O(id).TR_Flag = true var html = Html(id) var len = html.length var freq = msecs / len var ctr1 = 0 var ctr2 = 0 var iid = setInterval(DoTextRipple, freq) function DoTextRipple() { var temp = html.substr(0, ctr1) for (var j = 0 ; j < 7 ; ++j) temp += InsVars("<font size='+#1'>#2</font>", 4 - Math.abs(j - 3), html.substr(ctr1 + j, 1)) Html(id, temp + html.substr(ctr1 + j)) if (++ctr1 == len) { ctr1 = 0 if (++ctr2 == number) { if (O(id).innerText) O(id).innerText = html else O(id).textContent = html O(id).TR_Flag = false clearInterval(iid) } } } } function Lightbox(id, col1, col2, opacity, msecs) { S(id).cursor = 'pointer' if (!O('LB_DIV')) { var newdiv = document.createElement('div') newdiv.setAttribute('id', 'LB_DIV') document.body.appendChild(newdiv) } S(document.body).overflow = HID Hide(Array(id, 'LB_DIV')) Locate('LB_DIV', ABS, 0, 0) Resize('LB_DIV', GetWindowWidth(), GetWindowHeight()) S('LB_DIV').zIndex = ZINDEX Opacity(id, 0) Position(id, ABS) S(id).zIndex = ++ZINDEX Show(Array(id, 'LB_DIV')) Center(id) Fade('LB_DIV', 0, opacity, msecs) FadeIn(id, msecs, 0) ColorFade('LB_DIV', col1, col2, 'back', msecs, 1) O(id).onclick = DismissLB function DismissLB() { Fade('LB_DIV', opacity, 0, msecs) ColorFade('LB_DIV', col2, col1, 'back', msecs, 1) Chain(Array( InsVars("FadeOut(Array('#1', 'LB_DIV'), #2, 0)", id, msecs), InsVars("Hide(Array('#1', 'LB_DIV'))", id), "S(document.body, 'overflow', 'auto')" )) } } function Slideshow(id, images, msecs, wait) { var len = images.length O(id).SS_Stop = (wait == 'stop') ? true : false if (!O(id).SS_Stop && !O(id).SS_Flag) { if (!O('SS_IMG1')) { var newimg = document.createElement('img') newimg.setAttribute('id', 'SS_IMG1') O(id).appendChild(newimg) newimg = document.createElement('img') newimg.setAttribute('id', 'SS_IMG2') O(id).appendChild(newimg) Locate('SS_IMG2', ABS, 0, 0) } var index = 0 O('SS_IMG1').src = images[0] O(id).SS_Flag = true Opacity('SS_IMG2', 0) FadeIn('SS_IMG1', msecs, 0) setTimeout(DoSlideshow, msecs + wait) } function DoSlideshow() { O('SS_IMG1').src = images[index] Opacity('SS_IMG1', 100) Opacity('SS_IMG2', 0) index = ++index % len O('SS_IMG2').src = images[index] var next = InsVars("O('SS_IMG1').src = '#1'", images[(index + 1) % len]) FadeBetween('SS_IMG1', 'SS_IMG2', msecs, 0, next) if (!O(id).SS_Stop) setTimeout(DoSlideshow, msecs + wait) else O(id).SS_Flag = false } } function Billboard(id, objects, random, msecs, wait) { var len = objects.length if (!O(id).BB_Ready) { var h = 0 O(id).BB_Index = 0 O(id).BB_Ready = true FadeOut(objects.slice(1), 1, 0) for (j = 1 ; j < len ; ++j) { h -= H(O(objects[j-1])) Locate(O(objects[j]), REL, 0, h) } } O(id).BB_Stop = (wait == 'stop') ? true : false if (!O(id).BB_Stop && !O(id).BB_Flag) O(id).BB_IID = setTimeout(DoBillboard, msecs + wait) function DoBillboard() { O(id).BB_Flag = true if (O(id).BB_Stop) { O(id).BB_Flag = false clearTimeout(O(id).BB_IID) return } else FadeOut(objects[O(id).BB_Index], msecs, 0) if (random) { var rand = O(id).BB_Index while (rand == O(id).BB_Index ) rand = Math.floor(Math.random() * len) O(id).BB_Index = rand } else O(id).BB_Index = ++O(id).BB_Index % len FadeIn(objects[O(id).BB_Index ], msecs, 0) clearTimeout(O(id).BB_IID) O(id).BB_IID = setTimeout(DoBillboard, msecs + wait) } } function GoogleChart(id, title, tcolor, tsize, type, bwidth, labels, legends, colors, bgfill, width, height, data) { var types = { 'line' : 'lc', 'vbar' : 'bvg', 'hbar' : 'bhg', 'gometer' : 'gom', 'pie' : 'p', 'pie3d' : 'p3', 'venn' : 'v', 'radar' : 'r' } if (typeof type == UNDEF) type = 'pie' var t1 = escape(title) var t2 = types[type] var tail = 'chtt=' + t1 + '&cht=' + t2 + '&chs=' + width + 'x' + height + '&chbh=' + bwidth + '&chxt=x,y' + '&chd=t:' + data if (tcolor && tsize) tail += '&chts=' + tcolor + ',' + tsize if (labels) tail += '&chl=' + labels if (legends) tail += '&chdl=' + legends if (colors) tail += '&chco=' + colors if (bgfill) tail += '&chf=bg,s,' + bgfill Html(id, "<img src='http://chart.apis.google.com/chart?" + tail + "' />") } function PlaySound(id, file, loop) { Resize(id, 0, 0) Locate(id, ABS, 0, 0) if (loop == 'stop') Html(id, '') else Html(id, InsVars("<embed src='#1' hidden='true' " + "autostart='true' loop='#2' />", file, loop)) } function EmbedYouTube(video, width, height, hq, full, auto) { if (hq) hq = '&ap=%2526fmt%3D18' else hq = '' if (width && !height) height = width * 0.7500 if (!width && height) width = height * 1.3333 if (!width) width = 425 if (!height) height = 324 var temp = InsVars("<object width='#1' height='#2'>" + "<param name='movie' value='http://www.youtube.com/v/" + "#3&amp;fs=1&amp;autoplay=#4#5'>", width, height, video, auto, hq) temp += InsVars("</param><param name='allowFullScreen' " + "value='#1'></param><param name='allowscriptaccess' " + "value='always'></param>", full) temp += InsVars("<embed src='http://www.youtube.com" + "/v/#1&amp;fs=1&amp;autoplay=#2#3' type='application/" + "x-shockwave-flash' allowscriptaccess='always' " + "allowfullscreen='true'", video, auto, hq) temp += InsVars("width='#1' height='#2'></embed></object>", width, height) return temp } function PulsateOnMouseover(id, op1, op2, msecs) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) PulsateOnMouseover(id[j], op1, op2, msecs) return } var finish = false var iid Opacity(id, op1) O(id).FA_Level = op1 O(id).onmouseover = PulsateOn O(id).onmouseout = function() { finish = true } function PulsateOn() { var faded = false finish = false if (iid) clearInterval(iid) iid = setInterval(DoPulsate, INTERVAL) function DoPulsate() { if (!faded && O(id).FA_Level == op1) { if (finish) clearInterval(iid) else { Fade(id, op1, op2, msecs / 2, 0) faded = true } } else if (!O(id).FA_Flag) { Fade(id, op2, op1, msecs / 2, 0) faded = false } } } } function ProcessCookie(action, name, value, seconds, path, domain, secure) { if (action == 'save') { var date = new Date() date.setTime(parseInt(date.getTime() + seconds * 1000)) var expires = seconds ? '; expires=' + date.toGMTString() : '' path = path ? '; path=' + path : '' domain = domain ? '; domain=' + domain : '' secure = secure ? '; secure=' + secure : '' document.cookie = name + '=' + escape(value) + expires + path } else if (action == 'read') { if (!document.cookie.length) return false else { var start = document.cookie.indexOf(name + '=') if (start == -1) return false else { start += name.length + 1 var end = document.cookie.indexOf(';', start) end = (end == -1) ? document.cookie.length : end return unescape(document.cookie.substring(start, end)) } } } else if (action == 'erase') ProcessCookie('save', name, '', -60) } function CreateAjaxObject(callback, force) { try { var ajax = new XMLHttpRequest() } catch(e1) { try { ajax = new ActiveXObject("Msxml2.XMLHTTP") } catch(e2) { try { ajax = new ActiveXObject("Microsoft.XMLHTTP") } catch(e3) { ajax = false } } } if (ajax) ajax.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200 && this.responseText != null) callback.call(this.responseText) } return ajax } function GetAjaxRequest(callback, url, args) { var nocache = '&nocache=' + Math.random() * 1000000 var ajax = new CreateAjaxObject(callback) if (!ajax) return false ajax.open('GET', url + '?' + args + nocache, true) ajax.send(null) return true } function PostAjaxRequest(callback, url, args) { var contenttype = 'application/x-www-form-urlencoded' var ajax = new CreateAjaxObject(callback) if (!ajax) return false ajax.open('POST', url, true) ajax.setRequestHeader('Content-type', contenttype) ajax.setRequestHeader('Content-length', args.length) ajax.setRequestHeader('Connection', 'close') ajax.send(args) return true } function FrameBust(message) { if (top != self) { if (message) { if (confirm(message)) top.location.replace(self.location.href) } else top.location.replace(self.location.href) } } function ProtectEmail() { var a = '' for (var j=0 ; j < arguments.length ; ++j) a += arguments[j] return "<a hr" + "ef" + "='mai" + "lt" + "o:" + a + "'>" + a + "</a>" } function FieldPrompt(id, prompt, inputcolor, promptcolor, promptstyle) { inputcolor = inputcolor ? inputcolor : '#000000' promptcolor = promptcolor ? promptcolor : '#888888' promptstyle = promptstyle ? promptstyle : 'italic' if (BROWSER == 'Opera' || BROWSER == 'Chrome') ResizeWidth(id, W(id)) FP_On() O(id).onfocus = FP_Off O(id).onblur = FP_On function FP_Off() { if (O(id).value == prompt) { O(id).FP_Empty = true O(id).value = '' S(id).fontStyle = '' S(id).color = inputcolor } else O(id).FP_Empty = false } function FP_On() { if (O(id).value == '' || O(id).value == prompt) { O(id).FP_Empty = true O(id).value = prompt S(id).fontStyle = promptstyle S(id).color = promptcolor } else O(id).FP_Empty = false } } function ResizeTextarea(id, min, max) { if (id instanceof Array) { for (var j = 0 ; j < id.length ; ++j) ResizeTextarea(id[j], min, max) return } min = min ? min : 0 max = max ? max : 10 O(id).onmouseup = DoResizeTextarea O(id).onkeyup = DoResizeTextarea function DoResizeTextarea() { while (O(id).scrollHeight > O(id).clientHeight && O(id).rows < max) ++O(id).rows while (O(id).scrollHeight < O(id).clientHeight && O(id).rows > min) --O(id).rows } } function ValidateEmail(email) { var at = email.indexOf('@') if (at == -1 || /[^\w\-\.\@\_\+]/.test(email)) return false var left = email.substr(0, at) var right = email.substr(at + 1) var llen = left.length var rlen = right.length if (llen < 1 || llen > 64 || rlen < 4 || rlen > 254 || right.indexOf('.') == -1) return false return true } function ValidatePassword(pass, min, max, upper, lower, dig, punct) { var len = pass.length var valid = true if (len < min || len > max) valid = false else if (upper && !/[A-Z]/.test(pass)) valid = false else if (lower && !/[a-z]/.test(pass)) valid = false else if (dig && !/[0-9]/.test(pass)) valid = false else if (punct && !/[^a-zA-Z0-9]/.test(pass)) valid = false return valid } function CleanupString(string, allspaces, alldigs, alltext, allpunct, uptolow, lowtoup, spacestosingle) { if (allspaces) string = string.replace(/[\s]/g, '') if (alldigs) string = string.replace(/[\d]/g, '') if (alltext) string = string.replace(/[a-zA-Z]/g, '') if (allpunct) string = string.replace(/[^\sa-zA-Z0-9]/g, '') if (uptolow) string = string.toLowerCase() if (lowtoup) string = string.toUpperCase() if (spacestosingle) string = string.replace(/[\s]+/g, ' ') return string } function ValidateCreditCard(number, month, year) { number += '' month += '' year += '' number = CleanupString(number, true, false, true, true) month = CleanupString(month, true, false, true, true) year = CleanupString(year, true, false, true, true) var left = number.substr(0, 4) var cclen = number.length var chksum = 0 if (left >= 3000 && left <= 3059 || left >= 3600 && left <= 3699 || left >= 3800 && left <= 3889) { // Diners Club if (cclen != 14) return false } else if (left >= 3088 && left <= 3094 || left >= 3096 && left <= 3102 || left >= 3112 && left <= 3120 || left >= 3158 && left <= 3159 || left >= 3337 && left <= 3349 || left >= 3528 && left <= 3589) { // JCB if (cclen != 16) return false } else if (left >= 3400 && left <= 3499 || left >= 3700 && left <= 3799) { // American Express if (cclen != 15) return false } else if (left >= 3890 && left <= 3899) { // Carte Blanche if (cclen != 14) return false } else if (left >= 4000 && left <= 4999) { // Visa if (cclen != 13 && cclen != 16) return false } else if (left >= 5100 && left <= 5599) { // MasterCard if (cclen != 16) return false } else if (left == 5610) { // Australian BankCard if (cclen != 16) return false } else if (left == 6011) { // Discover if (cclen != 16) return false } else return false // Unrecognized Card for (var j = 1 - (cclen % 2) ; j < cclen ; j += 2) if (j < cclen) chksum += number[j] * 1 for (j = cclen % 2 ; j < cclen ; j += 2) { if (j < cclen) { d = number[j] * 2 chksum += d < 10 ? d : d - 9 } } if (chksum % 10 != 0) return false var date = new Date() date.setTime(date.getTime()) if (year.length == 4) year = year.substr(2, 2) if (year > 50) return false else if (year < (date.getFullYear() - 2000)) return false else if ((date.getMonth() + 1 ) > month) return false else return true } function RollingCopyright(start) { var date = new Date() date = date.getFullYear() return '© ' + start + "-" + date } function Alert(value) { var divs = Array('ALERT_DIV', 'SHADOW_DIV') var warn = "<font color=red size=6 style='vertical-align:middle;'>" + "Δ</font> " var ok = "<center><input id='ALERT_OK' type='submit' /></center>" var mess = warn + value + '<br /><br />' + ok var html = "<div id='ALERT_TITLE'></div>" + "<div id='ALERT_MESSAGE'></div>" if (!O('ALERT_DIV')) { var newdiv = document.createElement('div') newdiv.setAttribute('id', 'SHADOW_DIV') document.body.appendChild(newdiv) newdiv = document.createElement('div') newdiv.setAttribute('id', 'ALERT_DIV') document.body.appendChild(newdiv) Position(divs, ABS) Resize('ALERT_DIV', 350, 140) Resize('SHADOW_DIV', 354, 146) Center('ALERT_DIV') GoTo('SHADOW_DIV', X('ALERT_DIV') + 4, Y('ALERT_DIV') + 6) Opacity('SHADOW_DIV', 50) } AlertHide() Html('ALERT_DIV', html) Resize('ALERT_TITLE', 350, 22) Resize('ALERT_MESSAGE', 330, 98) Html('ALERT_TITLE', 'Message from the webpage') Html('ALERT_MESSAGE', mess) S('ALERT_TITLE').background = '#acc5e0' S('ALERT_TITLE').fontFamily = 'Arial' S('ALERT_TITLE').paddingTop = '2px' S('ALERT_TITLE').textAlign = 'center' S('ALERT_TITLE').fontSize = '14px' S('ALERT_MESSAGE').fontFamily = 'Arial' S('ALERT_MESSAGE').fontSize = '12px' S('ALERT_MESSAGE').padding = '10px' S('ALERT_MESSAGE').overflow = 'auto' S('ALERT_DIV').background = '#f0f0f0' S('ALERT_DIV').border = 'solid #444444 1px' S('SHADOW_DIV').background = '#444444' O('ALERT_OK').value = ' OK ' O('ALERT_OK').onclick = AlertHide Visible(divs) function AlertHide() { Invisible(divs) } } function ReplaceAlert() { window.alert = Alert } function ToolTip(id, tip, font, size, textc, backc, bordc, bstyle, bwidth, msecs, timeout) { var tt = 'TT_' + O(id).id if (!O(tt)) { var newdiv = document.createElement('div') newdiv.setAttribute('id', tt) document.body.appendChild(newdiv) Opacity(tt, 0) Position(tt, ABS) font = font ? font : 'Arial' size = size ? size : 'small' textc = textc ? textc : '#884444' backc = backc ? backc : '#ffff88' bordc = bordc ? bordc : '#aaaaaa' bstyle = bstyle ? bstyle : 'dotted' bwidth = bwidth ? bwidth : 1 msecs = msecs ? msecs : 250 S(tt).fontFamily = font S(tt).fontSize = size S(tt).padding = '3px 5px 3px 5px' S(tt).color = textc S(tt).background = backc S(tt).borderColor = bordc S(tt).borderStyle = bstyle S(tt).borderWidth = Px(bwidth) Html(tt, tip) } O(id).onmouseover = DoToolTip O(id).onmouseout = ToolTipHide O(tt).Hidden = false function DoToolTip() { GoTo(tt, MOUSE_X + 15, MOUSE_Y + 15) O(tt).zIndex = ZINDEX + 1 FadeIn(tt, msecs) O(tt).Hidden = false if (timeout) { if (O(tt).IID) clearTimeout(O(tt).IID) O(tt).IID = setTimeout(ToolTipHide, timeout) } } function ToolTipHide() { if (!O(tt).Hidden) { FadeOut(tt, msecs) O(tt).Hidden = true } } } function CursorTrail(image, length, state) { var w = GetWindowWidth() var h = GetWindowHeight() var c = 'CT_' if (!state) return clearInterval(CT_IID) if (!O('TT_0')) { for (var j = 0 ; j < 10 ; ++j) { var newimg = document.createElement('img') newimg.setAttribute('id', c + j) document.body.appendChild(newimg) Position(newimg, ABS) Opacity(newimg, (j + 1) * 9) newimg.src = image O(c + j).X = -9999 O(c + j).Y = -9999 } } CT_IID = setInterval(DoCurTrail, length) function DoCurTrail() { for (var j = 0 ; j < 10 ; ++j) { GoTo(c + j, O(c + j).X + 2, O(c + j).Y + 2) S(c + j).zIndex = ZINDEX + 1 if (O(c + j).X == MOUSE_X && O(c + j).Y == MOUSE_Y) Hide(c + j) else Show(c + j) if (j > 0) { O(c + (j - 1)).X = O(c + j).X O(c + (j - 1)).Y = O(c + j).Y } } O(c + 9).X = MOUSE_X < (w - 12) ? MOUSE_X : -9999 O(c + 9).Y = MOUSE_Y < (h - 20) ? MOUSE_Y : -9999 } } function TouchEnable(state) { var db = document.body if (state) { var iid = null var flag = false PreventAction(db, 'both', true) db.onmousedown = StartTE db.onmouseup = StopTE } else { PreventAction(db, 'both', false) db.onmousedown = '' db.onmouseup = '' return } function StartTE(e) { if (!flag) { var oldmousex = MOUSE_X var oldmousey = MOUSE_Y var tempmousex = MOUSE_X var tempmousey = MOUSE_Y flag = true iid = setInterval(DoTE, 10) } return false function DoTE() { if (MOUSE_DOWN && MOUSE_IN) { if (MOUSE_X != tempmousex || MOUSE_Y != tempmousey) { tempmousex = MOUSE_X tempmousey = MOUSE_Y window.scrollBy(oldmousex - MOUSE_X, oldmousey - MOUSE_Y) } } else StopTE() } } function StopTE() { flag = false clearInterval(iid) } } // Based on a function by Ryan Morr at: // http://ryanmorr.com/archives/ondomready-no-browser-sniffing // // Use this in place of window.onload to start your code much more // quickly than waiting for window.onload, which only triggers after // all contents such as images are also loaded - whereas this code // triggers as soon as the DOM is complete and in a useable state. // // Example: // // OnDOMReady(function() // { // // Your code goes here... // }) function OnDOMReady(func) { var timer = setInterval(onChange, 5) var ready = false if(document.addEventListener) document.addEventListener( "DOMContentLoaded", onChange, false) document.onreadystatechange = window.onload = onChange function onChange(e) { if(e && e.type == "DOMContentLoaded") { fireDOMReady() } else if(e && e.type == "load") { fireDOMReady() } else if(document.readyState) { if((/loaded|complete/).test(document.readyState)) { fireDOMReady() } else if(!!document.documentElement.doScroll) { try { ready || document.documentElement.doScroll('left') } catch(e) { return } fireDOMReady(); } } } function fireDOMReady() { if(!ready) { ready = true func.call() if(document.removeEventListener) document.removeEventListener( "DOMContentLoaded", onChange, false) clearInterval(timer) document.onreadystatechange = window.onload = timer = null } } }
JavaScript
/************************************/ /* PC.js: Version 1.0 */ /* From Plug-in CSS, by Robin Nixon */ /* McGraw-Hill 2011 */ /* */ /* Plug-ins 58-100: Dynamic classes */ /* and Superclasses */ /************************************/ Initialize() OnDOMReady(function() { var gfurl = 'http://fonts.googleapis.com/css?family=' var wheight = GetWindowHeight() var tags = document.getElementsByTagName("*") var numtags = tags.length var font = '' var elems = [] var gfonts = [] var cites = [] var refers = [] var sclasses = [] var gfindex = 0 var cindex = 0 var demand = false var index, index2, thistag, regex, oldclassname loadsclasses(sclasses) for (index = 0 ; index < numtags ; ++ index) { thistag = tags[index] var tagname = thistag.tagName.toLowerCase() var tagtype = (thistag.type) ? thistag.type.toLowerCase() : '' var classname = thistag.className.toLowerCase() var cnamecopy = classname var origcname = thistag.className var repeat = true /**********************/ /* Chapter 8: Objects */ /**********************/ /* 58: nojs and onlyjs classes */ if (classname.search(/\bnojs\b/, 0) != -1) Hide(thistag) if (classname.search(/\bonlyjs\b/, 0) != -1) Show(thistag) /* 59: middle class */ if (classname.search(/\bmiddle\b/, 0) != -1) { S(thistag).marginTop = S(thistag).marginBottom = Px((H(thistag.parentNode) - H(thistag)) / 2) } /* 60: center class */ if (classname.search(/\bcenter\b/, 0) != -1) { S(thistag).marginLeft = S(thistag).marginRight = Px((W(thistag.parentNode) - W(thistag)) / 2) } /* 61: top class */ if (classname.search(/\btop\b/, 0) != -1) { S(thistag).marginTop = '0px'; S(thistag).marginBottom = Px(H(thistag.parentNode) -H(thistag)) } /* 62: bottom class */ if (classname.search(/\bbottom\b/, 0) != -1) { S(thistag).marginTop = Px(H(thistag.parentNode) -H(thistag)) S(thistag).marginBottom = '0px'; } /* 63: left class */ if (classname.search(/\bleft\b/, 0) != -1) { S(thistag).marginLeft = '0px'; S(thistag).marginRight = Px(W(thistag.parentNode) - W(thistag)) } /* 64: right class */ if (classname.search(/\bright\b/, 0) != -1) { S(thistag).marginLeft = Px(W(thistag.parentNode) - W(thistag)) S(thistag).marginRight = '0px'; } /* 65: ondemand class */ if (classname.search(/\bondemand\b/, 0) != -1 && tagname == 'img') { if (Y(thistag) > (SCROLL_Y + wheight)) { elems[index] = thistag.alt demand = true Opacity(thistag, 0) } else thistag.src = thistag.alt } /* 66: fadein class */ if (classname.search(/\bfadein\b/, 0) != -1) { cnamecopy.replace(/fadein\[([^\]]*)\]/, function() { Opacity(thistag, 0); FadeIn(thistag, arguments[1]) } ) } /* 67: fadeout class */ if (classname.search(/\bfadeout\b/, 0) != -1) { cnamecopy.replace(/fadeout\[([^\]]*)\]/, function() { FadeOut(thistag, arguments[1]) } ) } /* 68: resizeta class */ if (classname.search(/\bresizeta\b/, 0) != -1 && tagname == 'textarea') { cnamecopy.replace(/resizeta\[([^\|]*)\|([^\]]*)\]/, function() { ResizeTextarea(thistag, arguments[1], arguments[2]) } ) } /* 69: rotate class */ if (classname.search(/\brotate\b/, 0) != -1) { cnamecopy.replace(/rotate\[([^\]]*)\]/, function() { var r = arguments[1] S(thistag).MozTransform = 'rotate(' + r + 'deg)' S(thistag).WebkitTransform = 'rotate(' + r + 'deg)' S(thistag).OTransform = 'rotate(' + r + 'deg)' S(thistag).transform = 'rotate(' + r + 'deg)' if (typeof S(thistag).filter != UNDEF) { var rad = r * (Math.PI * 2 / 360) var cosrad = Math.cos(rad) var sinrad = Math.sin(rad) var w = W(thistag) var h = H(thistag) var filter = 'progid:DXImageTransform.Microsoft.' + 'Matrix(M11=' + cosrad + ', M12=' + -sinrad + ', M21=' + sinrad + ', M22=' + cosrad + ", SizingMethod='auto expand')" S(thistag).filter = filter Locate(thistag, REL, -((W(thistag) - w) / 2), -((H(thistag) - h) / 2)) } } ) } /* 70: w class */ if (classname.search(/\bw\b/, 0) != -1) { cnamecopy.replace(/w\[([^\]]*)\]/, function() { S(thistag).width = Px(arguments[1]) } ) } /* 71: h class */ if (classname.search(/\bh\b/, 0) != -1) { cnamecopy.replace(/h\[([^\]]*)\]/, function() { S(thistag).height = Px(arguments[1]) } ) } /* 72: x class */ if (classname.search(/\bx\b/, 0) != -1) { cnamecopy.replace(/x\[([^\]]*)\]/, function() { S(thistag).left = Px(arguments[1]) } ) } /* 73: y class */ if (classname.search(/\by\b/, 0) != -1) { cnamecopy.replace(/y\[([^\]]*)\]/, function() { S(thistag).top = Px(arguments[1]) } ) } /* 74: color class */ if (classname.search(/\bcolor\b/, 0) != -1) { cnamecopy.replace(/color\[([^\]]*)\]/, function() { S(thistag).color = arguments[1] } ) } /* 75: bcolor class */ if (classname.search(/\bbcolor\b/, 0) != -1) { cnamecopy.replace(/bcolor\[([^\]]*)\]/, function() { S(thistag).backgroundColor = arguments[1] } ) } /**********************************/ /* Chapter 9: Text and Typography */ /**********************************/ /* 76: typetext class */ if (classname.search(/\btypetext\b/, 0) != -1) { cnamecopy.replace(/typetext\[([^\]]*)\]/, function() { TextType(thistag, 1, arguments[1]) } ) } /* 77: digitsonly class */ if (classname.search(/\bdigitsonly\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 0, 1, 1) } } /* 78: textonly class */ if (classname.search(/\btextonly\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 1, 0, 1) } } /* 79: nospaces class */ if (classname.search(/\bnospaces\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 1) } } /* 80: nopunct class */ if (classname.search(/\bnopunct\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 0, 0, 1) } } /* 81: minwhitespace class */ if (classname.search(/\bminwhitespace\b/, 0) != -1) { thistag.onchange = thistag.onmouseout = thistag.onsubmit = function() { this.value = CleanupString(this.value, 0, 0, 0, 0, 0, 0, 1) } } /* 82: gfont class */ if (classname.search(/\bgfont\b/, 0) != -1) { cnamecopy.replace(/gfont\[([^\]]*)\]/, function() { switch(arguments[1]) { case 'cantarell' : font = 'Cantarell'; break case 'cardo' : font = 'Cardo'; break case 'crimson' : font = 'Crimson Text'; break case 'droidsans' : font = 'Droid Sans'; break case 'droidsansm' : font = 'Droid Sans Mono'; break case 'droidserif' : font = 'Droid Serif'; break case 'imfell' : font = 'IM Fell English'; break case 'inconsolata': font = 'Inconsolata'; break case 'josefin' : font = 'Josefin Sans Std Light'; break case 'lobster' : font = 'Lobster'; break case 'molengo' : font = 'Molengo'; break case 'neuton' : font = 'Neuton'; break case 'nobile' : font = 'Nobile'; break case 'oflsorts' : font = 'OFL Sorts Mill Goudy TT';break case 'oldstandard': font = 'Old Standard TT'; break case 'reenie' : font = 'Reenie Beanie'; break case 'tangerine' : font = 'Tangerine'; break case 'vollkorn' : font = 'Vollkorn'; break case 'yanone' : font = 'Yanone Kaffeesatz'; break } if (!window[font]) { window[font] = true gfonts[gfindex++] = font } S(thistag).fontFamily = font } ) } /* 83: textmiddle class */ if (classname.search(/\btextmiddle\b/, 0) != -1) { S(thistag).lineHeight = Px(H(thistag)) } /* 84: textglow class */ if (classname.search(/\btextglow\b/, 0) != -1) { cnamecopy.replace(/textglow\[([^\|]*)\|([^\|]*)\|([^\]]*)\]/, function() { ColorFade(thistag, arguments[1], arguments[2], 'text', arguments[3]) } ) } /* 85: backglow class */ if (classname.search(/\bbackglow\b/, 0) != -1) { cnamecopy.replace(/backglow\[([^\|]*)\|([^\|]*)\|([^\]]*)\]/, function() { ColorFade(thistag, arguments[1], arguments[2], '', arguments[3]) } ) } /**************************/ /* Chapter 10: Navigation */ /**************************/ /* 86: placeholder class */ if (classname.search(/\bplaceholder\b/, 0) != -1 && tagname == 'input') { origcname.replace(/placeholder\[([^\]]*)\]/, function() { if (thistag.placeholder == '' || typeof thistag.placeholder == UNDEF) FieldPrompt(thistag, arguments[1]) } ) } /* 87: autofocus class */ if (classname.search(/\bautofocus\b/, 0) != -1 && tagname == 'input' || tagname == 'select' || tagname == 'textarea' || tagname == 'button') { if (tagtype != 'hidden') thistag.focus() } /* 88: cite class */ if (classname.search(/\bcite\b/, 0) != -1) { origcname.replace(/cite\[([^\]]*)\]/, function() { cites[cindex++] = arguments[1] S(thistag).verticalAlign = 'super' S(thistag).textDecoration = 'none' S(thistag).fontSize = '50%' Html(thistag, Html(thistag) + InsVars("<a href='#cite#1'>[#1]</a>", cindex)) } ) } /* 89: ref class */ if (classname.search(/\bref\b/, 0) != -1) { cnamecopy.replace(/ref\[([^\|]*)\|([^\]]*)\]/, function() { var a1 = arguments[1] var a2 = arguments[2] if (typeof refers[a1] == UNDEF) { refers[a1] = Array() refers[a1]['count'] = 1 refers[a1][a2] = 1 } else if (typeof refers[a1][a2] == UNDEF) refers[a1][a2] = ++refers[a1]['count'] Html(thistag, refers[a1][a2]) } ) } /* 90: nocopy class */ if (classname.search(/\bnocopy\b/, 0) != -1) { PreventAction(thistag, 'both', true) } /****************************************/ /* Chapter 11: Incorporating JavaScript */ /****************************************/ /* 91: embedjs class */ if (classname.search(/\bembedjs\b/, 0) != -1) { Html(thistag, Html(thistag).replace(/\[\[([^\]]*)\]\]/g, function() { arguments[1] = arguments[1].replace(/</g, '<') arguments[1] = arguments[1].replace(/>/g, '>') try { return eval(arguments[1]) } catch(e) { return "<span class='red'>[" + e + "]</span>" } } )) } /* 92: if class */ if (classname.search(/\bif\b/, 0) != -1) { origcname.replace(/(if|IF)\[([^\]]*)\]/, function() { if (!eval(arguments[2])) Html(thistag, '<!-- ' + Html(thistag) + ' -->') } ) } /* 93: ifnot class */ if (classname.search(/\bifnot\b/, 0) != -1) { origcname.replace(/(ifnot|IFNOT)\[([^\]]*)\]/, function() { if (eval(arguments[2])) Html(thistag, '<!-- ' + Html(thistag) + ' -->') } ) } /****************************/ /* Chapter 12: Superclasses */ /****************************/ // Load in superclasses from meta tags if (thistag.tagName == 'META' && thistag.httpEquiv.toUpperCase() == 'SCLASS') sclasses[thistag.name] = thistag.content // Apply superclasses while (repeat) { oldclassname = thistag.className for (index2 in sclasses) { regex = new RegExp('\\b' + index2 + '\\b', 'g') thistag.className = thistag.className.replace(regex, sclasses[index2]) } if (thistag.className != oldclassname) repeat = true else repeat = false } } // Import Google Fonts Stylesheets for (index = 0 ; index < gfindex ; ++index) { var newcss = document.createElement('link') newcss.setAttribute('href', gfurl + escape(gfonts[index])) newcss.setAttribute('rel', 'stylesheet') newcss.setAttribute('type', 'text/css') document.getElementsByTagName('head')[0].appendChild(newcss) } if (gfindex && window.opera) setTimeout(function()// Required by Opera { document.body.style += "" }, 1) // to redraw browser // Add citations to 'citations' object if (cindex > 0) { var html = '<ol>' for (index = 0 ; index < cindex ; ++index) html += InsVars('<a name=cite#1></a><li>#2</li>', index + 1, cites[index]) // Check that 'citations' exists before inserting HTML if (typeof O('citations') != UNDEF) Html('citations', html + '</ol>') } // If there are unloaded images outside the current view if (demand) setTimeout(DoOnDemand, 10) // Perform on demand image loading function DoOnDemand() { demand = false for (index = 0 ; index < numtags ; ++index) { thistag = tags[index] if (elems[index]) { demand = true if (Y(thistag) < (SCROLL_Y + wheight)) { thistag.onload = function() { FadeIn(this, 500) } thistag.src = elems[index] elems[index] = '' } } } // repeat if there are still any unloaded images if (demand) setTimeout(DoOnDemand, 10) } }) function loadsclasses(sclasses) { /* 94 - 100: Superclasses */ sclasses['clickable'] = 'nooutline pointer' sclasses['rssbutton'] = 'carrot1 carrot2_a smallestround b white ' + 'yellow_h smallbutton clickable' sclasses['border'] = 'bwidth1 bsolid bblack' sclasses['abstopleft'] = 'absolute totop toleft' sclasses['rollover'] = 'trans00 trans10_h' sclasses['rollover_h'] = 'abstopleft trans10 trans00_h' sclasses['vtab'] = 'leftpadding10 leftpadding40_h ' + 'rightpadding5 b transitionallfast_l' sclasses['htab'] = 'absolute center toppadding20_h b ' + 'transitionallfast_l' } /************************************************************************ You can add more classes to your HTML using meta tags, like this... <meta http-equiv='sclass' name='clickable' content='nooutline pointer' /> which replicates one of the superclasses built into this script. You can override it, or add more superclasses with new names and values. You can also add them to this file using the syntax shown above. ************************************************************************/
JavaScript
// JavaScript Document /* TODO: 로컬스토리지 저장 목록 - 최근 검색기록 - 관심품목 & 관련메모 : User Key가 동일한 경우 모든 웹브라우저 && 로그인 한 각 PC 마다 동기화 필수 - 광고내용 & 업체정보 : 웹소켓을 이용한 비동기 server-push 방식으로 저장 후 검색에 연동한 광고노출 또는 랜덤 노출 초기화싯점에서 기능탐지, 브라우저탐지,.... (페이지수준으로 분기) 자바스크립트 패턴 #인사이트 p.92 자바스크립트 패턴 #인사이트 p.245 var isIE = /*@cc_on!@/false; // true 반환, 주의:@/ 사이에 * 추가할 것 자바스크립트 완벽가이드 #인사이트 p.346, 347 IE에서만 실행되는 자바스크립트 조건부 주석 /*@cc_on @if(@_jscript) // @_jscript는 마이크로소프트의 자바스크립트 인터프리터 이름 alert('IE'); @end @/ // 주의:@/ 사이에 * 추가할 것 //*************** 추가 데이터전달 자바스크립트 객체지향프로그래밍 #위키북스 p.344 1. $('p').bind('click', {foo: 'bar'}, handler); function handler(e) { alert(e.data.foo); } 자바스크립트 객체지향프로그래밍 #위키북스 p. 2. $('p').load(url, {foo: 'bar'}, callback); //*************** 자바스크립트 패턴 #인사이트 p.92 function func(p, q) { console.log('argument.length: ' + arguments.length); console.log('func.length:' + func.length); } func('p', 'q', 'r'); // func.length:2 , argument.length: 3 func('p'); // func.length:2 , argument.length: 1 //************* /**/ $(document).ready(function() { var storage = null, SERVICE_NAME = null, // 퍼펙트자바스크립트 #위키북스 p.486 p.487 localStorage 네임스페이스 관리 support_stroage = window.localStorage || window.sessionStorage; // window['localStorage'] /* if(support_stroage) { alert('지원'); } else { alert('No!!'); } */ window.onload = function() { try { storage = JSON.parse(localStorage.SERVICE_NAME || '{}'); } catch(e) { storage = {}; } if(support_stroage) { // 꼭 필요한 HTML5 그리고 HTML5 API #puple p.242 if(!localStorage.version) { localStorage.version = '1.0'; } Storage.prototype.setObject = function(key, value) { // storage[key] = value; // localStorage.SERVICE_NAME = JSON.stringify(storage); // this.setItem(localStorage.SERVICE_NAME, JSON.stringify(storage)); this.setItem(key, JSON.stringify(value)); } Storage.prototype.getObject = function(key, value) { return this.getItem(key) && JSON.parse(this.getItem(key)); } } }; window.onbeforeunload = function() { localStorage.SERVICE_NAME = JSON.stringify(storage); }; window.onstorage = function(e) { if(e.key === (SERVICE_NAME && e.newValue)) { storage = JSON.parse(e.newValue); } }; /* function setStorage(key, value) { storage[key] = value; localStorage.SERVICE_NAME = JSON.stringify(storage); } /**/ var printMessage = function(msg) { $('#noti').append('<p>' + msg + '</p>'); } var socket = io.connect('http://localhost:52273'); socket.on('news', function (data) { log(data.hello); socket.emit('my other event', { my: 'data' }); }); socket.on('co', function (data) { // alert('data: ' + data); log('data: ' + data); }); socket.on('connect', function () { printMessage('서버의 소켓에 연결되었습니다.'); // 클라이언트에 출력 socket.send('클라이언트에서 보내는 메시지'); // 서버에 출력 }); socket.on('message', function (msg) { printMessage(msg); // log(msg); }); socket.on('msg', function (data) { printMessage(data.msg + ' : ' + data.now); }); /* // 예약이벤트 : message, connect, disconnect, open, close, error, retry, reconnect // json 객체 전송시 socket.emit('message', {msg: '문자열'}) socket.json.send({msg: '문자열'}); // json 객체 수신시 socket.on('message', function (data) { console.log(data.msg);}); /**/ /* ////**************************** var support_socket = !!window.WebSocket; if(support_socket) { var url = 'ws://localhost:8080/'; var socket = (window.MozWebsocket) ? new MozWebsocket(url) : new WebSocket(url); // var socket = new WebSocket(url); if(socket) { log('소켓 지원'); } socket.onopen = function() { log('open'); socket.send('socket open'); } socket.send = function(s) { log(s); } socket.send('Socket Test'); socket.onmessage = function(e) { log('서버로 부터 받은 메시지: ' + e.data); } socket.onclose = function(e) { log('closed'); } } else { alert('소켓 지원 불가'); } /**/ $('dd a', '#searchResult').live({ // 주의: jquery.1.8이하에서 live 사용 click: function(e) { var serial = $(this).data('serial') || $(this).attr('data-serial') || $(this).dataset.serial, supl = /^s\d{5}/, prt = /^p\d{5}/; $('#loadingImg').removeClass('hidden'); e.preventDefault(); /*@cc_on // IE @if(@_jscript) // $(this).after().load($(this).attr('href') '#site_content'); @else*/ // $('#site_content').load($(this).attr('href') + ' #site_content'); /*@end @*/ $('#site_content').load($(this).attr('href') + ' #site_content'); if(support_stroage && !!supl.test(serial)) { // SERVICE_NAME = 'SUP'; // localStorage.setObject(SERVICE_NAME, time.unix_timestamp()); localStorage.setObject(serial, time.unix_timestamp()); // localStorage.clear(); } $('#loadingImg').addClass('hidden'); } /* mouseover: function() { // TODO: 관심품목 등록, 메모 작성메뉴를 이곳에??? }, mouseout: function() { }, contextmenu: function(e) { // TODO: 비즈메뉴(광고등록)를 이곳에??? 비즈회원에게만 조건부 활성화? alert('assa!!'); e.preventDefault(); }, /**/ }); $('#makerPool span a').live({ // 주의: live 사용 click: function(e) { e.preventDefault(); var href = e.target.href.split('#'), waitingAd = "<img src='http://placehold.it/200x100' /><br /> 이곳은 광고 영역입니다.<br /> mouseover시 우측에 광고박스 표시합니다."; $('#showChoice').empty(); $('dl').addClass('hidden'); $('#'+href[1]).closest('dl').clone(true) .appendTo('#showChoice') .removeClass('hidden'); $('#showChoice').append(waitingAd); } }); });
JavaScript
// JavaScript Document /* 자바스크립트 파일에서 외부 자바스크립트 병렬임포트 지원 jquery-ui는 jquery에 의존적이므로 다운로드를 지연시킨다. var labjs = $LAB .script("js/libs/jquery.min.js").wait() .script("js/libs/jquery-ui.min.js") .script("js/global.js"); labjs.wait(function(){ $('header').effect("pulsate", { times:3 }, 2000); }); var labjs = $LAB.script("/2013p79/common/class/search/js/sharing.js").hello(); labjs.hello(); */ $LAB .script("/2013p79/common/class/search/js/sharing.js");
JavaScript
// JavaScript Document $LAB .script("/2013p79/common/class/search/js/sharing.js");
JavaScript
// JavaScript Document /* TODO: 로컬스토리지 저장 목록 - 최근 검색기록 - 관심품목 & 관련메모 : User Key가 동일한 경우 모든 웹브라우저 && 로그인 한 각 PC 마다 동기화 필수 - 광고내용 & 업체정보 : 웹소켓을 이용한 비동기 server-push 방식으로 저장 후 검색에 연동한 광고노출 또는 랜덤 노출 Cr, FF에서는 SQlite를 사용하여 localStorage 동작 초기화싯점에서 기능탐지, 브라우저탐지,.... (페이지수준으로 분기) 자바스크립트 패턴 #인사이트 p.92 자바스크립트 패턴 #인사이트 p.245 var isIE = /*@cc_on!@/false; // true 반환, 주의:@/ 사이에 * 추가할 것 자바스크립트 완벽가이드 #인사이트 p.346, 347 IE에서만 실행되는 자바스크립트 조건부 주석 /*@cc_on @if(@_jscript) // @_jscript는 마이크로소프트의 자바스크립트 인터프리터 이름 alert('IE'); @end @/ // 주의:@/ 사이에 * 추가할 것 //*************** 추가 데이터전달 자바스크립트 객체지향프로그래밍 #위키북스 p.344 1. $('p').bind('click', {foo: 'bar'}, handler); function handler(e) { alert(e.data.foo); } 자바스크립트 객체지향프로그래밍 #위키북스 p. 2. $('p').load(url, {foo: 'bar'}, callback); //*************** 자바스크립트 패턴 #인사이트 p.92 function func(p, q) { console.log('argument.length: ' + arguments.length); console.log('func.length:' + func.length); } func('p', 'q', 'r'); // func.length:2 , argument.length: 3 func('p'); // func.length:2 , argument.length: 1 //************* jquery에서 each 사용 시 break 또는 continue를 사용해야 할 때 1. continue => return true; 2. break => return false; /**/ $(document).ready(function() { var exUrl = null, storage = null, pushUrl = null, SERVICE_NAME = null, // 퍼펙트자바스크립트 #위키북스 p.486 p.487 localStorage 네임스페이스 관리 support_stroage = window.localStorage || window.sessionStorage, // window['localStorage'] Storage = Storage || window.Storage; // IE if(support_stroage) { // 꼭 필요한 HTML5 그리고 HTML5 API #puple p.242 if(!localStorage.version) { localStorage.version = '1.0'; // } try { storage = JSON.parse(localStorage.SERVICE_NAME || '{}'); } catch(e) { storage = {}; } // storage[key] = value; // localStorage.SERVICE_NAME = JSON.stringify(storage); // this.setItem(localStorage.SERVICE_NAME, JSON.stringify(storage)); function storageEvt(e) { if(e.key === (SERVICE_NAME && e.newValue)) { storage = JSON.parse(e.newValue); } } evt.add('document', 'storage', storageEvt); function setStorage(key, value) { storage[key] = value; localStorage.SERVICE_NAME = JSON.stringify(storage); } try { Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); } } catch(e) { if (e == QUOTA_EXCEEDED_ERR) { alert('할당량 초과!'); } function setItemLocal(key, value) { localStorage.setItem(key, JSON.stringify(value)); } // evt.add('document', 'beforeunload', setItemLocal); } try { Storage.prototype.getObject = function(key) { return this.getItem(key) && JSON.parse(this.getItem(key)); } } catch(e) { function getItemLocal(key) { return JSON.parse(localStorage.getItem(key)); } // evt.add('document', 'load', getItemLocal); } } else { // support_stroage를 지원하지 않는경우 cookie 이용, polyfill보다 동작이 빠르다 $(function() { // 꼭 필요한 HTML5 그리고 HTML5 API #puple p.240 function createCookie(name, value, days) { var expire = ''; if(days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var result = '', nameEQ = name + "=", ca = document.cookie.split(';'); for(var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) =' ') { c = c.substring(1, c.length); } if(c.indexOf(nameEQ) == 0) { result = c.substring(nameEQ.length, c.length); } else { result = ''; } } return result; } localStorage = (function() { return { setItem: function(key, value) { createCookie(key, value, 3000); }, getItem: function(key) { return readCookie(key); }, removeItem: function(key) { createCookie(key, value, 0); } }; } ()); }()); } // EOF if(support_stroage) /**/ /* // polyfill localStorage IE7 에서 영구저장소 이용시 : 인터넷에서 발췌 if(!window.localStorage) window.localStorage = (function () { var userdataKey = 'localStorage', userdata = document.createElement('b'); userdata.style.display = 'none'; userdata.style.behavior = 'url("#default#userData")'; // userdata.addBehavior('#default#userdata'); document.body.appendChild(userdata); userdata.load(userdataKey); return { setItem: function (key, val) { userdata.setAttribute(key, val); userdata.save(userdataKey); }, removeItem: function (key) { userdata.removeAttribute(key); userdata.save(userdataKey); }, getItem: function (key) { return userdata.getAttribute(key); } } })(); /**/ var wn = window.navigator, ws = window.screen, userInfo = { "hp" : "01022223333", "UA" : wn.userAgent, "paltform" : wn.platform, "screen" : ws.width +" * "+ ws.height, "colorDepth" : ws.colorDepth, "last_update" : time.unix_timestamp() }; $.getJSON("http://jsonip.com?callback=?", function(data){ userInfo.ip = data.ip; // alert(userInfo.ip); try { localStorage.setObject('client', userInfo); } catch(e) { localStorage.setItem('client', JSON.stringify(userInfo)); // IE7, IE8 fallback } }); // localStorage.clear(); /* socket.io // 예약이벤트 : message, connect, disconnect, open, close, error, retry, reconnect // json 객체 전송시 socket.emit('message', {msg: '문자열'}) socket.json.send({msg: '문자열'}); // json 객체 수신시 socket.on('message', function (data) { console.log(data.msg);}); var ss; var printMessage = function(msg) { $('#noti').append('<p>' + msg + '</p>'); } var socket = io.connect('http://localhost:52273'); socket.on('news', function (data) { console.log(data.hello); socket.emit('my other event', { my: 'data' }); }); socket.on('co', function (data) { ss = JSON.parse(data); // console.log('data: ' + data); }); socket.on('connect', function () { printMessage('서버의 소켓에 연결되었습니다.'); // 클라이언트에 출력 socket.send('클라이언트에서 보내는 메시지'); // 서버에 출력 }); socket.on('message', function (msg) { printMessage(msg); // console.log(msg); }); socket.on('msg', function (data) { printMessage(data.msg + ' : ' + data.now); }); /**/ var arrangeCol = function() { $('span', 'dd').each(function() { var w = $(this).data('width') || $(this).attr('data-width'); if(w == undefined) return true; $(this).css({'width': w +'px', 'display':'inline-block'}); }); }; if($('#rdoSupplies:checked').length == 1 ) { $('#rdoSupplies').next('label').addClass('active'); } else { $('#rdoPrinter').next('label').addClass('active'); } $('#rdoPrinter, #rdoSupplies').bind({ click: function() { $('#txtKeyString').focus(); $('#frmSearch label').removeClass('active'); $(this).next('label').addClass('active'); } }); $('#txtKeyString').bind({ click: function() { // TODO: 광고는 localStorage에서 가져올 것, 광고에 ID부여하여 표시여부 제어 var waitingAd = "<img id='ad_banner' src='http://placehold.it/200x100' class='fadein[8000]' /> <p>로컬스토리지에 저장된 광고를 끌어옴</p>"; $(this).val(''); $('#site_content').empty().append("<div id='site_content_sub' ></div>"); if($('#ad_banner').length == 0) { $('#site_content_sub').append(waitingAd); } }, keyup: function() { var $searchVal = $(this).val(), num = 0; for (var i=0, len = $searchVal.length; i<len; i++) { var ch = $searchVal.charAt(i).trim(); if(ch.length) { num++; } } if(num < 3) { $('#btnSearch').attr('disabled', true); } else { $('#btnSearch').attr('disabled', false); } } }); $('#loadingImg').bind({ ajaxStart: function() { $(this).removeClass('hidden'); }, ajaxStop: function() { $(this).addClass('hidden'); } }); $('#frmSearch').bind({ submit: function(e) { var $searchVal = $('#txtKeyString').val(), pattern = /[A-Za-z0-9\' \']{3,20}/, $chkRdoVal = $('#rdoPrinter:checked').val() || $('#rdoSupplies:checked').val(), $chkSpanVal = ($chkRdoVal === 'printer') ? '프린터' : '소모품', url = '/2013p79/common/class/search/goto.php', qString = $('#frmSearch').serialize(), num = 0, str = null; e.preventDefault(); for (var i=0, len = $searchVal.length; i<len; i++) { var ch = $searchVal.charAt(i).trim(); if(ch.length) { num++; } } if(!pattern.test($searchVal) || num < 3) { return false; } if(exUrl == qString) { $('#showChoice').empty(); $('dl').removeClass('hidden'); return false; } exUrl = qString; str = url + '?' + qString; $('#site_content_sub').load(str + ' #site_content', arrangeCol); str = str.split('2013p79/'); pushUrl = {"prev_url" : str[1]}; history.pushState(pushUrl, null, '/2013p79/'); // $('#site_footer').remove(); } }); $('#makerPool span a').live({ // 주의: live 사용 click: function(e) { e.preventDefault(); var href = e.target.href.split('#'), waitingAd = "<img src='http://placehold.it/200x100' /><br /> 이곳은 광고 영역입니다.<br /> mouseover시 우측에 광고박스 표시합니다."; $('#showChoice').empty(); $('dl').addClass('hidden'); $('#'+href[1]).closest('dl').clone(true) .appendTo('#showChoice') .removeClass('hidden'); $('#showChoice').append(waitingAd); } }); // $('dd a.mylinks', '#content_main').addcontextmenu('contextmenu1'); $('dd a', '#content_main').live({ // 주의: jquery.1.8이하에서 live 사용 click: function(e) { var serial = $(this).data('serial') || $(this).attr('data-serial') || $(this).dataset.serial, supl = /^s\d{5}/, prt = /^p\d{5}/ str = null ; e.preventDefault(); exUrl = null; $('#site_content_sub').load($(this).attr('href') + ' #site_content', arrangeCol); str = $(this).attr('href').split('2013p79/'); pushUrl = {"prev_url" : str[1]}; history.pushState(pushUrl, null, '/2013p79/'); // $('#site_footer').remove(); if(support_stroage && !!supl.test(serial)) { /* try { SERVICE_NAME = 'SUP'; localStorage.setObject(SERVICE_NAME, time.unix_timestamp()); localStorage.setObject(serial, time.unix_timestamp()); localStorage.setObject(serial, ss); } catch(e) { // IE : Stroage 지원하지 않는 경우 setItemLocal(serial, 'ss'); } /**/ // localStorage.clear(); } /**/ }, contextmenu: function(e) { $(this).css('backgroundColor','yellow'); } /* mouseover: function() { // TODO: 관심품목 등록, 메모 작성메뉴를 이곳에??? }, mouseout: function() { }, contextmenu: function(e) { // TODO: 비즈메뉴(광고등록)를 이곳에??? 비즈회원에게만 조건부 활성화? alert('assa!!'); e.preventDefault(); }, /**/ }); $('#goTop').addClass('hidden'); $(window).scroll(function() { var goTop = $('#goTop'), flag=1; $(goTop).removeClass('hidden'); $(goTop).click(function(){ $(goTop).mouseleave(function() { if(flag == 0) return false; flag = 0; $(goTop).addClass('hidden'); }); }); }); /* window.onpopstate = function() { if(history.state && history.state.prev_url) { // location.replace(history.state.prev_url); location.href = history.state.prev_url; } }; */ $(window).bind('popstate', function() { if(history.state && history.state.prev_url) { // location.replace(history.state.prev_url); location.href = history.state.prev_url; // arrangeCol(); } }); }); /* $(function(){ // contextmenu 목차는 PageSite.php에 $.contextMenu('html5'); // $('.data-title').attr('data-menutitle','OnBiz'); }); */
JavaScript
// JavaScript Document
JavaScript
// JavaScript Document window.onorientationchange = function() { // 자바스크립트쿡북 #한빛미디어 p.187 Sa. var ori = window.orientation; switch(ori) { case 0: // 세로방향 break; case 90: case -90: // 가로방향 break; } }
JavaScript
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; if ($.event.fixHooks) { for ( var i=types.length; i; ) { $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i=types.length; i; ) { this.addEventListener( types[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i=types.length; i; ) { this.removeEventListener( types[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } // New school multidimensional scroll (touchpads) deltas deltaY = delta; // Gecko if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = -1*delta; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })(jQuery); /** * @version 2.0 * @package jquery * @subpackage lofslidernews * @copyright Copyright (C) JAN 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved. * @website http://landofcoder.com * @license This plugin is dual-licensed under the GNU General Public License and the MIT License */ // JavaScript Document (function($) { $.fn.lofJSidernews = function( settings ) { return this.each(function() { // get instance of the lofSiderNew. new $.lofSidernews( this, settings ); }); } $.lofSidernews = function( obj, settings ){ this.settings = { direction : '', mainItemSelector : 'li', navInnerSelector : 'ul', navSelector : 'li' , navigatorEvent : 'click'/* click|mouseenter */, wapperSelector: '.sliders-wrap-inner', interval : 5000, auto : false, // whether to automatic play the slideshow maxItemDisplay : 3, startItem : 0, navPosition : 'vertical',/* values: horizontal|vertical*/ navigatorHeight : 100, navigatorWidth : 310, duration : 600, navItemsSelector : '.navigator-wrap-inner li', navOuterSelector : '.navigator-wrapper' , isPreloaded : true, easing : 'easeInOutQuad', onPlaySlider:function(obj, slider){}, onComplete:function(slider, index){ } } $.extend( this.settings, settings ||{} ); this.nextNo = null; this.previousNo = null; this.maxWidth = this.settings.mainWidth || 684; this.wrapper = $( obj ).find( this.settings.wapperSelector ); var wrapOuter = $('<div class="sliders-wrapper"></div>').width( this.maxWidth ); this.wrapper.wrap( wrapOuter ); this.slides = this.wrapper.find( this.settings.mainItemSelector ); if( !this.wrapper.length || !this.slides.length ) return ; // set width of wapper if( this.settings.maxItemDisplay > this.slides.length ){ this.settings.maxItemDisplay = this.slides.length; } this.currentNo = isNaN(this.settings.startItem)||this.settings.startItem > this.slides.length?0:this.settings.startItem; this.navigatorOuter = $( obj ).find( this.settings.navOuterSelector ); this.navigatorItems = $( obj ).find( this.settings.navItemsSelector ) ; this.navigatorInner = this.navigatorOuter.find( this.settings.navInnerSelector ); // if use automactic calculate width of navigator if( this.settings.navigatorHeight == null || this.settings.navigatorWidth == null ){ this.settings.navigatorHeight = this.navigatorItems.eq(0).outerWidth(true); this.settings.navigatorWidth = this.navigatorItems.eq(0).outerHeight(true); } if( this.settings.navPosition == 'horizontal' ){ this.navigatorInner.width( this.slides.length * this.settings.navigatorWidth ); this.navigatorOuter.width( this.settings.maxItemDisplay * this.settings.navigatorWidth ); this.navigatorOuter.height( this.settings.navigatorHeight ); } else { this.navigatorInner.height( this.slides.length * this.settings.navigatorHeight ); this.navigatorOuter.height( this.settings.maxItemDisplay * this.settings.navigatorHeight ); this.navigatorOuter.width( this.settings.navigatorWidth ); } this.slides.width( this.settings.mainWidth ); this.navigratorStep = this.__getPositionMode( this.settings.navPosition ); this.directionMode = this.__getDirectionMode(); if( this.settings.direction == 'opacity') { this.wrapper.addClass( 'lof-opacity' ); $(this.slides).css({'opacity':0,'z-index':1}).eq(this.currentNo).css({'opacity':1,'z-index':3}); } else { this.wrapper.css({'left':'-'+this.currentNo*this.maxSize+'px', 'width':( this.maxWidth ) * this.slides.length } ); } if( this.settings.isPreloaded ) { this.preLoadImage( this.onComplete ); } else { this.onComplete(); } $buttonControl = $( ".button-control", obj); if( this.settings.auto ){ $buttonControl.addClass("action-stop"); } else { $buttonControl.addClass("action-start"); } var self = this; $( obj ).hover(function(){ self.stop(); $buttonControl.addClass("action-start").removeClass("action-stop").addClass("hover-stop"); }, function(){ if( $buttonControl.hasClass("hover-stop") ){ if( self.settings.auto ){ $buttonControl.removeClass("action-start").removeClass("hover-stop").addClass("action-stop"); self.play( self.settings.interval,'next', true ); } } } ); $buttonControl.click( function() { if( $buttonControl.hasClass("action-start") ){ self.settings.auto =true; self.play( self.settings.interval,'next', true ); $buttonControl.removeClass("action-start").addClass("action-stop"); } else{ self.settings.auto =false; self.stop(); $buttonControl.addClass("action-start").removeClass("action-stop"); } } ); } $.lofSidernews.fn = $.lofSidernews.prototype; $.lofSidernews.fn.extend = $.lofSidernews.extend = $.extend; $.lofSidernews.fn.extend({ startUp:function( obj, wrapper ) { seft = this; this.navigatorItems.each( function(index, item ){ $(item).bind( seft.settings.navigatorEvent,( function(){ seft.jumping( index, true ); seft.setNavActive( index, item ); } )); $(item).css( {'height': seft.settings.navigatorHeight, 'width': seft.settings.navigatorWidth} ); }) this.registerWheelHandler( this.navigatorOuter, this ); this.setNavActive( this.currentNo ); this.settings.onComplete( this.slides.eq(this.currentNo ),this.currentNo ); if( this.settings.buttons && typeof (this.settings.buttons) == "object" ){ this.registerButtonsControl( 'click', this.settings.buttons, this ); } if( this.settings.auto ) this.play( this.settings.interval,'next', true ); return this; }, onComplete:function(){ setTimeout( function(){ $('.preload').fadeOut( 900, function(){ $('.preload').remove(); } ); }, 400 ); this.startUp( ); }, preLoadImage:function( callback ){ var self = this; var images = this.wrapper.find( 'img' ); var count = 0; images.each( function(index,image){ if( !image.complete ){ image.onload =function(){ count++; if( count >= images.length ){ self.onComplete(); } } image.onerror =function(){ count++; if( count >= images.length ){ self.onComplete(); } } }else { count++; if( count >= images.length ){ self.onComplete(); } } } ); }, navivationAnimate:function( currentIndex ) { if (currentIndex <= this.settings.startItem || currentIndex - this.settings.startItem >= this.settings.maxItemDisplay-1) { this.settings.startItem = currentIndex - this.settings.maxItemDisplay+2; if (this.settings.startItem < 0) this.settings.startItem = 0; if (this.settings.startItem >this.slides.length-this.settings.maxItemDisplay) { this.settings.startItem = this.slides.length-this.settings.maxItemDisplay; } } this.navigatorInner.stop().animate( eval('({'+this.navigratorStep[0]+':-'+this.settings.startItem*this.navigratorStep[1]+'})'), {duration:500, easing:'easeInOutQuad'} ); }, setNavActive:function( index, item ){ if( (this.navigatorItems) ){ this.navigatorItems.removeClass( 'active' ); $(this.navigatorItems.get(index)).addClass( 'active' ); this.navivationAnimate( this.currentNo ); } }, __getPositionMode:function( position ){ if( position == 'horizontal' ){ return ['left', this.settings.navigatorWidth]; } return ['top', this.settings.navigatorHeight]; }, __getDirectionMode:function(){ switch( this.settings.direction ){ case 'opacity': this.maxSize=0; return ['opacity','opacity']; default: this.maxSize=this.maxWidth; return ['left','width']; } }, registerWheelHandler:function( element, obj ){ element.bind('mousewheel', function(event, delta ) { var dir = delta > 0 ? 'Up' : 'Down', vel = Math.abs(delta); if( delta > 0 ){ obj.previous( true ); } else { obj.next( true ); } return false; }); }, registerButtonsControl:function( eventHandler, objects, self ){ for( var action in objects ){ switch (action.toString() ){ case 'next': objects[action].click( function() { self.next( true) } ); break; case 'previous': objects[action].click( function() { self.previous( true) } ); break; } } return this; }, onProcessing:function( manual, start, end ){ this.previousNo = this.currentNo + (this.currentNo>0 ? -1 : this.slides.length-1); this.nextNo = this.currentNo + (this.currentNo < this.slides.length-1 ? 1 : 1- this.slides.length); return this; }, finishFx:function( manual ){ if( manual ) this.stop(); if( manual && this.settings.auto ){ this.play( this.settings.interval,'next', true ); } this.setNavActive( this.currentNo ); this.settings.onPlaySlider( this, $(this.slides).eq(this.currentNo) ); }, getObjectDirection:function( start, end ){ return eval("({'"+this.directionMode[0]+"':-"+(this.currentNo*start)+"})"); }, fxStart:function( index, obj, currentObj ){ var s = this; if( this.settings.direction == 'opacity' ) { $(this.slides).stop().animate({opacity:0}, {duration: this.settings.duration, easing:this.settings.easing,complete:function(){ s.slides.css("z-index","1") s.slides.eq(index).css("z-index","3"); }} ); $(this.slides).eq(index).stop().animate( {opacity:1}, { duration : this.settings.duration, easing :this.settings.easing, complete :function(){ s.settings.onComplete($(s.slides).eq(index),index); }} ); }else { this.wrapper.stop().animate( obj, {duration: this.settings.duration, easing:this.settings.easing,complete:function(){ s.settings.onComplete($(s.slides).eq(index),index) } } ); } return this; }, jumping:function( no, manual ){ this.stop(); if( this.currentNo == no ) return; var obj = eval("({'"+this.directionMode[0]+"':-"+(this.maxSize*no)+"})"); this.onProcessing( null, manual, 0, this.maxSize ) .fxStart( no, obj, this ) .finishFx( manual ); this.currentNo = no; }, next:function( manual , item){ this.currentNo += (this.currentNo < this.slides.length-1) ? 1 : (1 - this.slides.length); this.onProcessing( item, manual, 0, this.maxSize ) .fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this ) .finishFx( manual ); }, previous:function( manual, item ){ this.currentNo += this.currentNo > 0 ? -1 : this.slides.length - 1; this.onProcessing( item, manual ) .fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this ) .finishFx( manual ); }, play:function( delay, direction, wait ){ this.stop(); if(!wait){ this[direction](false); } var self = this; this.isRun = setTimeout(function() { self[direction](true); }, delay); }, stop:function(){ if (this.isRun == null) return; clearTimeout(this.isRun); this.isRun = null; } }) })(jQuery)
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * 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 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 OWNER 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. * */ // t: current time, b: begInnIng value, c: change In value, d: duration jQuery.easing['jswing'] = jQuery.easing['swing']; jQuery.extend( jQuery.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert(jQuery.easing.default); return jQuery.easing[jQuery.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * 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 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 OWNER 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. * */
JavaScript
/** * TextAreaExpander plugin for jQuery * v1.0 * Expands or contracts a textarea height depending on the * quatity of content entered by the user in the box. * * By Craig Buckler, Optimalworks.net * * As featured on SitePoint.com: * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/ * * Please use as you wish at your own risk. */ /** * Usage: * * From JavaScript, use: * $(<node>).TextAreaExpander(<minHeight>, <maxHeight>); * where: * <node> is the DOM node selector, e.g. "textarea" * <minHeight> is the minimum textarea height in pixels (optional) * <maxHeight> is the maximum textarea height in pixels (optional) * * Alternatively, in you HTML: * Assign a class of "expand" to any <textarea> tag. * e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea> * * Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height. * e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea> * The textarea will use an appropriate height between 50 and 200 pixels. */ (function($) { // jQuery plugin definition $.fn.TextAreaExpander = function(minHeight, maxHeight) { var hCheck = !($.browser.msie || $.browser.opera); // resize a textarea function ResizeTextarea(e) { // event or initialize element? e = e.target || e; // find content length and box width var vlen = e.value.length, ewidth = e.offsetWidth; if (vlen != e.valLength || ewidth != e.boxWidth) { if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px"; var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax)); e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden"); e.style.height = h + "px"; e.valLength = vlen; e.boxWidth = ewidth; } return true; }; // initialize this.each(function() { // is a textarea? if (this.nodeName.toLowerCase() != "textarea") return; // set height restrictions var p = this.className.match(/expand(\d+)\-*(\d+)*/i); this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0); this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999); // initial resize ResizeTextarea(this); // zero vertical padding and add events if (!this.Initialized) { this.Initialized = true; $(this).css("padding-top", 0).css("padding-bottom", 0); $(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea); } }); return this; }; })(jQuery); // initialize all expanding textareas jQuery(document).ready(function() { jQuery("textarea[class*=expand]").TextAreaExpander(); });
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * 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 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 OWNER 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. * */ // t: current time, b: begInnIng value, c: change In value, d: duration eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{})) /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * 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 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 OWNER 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. * */
JavaScript
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.4 * * Requires: 1.2.2+ */ (function(d){function g(a){var b=a||window.event,i=[].slice.call(arguments,1),c=0,h=0,e=0;a=d.event.fix(b);a.type="mousewheel";if(a.wheelDelta)c=a.wheelDelta/120;if(a.detail)c=-a.detail/3;e=c;if(b.axis!==undefined&&b.axis===b.HORIZONTAL_AXIS){e=0;h=-1*c}if(b.wheelDeltaY!==undefined)e=b.wheelDeltaY/120;if(b.wheelDeltaX!==undefined)h=-1*b.wheelDeltaX/120;i.unshift(a,c,h,e);return d.event.handle.apply(this,i)}var f=["DOMMouseScroll","mousewheel"];d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a= f.length;a;)this.addEventListener(f[--a],g,false);else this.onmousewheel=g},teardown:function(){if(this.removeEventListener)for(var a=f.length;a;)this.removeEventListener(f[--a],g,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
JavaScript
/* * FancyBox - jQuery Plugin * Simple and fancy lightbox alternative * * Examples and documentation at: http://fancybox.net * * Copyright (c) 2008 - 2010 Janis Skarnelis * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated. * * Version: 1.3.4 (11/11/2010) * Requires: jQuery v1.3+ * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right, selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [], ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i, loadingTimer, loadingFrame = 1, titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }), isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest, /* * Private methods */ _abort = function() { loading.hide(); imgPreloader.onerror = imgPreloader.onload = null; if (ajaxLoader) { ajaxLoader.abort(); } tmp.empty(); }, _error = function() { if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) { loading.hide(); busy = false; return; } selectedOpts.titleShow = false; selectedOpts.width = 'auto'; selectedOpts.height = 'auto'; tmp.html( '<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' ); _process_inline(); }, _start = function() { var obj = selectedArray[ selectedIndex ], href, type, title, str, emb, ret; _abort(); selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox'))); ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts); if (ret === false) { busy = false; return; } else if (typeof ret == 'object') { selectedOpts = $.extend(selectedOpts, ret); } title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || ''; if (obj.nodeName && !selectedOpts.orig) { selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj); } if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) { title = selectedOpts.orig.attr('alt'); } href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null; if ((/^(?:javascript)/i).test(href) || href == '#') { href = null; } if (selectedOpts.type) { type = selectedOpts.type; if (!href) { href = selectedOpts.content; } } else if (selectedOpts.content) { type = 'html'; } else if (href) { if (href.match(imgRegExp)) { type = 'image'; } else if (href.match(swfRegExp)) { type = 'swf'; } else if ($(obj).hasClass("iframe")) { type = 'iframe'; } else if (href.indexOf("#") === 0) { type = 'inline'; } else { type = 'ajax'; } } if (!type) { _error(); return; } if (type == 'inline') { obj = href.substr(href.indexOf("#")); type = $(obj).length > 0 ? 'inline' : 'ajax'; } selectedOpts.type = type; selectedOpts.href = href; selectedOpts.title = title; if (selectedOpts.autoDimensions) { if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') { selectedOpts.width = 'auto'; selectedOpts.height = 'auto'; } else { selectedOpts.autoDimensions = false; } } if (selectedOpts.modal) { selectedOpts.overlayShow = true; selectedOpts.hideOnOverlayClick = false; selectedOpts.hideOnContentClick = false; selectedOpts.enableEscapeButton = false; selectedOpts.showCloseButton = false; } selectedOpts.padding = parseInt(selectedOpts.padding, 10); selectedOpts.margin = parseInt(selectedOpts.margin, 10); tmp.css('padding', (selectedOpts.padding + selectedOpts.margin)); $('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() { $(this).replaceWith(content.children()); }); switch (type) { case 'html' : tmp.html( selectedOpts.content ); _process_inline(); break; case 'inline' : if ( $(obj).parent().is('#fancybox-content') === true) { busy = false; return; } $('<div class="fancybox-inline-tmp" />') .hide() .insertBefore( $(obj) ) .bind('fancybox-cleanup', function() { $(this).replaceWith(content.children()); }).bind('fancybox-cancel', function() { $(this).replaceWith(tmp.children()); }); $(obj).appendTo(tmp); _process_inline(); break; case 'image': busy = false; $.fancybox.showActivity(); imgPreloader = new Image(); imgPreloader.onerror = function() { _error(); }; imgPreloader.onload = function() { busy = true; imgPreloader.onerror = imgPreloader.onload = null; _process_image(); }; imgPreloader.src = href; break; case 'swf': selectedOpts.scrolling = 'no'; str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>'; emb = ''; $.each(selectedOpts.swf, function(name, val) { str += '<param name="' + name + '" value="' + val + '"></param>'; emb += ' ' + name + '="' + val + '"'; }); str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>'; tmp.html(str); _process_inline(); break; case 'ajax': busy = false; $.fancybox.showActivity(); selectedOpts.ajax.win = selectedOpts.ajax.success; ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, { url : href, data : selectedOpts.ajax.data || {}, error : function(XMLHttpRequest, textStatus, errorThrown) { if ( XMLHttpRequest.status > 0 ) { _error(); } }, success : function(data, textStatus, XMLHttpRequest) { var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader; if (o.status == 200) { if ( typeof selectedOpts.ajax.win == 'function' ) { ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest); if (ret === false) { loading.hide(); return; } else if (typeof ret == 'string' || typeof ret == 'object') { data = ret; } } tmp.html( data ); _process_inline(); } } })); break; case 'iframe': _show(); break; } }, _process_inline = function() { var w = selectedOpts.width, h = selectedOpts.height; if (w.toString().indexOf('%') > -1) { w = parseInt( ($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px'; } else { w = w == 'auto' ? 'auto' : w + 'px'; } if (h.toString().indexOf('%') > -1) { h = parseInt( ($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px'; } else { h = h == 'auto' ? 'auto' : h + 'px'; } tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>'); selectedOpts.width = tmp.width(); selectedOpts.height = tmp.height(); _show(); }, _process_image = function() { selectedOpts.width = imgPreloader.width; selectedOpts.height = imgPreloader.height; $("<img />").attr({ 'id' : 'fancybox-img', 'src' : imgPreloader.src, 'alt' : selectedOpts.title }).appendTo( tmp ); _show(); }, _show = function() { var pos, equal; loading.hide(); if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) { $.event.trigger('fancybox-cancel'); busy = false; return; } busy = true; $(content.add( overlay )).unbind(); $(window).unbind("resize.fb scroll.fb"); $(document).unbind('keydown.fb'); if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') { wrap.css('height', wrap.height()); } currentArray = selectedArray; currentIndex = selectedIndex; currentOpts = selectedOpts; if (currentOpts.overlayShow) { overlay.css({ 'background-color' : currentOpts.overlayColor, 'opacity' : currentOpts.overlayOpacity, 'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto', 'height' : $(document).height() }); if (!overlay.is(':visible')) { if (isIE6) { $('select:not(#fancybox-tmp select)').filter(function() { return this.style.visibility !== 'hidden'; }).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() { this.style.visibility = 'inherit'; }); } overlay.show(); } } else { overlay.hide(); } final_pos = _get_zoom_to(); _process_title(); if (wrap.is(":visible")) { $( close.add( nav_left ).add( nav_right ) ).hide(); pos = wrap.position(), start_pos = { top : pos.top, left : pos.left, width : wrap.width(), height : wrap.height() }; equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height); content.fadeTo(currentOpts.changeFade, 0.3, function() { var finish_resizing = function() { content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish); }; $.event.trigger('fancybox-change'); content .empty() .removeAttr('filter') .css({ 'border-width' : currentOpts.padding, 'width' : final_pos.width - currentOpts.padding * 2, 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2 }); if (equal) { finish_resizing(); } else { fx.prop = 0; $(fx).animate({prop: 1}, { duration : currentOpts.changeSpeed, easing : currentOpts.easingChange, step : _draw, complete : finish_resizing }); } }); return; } wrap.removeAttr("style"); content.css('border-width', currentOpts.padding); if (currentOpts.transitionIn == 'elastic') { start_pos = _get_zoom_from(); content.html( tmp.contents() ); wrap.show(); if (currentOpts.opacity) { final_pos.opacity = 0; } fx.prop = 0; $(fx).animate({prop: 1}, { duration : currentOpts.speedIn, easing : currentOpts.easingIn, step : _draw, complete : _finish }); return; } if (currentOpts.titlePosition == 'inside' && titleHeight > 0) { title.show(); } content .css({ 'width' : final_pos.width - currentOpts.padding * 2, 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2 }) .html( tmp.contents() ); wrap .css(final_pos) .fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish ); }, _format_title = function(title) { if (title && title.length) { if (currentOpts.titlePosition == 'float') { return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>'; } return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>'; } return false; }, _process_title = function() { titleStr = currentOpts.title || ''; titleHeight = 0; title .empty() .removeAttr('style') .removeClass(); if (currentOpts.titleShow === false) { title.hide(); return; } titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr); if (!titleStr || titleStr === '') { title.hide(); return; } title .addClass('fancybox-title-' + currentOpts.titlePosition) .html( titleStr ) .appendTo( 'body' ) .show(); switch (currentOpts.titlePosition) { case 'inside': title .css({ 'width' : final_pos.width - (currentOpts.padding * 2), 'marginLeft' : currentOpts.padding, 'marginRight' : currentOpts.padding }); titleHeight = title.outerHeight(true); title.appendTo( outer ); final_pos.height += titleHeight; break; case 'over': title .css({ 'marginLeft' : currentOpts.padding, 'width' : final_pos.width - (currentOpts.padding * 2), 'bottom' : currentOpts.padding }) .appendTo( outer ); break; case 'float': title .css('left', parseInt((title.width() - final_pos.width - 40)/ 2, 10) * -1) .appendTo( wrap ); break; default: title .css({ 'width' : final_pos.width - (currentOpts.padding * 2), 'paddingLeft' : currentOpts.padding, 'paddingRight' : currentOpts.padding }) .appendTo( wrap ); break; } title.hide(); }, _set_navigation = function() { if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) { $(document).bind('keydown.fb', function(e) { if (e.keyCode == 27 && currentOpts.enableEscapeButton) { e.preventDefault(); $.fancybox.close(); } else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') { e.preventDefault(); $.fancybox[ e.keyCode == 37 ? 'prev' : 'next'](); } }); } if (!currentOpts.showNavArrows) { nav_left.hide(); nav_right.hide(); return; } if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) { nav_left.show(); } if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) { nav_right.show(); } }, _finish = function () { if (!$.support.opacity) { content.get(0).style.removeAttribute('filter'); wrap.get(0).style.removeAttribute('filter'); } if (selectedOpts.autoDimensions) { content.css('height', 'auto'); } wrap.css('height', 'auto'); if (titleStr && titleStr.length) { title.show(); } if (currentOpts.showCloseButton) { close.show(); } _set_navigation(); if (currentOpts.hideOnContentClick) { content.bind('click', $.fancybox.close); } if (currentOpts.hideOnOverlayClick) { overlay.bind('click', $.fancybox.close); } $(window).bind("resize.fb", $.fancybox.resize); if (currentOpts.centerOnScroll) { $(window).bind("scroll.fb", $.fancybox.center); } if (currentOpts.type == 'iframe') { $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content); } wrap.show(); busy = false; $.fancybox.center(); currentOpts.onComplete(currentArray, currentIndex, currentOpts); _preload_images(); }, _preload_images = function() { var href, objNext; if ((currentArray.length -1) > currentIndex) { href = currentArray[ currentIndex + 1 ].href; if (typeof href !== 'undefined' && href.match(imgRegExp)) { objNext = new Image(); objNext.src = href; } } if (currentIndex > 0) { href = currentArray[ currentIndex - 1 ].href; if (typeof href !== 'undefined' && href.match(imgRegExp)) { objNext = new Image(); objNext.src = href; } } }, _draw = function(pos) { var dim = { width : parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10), height : parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10), top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10), left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10) }; if (typeof final_pos.opacity !== 'undefined') { dim.opacity = pos < 0.5 ? 0.5 : pos; } wrap.css(dim); content.css({ 'width' : dim.width - currentOpts.padding * 2, 'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2 }); }, _get_viewport = function() { return [ $(window).width() - (currentOpts.margin * 2), $(window).height() - (currentOpts.margin * 2), $(document).scrollLeft() + currentOpts.margin, $(document).scrollTop() + currentOpts.margin ]; }, _get_zoom_to = function () { var view = _get_viewport(), to = {}, resize = currentOpts.autoScale, double_padding = currentOpts.padding * 2, ratio; if (currentOpts.width.toString().indexOf('%') > -1) { to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10); } else { to.width = currentOpts.width + double_padding; } if (currentOpts.height.toString().indexOf('%') > -1) { to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10); } else { to.height = currentOpts.height + double_padding; } if (resize && (to.width > view[0] || to.height > view[1])) { if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') { ratio = (currentOpts.width ) / (currentOpts.height ); if ((to.width ) > view[0]) { to.width = view[0]; to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10); } if ((to.height) > view[1]) { to.height = view[1]; to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10); } } else { to.width = Math.min(to.width, view[0]); to.height = Math.min(to.height, view[1]); } } to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10); to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10); return to; }, _get_obj_pos = function(obj) { var pos = obj.offset(); pos.top += parseInt( obj.css('paddingTop'), 10 ) || 0; pos.left += parseInt( obj.css('paddingLeft'), 10 ) || 0; pos.top += parseInt( obj.css('border-top-width'), 10 ) || 0; pos.left += parseInt( obj.css('border-left-width'), 10 ) || 0; pos.width = obj.width(); pos.height = obj.height(); return pos; }, _get_zoom_from = function() { var orig = selectedOpts.orig ? $(selectedOpts.orig) : false, from = {}, pos, view; if (orig && orig.length) { pos = _get_obj_pos(orig); from = { width : pos.width + (currentOpts.padding * 2), height : pos.height + (currentOpts.padding * 2), top : pos.top - currentOpts.padding - 20, left : pos.left - currentOpts.padding - 20 }; } else { view = _get_viewport(); from = { width : currentOpts.padding * 2, height : currentOpts.padding * 2, top : parseInt(view[3] + view[1] * 0.5, 10), left : parseInt(view[2] + view[0] * 0.5, 10) }; } return from; }, _animate_loading = function() { if (!loading.is(':visible')){ clearInterval(loadingTimer); return; } $('div', loading).css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; /* * Public methods */ $.fn.fancybox = function(options) { if (!$(this).length) { return this; } $(this) .data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {}))) .unbind('click.fb') .bind('click.fb', function(e) { e.preventDefault(); if (busy) { return; } busy = true; $(this).blur(); selectedArray = []; selectedIndex = 0; var rel = $(this).attr('rel') || ''; if (!rel || rel == '' || rel === 'nofollow') { selectedArray.push(this); } else { selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]"); selectedIndex = selectedArray.index( this ); } _start(); return; }); return this; }; $.fancybox = function(obj) { var opts; if (busy) { return; } busy = true; opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {}; selectedArray = []; selectedIndex = parseInt(opts.index, 10) || 0; if ($.isArray(obj)) { for (var i = 0, j = obj.length; i < j; i++) { if (typeof obj[i] == 'object') { $(obj[i]).data('fancybox', $.extend({}, opts, obj[i])); } else { obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts)); } } selectedArray = jQuery.merge(selectedArray, obj); } else { if (typeof obj == 'object') { $(obj).data('fancybox', $.extend({}, opts, obj)); } else { obj = $({}).data('fancybox', $.extend({content : obj}, opts)); } selectedArray.push(obj); } if (selectedIndex > selectedArray.length || selectedIndex < 0) { selectedIndex = 0; } _start(); }; $.fancybox.showActivity = function() { clearInterval(loadingTimer); loading.show(); loadingTimer = setInterval(_animate_loading, 66); }; $.fancybox.hideActivity = function() { loading.hide(); }; $.fancybox.next = function() { return $.fancybox.pos( currentIndex + 1); }; $.fancybox.prev = function() { return $.fancybox.pos( currentIndex - 1); }; $.fancybox.pos = function(pos) { if (busy) { return; } pos = parseInt(pos); selectedArray = currentArray; if (pos > -1 && pos < currentArray.length) { selectedIndex = pos; _start(); } else if (currentOpts.cyclic && currentArray.length > 1) { selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1; _start(); } return; }; $.fancybox.cancel = function() { if (busy) { return; } busy = true; $.event.trigger('fancybox-cancel'); _abort(); selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts); busy = false; }; // Note: within an iframe use - parent.$.fancybox.close(); $.fancybox.close = function() { if (busy || wrap.is(':hidden')) { return; } busy = true; if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) { busy = false; return; } _abort(); $(close.add( nav_left ).add( nav_right )).hide(); $(content.add( overlay )).unbind(); $(window).unbind("resize.fb scroll.fb"); $(document).unbind('keydown.fb'); content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank'); if (currentOpts.titlePosition !== 'inside') { title.empty(); } wrap.stop(); function _cleanup() { overlay.fadeOut('fast'); title.empty().hide(); wrap.hide(); $.event.trigger('fancybox-cleanup'); content.empty(); currentOpts.onClosed(currentArray, currentIndex, currentOpts); currentArray = selectedOpts = []; currentIndex = selectedIndex = 0; currentOpts = selectedOpts = {}; busy = false; } if (currentOpts.transitionOut == 'elastic') { start_pos = _get_zoom_from(); var pos = wrap.position(); final_pos = { top : pos.top , left : pos.left, width : wrap.width(), height : wrap.height() }; if (currentOpts.opacity) { final_pos.opacity = 1; } title.empty().hide(); fx.prop = 1; $(fx).animate({ prop: 0 }, { duration : currentOpts.speedOut, easing : currentOpts.easingOut, step : _draw, complete : _cleanup }); } else { wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup); } }; $.fancybox.resize = function() { if (overlay.is(':visible')) { overlay.css('height', $(document).height()); } $.fancybox.center(true); }; $.fancybox.center = function() { var view, align; if (busy) { return; } align = arguments[0] === true ? 1 : 0; view = _get_viewport(); if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) { return; } wrap .stop() .animate({ 'top' : parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)), 'left' : parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding)) }, typeof arguments[0] == 'number' ? arguments[0] : 200); }; $.fancybox.init = function() { if ($("#fancybox-wrap").length) { return; } $('body').append( tmp = $('<div id="fancybox-tmp"></div>'), loading = $('<div id="fancybox-loading"><div></div></div>'), overlay = $('<div id="fancybox-overlay"></div>'), wrap = $('<div id="fancybox-wrap"></div>') ); outer = $('<div id="fancybox-outer"></div>') .append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>') .appendTo( wrap ); outer.append( content = $('<div id="fancybox-content"></div>'), close = $('<a id="fancybox-close"></a>'), title = $('<div id="fancybox-title"></div>'), nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'), nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>') ); close.click($.fancybox.close); loading.click($.fancybox.cancel); nav_left.click(function(e) { e.preventDefault(); $.fancybox.prev(); }); nav_right.click(function(e) { e.preventDefault(); $.fancybox.next(); }); if ($.fn.mousewheel) { wrap.bind('mousewheel.fb', function(e, delta) { if (busy) { e.preventDefault(); } else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) { e.preventDefault(); $.fancybox[ delta > 0 ? 'prev' : 'next'](); } }); } if (!$.support.opacity) { wrap.addClass('fancybox-ie'); } if (isIE6) { loading.addClass('fancybox-ie6'); wrap.addClass('fancybox-ie6'); $('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer); } }; $.fn.fancybox.defaults = { padding : 0, margin : 30, opacity : false, modal : false, cyclic : false, scrolling : 'auto', // 'auto', 'yes' or 'no' width : 560, height : 340, autoScale : true, autoDimensions : true, centerOnScroll : false, ajax : {}, swf : { wmode: 'transparent' }, hideOnOverlayClick : true, hideOnContentClick : false, overlayShow : true, overlayOpacity : 0.7, overlayColor : '#777', titleShow : true, titlePosition : 'float', // 'float', 'outside', 'inside' or 'over' titleFormat : null, titleFromAlt : false, transitionIn : 'fade', // 'elastic', 'fade' or 'none' transitionOut : 'fade', // 'elastic', 'fade' or 'none' speedIn : 300, speedOut : 300, changeSpeed : 300, changeFade : 'fast', easingIn : 'swing', easingOut : 'swing', showCloseButton : true, showNavArrows : true, enableEscapeButton : true, enableKeyboardNav : true, onStart : function(){}, onCancel : function(){}, onComplete : function(){}, onCleanup : function(){}, onClosed : function(){}, onError : function(){} }; $(document).ready(function() { $.fancybox.init(); }); })(jQuery);
JavaScript
/*! * jQuery Raty - A Star Rating Plugin - http://wbotelhos.com/raty * ------------------------------------------------------------------- * * jQuery Raty is a plugin that generates a customizable star rating. * * Licensed under The MIT License * * @version 2.4.5 * @since 2010.06.11 * @author Washington Botelho * @documentation wbotelhos.com/raty * @twitter twitter.com/wbotelhos * * Usage: * ------------------------------------------------------------------- * $('#star').raty(); * * <div id="star"></div> * */ ;(function($) { var methods = { init: function(settings) { return this.each(function() { var self = this, $this = $(self).empty(); self.opt = $.extend(true, {}, $.fn.raty.defaults, settings); $this.data('settings', self.opt); self.opt.number = methods.between(self.opt.number, 0, 20); if (self.opt.path.substring(self.opt.path.length - 1, self.opt.path.length) != '/') { self.opt.path += '/'; } if (typeof self.opt.score == 'function') { self.opt.score = self.opt.score.call(self); } if (self.opt.score) { self.opt.score = methods.between(self.opt.score, 0, self.opt.number); } for (var i = 1; i <= self.opt.number; i++) { $('<img />', { src : self.opt.path + ((!self.opt.score || self.opt.score < i) ? self.opt.starOff : self.opt.starOn), alt : i, title : (i <= self.opt.hints.length && self.opt.hints[i - 1] !== null) ? self.opt.hints[i - 1] : i }).appendTo(self); if (self.opt.space) { $this.append((i < self.opt.number) ? '&#160;' : ''); } } self.stars = $this.children('img:not(".raty-cancel")'); self.score = $('<input />', { type: 'hidden', name: self.opt.scoreName }).appendTo(self); if (self.opt.score && self.opt.score > 0) { self.score.val(self.opt.score); methods.roundStar.call(self, self.opt.score); } if (self.opt.iconRange) { methods.fill.call(self, self.opt.score); } methods.setTarget.call(self, self.opt.score, self.opt.targetKeep); var space = self.opt.space ? 4 : 0, width = self.opt.width || (self.opt.number * self.opt.size + self.opt.number * space); if (self.opt.cancel) { self.cancel = $('<img />', { src: self.opt.path + self.opt.cancelOff, alt: 'x', title: self.opt.cancelHint, 'class': 'raty-cancel' }); if (self.opt.cancelPlace == 'left') { $this.prepend('&#160;').prepend(self.cancel); } else { $this.append('&#160;').append(self.cancel); } width += (self.opt.size + space); } if (self.opt.readOnly) { methods.fixHint.call(self); if (self.cancel) { self.cancel.hide(); } } else { $this.css('cursor', 'pointer'); methods.bindAction.call(self); } $this.css('width', width); }); }, between: function(value, min, max) { return Math.min(Math.max(parseFloat(value), min), max); }, bindAction: function() { var self = this, $this = $(self); $this.mouseleave(function() { var score = self.score.val() || undefined; methods.initialize.call(self, score); methods.setTarget.call(self, score, self.opt.targetKeep); if (self.opt.mouseover) { self.opt.mouseover.call(self, score); } }); var action = self.opt.half ? 'mousemove' : 'mouseover'; if (self.opt.cancel) { self.cancel.mouseenter(function() { $(this).attr('src', self.opt.path + self.opt.cancelOn); self.stars.attr('src', self.opt.path + self.opt.starOff); methods.setTarget.call(self, null, true); if (self.opt.mouseover) { self.opt.mouseover.call(self, null); } }).mouseleave(function() { $(this).attr('src', self.opt.path + self.opt.cancelOff); if (self.opt.mouseover) { self.opt.mouseover.call(self, self.score.val() || null); } }).click(function(evt) { self.score.removeAttr('value'); if (self.opt.click) { self.opt.click.call(self, null, evt); } }); } self.stars.bind(action, function(evt) { var value = parseInt(this.alt, 10); if (self.opt.half) { var position = parseFloat((evt.pageX - $(this).offset().left) / self.opt.size), diff = (position > .5) ? 1 : .5; value = parseFloat(this.alt) - 1 + diff; methods.fill.call(self, value); if (self.opt.precision) { value = value - diff + position; } methods.showHalf.call(self, value); } else { methods.fill.call(self, value); } $this.data('score', value); methods.setTarget.call(self, value, true); if (self.opt.mouseover) { self.opt.mouseover.call(self, value, evt); } }).click(function(evt) { self.score.val((self.opt.half || self.opt.precision) ? $this.data('score') : this.alt); if (self.opt.click) { self.opt.click.call(self, self.score.val(), evt); } }); }, cancel: function(isClick) { return $(this).each(function() { var self = this, $this = $(self); if ($this.data('readonly') === true) { return this; } if (isClick) { methods.click.call(self, null); } else { methods.score.call(self, null); } self.score.removeAttr('value'); }); }, click: function(score) { return $(this).each(function() { if ($(this).data('readonly') === true) { return this; } methods.initialize.call(this, score); if (this.opt.click) { this.opt.click.call(this, score); } else { methods.error.call(this, 'you must add the "click: function(score, evt) { }" callback.'); } methods.setTarget.call(this, score, true); }); }, error: function(message) { $(this).html(message); $.error(message); }, fill: function(score) { var self = this, number = self.stars.length, count = 0, $star , star , icon ; for (var i = 1; i <= number; i++) { $star = self.stars.eq(i - 1); if (self.opt.iconRange && self.opt.iconRange.length > count) { star = self.opt.iconRange[count]; if (self.opt.single) { icon = (i == score) ? (star.on || self.opt.starOn) : (star.off || self.opt.starOff); } else { icon = (i <= score) ? (star.on || self.opt.starOn) : (star.off || self.opt.starOff); } if (i <= star.range) { $star.attr('src', self.opt.path + icon); } if (i == star.range) { count++; } } else { if (self.opt.single) { icon = (i == score) ? self.opt.starOn : self.opt.starOff; } else { icon = (i <= score) ? self.opt.starOn : self.opt.starOff; } $star.attr('src', self.opt.path + icon); } } }, fixHint: function() { var $this = $(this), score = parseInt(this.score.val(), 10), hint = this.opt.noRatedMsg; if (!isNaN(score) && score > 0) { hint = (score <= this.opt.hints.length && this.opt.hints[score - 1] !== null) ? this.opt.hints[score - 1] : score; } $this.data('readonly', true).css('cursor', 'default').attr('title', hint); this.score.attr('readonly', 'readonly'); this.stars.attr('title', hint); }, getScore: function() { var score = [], value ; $(this).each(function() { value = this.score.val(); score.push(value ? parseFloat(value) : undefined); }); return (score.length > 1) ? score : score[0]; }, readOnly: function(isReadOnly) { return this.each(function() { var $this = $(this); if ($this.data('readonly') === isReadOnly) { return this; } if (this.cancel) { if (isReadOnly) { this.cancel.hide(); } else { this.cancel.show(); } } if (isReadOnly) { $this.unbind(); $this.children('img').unbind(); methods.fixHint.call(this); } else { methods.bindAction.call(this); methods.unfixHint.call(this); } $this.data('readonly', isReadOnly); }); }, reload: function() { return methods.set.call(this, {}); }, roundStar: function(score) { var diff = (score - Math.floor(score)).toFixed(2); if (diff > this.opt.round.down) { var icon = this.opt.starOn; // Full up: [x.76 .. x.99] if (diff < this.opt.round.up && this.opt.halfShow) { // Half: [x.26 .. x.75] icon = this.opt.starHalf; } else if (diff < this.opt.round.full) { // Full down: [x.00 .. x.5] icon = this.opt.starOff; } this.stars.eq(Math.ceil(score) - 1).attr('src', this.opt.path + icon); } // Full down: [x.00 .. x.25] }, score: function() { return arguments.length ? methods.setScore.apply(this, arguments) : methods.getScore.call(this); }, set: function(settings) { this.each(function() { var $this = $(this), actual = $this.data('settings'), clone = $this.clone().removeAttr('style').insertBefore($this); $this.remove(); clone.raty($.extend(actual, settings)); }); return $(this.selector); }, setScore: function(score) { return $(this).each(function() { if ($(this).data('readonly') === true) { return this; } methods.initialize.call(this, score); methods.setTarget.call(this, score, true); }); }, setTarget: function(value, isKeep) { if (this.opt.target) { var $target = $(this.opt.target); if ($target.length == 0) { methods.error.call(this, 'target selector invalid or missing!'); } var score = value; if (!isKeep || score === undefined) { score = this.opt.targetText; } else { if (this.opt.targetType == 'hint') { score = (score === null && this.opt.cancel) ? this.opt.cancelHint : this.opt.hints[Math.ceil(score - 1)]; } else { score = this.opt.precision ? parseFloat(score).toFixed(1) : parseInt(score, 10); } } if (this.opt.targetFormat.indexOf('{score}') < 0) { methods.error.call(this, 'template "{score}" missing!'); } if (value !== null) { score = this.opt.targetFormat.toString().replace('{score}', score); } if ($target.is(':input')) { $target.val(score); } else { $target.html(score); } } }, showHalf: function(score) { var diff = (score - Math.floor(score)).toFixed(1); if (diff > 0 && diff < .6) { this.stars.eq(Math.ceil(score) - 1).attr('src', this.opt.path + this.opt.starHalf); } }, initialize: function(score) { score = !score ? 0 : methods.between(score, 0, this.opt.number); methods.fill.call(this, score); if (score > 0) { if (this.opt.halfShow) { methods.roundStar.call(this, score); } this.score.val(score); } }, unfixHint: function() { for (var i = 0; i < this.opt.number; i++) { this.stars.eq(i).attr('title', (i < this.opt.hints.length && this.opt.hints[i] !== null) ? this.opt.hints[i] : i); } $(this).data('readonly', false).css('cursor', 'pointer').removeAttr('title'); this.score.attr('readonly', 'readonly'); } }; $.fn.raty = 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!'); } }; $.fn.raty.defaults = { cancel : false, cancelHint : 'cancel this rating!', cancelOff : 'cancel-off.png', cancelOn : 'cancel-on.png', cancelPlace : 'left', click : undefined, half : false, halfShow : true, hints : ['mauvais', 'faible', 'moyen', 'bon', 'excelent'], iconRange : undefined, mouseover : undefined, noRatedMsg : 'not rated yet', number : 5, path : '/assets/images/', precision : false, round : { down: .25, full: .6, up: .76 }, readOnly : false, score : undefined, scoreName : 'score', single : false, size : 32, space : true, starHalf : 'star-half.png', starOff : 'star-off.png', starOn : 'star-on.png', target : undefined, targetFormat : '{score}', targetKeep : false, targetText : '', targetType : 'hint', width : undefined }; })(jQuery);
JavaScript
/* * Autocomplete - jQuery plugin 1.1pre * * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.autocomplete.js 5785 2008-07-12 10:37:33Z joern.zaefferer $ * */ ;(function($) { $.fn.extend({ autocomplete: function(urlOrData, options) { var isUrl = typeof urlOrData == "string"; options = $.extend({}, $.Autocompleter.defaults, { url: isUrl ? urlOrData : null, data: isUrl ? null : urlOrData, delay: isUrl ? $.Autocompleter.defaults.delay : 10, max: options && !options.scroll ? 10 : 150 }, options); // if highlight is set to false, replace it with a do-nothing function options.highlight = options.highlight || function(value) { return value; }; // if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem; return this.each(function() { new $.Autocompleter(this, options); }); }, result: function(handler) { return this.bind("result", handler); }, search: function(handler) { return this.trigger("search", [handler]); }, flushCache: function() { return this.trigger("flushCache"); }, setOptions: function(options){ return this.trigger("setOptions", [options]); }, unautocomplete: function() { return this.trigger("unautocomplete"); } }); $.Autocompleter = function(input, options) { var KEY = { UP: 38, DOWN: 40, DEL: 46, TAB: 9, RETURN: 13, ESC: 27, COMMA: 188, PAGEUP: 33, PAGEDOWN: 34, BACKSPACE: 8 }; // Create $ object for input element var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass); var timeout; var previousValue = ""; var cache = $.Autocompleter.Cache(options); var hasFocus = 0; var lastKeyPressCode; var config = { mouseDownOnSelect: false }; var select = $.Autocompleter.Select(options, input, selectCurrent, config); var blockSubmit; // prevent form submit in opera when selecting with return key $.browser.opera && $(input.form).bind("submit.autocomplete", function() { if (blockSubmit) { blockSubmit = false; return false; } }); // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // track last key pressed lastKeyPressCode = event.keyCode; switch(event.keyCode) { case KEY.UP: event.preventDefault(); if ( select.visible() ) { select.prev(); } else { onChange(0, true); } break; case KEY.DOWN: event.preventDefault(); if ( select.visible() ) { select.next(); } else { onChange(0, true); } break; case KEY.PAGEUP: event.preventDefault(); if ( select.visible() ) { select.pageUp(); } else { onChange(0, true); } break; case KEY.PAGEDOWN: event.preventDefault(); if ( select.visible() ) { select.pageDown(); } else { onChange(0, true); } break; // matches also semicolon case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case KEY.TAB: case KEY.RETURN: if( selectCurrent() ) { // stop default to prevent a form submit, Opera needs special handling event.preventDefault(); blockSubmit = true; return false; } break; case KEY.ESC: select.hide(); break; default: clearTimeout(timeout); timeout = setTimeout(onChange, options.delay); break; } }).focus(function(){ // track whether the field has focus, we shouldn't process any // results if the field no longer has focus hasFocus++; }).blur(function() { hasFocus = 0; if (!config.mouseDownOnSelect) { hideResults(); } }).click(function() { // show select when clicking in a focused field if ( hasFocus++ > 1 && !select.visible() ) { onChange(0, true); } }).bind("search", function() { // TODO why not just specifying both arguments? var fn = (arguments.length > 1) ? arguments[1] : null; function findValueCallback(q, data) { var result; if( data && data.length ) { for (var i=0; i < data.length; i++) { if( data[i].result.toLowerCase() == q.toLowerCase() ) { result = data[i]; break; } } } if( typeof fn == "function" ) fn(result); else $input.trigger("result", result && [result.data, result.value]); } $.each(trimWords($input.val()), function(i, value) { request(value, findValueCallback, findValueCallback); }); }).bind("flushCache", function() { cache.flush(); }).bind("setOptions", function() { $.extend(options, arguments[1]); // if we've updated the data, repopulate if ( "data" in arguments[1] ) cache.populate(); }).bind("unautocomplete", function() { select.unbind(); $input.unbind(); $(input.form).unbind(".autocomplete"); }); function selectCurrent() { var selected = select.selected(); if( !selected ) return false; var v = selected.result; previousValue = v; if ( options.multiple ) { var words = trimWords($input.val()); if ( words.length > 1 ) { v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v; } v += options.multipleSeparator; } $input.val(v); hideResultsNow(); $input.trigger("result", [selected.data, selected.value]); return true; } function onChange(crap, skipPrevCheck) { if( lastKeyPressCode == KEY.DEL ) { select.hide(); return; } var currentValue = $input.val(); if ( !skipPrevCheck && currentValue == previousValue ) return; previousValue = currentValue; currentValue = lastWord(currentValue); if ( currentValue.length >= options.minChars) { $input.addClass(options.loadingClass); if (!options.matchCase) currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else { stopLoading(); select.hide(); } }; function trimWords(value) { if ( !value ) { return [""]; } var words = value.split( options.multipleSeparator ); var result = []; $.each(words, function(i, value) { if ( $.trim(value) ) result[i] = $.trim(value); }); return result; } function lastWord(value) { if ( !options.multiple ) return value; var words = trimWords(value); return words[words.length - 1]; } // fills in the input box w/the first match (assumed to be the best match) // q: the term entered // sValue: the first matching result function autoFill(q, sValue){ // autofill in the complete box w/the first match as long as the user hasn't entered in more data // if the last user key pressed was backspace, don't autofill if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) { // fill in the value (keep the case the user has typed) $input.val($input.val() + sValue.substring(lastWord(previousValue).length)); // select the portion of the value not typed by the user (so the next character will erase) $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length); } }; function hideResults() { clearTimeout(timeout); timeout = setTimeout(hideResultsNow, 200); }; function hideResultsNow() { var wasVisible = select.visible(); select.hide(); clearTimeout(timeout); stopLoading(); if (options.mustMatch) { // call search and run callback $input.search( function (result){ // if no value found, clear the input box if( !result ) { if (options.multiple) { var words = trimWords($input.val()).slice(0, -1); $input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") ); } else $input.val( "" ); } } ); } if (wasVisible) // position cursor at end of input field $.Autocompleter.Selection(input, input.value.length, input.value.length); }; function receiveData(q, data) { if ( data && data.length && hasFocus ) { stopLoading(); select.display(data, q); autoFill(q, data[0].value); select.show(); } else { hideResultsNow(); } }; function request(term, success, failure) { if (!options.matchCase) term = term.toLowerCase(); var data = cache.load(term); // recieve the cached data if (data && data.length) { success(term, data); // if an AJAX url has been supplied, try loading the data now } else if( (typeof options.url == "string") && (options.url.length > 0) ){ var extraParams = { timestamp: +new Date() }; $.each(options.extraParams, function(key, param) { extraParams[key] = typeof param == "function" ? param() : param; }); $.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, dataType: options.dataType, url: options.url, data: $.extend({ q: lastWord(term), limit: options.max }, extraParams), success: function(data) { var parsed = options.parse && options.parse(data) || parse(data); cache.add(term, parsed); success(term, parsed); } }); } else { // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match select.emptyList(); failure(term); } }; function parse(data) { var parsed = []; var rows = data.split("\n"); for (var i=0; i < rows.length; i++) { var row = $.trim(rows[i]); if (row) { row = row.split("|"); parsed[parsed.length] = { data: row, value: row[0], result: options.formatResult && options.formatResult(row, row[0]) || row[0] }; } } return parsed; }; function stopLoading() { $input.removeClass(options.loadingClass); }; }; $.Autocompleter.defaults = { inputClass: "ac_input", resultsClass: "ac_results", loadingClass: "ac_loading", minChars: 1, delay: 400, matchCase: false, matchSubset: true, matchContains: false, cacheLength: 10, max: 100, mustMatch: false, extraParams: {}, selectFirst: true, formatItem: function(row) { return row[0]; }, formatMatch: null, autoFill: false, width: 0, multiple: false, multipleSeparator: ", ", highlight: function(value, term) { return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>"); }, scroll: true, scrollHeight: 180 }; $.Autocompleter.Cache = function(options) { var data = {}; var length = 0; function matchSubset(s, sub) { if (!options.matchCase) s = s.toLowerCase(); var i = s.indexOf(sub); if (options.matchContains == "word"){ i = s.toLowerCase().search("\\b" + sub.toLowerCase()); } if (i == -1) return false; return i == 0 || options.matchContains; }; function add(q, value) { if (length > options.cacheLength){ flush(); } if (!data[q]){ length++; } data[q] = value; } function populate(){ if( !options.data ) return false; // track the matches var stMatchSets = {}, nullData = 0; // no url was specified, we need to adjust the cache length to make sure it fits the local data store if( !options.url ) options.cacheLength = 1; // track all options for minChars = 0 stMatchSets[""] = []; // loop through the array and create a lookup structure for ( var i = 0, ol = options.data.length; i < ol; i++ ) { var rawValue = options.data[i]; // if rawValue is a string, make an array otherwise just reference the array rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; var value = options.formatMatch(rawValue, i+1, options.data.length); if ( value === false ) continue; var firstChar = value.charAt(0).toLowerCase(); // if no lookup array for this character exists, look it up now if( !stMatchSets[firstChar] ) stMatchSets[firstChar] = []; // if the match is a string var row = { value: value, data: rawValue, result: options.formatResult && options.formatResult(rawValue) || value }; // push the current match into the set list stMatchSets[firstChar].push(row); // keep track of minChars zero items if ( nullData++ < options.max ) { stMatchSets[""].push(row); } }; // add the data items to the cache $.each(stMatchSets, function(i, value) { // increase the cache size options.cacheLength++; // add to the cache add(i, value); }); } // populate any existing data setTimeout(populate, 25); function flush(){ data = {}; length = 0; } return { flush: flush, add: add, populate: populate, load: function(q) { if (!options.cacheLength || !length) return null; /* * if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches */ if( !options.url && options.matchContains ){ // track all matches var csub = []; // loop through all the data grids for matches for( var k in data ){ // don't search through the stMatchSets[""] (minChars: 0) cache // this prevents duplicates if( k.length > 0 ){ var c = data[k]; $.each(c, function(i, x) { // if we've got a match, add it to the array if (matchSubset(x.value, q)) { csub.push(x); } }); } } return csub; } else // if the exact item exists, use it if (data[q]){ return data[q]; } else if (options.matchSubset) { for (var i = q.length - 1; i >= options.minChars; i--) { var c = data[q.substr(0, i)]; if (c) { var csub = []; $.each(c, function(i, x) { if (matchSubset(x.value, q)) { csub[csub.length] = x; } }); return csub; } } } return null; } }; }; $.Autocompleter.Select = function (options, input, select, config) { var CLASSES = { ACTIVE: "ac_over" }; var listItems, active = -1, data, term = "", needsInit = true, element, list; // Create results function init() { if (!needsInit) return; element = $("<div/>") .hide() .addClass(options.resultsClass) .css("position", "absolute") .appendTo(document.body); list = $("<ul/>").appendTo(element).mouseover( function(event) { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); $(target(event)).addClass(CLASSES.ACTIVE); } }).click(function(event) { $(target(event)).addClass(CLASSES.ACTIVE); select(); // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus input.focus(); return false; }).mousedown(function() { config.mouseDownOnSelect = true; }).mouseup(function() { config.mouseDownOnSelect = false; }); if( options.width > 0 ) element.css("width", options.width); needsInit = false; } function target(event) { var element = event.target; while(element && element.tagName != "LI") element = element.parentNode; // more fun with IE, sometimes event.target is empty, just ignore it then if(!element) return []; return element; } function moveSelect(step) { listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); movePosition(step); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); if(options.scroll) { var offset = 0; listItems.slice(0, active).each(function() { offset += this.offsetHeight; }); if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight()); } else if(offset < list.scrollTop()) { list.scrollTop(offset); } } }; function movePosition(step) { active += step; if (active < 0) { active = listItems.size() - 1; } else if (active >= listItems.size()) { active = 0; } } function limitNumberOfItems(available) { return options.max && options.max < available ? options.max : available; } function fillList() { list.empty(); var max = limitNumberOfItems(data.length); for (var i=0; i < max; i++) { if (!data[i]) continue; var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term); if ( formatted === false ) continue; var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0]; $.data(li, "ac_data", data[i]); } listItems = list.find("li"); if ( options.selectFirst ) { listItems.slice(0, 1).addClass(CLASSES.ACTIVE); active = 0; } // apply bgiframe if available if ( $.fn.bgiframe ) list.bgiframe(); } return { display: function(d, q) { init(); data = d; term = q; fillList(); }, next: function() { moveSelect(1); }, prev: function() { moveSelect(-1); }, pageUp: function() { if (active != 0 && active - 8 < 0) { moveSelect( -active ); } else { moveSelect(-8); } }, pageDown: function() { if (active != listItems.size() - 1 && active + 8 > listItems.size()) { moveSelect( listItems.size() - 1 - active ); } else { moveSelect(8); } }, hide: function() { element && element.hide(); listItems && listItems.removeClass(CLASSES.ACTIVE); active = -1; }, visible : function() { return element && element.is(":visible"); }, current: function() { return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]); }, show: function() { var offset = $(input).offset(); element.css({ width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), top: offset.top + input.offsetHeight, left: offset.left }).show(); if(options.scroll) { list.scrollTop(0); list.css({ maxHeight: options.scrollHeight, overflow: 'auto' }); if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { var listHeight = 0; listItems.each(function() { listHeight += this.offsetHeight; }); var scrollbarsVisible = listHeight > options.scrollHeight; list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight ); if (!scrollbarsVisible) { // IE doesn't recalculate width when scrollbar disappears listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); } } } }, selected: function() { var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE); return selected && selected.length && $.data(selected[0], "ac_data"); }, emptyList: function (){ list && list.empty(); }, unbind: function() { element && element.remove(); } }; }; $.Autocompleter.Selection = function(field, start, end) { if( field.createTextRange ){ var selRange = field.createTextRange(); selRange.collapse(true); selRange.moveStart("character", start); selRange.moveEnd("character", end); selRange.select(); } else if( field.setSelectionRange ){ field.setSelectionRange(start, end); } else { if( field.selectionStart ){ field.selectionStart = start; field.selectionEnd = end; } } field.focus(); }; })(jQuery);
JavaScript
// ColorBox v1.3.17.1 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+ // Copyright (c) 2011 Jack Moore - jack@colorpowered.com // Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php (function ($, document, window) { var // ColorBox Default Settings. // See http://colorpowered.com/colorbox for details. defaults = { transition: "elastic", speed: 300, width: false, initialWidth: "600", innerWidth: false, maxWidth: false, height: false, initialHeight: "450", innerHeight: false, maxHeight: false, scalePhotos: true, scrolling: true, inline: false, html: false, iframe: false, fastIframe: true, photo: false, href: false, title: false, rel: false, opacity: 0.9, preloading: true, current: "image {current} of {total}", previous: "previous", next: "next", close: "close", open: false, returnFocus: true, loop: true, slideshow: false, slideshowAuto: true, slideshowSpeed: 2500, slideshowStart: "start slideshow", slideshowStop: "stop slideshow", onOpen: false, onLoad: false, onComplete: false, onCleanup: false, onClosed: false, overlayClose: true, escKey: true, arrowKey: true, top: false, bottom: false, left: false, right: false, fixed: false, data: false }, // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', // Events event_open = prefix + '_open', event_load = prefix + '_load', event_complete = prefix + '_complete', event_cleanup = prefix + '_cleanup', event_closed = prefix + '_closed', event_purge = prefix + '_purge', // Special Handling for IE isIE = $.browser.msie && !$.support.opacity, // Detects IE6,7,8. IE9 supports opacity. Feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome, hence the user-agent test. isIE6 = isIE && $.browser.version < 7, event_ie6 = prefix + '_IE6', // Cached jQuery Object Variables $overlay, $box, $wrap, $content, $topBorder, $leftBorder, $rightBorder, $bottomBorder, $related, $window, $loaded, $loadingBay, $loadingOverlay, $title, $current, $slideshow, $next, $prev, $close, $groupControls, // Variables for cached values or use across multiple functions settings = {}, interfaceHeight, interfaceWidth, loadedHeight, loadedWidth, element, index, photo, open, active, closing, handler, loadingTimer, publicMethod, boxElement = prefix + 'Element'; // **************** // HELPER FUNCTIONS // **************** // jQuery object generator to reduce code size function $div(id, cssText) { var div = document.createElement('div'); if (id) { div.id = prefix + id; } div.style.cssText = cssText || ''; return $(div); } // Convert % values to pixels function setSize(size, dimension) { dimension = dimension === 'x' ? $window.width() : $window.height(); return (typeof size === 'string') ? Math.round((/%/.test(size) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size; } // Checks an href to see if it is a photo. // There is a force photo option (photo: true) for hrefs that cannot be matched by this regex. function isImage(url) { return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url); } // Assigns function results to their respective settings. This allows functions to be used as values. function process(settings) { for (var i in settings) { if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time. settings[i] = settings[i].call(element); } } settings.rel = settings.rel || element.rel || 'nofollow'; settings.href = settings.href || $(element).attr('href'); settings.title = settings.title || element.title; if (typeof settings.href === "string") { settings.href = $.trim(settings.href); } } function trigger(event, callback) { if (callback) { callback.call(element); } $.event.trigger(event); } // Slideshow functionality function slideshow() { var timeOut, className = prefix + "Slideshow_", click = "click." + prefix, start, stop, clear; if (settings.slideshow && $related[1]) { start = function () { $slideshow .text(settings.slideshowStop) .unbind(click) .bind(event_complete, function () { if (index < $related.length - 1 || settings.loop) { timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); } }) .bind(event_load, function () { clearTimeout(timeOut); }) .one(click + ' ' + event_cleanup, stop); $box.removeClass(className + "off").addClass(className + "on"); timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); }; stop = function () { clearTimeout(timeOut); $slideshow .text(settings.slideshowStart) .unbind([event_complete, event_load, event_cleanup, click].join(' ')) .one(click, start); $box.removeClass(className + "on").addClass(className + "off"); }; if (settings.slideshowAuto) { start(); } else { stop(); } } else { $box.removeClass(className + "off " + className + "on"); } } function launch(elem) { if (!closing) { element = elem; process($.extend(settings, $.data(element, colorbox))); $related = $(element); index = 0; if (settings.rel !== 'nofollow') { $related = $('.' + boxElement).filter(function () { var relRelated = $.data(this, colorbox).rel || this.rel; return (relRelated === settings.rel); }); index = $related.index(element); // Check direct calls to ColorBox. if (index === -1) { $related = $related.add(element); index = $related.length - 1; } } if (!open) { open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys. $box.show(); if (settings.returnFocus) { try { element.blur(); $(element).one(event_closed, function () { try { this.focus(); } catch (e) { // do nothing } }); } catch (e) { // do nothing } } // +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5' $overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show(); // Opens inital empty ColorBox prior to content being loaded. settings.w = setSize(settings.initialWidth, 'x'); settings.h = setSize(settings.initialHeight, 'y'); publicMethod.position(0); if (isIE6) { $window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () { $overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()}); }).trigger('resize.' + event_ie6); } trigger(event_open, settings.onOpen); $groupControls.add($title).hide(); $close.html(settings.close).show(); } publicMethod.load(true); } } // **************** // PUBLIC FUNCTIONS // Usage format: $.fn.colorbox.close(); // Usage from within an iframe: parent.$.fn.colorbox.close(); // **************** publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) { var $this = this, autoOpen; if (!$this[0] && $this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit. return $this; } options = options || {}; if (callback) { options.onComplete = callback; } if (!$this[0] || $this.selector === undefined) { // detects $.colorbox() and $.fn.colorbox() $this = $('<a/>'); options.open = true; // assume an immediate open } $this.each(function () { $.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options)); $(this).addClass(boxElement); }); autoOpen = options.open; if ($.isFunction(autoOpen)) { autoOpen = autoOpen.call($this); } if (autoOpen) { launch($this[0]); } return $this; }; // Initialize ColorBox: store common calculations, preload the interface graphics, append the html. // This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only // having to run once, instead of each time colorbox is opened. publicMethod.init = function () { // Create & Append jQuery Objects $window = $(window); $box = $div().attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}); $overlay = $div("Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $div("Wrapper"); $content = $div("Content").append( $loaded = $div("LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $div("LoadingOverlay").add($div("LoadingGraphic")), $title = $div("Title"), $current = $div("Current"), $next = $div("Next"), $prev = $div("Previous"), $slideshow = $div("Slideshow").bind(event_open, slideshow), $close = $div("Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $div().append( $div("TopLeft"), $topBorder = $div("TopCenter"), $div("TopRight") ), $div(false, 'clear:left').append( $leftBorder = $div("MiddleLeft"), $content, $rightBorder = $div("MiddleRight") ), $div(false, 'clear:left').append( $div("BottomLeft"), $bottomBorder = $div("BottomCenter"), $div("BottomRight") ) ).children().children().css({'float': 'left'}); $loadingBay = $div(false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $('body').prepend($overlay, $box.append($wrap, $loadingBay)); $content.children() .hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); }).addClass('hover'); // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6 interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Setting padding to remove the need to do size conversions during the animation step. $box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide(); // Setup button events. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $groupControls = $next.add($prev).add($current).add($slideshow); // Adding the 'hover' class allowed the browser to load the hover-state // background graphics. The class can now can be removed. $content.children().removeClass('hover'); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Set Navigation Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1]) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); }; publicMethod.remove = function () { $box.add($overlay).remove(); $('.' + boxElement).removeData(colorbox).removeClass(boxElement); }; publicMethod.position = function (speed, loadedCallback) { var animate_speed, top = 0, left = 0; // remove the modal so that it doesn't influence the document width/height $box.hide(); if (settings.fixed && !isIE6) { $box.css({position: 'fixed'}); } else { top = $window.scrollTop(); left = $window.scrollLeft(); $box.css({position: 'absolute'}); } // keeps the top and left positions within the browser's viewport. if (settings.right !== false) { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0); } else if (settings.left !== false) { left += setSize(settings.left, 'x'); } else { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2; } if (settings.bottom !== false) { top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0); } else if (settings.top !== false) { top += setSize(settings.top, 'y'); } else { top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight, 0) / 2; } $box.show(); // setting the speed to 0 to reduce the delay between same-sized content. animate_speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed; // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly, // but it has to be shrank down around the size of div#colorbox when it's done. If not, // it can invoke an obscure IE bug when using iframes. $wrap[0].style.width = $wrap[0].style.height = "9999px"; function modalDimensions(that) { // loading overlay height has to be explicitly set for IE6. $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width; $loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height; } $box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, { duration: animate_speed, complete: function () { modalDimensions(this); active = false; // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation. $wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px"; $wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px"; if (loadedCallback) { loadedCallback(); } }, step: function () { modalDimensions(this); } }); }; publicMethod.resize = function (options) { if (open) { options = options || {}; if (options.width) { settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth; } if (options.innerWidth) { settings.w = setSize(options.innerWidth, 'x'); } $loaded.css({width: settings.w}); if (options.height) { settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight; } if (options.innerHeight) { settings.h = setSize(options.innerHeight, 'y'); } if (!options.innerHeight && !options.height) { var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be. settings.h = $child.height(); $child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation } $loaded.css({height: settings.h}); publicMethod.position(settings.transition === "none" ? 0 : settings.speed); } }; publicMethod.prep = function (object) { if (!open) { return; } var speed = settings.transition === "none" ? 0 : settings.speed; $window.unbind('resize.' + prefix); $loaded.remove(); $loaded = $div('LoadedContent').html(object); function getWidth() { settings.w = settings.w || $loaded.width(); settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w; return settings.w; } function getHeight() { settings.h = settings.h || $loaded.height(); settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h; return settings.h; } $loaded.hide() .appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations. .css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'}) .css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height. .prependTo($content); $loadingBay.hide(); // floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width. //$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'}); $(photo).css({'float': 'none'}); // Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay. if (isIE6) { $('select').not($box.find('select')).filter(function () { return this.style.visibility !== 'hidden'; }).css({'visibility': 'hidden'}).one(event_cleanup, function () { this.style.visibility = 'inherit'; }); } function setPosition(s) { publicMethod.position(s, function () { var prev, prevSrc, next, nextSrc, total = $related.length, iframe, complete; if (!open) { return; } function removeFilter() { if (isIE) { $box[0].style.removeAttribute('filter'); } } complete = function () { clearTimeout(loadingTimer); $loadingOverlay.hide(); trigger(event_complete, settings.onComplete); }; if (isIE) { //This fadeIn helps the bicubic resampling to kick-in. if (photo) { $loaded.fadeIn(100); } } $title.html(settings.title).add($loaded).show(); if (total > 1) { // handle grouping if (typeof settings.current === "string") { $current.html(settings.current.replace(/\{current\}/, index + 1).replace(/\{total\}/, total)).show(); } $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next); $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous); prev = index ? $related[index - 1] : $related[total - 1]; next = index < total - 1 ? $related[index + 1] : $related[0]; if (settings.slideshow) { $slideshow.show(); } // Preloads images within a rel group if (settings.preloading) { nextSrc = $.data(next, colorbox).href || next.href; prevSrc = $.data(prev, colorbox).href || prev.href; nextSrc = $.isFunction(nextSrc) ? nextSrc.call(next) : nextSrc; prevSrc = $.isFunction(prevSrc) ? prevSrc.call(prev) : prevSrc; if (isImage(nextSrc)) { $('<img/>')[0].src = nextSrc; } if (isImage(prevSrc)) { $('<img/>')[0].src = prevSrc; } } } else { $groupControls.hide(); } if (settings.iframe) { iframe = $('<iframe/>').addClass(prefix + 'Iframe')[0]; if (settings.fastIframe) { complete(); } else { $(iframe).one('load', complete); } iframe.name = prefix + (+new Date()); iframe.src = settings.href; if (!settings.scrolling) { iframe.scrolling = "no"; } if (isIE) { iframe.frameBorder = 0; iframe.allowTransparency = "true"; } $(iframe).appendTo($loaded).one(event_purge, function () { iframe.src = "//about:blank"; }); } else { complete(); } if (settings.transition === 'fade') { $box.fadeTo(speed, 1, removeFilter); } else { removeFilter(); } $window.bind('resize.' + prefix, function () { publicMethod.position(0); }); }); } if (settings.transition === 'fade') { $box.fadeTo(speed, 0, function () { setPosition(0); }); } else { setPosition(speed); } }; publicMethod.load = function (launched) { var href, setResize, prep = publicMethod.prep; active = true; photo = false; element = $related[index]; if (!launched) { process($.extend(settings, $.data(element, colorbox))); } trigger(event_purge); trigger(event_load, settings.onLoad); settings.h = settings.height ? setSize(settings.height, 'y') - loadedHeight - interfaceHeight : settings.innerHeight && setSize(settings.innerHeight, 'y'); settings.w = settings.width ? setSize(settings.width, 'x') - loadedWidth - interfaceWidth : settings.innerWidth && setSize(settings.innerWidth, 'x'); // Sets the minimum dimensions for use in image scaling settings.mw = settings.w; settings.mh = settings.h; // Re-evaluate the minimum width and height based on maxWidth and maxHeight values. // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead. if (settings.maxWidth) { settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth; settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw; } if (settings.maxHeight) { settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight; settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh; } href = settings.href; loadingTimer = setTimeout(function () { $loadingOverlay.show(); }, 100); if (settings.inline) { // Inserts an empty placeholder where inline content is being pulled from. // An event is bound to put inline content back when ColorBox closes or loads new content. $div().hide().insertBefore($(href)[0]).one(event_purge, function () { $(this).replaceWith($loaded.children()); }); prep($(href)); } else if (settings.iframe) { // IFrame element won't be added to the DOM until it is ready to be displayed, // to avoid problems with DOM-ready JS that might be trying to run in that iframe. prep(" "); } else if (settings.html) { prep(settings.html); } else if (isImage(href)) { $(photo = new Image()) .addClass(prefix + 'Photo') .error(function () { settings.title = false; prep($div('Error').text('This image could not be loaded')); }) .load(function () { var percent; photo.onload = null; //stops animated gifs from firing the onload repeatedly. if (settings.scalePhotos) { setResize = function () { photo.height -= photo.height * percent; photo.width -= photo.width * percent; }; if (settings.mw && photo.width > settings.mw) { percent = (photo.width - settings.mw) / photo.width; setResize(); } if (settings.mh && photo.height > settings.mh) { percent = (photo.height - settings.mh) / photo.height; setResize(); } } if (settings.h) { photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px'; } if ($related[1] && (index < $related.length - 1 || settings.loop)) { photo.style.cursor = 'pointer'; photo.onclick = function () { publicMethod.next(); }; } if (isIE) { photo.style.msInterpolationMode = 'bicubic'; } setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise. prep(photo); }, 1); }); setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise. photo.src = href; }, 1); } else if (href) { $loadingBay.load(href, settings.data, function (data, status, xhr) { prep(status === 'error' ? $div('Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents()); }); } }; // Navigates to the next page/image in a set. publicMethod.next = function () { if (!active && $related[1] && (index < $related.length - 1 || settings.loop)) { index = index < $related.length - 1 ? index + 1 : 0; publicMethod.load(); } }; publicMethod.prev = function () { if (!active && $related[1] && (index || settings.loop)) { index = index ? index - 1 : $related.length - 1; publicMethod.load(); } }; // Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close(); publicMethod.close = function () { if (open && !closing) { closing = true; open = false; trigger(event_cleanup, settings.onCleanup); $window.unbind('.' + prefix + ' .' + event_ie6); $overlay.fadeTo(200, 0); $box.stop().fadeTo(300, 0, function () { $box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide(); trigger(event_purge); $loaded.remove(); setTimeout(function () { closing = false; trigger(event_closed, settings.onClosed); }, 1); }); } }; // A method for fetching the current element ColorBox is referencing. // returns a jQuery object. publicMethod.element = function () { return $(element); }; publicMethod.settings = defaults; // Bind the live event before DOM-ready for maximum performance in IE6 & 7. handler = function (e) { // checks to see if it was a non-left mouse-click and for clicks modified with ctrl, shift, or alt. if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) { e.preventDefault(); launch(this); } }; if ($.fn.delegate) { $(document).delegate('.' + boxElement, 'click', handler); } else { $('.' + boxElement).live('click', handler); } // Initializes ColorBox when the DOM has loaded $(publicMethod.init); }(jQuery, document, this));
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There templates will be displayed as a dropdown in all media dialog if the "template_external_list_url" // option is defined in TinyMCE init. var tinyMCETemplateList = [ // Name, URL, Description ["Simple snippet", "templates/snippet1.htm", "Simple HTML snippet."], ["Layout", "templates/layout1.htm", "HTML Layout."] ];
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There links will be displayed as a dropdown in all link dialogs if the "external_link_list_url" // option is defined in TinyMCE init. var tinyMCELinkList = new Array( // Name, URL ["Moxiecode", "http://www.moxiecode.com"], ["Freshmeat", "http://www.freshmeat.com"], ["Sourceforge", "http://www.sourceforge.com"] );
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There images will be displayed as a dropdown in all image dialogs if the "external_link_image_url" // option is defined in TinyMCE init. var tinyMCEImageList = new Array( // Name, URL ["Logo 1", "media/logo.jpg"], ["Logo 2 Over", "media/logo_over.jpg"] );
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There flash movies will be displayed as a dropdown in all media dialog if the "media_external_list_url" // option is defined in TinyMCE init. var tinyMCEMediaList = [ // Name, URL ["Some Flash", "media/sample.swf"], ["Some Quicktime", "media/sample.mov"], ["Some AVI", "media/sample.avi"], ["Some RealMedia", "media/sample.rm"], ["Some Shockwave", "media/sample.dcr"], ["Some Video", "media/sample.mp4"], ["Some FLV", "media/sample.flv"], ];
JavaScript
// ColorBox v1.3.17.1 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+ // Copyright (c) 2011 Jack Moore - jack@colorpowered.com // Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php (function ($, document, window) { var // ColorBox Default Settings. // See http://colorpowered.com/colorbox for details. defaults = { transition: "elastic", speed: 300, width: false, initialWidth: "600", innerWidth: false, maxWidth: false, height: false, initialHeight: "450", innerHeight: false, maxHeight: false, scalePhotos: true, scrolling: true, inline: false, html: false, iframe: false, fastIframe: true, photo: false, href: false, title: false, rel: false, opacity: 0.9, preloading: true, current: "image {current} of {total}", previous: "previous", next: "next", close: "close", open: false, returnFocus: true, loop: true, slideshow: false, slideshowAuto: true, slideshowSpeed: 2500, slideshowStart: "start slideshow", slideshowStop: "stop slideshow", onOpen: false, onLoad: false, onComplete: false, onCleanup: false, onClosed: false, overlayClose: true, escKey: true, arrowKey: true, top: false, bottom: false, left: false, right: false, fixed: false, data: false }, // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', // Events event_open = prefix + '_open', event_load = prefix + '_load', event_complete = prefix + '_complete', event_cleanup = prefix + '_cleanup', event_closed = prefix + '_closed', event_purge = prefix + '_purge', // Special Handling for IE isIE = $.browser.msie && !$.support.opacity, // Detects IE6,7,8. IE9 supports opacity. Feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome, hence the user-agent test. isIE6 = isIE && $.browser.version < 7, event_ie6 = prefix + '_IE6', // Cached jQuery Object Variables $overlay, $box, $wrap, $content, $topBorder, $leftBorder, $rightBorder, $bottomBorder, $related, $window, $loaded, $loadingBay, $loadingOverlay, $title, $current, $slideshow, $next, $prev, $close, $groupControls, // Variables for cached values or use across multiple functions settings = {}, interfaceHeight, interfaceWidth, loadedHeight, loadedWidth, element, index, photo, open, active, closing, handler, loadingTimer, publicMethod, boxElement = prefix + 'Element'; // **************** // HELPER FUNCTIONS // **************** // jQuery object generator to reduce code size function $div(id, cssText) { var div = document.createElement('div'); if (id) { div.id = prefix + id; } div.style.cssText = cssText || ''; return $(div); } // Convert % values to pixels function setSize(size, dimension) { dimension = dimension === 'x' ? $window.width() : $window.height(); return (typeof size === 'string') ? Math.round((/%/.test(size) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size; } // Checks an href to see if it is a photo. // There is a force photo option (photo: true) for hrefs that cannot be matched by this regex. function isImage(url) { return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url); } // Assigns function results to their respective settings. This allows functions to be used as values. function process(settings) { for (var i in settings) { if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time. settings[i] = settings[i].call(element); } } settings.rel = settings.rel || element.rel || 'nofollow'; settings.href = settings.href || $(element).attr('href'); settings.title = settings.title || element.title; if (typeof settings.href === "string") { settings.href = $.trim(settings.href); } } function trigger(event, callback) { if (callback) { callback.call(element); } $.event.trigger(event); } // Slideshow functionality function slideshow() { var timeOut, className = prefix + "Slideshow_", click = "click." + prefix, start, stop, clear; if (settings.slideshow && $related[1]) { start = function () { $slideshow .text(settings.slideshowStop) .unbind(click) .bind(event_complete, function () { if (index < $related.length - 1 || settings.loop) { timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); } }) .bind(event_load, function () { clearTimeout(timeOut); }) .one(click + ' ' + event_cleanup, stop); $box.removeClass(className + "off").addClass(className + "on"); timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); }; stop = function () { clearTimeout(timeOut); $slideshow .text(settings.slideshowStart) .unbind([event_complete, event_load, event_cleanup, click].join(' ')) .one(click, start); $box.removeClass(className + "on").addClass(className + "off"); }; if (settings.slideshowAuto) { start(); } else { stop(); } } else { $box.removeClass(className + "off " + className + "on"); } } function launch(elem) { if (!closing) { element = elem; process($.extend(settings, $.data(element, colorbox))); $related = $(element); index = 0; if (settings.rel !== 'nofollow') { $related = $('.' + boxElement).filter(function () { var relRelated = $.data(this, colorbox).rel || this.rel; return (relRelated === settings.rel); }); index = $related.index(element); // Check direct calls to ColorBox. if (index === -1) { $related = $related.add(element); index = $related.length - 1; } } if (!open) { open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys. $box.show(); if (settings.returnFocus) { try { element.blur(); $(element).one(event_closed, function () { try { this.focus(); } catch (e) { // do nothing } }); } catch (e) { // do nothing } } // +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5' $overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show(); // Opens inital empty ColorBox prior to content being loaded. settings.w = setSize(settings.initialWidth, 'x'); settings.h = setSize(settings.initialHeight, 'y'); publicMethod.position(0); if (isIE6) { $window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () { $overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()}); }).trigger('resize.' + event_ie6); } trigger(event_open, settings.onOpen); $groupControls.add($title).hide(); $close.html(settings.close).show(); } publicMethod.load(true); } } // **************** // PUBLIC FUNCTIONS // Usage format: $.fn.colorbox.close(); // Usage from within an iframe: parent.$.fn.colorbox.close(); // **************** publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) { var $this = this, autoOpen; if (!$this[0] && $this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit. return $this; } options = options || {}; if (callback) { options.onComplete = callback; } if (!$this[0] || $this.selector === undefined) { // detects $.colorbox() and $.fn.colorbox() $this = $('<a/>'); options.open = true; // assume an immediate open } $this.each(function () { $.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options)); $(this).addClass(boxElement); }); autoOpen = options.open; if ($.isFunction(autoOpen)) { autoOpen = autoOpen.call($this); } if (autoOpen) { launch($this[0]); } return $this; }; // Initialize ColorBox: store common calculations, preload the interface graphics, append the html. // This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only // having to run once, instead of each time colorbox is opened. publicMethod.init = function () { // Create & Append jQuery Objects $window = $(window); $box = $div().attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''}); $overlay = $div("Overlay", isIE6 ? 'position:absolute' : '').hide(); $wrap = $div("Wrapper"); $content = $div("Content").append( $loaded = $div("LoadedContent", 'width:0; height:0; overflow:hidden'), $loadingOverlay = $div("LoadingOverlay").add($div("LoadingGraphic")), $title = $div("Title"), $current = $div("Current"), $next = $div("Next"), $prev = $div("Previous"), $slideshow = $div("Slideshow").bind(event_open, slideshow), $close = $div("Close") ); $wrap.append( // The 3x3 Grid that makes up ColorBox $div().append( $div("TopLeft"), $topBorder = $div("TopCenter"), $div("TopRight") ), $div(false, 'clear:left').append( $leftBorder = $div("MiddleLeft"), $content, $rightBorder = $div("MiddleRight") ), $div(false, 'clear:left').append( $div("BottomLeft"), $bottomBorder = $div("BottomCenter"), $div("BottomRight") ) ).children().children().css({'float': 'left'}); $loadingBay = $div(false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $('body').prepend($overlay, $box.append($wrap, $loadingBay)); $content.children() .hover(function () { $(this).addClass('hover'); }, function () { $(this).removeClass('hover'); }).addClass('hover'); // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6 interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Setting padding to remove the need to do size conversions during the animation step. $box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide(); // Setup button events. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $groupControls = $next.add($prev).add($current).add($slideshow); // Adding the 'hover' class allowed the browser to load the hover-state // background graphics. The class can now can be removed. $content.children().removeClass('hover'); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Set Navigation Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1]) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); }; publicMethod.remove = function () { $box.add($overlay).remove(); $('.' + boxElement).removeData(colorbox).removeClass(boxElement); }; publicMethod.position = function (speed, loadedCallback) { var animate_speed, top = 0, left = 0; // remove the modal so that it doesn't influence the document width/height $box.hide(); if (settings.fixed && !isIE6) { $box.css({position: 'fixed'}); } else { top = $window.scrollTop(); left = $window.scrollLeft(); $box.css({position: 'absolute'}); } // keeps the top and left positions within the browser's viewport. if (settings.right !== false) { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0); } else if (settings.left !== false) { left += setSize(settings.left, 'x'); } else { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2; } if (settings.bottom !== false) { top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0); } else if (settings.top !== false) { top += setSize(settings.top, 'y'); } else { top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight, 0) / 2; } $box.show(); // setting the speed to 0 to reduce the delay between same-sized content. animate_speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed; // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly, // but it has to be shrank down around the size of div#colorbox when it's done. If not, // it can invoke an obscure IE bug when using iframes. $wrap[0].style.width = $wrap[0].style.height = "9999px"; function modalDimensions(that) { // loading overlay height has to be explicitly set for IE6. $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width; $loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height; } $box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, { duration: animate_speed, complete: function () { modalDimensions(this); active = false; // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation. $wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px"; $wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px"; if (loadedCallback) { loadedCallback(); } }, step: function () { modalDimensions(this); } }); }; publicMethod.resize = function (options) { if (open) { options = options || {}; if (options.width) { settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth; } if (options.innerWidth) { settings.w = setSize(options.innerWidth, 'x'); } $loaded.css({width: settings.w}); if (options.height) { settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight; } if (options.innerHeight) { settings.h = setSize(options.innerHeight, 'y'); } if (!options.innerHeight && !options.height) { var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be. settings.h = $child.height(); $child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation } $loaded.css({height: settings.h}); publicMethod.position(settings.transition === "none" ? 0 : settings.speed); } }; publicMethod.prep = function (object) { if (!open) { return; } var speed = settings.transition === "none" ? 0 : settings.speed; $window.unbind('resize.' + prefix); $loaded.remove(); $loaded = $div('LoadedContent').html(object); function getWidth() { settings.w = settings.w || $loaded.width(); settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w; return settings.w; } function getHeight() { settings.h = settings.h || $loaded.height(); settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h; return settings.h; } $loaded.hide() .appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations. .css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'}) .css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height. .prependTo($content); $loadingBay.hide(); // floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width. //$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'}); $(photo).css({'float': 'none'}); // Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay. if (isIE6) { $('select').not($box.find('select')).filter(function () { return this.style.visibility !== 'hidden'; }).css({'visibility': 'hidden'}).one(event_cleanup, function () { this.style.visibility = 'inherit'; }); } function setPosition(s) { publicMethod.position(s, function () { var prev, prevSrc, next, nextSrc, total = $related.length, iframe, complete; if (!open) { return; } function removeFilter() { if (isIE) { $box[0].style.removeAttribute('filter'); } } complete = function () { clearTimeout(loadingTimer); $loadingOverlay.hide(); trigger(event_complete, settings.onComplete); }; if (isIE) { //This fadeIn helps the bicubic resampling to kick-in. if (photo) { $loaded.fadeIn(100); } } $title.html(settings.title).add($loaded).show(); if (total > 1) { // handle grouping if (typeof settings.current === "string") { $current.html(settings.current.replace(/\{current\}/, index + 1).replace(/\{total\}/, total)).show(); } $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next); $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous); prev = index ? $related[index - 1] : $related[total - 1]; next = index < total - 1 ? $related[index + 1] : $related[0]; if (settings.slideshow) { $slideshow.show(); } // Preloads images within a rel group if (settings.preloading) { nextSrc = $.data(next, colorbox).href || next.href; prevSrc = $.data(prev, colorbox).href || prev.href; nextSrc = $.isFunction(nextSrc) ? nextSrc.call(next) : nextSrc; prevSrc = $.isFunction(prevSrc) ? prevSrc.call(prev) : prevSrc; if (isImage(nextSrc)) { $('<img/>')[0].src = nextSrc; } if (isImage(prevSrc)) { $('<img/>')[0].src = prevSrc; } } } else { $groupControls.hide(); } if (settings.iframe) { iframe = $('<iframe/>').addClass(prefix + 'Iframe')[0]; if (settings.fastIframe) { complete(); } else { $(iframe).one('load', complete); } iframe.name = prefix + (+new Date()); iframe.src = settings.href; if (!settings.scrolling) { iframe.scrolling = "no"; } if (isIE) { iframe.frameBorder = 0; iframe.allowTransparency = "true"; } $(iframe).appendTo($loaded).one(event_purge, function () { iframe.src = "//about:blank"; }); } else { complete(); } if (settings.transition === 'fade') { $box.fadeTo(speed, 1, removeFilter); } else { removeFilter(); } $window.bind('resize.' + prefix, function () { publicMethod.position(0); }); }); } if (settings.transition === 'fade') { $box.fadeTo(speed, 0, function () { setPosition(0); }); } else { setPosition(speed); } }; publicMethod.load = function (launched) { var href, setResize, prep = publicMethod.prep; active = true; photo = false; element = $related[index]; if (!launched) { process($.extend(settings, $.data(element, colorbox))); } trigger(event_purge); trigger(event_load, settings.onLoad); settings.h = settings.height ? setSize(settings.height, 'y') - loadedHeight - interfaceHeight : settings.innerHeight && setSize(settings.innerHeight, 'y'); settings.w = settings.width ? setSize(settings.width, 'x') - loadedWidth - interfaceWidth : settings.innerWidth && setSize(settings.innerWidth, 'x'); // Sets the minimum dimensions for use in image scaling settings.mw = settings.w; settings.mh = settings.h; // Re-evaluate the minimum width and height based on maxWidth and maxHeight values. // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead. if (settings.maxWidth) { settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth; settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw; } if (settings.maxHeight) { settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight; settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh; } href = settings.href; loadingTimer = setTimeout(function () { $loadingOverlay.show(); }, 100); if (settings.inline) { // Inserts an empty placeholder where inline content is being pulled from. // An event is bound to put inline content back when ColorBox closes or loads new content. $div().hide().insertBefore($(href)[0]).one(event_purge, function () { $(this).replaceWith($loaded.children()); }); prep($(href)); } else if (settings.iframe) { // IFrame element won't be added to the DOM until it is ready to be displayed, // to avoid problems with DOM-ready JS that might be trying to run in that iframe. prep(" "); } else if (settings.html) { prep(settings.html); } else if (isImage(href)) { $(photo = new Image()) .addClass(prefix + 'Photo') .error(function () { settings.title = false; prep($div('Error').text('This image could not be loaded')); }) .load(function () { var percent; photo.onload = null; //stops animated gifs from firing the onload repeatedly. if (settings.scalePhotos) { setResize = function () { photo.height -= photo.height * percent; photo.width -= photo.width * percent; }; if (settings.mw && photo.width > settings.mw) { percent = (photo.width - settings.mw) / photo.width; setResize(); } if (settings.mh && photo.height > settings.mh) { percent = (photo.height - settings.mh) / photo.height; setResize(); } } if (settings.h) { photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px'; } if ($related[1] && (index < $related.length - 1 || settings.loop)) { photo.style.cursor = 'pointer'; photo.onclick = function () { publicMethod.next(); }; } if (isIE) { photo.style.msInterpolationMode = 'bicubic'; } setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise. prep(photo); }, 1); }); setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise. photo.src = href; }, 1); } else if (href) { $loadingBay.load(href, settings.data, function (data, status, xhr) { prep(status === 'error' ? $div('Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents()); }); } }; // Navigates to the next page/image in a set. publicMethod.next = function () { if (!active && $related[1] && (index < $related.length - 1 || settings.loop)) { index = index < $related.length - 1 ? index + 1 : 0; publicMethod.load(); } }; publicMethod.prev = function () { if (!active && $related[1] && (index || settings.loop)) { index = index ? index - 1 : $related.length - 1; publicMethod.load(); } }; // Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close(); publicMethod.close = function () { if (open && !closing) { closing = true; open = false; trigger(event_cleanup, settings.onCleanup); $window.unbind('.' + prefix + ' .' + event_ie6); $overlay.fadeTo(200, 0); $box.stop().fadeTo(300, 0, function () { $box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide(); trigger(event_purge); $loaded.remove(); setTimeout(function () { closing = false; trigger(event_closed, settings.onClosed); }, 1); }); } }; // A method for fetching the current element ColorBox is referencing. // returns a jQuery object. publicMethod.element = function () { return $(element); }; publicMethod.settings = defaults; // Bind the live event before DOM-ready for maximum performance in IE6 & 7. handler = function (e) { // checks to see if it was a non-left mouse-click and for clicks modified with ctrl, shift, or alt. if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) { e.preventDefault(); launch(this); } }; if ($.fn.delegate) { $(document).delegate('.' + boxElement, 'click', handler); } else { $('.' + boxElement).live('click', handler); } // Initializes ColorBox when the DOM has loaded $(publicMethod.init); }(jQuery, document, this));
JavaScript
window.onload = function() { myHeight = new fx.Height('nav', {duration: 400}); myHeight.hide(); }
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). 10/24/2005 v(1.0.2) */ //base var fx = new Object(); fx.Base = function(){}; fx.Base.prototype = { setOptions: function(options) { this.options = { duration: 500, onComplete: '' } Object.extend(this.options, options || {}); }, go: function() { this.duration = this.options.duration; this.startTime = (new Date).getTime(); this.timer = setInterval (this.step.bind(this), 13); }, step: function() { var time = (new Date).getTime(); var Tpos = (time - this.startTime) / (this.duration); if (time >= this.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 { this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from; //this time-position, sinoidal transition thing is from script.aculo.us } this.increase(); }, custom: function(from, to) { if (this.timer != null) return; this.from = from; this.to = to; this.go(); }, 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.el.iniWidth = this.el.offsetWidth; this.el.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); } });
JavaScript
function create_menu(basepath) { var base = (basepath == 'null') ? '' : basepath; document.write( '<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' + '<td class="td" valign="top">' + '<ul>' + '<li><a href="'+base+'index.html">User Guide Home</a></li>' + '<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' + '</ul>' + '<h3>Basic Info</h3>' + '<ul>' + '<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' + '<li><a href="'+base+'license.html">License Agreement</a></li>' + '<li><a href="'+base+'changelog.html">Change Log</a></li>' + '<li><a href="'+base+'general/credits.html">Credits</a></li>' + '</ul>' + '<h3>Installation</h3>' + '<ul>' + '<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' + '<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' + '<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' + '<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' + '</ul>' + '<h3>Introduction</h3>' + '<ul>' + '<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' + '<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' + '<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' + '<li><a href="'+base+'overview/features.html">Supported Features</a></li>' + '<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' + '<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' + '<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>General Topics</h3>' + '<ul>' + '<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' + '<li><a href="'+base+'general/controllers.html">Controllers</a></li>' + '<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' + '<li><a href="'+base+'general/views.html">Views</a></li>' + '<li><a href="'+base+'general/models.html">Models</a></li>' + '<li><a href="'+base+'general/helpers.html">Helpers</a></li>' + '<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' + '<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' + '<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' + '<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' + '<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' + '<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' + '<li><a href="'+base+'general/routing.html">URI Routing</a></li>' + '<li><a href="'+base+'general/errors.html">Error Handling</a></li>' + '<li><a href="'+base+'general/caching.html">Caching</a></li>' + '<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' + '<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' + '<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' + '<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' + '<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' + '<li><a href="'+base+'general/security.html">Security</a></li>' + '<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' + '<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' + '</ul>' + '<h3>Additional Resources</h3>' + '<ul>' + '<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' + '<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>Class Reference</h3>' + '<ul>' + '<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' + '<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' + '<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' + '<li><a href="'+base+'libraries/config.html">Config Class</a></li>' + '<li><a href="'+base+'libraries/email.html">Email Class</a></li>' + '<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' + '<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' + '<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' + '<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' + '<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' + '<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' + '<li><a href="'+base+'libraries/input.html">Input Class</a></li>' + '<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' + '<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' + '<li><a href="'+base+'libraries/language.html">Language Class</a></li>' + '<li><a href="'+base+'libraries/output.html">Output Class</a></li>' + '<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' + '<li><a href="'+base+'libraries/security.html">Security Class</a></li>' + '<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' + '<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' + '<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' + '<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' + '<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' + '<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' + '<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' + '<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' + '<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>Driver Reference</h3>' + '<ul>' + '<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' + '<li><a href="'+base+'database/index.html">Database Class</a></li>' + '<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' + '</ul>' + '<h3>Helper Reference</h3>' + '<ul>' + '<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' + '<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' + '<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' + '<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' + '<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' + '<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' + '<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' + '<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' + '<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' + '<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' + '<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' + '<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' + '<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' + '<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' + '<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' + '<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' + '<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' + '<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' + '<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' + '<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' + '<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' + '</ul>' + '</td></tr></table>'); }
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There templates will be displayed as a dropdown in all media dialog if the "template_external_list_url" // option is defined in TinyMCE init. var tinyMCETemplateList = [ // Name, URL, Description ["Simple snippet", "templates/snippet1.htm", "Simple HTML snippet."], ["Layout", "templates/layout1.htm", "HTML Layout."] ];
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There links will be displayed as a dropdown in all link dialogs if the "external_link_list_url" // option is defined in TinyMCE init. var tinyMCELinkList = new Array( // Name, URL ["Moxiecode", "http://www.moxiecode.com"], ["Freshmeat", "http://www.freshmeat.com"], ["Sourceforge", "http://www.sourceforge.com"] );
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There images will be displayed as a dropdown in all image dialogs if the "external_link_image_url" // option is defined in TinyMCE init. var tinyMCEImageList = new Array( // Name, URL ["Logo 1", "media/logo.jpg"], ["Logo 2 Over", "media/logo_over.jpg"] );
JavaScript
// This list may be created by a server logic page PHP/ASP/ASPX/JSP in some backend system. // There flash movies will be displayed as a dropdown in all media dialog if the "media_external_list_url" // option is defined in TinyMCE init. var tinyMCEMediaList = [ // Name, URL ["Some Flash", "media/sample.swf"], ["Some Quicktime", "media/sample.mov"], ["Some AVI", "media/sample.avi"], ["Some RealMedia", "media/sample.rm"], ["Some Shockwave", "media/sample.dcr"], ["Some Video", "media/sample.mp4"], ["Some FLV", "media/sample.flv"], ];
JavaScript
//全局变量 var net = new Object(); //var ajax=new AJAXRequest([url],[callback],[content],[method],[async]); //下面是其构造函数 net.AjaxRequest = function (url, onload, onerror, method, params) { this.req = null; this.onload = onload; this.onerror = (onerror) ? onerror : this.defaultError; this.loadDate(url, method, params); }; //定义对象的方法,通过prototype定义方法的好处是每个对象不会有该函数的一个copy net.AjaxRequest.prototype.loadDate = function (url, method, params) { if (!method) { method = "GET"; } if (window.XMLHttpRequest) { this.req = new XMLHttpRequest(); } else { if (window.ActiveXObject) { this.req = new ActiveXObject("Microsoft.XMLHTTP"); } } if (this.req) { try { var loader = this;//this 指当前函数loadXMLDoc所依附对象即AjaxRequest实例 this.req.onreadystatechange = function () { net.AjaxRequest.onReadyState.call(loader);//将onReadyState该静态方法依附给loader对象,请注意这种调用方法! }; this.req.open(method, url, true); //this.req.send(params); this.req.send(null); } catch (err) { this.onerror.call(this); } } }; //重构onReadyState函数 net.AjaxRequest.onReadyState = function () { var req = this.req; var ready = req.readyState; if (ready == 4) { if (req.status == 200) { this.onload.call(this); } else { this.onerror.call(this); } } }; //默认错误处理函数 net.AjaxRequest.prototype.defaultError = function () { alert("error fetching data!" + "\n\nreadyState:" + this.req.readyState + "\nstatus: " + this.req.status + "\nheaders: " + this.req.getAllResponseHeaders()); };
JavaScript
var p =new Array(); p[0] = "选择省份"; p[1] = "北京"; p[2] = "上海"; p[3] = "天津"; p[4] = "重庆"; p[5] = "河北"; p[6] = "山西"; p[7] = "内蒙古 "; p[8] = "辽宁 "; p[9] = "吉林"; p[10] = "黑龙江 "; p[11] = "江苏"; p[12] = "浙江"; p[13] = "安徽"; p[14] = "福建"; p[15] = "江西"; p[16] = "山东"; p[17] = "河南"; p[18] = "湖北"; p[19] = "湖南"; p[20] = "广东"; p[21] = "广西"; p[22] = "海南"; p[23] = "四川"; p[24] = "贵州"; p[25] = "云南"; p[26] = "西藏"; p[27] = "陕西"; p[28] = "甘肃"; p[29] = "宁夏"; p[30] = "青海"; p[31] = "新疆"; p[32] = "香港"; p[33] = "澳门"; p[34] = "台湾"; var c =new Array(); c[0] =new Array("选择城市"); c[1] =new Array("东城","西城","崇文","宣武","朝阳","丰台","石景山","海淀","门头沟","房山","通州","顺义","昌平","大兴","平谷","怀柔","密云","延庆"); c[2] =new Array("黄浦","卢湾","徐汇","长宁","静安","普陀","闸北","虹口","杨浦","闵行","宝山","嘉定","浦东","金山","松江","青浦","南汇","奉贤","崇明"); c[3] =new Array("和平","东丽","河东","西青","河西","津南","南开","北辰","河北","武清","红挢","塘沽","汉沽","大港","宁河","静海","宝坻","蓟县"); c[4] =new Array("万州","涪陵","渝中","大渡口","江北","沙坪坝","九龙坡","南岸","北碚","万盛","双挢","渝北","巴南","黔江","长寿","綦江","潼南","铜梁","大足","荣昌","壁山","梁平","城口","丰都","垫江","武隆","忠县","开县","云阳","奉节","巫山","巫溪","石柱","秀山","酉阳","彭水","江津","合川","永川","南川"); c[5] =new Array("石家庄","邯郸","邢台","保定","张家口","承德","廊坊","唐山","秦皇岛","沧州","衡水"); c[6] =new Array("太原","大同","阳泉","长治","晋城","朔州","吕梁","忻州","晋中","临汾","运城"); c[7] =new Array("呼和浩特","包头","乌海","赤峰","呼伦贝尔盟","阿拉善盟","哲里木盟","兴安盟","乌兰察布盟","锡林郭勒盟","巴彦淖尔盟","伊克昭盟"); c[8] =new Array("沈阳","大连","鞍山","抚顺","本溪","丹东","锦州","营口","阜新","辽阳","盘锦","铁岭","朝阳","葫芦岛"); c[9] =new Array("长春","吉林","四平","辽源","通化","白山","松原","白城","延边"); c[10] =new Array("哈尔滨","齐齐哈尔","牡丹江","佳木斯","大庆","绥化","鹤岗","鸡西","黑河","双鸭山","伊春","七台河","大兴安岭"); c[11] =new Array("南京,镇江,苏州,南通,扬州,盐城,徐州,连云港,常州,无锡,宿迁,泰州,淮安"); c[12] =new Array("杭州","宁波","温州","嘉兴","湖州","绍兴","金华","衢州","舟山","台州","丽水"); c[13] =new Array("合肥","芜湖","蚌埠","马鞍山","淮北","铜陵","安庆","黄山","滁州","宿州","池州","淮南","巢湖","阜阳","六安","宣城","亳州"); c[14] =new Array("福州","厦门","莆田","三明","泉州","漳州","南平","龙岩","宁德"); c[15] =new Array("南昌市","景德镇","九江","鹰潭","萍乡","新馀","赣州","吉安","宜春","抚州","上饶"); c[16] =new Array("济南","青岛","淄博","枣庄","东营","烟台","潍坊","济宁","泰安","威海","日照","莱芜","临沂","德州","聊城","滨州","菏泽"); c[17] =new Array("郑州","开封","洛阳","平顶山","安阳","鹤壁","新乡","焦作","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店","济源"); c[18] =new Array("武汉","宜昌","荆州","襄樊","黄石","荆门","黄冈","十堰","恩施","潜江","天门","仙桃","随州","咸宁","孝感","鄂州"); c[19] =new Array("长沙","常德","株洲","湘潭","衡阳","岳阳","邵阳","益阳","娄底","怀化","郴州","永州","湘西","张家界 "); c[20] =new Array("广州","深圳","珠海","汕头","东莞","中山","佛山","韶关","江门","湛江","茂名","肇庆","惠州","梅州","汕尾","河源","阳江","清远","潮州","揭阳","云浮"); c[21] =new Array("南宁","柳州","桂林","梧州","北海","防城港","钦州","贵港","玉林","南宁地区","柳州地区","贺州","百色","河池"); c[22] =new Array("海口","三亚"); c[23] =new Array("成都","绵阳","德阳","自贡","攀枝花","广元","内江","乐山","南充","宜宾","广安","达川","雅安","眉山","甘孜","凉山","泸州"); c[24] =new Array("贵阳","六盘水","遵义","安顺","铜仁","黔西南","毕节","黔东南","黔南"); c[25] =new Array("昆明","大理","曲靖","玉溪","昭通","楚雄","红河","文山","思茅","西双版纳","保山","德宏","丽江","怒江","迪庆","临沧"); c[26] =new Array("拉萨","日喀则","山南","林芝","昌都","阿里","那曲"); c[27] =new Array("西安","宝鸡","咸阳","铜川","渭南","延安","榆林","汉中","安康","商洛"); c[28] =new Array("兰州","嘉峪关","金昌","白银","天水","酒泉","张掖","武威","定西","陇南","平凉","庆阳","临夏","甘南"); c[29] =new Array("银川","石嘴山","吴忠","固原"); c[30] =new Array("西宁","海东","海南","海北","黄南","玉树","果洛","海西"); c[31] =new Array("乌鲁木齐","石河子","克拉玛依","伊犁","巴音郭勒","昌吉","克孜勒苏柯尔克孜","博尔塔拉","吐鲁番","哈密","喀什","和田","阿克苏 "); c[32] =new Array("香港特别行政区 "); c[33] =new Array("澳门特别行政区 "); c[34] =new Array("台北","高雄","台中","台南","屏东","南投","云林","新竹","彰化","苗栗","嘉义","花莲","桃园","宜兰","基隆","台东","金门","马祖","澎湖"); /* * 将省份添加到slect中去 */ function set_pro_select1(so) { ///alert(123); for (var i = 0, n = p.length; i < n; i++ ) { var opt = document.createElement('option'); opt.text = p[i]; opt.value = p[i]; // 有些浏览器不支持 options 属性的 add 方法, // 但支持 DOM 的 appendChild 方法(比如:Konqueror) if (so.options.add) { so.options.add(opt); } else { so.appendChild(opt); } } }; /* *将对应的城市添加到第二个select中去 */ function set_city_select1(so,pid){ for(var i = 0,n = c[pid].length;i < n;i++){ var opt=document.createElement('option'); opt.text = c[pid][i]; opt.value = c[pid][i]; if (so.options.add) { so.options.add(opt); } else { so.appendChild(opt); } } }; /* *清除城市select中的内容 */ function clear_select(so) { for (var i = so.options.length - 1; i > -1; i--) { // 有些浏览器不支持 options 属性的 remove 方法, // 但支持 DOM 的 removeChild 方法(比如:Konqueror) if (so.options.remove) { so.options.remove(i); } else { so.removeChild(so.options[i]); } } }; /* *改变省份 */ function change_province(pid) { set_city_select(pid); }; /* 用来初始化省份的菜单 */ function init(){ var so=document.getElementById('prov'); set_pro_select1(so); change_province(0); }; function set_city_select(pname){ for(i=0;i<35;i++) { if(pname==p[i]) pid=i; } var so = document.getElementById('city'); clear_select(so); set_city_select1(so,pid); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * An info panel, which complements the map view of the Store Locator. * Provides a list of stores, location search, feature filter, and directions. */ /** * 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. */ /** * An info panel, to complement the map view. * Provides a list of stores, location search, feature filter, and directions. * @example <pre> * var container = document.getElementById('panel'); * var panel = new storeLocator.Panel(container, { * view: view, * locationSearchLabel: 'Location:' * }); * google.maps.event.addListener(panel, 'geocode', function(result) { * geocodeMarker.setPosition(result.geometry.location); * }); * </pre> * @extends {google.maps.MVCObject} * @param {!Node} el the element to contain this panel. * @param {storeLocator.PanelOptions} opt_options * @constructor * @implements storeLocator_Panel */ storeLocator.Panel = function(el, opt_options) { this.el_ = $(el); this.el_.addClass('storelocator-panel'); this.settings_ = $.extend({ 'locationSearch': true, 'locationSearchLabel': 'Where are you?', 'featureFilter': true, 'directions': true, 'view': null }, opt_options); this.directionsRenderer_ = new google.maps.DirectionsRenderer({ draggable: true }); this.directionsService_ = new google.maps.DirectionsService; this.init_(); }; storeLocator['Panel'] = storeLocator.Panel; storeLocator.Panel.prototype = new google.maps.MVCObject; /** * Initialise the info panel * @private */ storeLocator.Panel.prototype.init_ = function() { var that = this; this.itemCache_ = {}; if (this.settings_['view']) { this.set('view', this.settings_['view']); } this.filter_ = $('<form class="storelocator-filter"/>'); this.el_.append(this.filter_); if (this.settings_['locationSearch']) { this.locationSearch_ = $('<div class="location-search"><h4>' + this.settings_['locationSearchLabel'] + '</h4><input></div>'); this.filter_.append(this.locationSearch_); if (typeof google.maps.places != 'undefined') { this.initAutocomplete_(); } else { this.filter_.submit(function() { that.searchPosition($('input', that.locationSearch_).val()); }); } this.filter_.submit(function() { return false; }); google.maps.event.addListener(this, 'geocode', function(place) { if (that.searchPositionTimeout_) { window.clearTimeout(that.searchPositionTimeout_); } if (!place.geometry) { that.searchPosition(place.name); return; } this.directionsFrom_ = place.geometry.location; if (that.directionsVisible_) { that.renderDirections_(); } var sl = that.get('view'); sl.highlight(null); var map = sl.getMap(); if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(13); } sl.refreshView(); that.listenForStoresUpdate_(); }); } if (this.settings_['featureFilter']) { // TODO(cbro): update this on view_changed this.featureFilter_ = $('<div class="feature-filter"/>'); var allFeatures = this.get('view').getFeatures().asList(); for (var i = 0, ii = allFeatures.length; i < ii; i++) { var feature = allFeatures[i]; var checkbox = $('<input type="checkbox"/>'); checkbox.data('feature', feature); $('<label/>').append(checkbox).append(feature.getDisplayName()) .appendTo(this.featureFilter_); } this.filter_.append(this.featureFilter_); this.featureFilter_.find('input').change(function() { var feature = $(this).data('feature'); that.toggleFeatureFilter_(feature); that.get('view').refreshView(); }); } this.storeList_ = $('<ul class="store-list"/>'); this.el_.append(this.storeList_); if (this.settings_['directions']) { this.directionsPanel_ = $('<div class="directions-panel"><form>' + '<input class="directions-to"/>' + '<input type="submit" value="Find directions"/>' + '<a href="#" class="close-directions">Close</a>' + '</form><div class="rendered-directions"></div></div>'); this.directionsPanel_.find('.directions-to').attr('readonly', 'readonly'); this.directionsPanel_.hide(); this.directionsVisible_ = false; this.directionsPanel_.find('form').submit(function() { that.renderDirections_(); return false; }); this.directionsPanel_.find('.close-directions').click(function() { that.hideDirections(); }); this.el_.append(this.directionsPanel_); } }; /** * Toggles a particular feature on/off in the feature filter. * @param {storeLocator.Feature} feature The feature to toggle. * @private */ storeLocator.Panel.prototype.toggleFeatureFilter_ = function(feature) { var featureFilter = this.get('featureFilter'); featureFilter.toggle(feature); this.set('featureFilter', featureFilter); }; /** * Global Geocoder instance, for convenience. * @type {google.maps.Geocoder} * @private */ storeLocator.geocoder_ = new google.maps.Geocoder; /** * Triggers an update for the store list in the Panel. Will wait for stores * to load asynchronously from the data source. * @private */ storeLocator.Panel.prototype.listenForStoresUpdate_ = function() { var that = this; var view = /** @type storeLocator.View */(this.get('view')); if (this.storesChangedListener_) { google.maps.event.removeListener(this.storesChangedListener_); } this.storesChangedListener_ = google.maps.event.addListenerOnce(view, 'stores_changed', function() { that.set('stores', view.get('stores')); }); }; /** * Search and pan to the specified address. * @param {string} searchText the address to pan to. */ storeLocator.Panel.prototype.searchPosition = function(searchText) { var that = this; var request = { address: searchText, bounds: this.get('view').getMap().getBounds() }; storeLocator.geocoder_.geocode(request, function(result, status) { if (status != google.maps.GeocoderStatus.OK) { //TODO(cbro): proper error handling return; } google.maps.event.trigger(that, 'geocode', result[0]); }); }; /** * Sets the associated View. * @param {storeLocator.View} view the view to set. */ storeLocator.Panel.prototype.setView = function(view) { this.set('view', view); }; /** * view_changed handler. * Sets up additional bindings between the info panel and the map view. */ storeLocator.Panel.prototype.view_changed = function() { var sl = /** @type {google.maps.MVCObject} */ (this.get('view')); this.bindTo('selectedStore', sl); var that = this; if (this.geolocationListener_) { google.maps.event.removeListener(this.geolocationListener_); } if (this.zoomListener_) { google.maps.event.removeListener(this.zoomListener_); } if (this.idleListener_) { google.maps.event.removeListener(this.idleListener_); } var center = sl.getMap().getCenter(); var updateList = function() { sl.clearMarkers(); that.listenForStoresUpdate_(); }; //TODO(cbro): somehow get the geolocated position and populate the 'from' box. this.geolocationListener_ = google.maps.event.addListener(sl, 'load', updateList); this.zoomListener_ = google.maps.event.addListener(sl.getMap(), 'zoom_changed', updateList); this.idleListener_ = google.maps.event.addListener(sl.getMap(), 'idle', function() { return that.idle_(sl.getMap()); }); updateList(); this.bindTo('featureFilter', sl); if (this.autoComplete_) { this.autoComplete_.bindTo('bounds', sl.getMap()); } }; /** * Adds autocomplete to the input box. * @private */ storeLocator.Panel.prototype.initAutocomplete_ = function() { var that = this; var input = $('input', this.locationSearch_)[0]; this.autoComplete_ = new google.maps.places.Autocomplete(input); if (this.get('view')) { this.autoComplete_.bindTo('bounds', this.get('view').getMap()); } google.maps.event.addListener(this.autoComplete_, 'place_changed', function() { google.maps.event.trigger(that, 'geocode', this.getPlace()); }); }; /** * Called on the view's map idle event. Refreshes the store list if the * user has navigated far away enough. * @param {google.maps.Map} map the current view's map. * @private */ storeLocator.Panel.prototype.idle_ = function(map) { if (!this.center_) { this.center_ = map.getCenter(); } else if (!map.getBounds().contains(this.center_)) { this.center_ = map.getCenter(); this.listenForStoresUpdate_(); } }; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_HTML_ = '<li class="no-stores">There are no' + ' stores in this area.</li>'; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">There are' + ' no stores in this area. However, stores closest to you are' + ' listed below.</li>'; /** * Handler for stores_changed. Updates the list of stores. * @this storeLocator.Panel */ storeLocator.Panel.prototype.stores_changed = function() { if (!this.get('stores')) { return; } var view = this.get('view'); var bounds = view && view.getMap().getBounds(); var that = this; var stores = this.get('stores'); var selectedStore = this.get('selectedStore'); this.storeList_.empty(); if (!stores.length) { this.storeList_.append(storeLocator.Panel.NO_STORES_HTML_); } else if (bounds && !bounds.contains(stores[0].getLocation())) { this.storeList_.append(storeLocator.Panel.NO_STORES_IN_VIEW_HTML_); } var clickHandler = function() { view.highlight(this['store'], true); }; // TODO(cbro): change 10 to a setting/option for (var i = 0, ii = Math.min(10, stores.length); i < ii; i++) { var storeLi = stores[i].getInfoPanelItem(); storeLi['store'] = stores[i]; if (selectedStore && stores[i].getId() == selectedStore.getId()) { $(storeLi).addClass('highlighted'); } if (!storeLi.clickHandler_) { storeLi.clickHandler_ = google.maps.event.addDomListener( storeLi, 'click', clickHandler); } that.storeList_.append(storeLi); } }; /** * Handler for selectedStore_changed. Highlights the selected store in the * store list. * @this storeLocator.Panel */ storeLocator.Panel.prototype.selectedStore_changed = function() { $('.highlighted', this.storeList_).removeClass('highlighted'); var that = this; var store = this.get('selectedStore'); if (!store) { return; } this.directionsTo_ = store; this.storeList_.find('#store-' + store.getId()).addClass('highlighted'); if (this.settings_['directions']) { this.directionsPanel_.find('.directions-to') .val(store.getDetails().title); } var node = that.get('view').getInfoWindow().getContent(); var directionsLink = $('<a/>') .text('Directions') .attr('href', '#') .addClass('action') .addClass('directions'); // TODO(cbro): Make these two permanent fixtures in InfoWindow. // Move out of Panel. var zoomLink = $('<a/>') .text('Zoom here') .attr('href', '#') .addClass('action') .addClass('zoomhere'); var streetViewLink = $('<a/>') .text('Street view') .attr('href', '#') .addClass('action') .addClass('streetview'); directionsLink.click(function() { that.showDirections(); return false; }); zoomLink.click(function() { that.get('view').getMap().setOptions({ center: store.getLocation(), zoom: 16 }); }); streetViewLink.click(function() { var streetView = that.get('view').getMap().getStreetView(); streetView.setPosition(store.getLocation()); streetView.setVisible(true); }); $(node).append(directionsLink).append(zoomLink).append(streetViewLink); }; /** * Hides the directions panel. */ storeLocator.Panel.prototype.hideDirections = function() { this.directionsVisible_ = false; this.directionsPanel_.fadeOut(); this.featureFilter_.fadeIn(); this.storeList_.fadeIn(); this.directionsRenderer_.setMap(null); }; /** * Shows directions to the selected store. */ storeLocator.Panel.prototype.showDirections = function() { var store = this.get('selectedStore'); this.featureFilter_.fadeOut(); this.storeList_.fadeOut(); this.directionsPanel_.find('.directions-to').val(store.getDetails().title); this.directionsPanel_.fadeIn(); this.renderDirections_(); this.directionsVisible_ = true; }; /** * Renders directions from the location in the input box, to the store that is * pre-filled in the 'to' box. * @private */ storeLocator.Panel.prototype.renderDirections_ = function() { var that = this; if (!this.directionsFrom_ || !this.directionsTo_) { return; } var rendered = this.directionsPanel_.find('.rendered-directions').empty(); this.directionsService_.route({ origin: this.directionsFrom_, destination: this.directionsTo_.getLocation(), travelMode: google.maps['DirectionsTravelMode'].DRIVING //TODO(cbro): region biasing, waypoints, travelmode }, function(result, status) { if (status != google.maps.DirectionsStatus.OK) { // TODO(cbro): better error handling return; } var renderer = that.directionsRenderer_; renderer.setPanel(rendered[0]); renderer.setMap(that.get('view').getMap()); renderer.setDirections(result); }); }; /** * featureFilter_changed event handler. */ storeLocator.Panel.prototype.featureFilter_changed = function() { this.listenForStoresUpdate_(); }; /** * Fired when searchPosition has been called. This happens when the user has * searched for a location from the location search box and/or autocomplete. * @name storeLocator.Panel#event:geocode * @param {google.maps.PlaceResult|google.maps.GeocoderResult} result * @event */ /** * Fired when the <code>Panel</code>'s <code>view</code> property changes. * @name storeLocator.Panel#event:view_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.Panel#event:featureFilter_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>stores</code> property changes. * @name storeLocator.Panel#event:stores_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>selectedStore</code> property * changes. * @name storeLocator.Panel#event:selectedStore_changed * @event */ /** * @example see storeLocator.Panel * @interface */ storeLocator.PanelOptions = function() {}; /** * Whether to show the location search box. Default is true. * @type boolean */ storeLocator.prototype.locationSearch; /** * The label to show above the location search box. Default is "Where are you * now?". * @type string */ storeLocator.PanelOptions.prototype.locationSearchLabel; /** * Whether to show the feature filter picker. Default is true. * @type boolean */ storeLocator.PanelOptions.prototype.featureFilter; /** * Whether to provide directions. Deafult is true. * @type boolean */ storeLocator.PanelOptions.prototype.directions; /** * The store locator model to bind to. * @type storeLocator.View */ storeLocator.PanelOptions.prototype.view;
JavaScript
// Copyright 2012 Google Inc. /** * @name Store Locator for Google Maps API V3 * @version 0.1 * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * @license * * Copyright 2012 Google Inc. * * 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. */ /** * Namespace for Store Locator. * @constructor */ var storeLocator = function() {}; window['storeLocator'] = storeLocator; /** * Convert from degrees to radians. * @private * @param {number} degrees the number in degrees. * @return {number} the number in radians. */ storeLocator.toRad_ = function(degrees) { return degrees * Math.PI / 180; };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Allows developers to specify a static set of stores to be used in the * storelocator. */ /** * 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 DataFeed with a static set of stores. Provides sorting of stores by * proximity and feature filtering (store must have <em>all</em> features from * the filter). * @example <pre> * var dataFeed = new storeLocator.StaticDataFeed(); * jQuery.getJSON('stores.json', function(json) { * var stores = parseStores(json); * dataFeed.setStores(stores); * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements {storeLocator.DataFeed} * @constructor * @implements storeLocator_StaticDataFeed */ storeLocator.StaticDataFeed = function() { /** * The static list of stores. * @private * @type {Array.<storeLocator.Store>} */ this.stores_ = []; }; storeLocator['StaticDataFeed'] = storeLocator.StaticDataFeed; /** * This will contain a callback to be called if getStores was called before * setStores (i.e. if the map is waiting for data from the data source). * @private * @type {Function} */ storeLocator.StaticDataFeed.prototype.firstCallback_; /** * Set the stores for this data feed. * @param {!Array.<!storeLocator.Store>} stores the stores for this data feed. */ storeLocator.StaticDataFeed.prototype.setStores = function(stores) { this.stores_ = stores; if (this.firstCallback_) { this.firstCallback_(); } else { delete this.firstCallback_; } }; /** * @inheritDoc */ storeLocator.StaticDataFeed.prototype.getStores = function(bounds, features, callback) { // Prevent race condition - if getStores is called before stores are loaded. if (!this.stores_.length) { var that = this; this.firstCallback_ = function() { that.getStores(bounds, features, callback); }; return; } // Filter stores for features. var stores = []; for (var i = 0, store; store = this.stores_[i]; i++) { if (store.hasAllFeatures(features)) { stores.push(store); } } this.sortByDistance_(bounds.getCenter(), stores); callback(stores); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.StaticDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Store model class for Store Locator library. */ /** * 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. */ /** * Represents a store. * @example <pre> * var latLng = new google.maps.LatLng(40.7585, -73.9861); * var store = new storeLocator.Store('times_square', latLng, null); * </pre> * <pre> * var features = new storeLocator.FeatureSet( * view.getFeatureById('24hour'), * view.getFeatureById('express'), * view.getFeatureById('wheelchair_access')); * * var store = new storeLocator.Store('times_square', latLng, features, { * title: 'Times Square', * address: '1 Times Square&lt;br>Manhattan, NY 10036' * }); * </pre> * <pre> * store.distanceTo(map.getCenter()); * * // override default info window * store.getInfoWindowContent = function() { * var details = this.getDetails(); * return '&lt;h1>' + details.title + '&lt;h1>' + details.address; * }; * </pre> * @param {string} id globally unique id of the store - should be suitable to * use as a HTML id. * @param {!google.maps.LatLng} location location of the store. * @param {storeLocator.FeatureSet} features the features of this store. * @param {Object.<string, *>=} props any additional properties. * <p> Recommended fields are: * 'title', 'address', 'phone', 'misc', 'web'. </p> * @constructor * @implements storeLocator_Store */ storeLocator.Store = function(id, location, features, props) { this.id_ = id; this.location_ = location; this.features_ = features || storeLocator.FeatureSet.NONE; this.props_ = props || {}; }; storeLocator['Store'] = storeLocator.Store; /** * Sets this store's Marker. * @param {google.maps.Marker} marker the marker to set on this store. */ storeLocator.Store.prototype.setMarker = function(marker) { this.marker_ = marker; google.maps.event.trigger(this, 'marker_changed', marker); }; /** * Gets this store's Marker * @return {google.maps.Marker} the store's marker. */ storeLocator.Store.prototype.getMarker = function() { return this.marker_; }; /** * Gets this store's ID. * @return {string} this store's ID. */ storeLocator.Store.prototype.getId = function() { return this.id_; }; /** * Gets this store's location. * @return {google.maps.LatLng} this store's location. */ storeLocator.Store.prototype.getLocation = function() { return this.location_; }; /** * Gets this store's features. * @return {storeLocator.FeatureSet} this store's features. */ storeLocator.Store.prototype.getFeatures = function() { return this.features_; }; /** * Checks whether this store has a particular feature. * @param {!storeLocator.Feature} feature the feature to check for. * @return {boolean} true if the store has the feature, false otherwise. */ storeLocator.Store.prototype.hasFeature = function(feature) { return this.features_.contains(feature); }; /** * Checks whether this store has all the given features. * @param {storeLocator.FeatureSet} features the features to check for. * @return {boolean} true if the store has all features, false otherwise. */ storeLocator.Store.prototype.hasAllFeatures = function(features) { if (!features) { return true; } var featureList = features.asList(); for (var i = 0, ii = featureList.length; i < ii; i++) { if (!this.hasFeature(featureList[i])) { return false; } } return true; }; /** * Gets additional details about this store. * @return {Object} additional properties of this store. */ storeLocator.Store.prototype.getDetails = function() { return this.props_; }; /** * Generates HTML for additional details about this store. * @private * @param {Array.<string>} fields the optional fields of this store to output. * @return {string} html version of additional fields of this store. */ storeLocator.Store.prototype.generateFieldsHTML_ = function(fields) { var html = []; for (var i = 0, ii = fields.length; i < ii; i++) { var prop = fields[i]; if (this.props_[prop]) { html.push('<div class="'); html.push(prop); html.push('">'); html.push(this.props_[prop]); html.push('</div>'); } } return html.join(''); }; /** * Generates a HTML list of this store's features. * @private * @return {string} html list of this store's features. */ storeLocator.Store.prototype.generateFeaturesHTML_ = function() { var html = []; html.push('<ul class="features">'); var featureList = this.features_.asList(); for (var i = 0, feature; feature = featureList[i]; i++) { html.push('<li>'); html.push(feature.getDisplayName()); html.push('</li>'); } html.push('</ul>'); return html.join(''); }; /** * Gets the HTML content for this Store, suitable for use in an InfoWindow. * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoWindowContent = function() { if (!this.content_) { // TODO(cbro): make this a setting? var fields = ['title', 'address', 'phone', 'misc', 'web']; var html = ['<div class="store">']; html.push(this.generateFieldsHTML_(fields)); html.push(this.generateFeaturesHTML_()); html.push('</div>'); this.content_ = html.join(''); } return this.content_; }; /** * Gets the HTML content for this Store, suitable for use in suitable for use * in the sidebar info panel. * @this storeLocator.Store * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoPanelContent = function() { return this.getInfoWindowContent(); }; /** * Keep a cache of InfoPanel items (DOM Node), keyed by the store ID. * @private * @type {Object} */ storeLocator.Store.infoPanelCache_ = {}; /** * Gets a HTML element suitable for use in the InfoPanel. * @return {Node} a HTML element. */ storeLocator.Store.prototype.getInfoPanelItem = function() { var cache = storeLocator.Store.infoPanelCache_; var store = this; var key = store.getId(); if (!cache[key]) { var content = store.getInfoPanelContent(); cache[key] = $('<li class="store" id="store-' + store.getId() + '">' + content + '</li>')[0]; } return cache[key]; }; /** * Gets the distance between this Store and a certain location. * @param {google.maps.LatLng} point the point to calculate distance to/from. * @return {number} the distance from this store to a given point. * @license * Latitude/longitude spherical geodesy formulae & scripts * (c) Chris Veness 2002-2010 * www.movable-type.co.uk/scripts/latlong.html */ storeLocator.Store.prototype.distanceTo = function(point) { var R = 6371; // mean radius of earth var location = this.getLocation(); var lat1 = storeLocator.toRad_(location.lat()); var lon1 = storeLocator.toRad_(location.lng()); var lat2 = storeLocator.toRad_(point.lat()); var lon2 = storeLocator.toRad_(point.lng()); var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; }; /** * Fired when the <code>Store</code>'s <code>marker</code> property changes. * @name storeLocator.Store#event:marker_changed * @param {google.maps.Marker} marker * @event */
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * FeatureSet class for Store Locator library. A mutable, ordered set of * storeLocator.Features. */ /** * 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 mutable, ordered set of <code>storeLocator.Feature</code>s. * @example <pre> * var feature1 = new storeLocator.Feature('1', 'Feature One'); * var feature2 = new storeLocator.Feature('2', 'Feature Two'); * var feature3 = new storeLocator.Feature('3', 'Feature Three'); * * var featureSet = new storeLocator.FeatureSet(feature1, feature2, feature3); * </pre> * @param {...storeLocator.Feature} var_args the initial features to add to * the set. * @constructor * @implements storeLocator_FeatureSet */ storeLocator.FeatureSet = function(var_args) { /** * Stores references to the actual Feature. * @private * @type {!Array.<storeLocator.Feature>} */ this.array_ = []; /** * Maps from a Feature's id to its array index. * @private * @type {Object.<string, number>} */ this.hash_ = {}; for (var i = 0, feature; feature = arguments[i]; i++) { this.add(feature); } }; storeLocator['FeatureSet'] = storeLocator.FeatureSet; /** * Adds the given feature to the set, if it doesn't exist in the set already. * Else, removes the feature from the set. * @param {!storeLocator.Feature} feature the feature to toggle. */ storeLocator.FeatureSet.prototype.toggle = function(feature) { if (this.contains(feature)) { this.remove(feature); } else { this.add(feature); } }; /** * Check if a feature exists within this set. * @param {!storeLocator.Feature} feature the feature. * @return {boolean} true if the set contains the given feature. */ storeLocator.FeatureSet.prototype.contains = function(feature) { return feature.getId() in this.hash_; }; /** * Gets a Feature object from the set, by the feature id. * @param {string} featureId the feature's id. * @return {storeLocator.Feature} the feature, if the set contains it. */ storeLocator.FeatureSet.prototype.getById = function(featureId) { if (featureId in this.hash_) { return this.array_[this.hash_[featureId]]; } return null; }; /** * Adds a feature to the set. * @param {storeLocator.Feature} feature the feature to add. */ storeLocator.FeatureSet.prototype.add = function(feature) { if (!feature) { return; } this.array_.push(feature); this.hash_[feature.getId()] = this.array_.length - 1; }; /** * Removes a feature from the set, if it already exists in the set. If it does * not already exist in the set, this function is a no op. * @param {!storeLocator.Feature} feature the feature to remove. */ storeLocator.FeatureSet.prototype.remove = function(feature) { if (!this.contains(feature)) { return; } this.array_[this.hash_[feature.getId()]] = null; delete this.hash_[feature.getId()]; }; /** * Get the contents of this set as an Array. * @return {Array.<!storeLocator.Feature>} the features in the set, in the order * they were inserted. */ storeLocator.FeatureSet.prototype.asList = function() { var filtered = []; for (var i = 0, ii = this.array_.length; i < ii; i++) { var elem = this.array_[i]; if (elem !== null) { filtered.push(elem); } } return filtered; }; /** * Empty feature set. * @type storeLocator.FeatureSet * @const */ storeLocator.FeatureSet.NONE = new storeLocator.FeatureSet;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * 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. */ /** * Data feed that returns stores based on a given bounds and a set of features. * @example <pre> * // always returns the same stores * function SimpleStaticFeed(stores) { * this.stores = stores; * } * SimpleStaticFeed.prototype.getStores = function(bounds, features, callback) { * callback(this.stores); * }; * new storeLocator.View(map, new SimpleStaticFeed()); * </pre> * @interface */ storeLocator.DataFeed = function() {}; storeLocator['DataFeed'] = storeLocator.DataFeed; /** * Fetch stores, based on bounds to search within, and features to filter on. * @param {google.maps.LatLngBounds} bounds the bounds to search within. * @param {storeLocator.FeatureSet} features the features to filter on. * @param {function(Array.<!storeLocator.Store>)} callback the callback * function. */ storeLocator.DataFeed.prototype.getStores = function(bounds, features, callback) {}; /** * The main store locator object. * @example <pre> * new storeLocator.View(map, dataFeed); * </pre> * <pre> * var features = new storeLocator.FeatureSet(feature1, feature2, feature3); * new storeLocator.View(map, dataFeed, { * markerIcon: 'icon.png', * features: features, * geolocation: false * }); * </pre> * <pre> * // refresh stores every 10 seconds, regardless of interaction on the map. * var view = new storeLocator.View(map, dataFeed, { * updateOnPan: false * }); * setTimeout(function() { * view.refreshView(); * }, 10000); * </pre> * <pre> * // custom MarkerOptions, by overriding the createMarker method. * view.createMarker = function(store) { * return new google.maps.Marker({ * position: store.getLocation(), * icon: store.getDetails().icon, * title: store.getDetails().title * }); * }; * </pre> * @extends {google.maps.MVCObject} * @param {google.maps.Map} map the map to operate upon. * @param {storeLocator.DataFeed} data the data feed to fetch stores from. * @param {storeLocator.ViewOptions} opt_options * @constructor * @implements storeLocator_View */ storeLocator.View = function(map, data, opt_options) { this.map_ = map; this.data_ = data; this.settings_ = $.extend({ 'updateOnPan': true, 'geolocation': true, 'features': new storeLocator.FeatureSet }, opt_options); this.init_(); google.maps.event.trigger(this, 'load'); this.set('featureFilter', new storeLocator.FeatureSet); }; storeLocator['View'] = storeLocator.View; storeLocator.View.prototype = new google.maps.MVCObject; /** * Attempt to perform geolocation and pan to the given location * @private */ storeLocator.View.prototype.geolocate_ = function() { var that = this; if (window.navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(pos) { var loc = new google.maps.LatLng( pos.coords.latitude, pos.coords.longitude); that.getMap().setCenter(loc); that.getMap().setZoom(11); google.maps.event.trigger(that, 'load'); }, undefined, /** @type GeolocationPositionOptions */({ maximumAge: 60 * 1000, timeout: 10 * 1000 })); } }; /** * Initialise the View object * @private */ storeLocator.View.prototype.init_ = function() { if (this.settings_['geolocation']) { this.geolocate_(); } this.markerCache_ = {}; this.infoWindow_ = new google.maps.InfoWindow; var that = this; var map = this.getMap(); this.set('updateOnPan', this.settings_['updateOnPan']); google.maps.event.addListener(this.infoWindow_, 'closeclick', function() { that.highlight(null); }); google.maps.event.addListener(map, 'click', function() { that.highlight(null); that.infoWindow_.close(); }); }; /** * Adds/remove hooks as appropriate. */ storeLocator.View.prototype.updateOnPan_changed = function() { if (this.updateOnPanListener_) { google.maps.event.removeListener(this.updateOnPanListener_); } if (this.get('updateOnPan') && this.getMap()) { var that = this; var map = this.getMap(); this.updateOnPanListener_ = google.maps.event.addListener(map, 'idle', function() { that.refreshView(); }); } }; /** * Add a store to the map. * @param {storeLocator.Store} store the store to add. */ storeLocator.View.prototype.addStoreToMap = function(store) { var marker = this.getMarker(store); store.setMarker(marker); var that = this; marker.clickListener_ = google.maps.event.addListener(marker, 'click', function() { that.highlight(store, false); }); if (marker.getMap() != this.getMap()) { marker.setMap(this.getMap()); } }; /** * Create a marker for a store. * @param {storeLocator.Store} store the store to produce a marker for. * @this storeLocator.View * @return {google.maps.Marker} a new marker. * @export */ storeLocator.View.prototype.createMarker = function(store) { var markerOptions = { position: store.getLocation() }; var opt_icon = this.settings_['markerIcon']; if (opt_icon) { markerOptions.icon = opt_icon; } return new google.maps.Marker(markerOptions); }; /** * Get a marker for a store. By default, this caches the value from * createMarker(store) * @param {storeLocator.Store} store the store to get the marker from. * @return {google.maps.Marker} the marker. */ storeLocator.View.prototype.getMarker = function(store) { var cache = this.markerCache_; var key = store.getId(); if (!cache[key]) { cache[key] = this['createMarker'](store); } return cache[key]; }; /** * Get a InfoWindow for a particular store. * @param {storeLocator.Store} store the store. * @return {google.maps.InfoWindow} the store's InfoWindow. */ storeLocator.View.prototype.getInfoWindow = function(store) { if (!store) { return this.infoWindow_; } var div = $(store.getInfoWindowContent()); this.infoWindow_.setContent(div[0]); return this.infoWindow_; }; /** * Gets all possible features for this View. * @return {storeLocator.FeatureSet} All possible features. */ storeLocator.View.prototype.getFeatures = function() { return this.settings_['features']; }; /** * Gets a feature by its id. Convenience method. * @param {string} id the feature's id. * @return {storeLocator.Feature|undefined} The feature, if the id is valid. * undefined if not. */ storeLocator.View.prototype.getFeatureById = function(id) { if (!this.featureById_) { this.featureById_ = {}; for (var i = 0, feature; feature = this.settings_['features'][i]; i++) { this.featureById_[feature.getId()] = feature; } } return this.featureById_[id]; }; /** * featureFilter_changed event handler. */ storeLocator.View.prototype.featureFilter_changed = function() { google.maps.event.trigger(this, 'featureFilter_changed', this.get('featureFilter')); if (this.get('stores')) { this.clearMarkers(); } }; /** * Clears the visible markers on the map. */ storeLocator.View.prototype.clearMarkers = function() { for (var marker in this.markerCache_) { this.markerCache_[marker].setMap(null); var listener = this.markerCache_[marker].clickListener_; if (listener) { google.maps.event.removeListener(listener); } } }; /** * Refresh the map's view. This will fetch new data based on the map's bounds. */ storeLocator.View.prototype.refreshView = function() { var that = this; this.data_.getStores(this.getMap().getBounds(), (/** @type {storeLocator.FeatureSet} */ this.get('featureFilter')), function(stores) { var oldStores = that.get('stores'); if (oldStores) { for (var i = 0, ii = oldStores.length; i < ii; i++) { google.maps.event.removeListener( oldStores[i].getMarker().clickListener_); } } that.set('stores', stores); }); }; /** * stores_changed event handler. * This will display all new stores on the map. * @this storeLocator.View */ storeLocator.View.prototype.stores_changed = function() { var stores = this.get('stores'); for (var i = 0, store; store = stores[i]; i++) { this.addStoreToMap(store); } }; /** * Gets the view's Map. * @return {google.maps.Map} the view's Map. */ storeLocator.View.prototype.getMap = function() { return this.map_; }; /** * Select a particular store. * @param {storeLocator.Store} store the store to highlight. * @param {boolean} pan if panning to the store on the map is desired. */ storeLocator.View.prototype.highlight = function(store, pan) { var infoWindow = this.getInfoWindow(store); if (store) { var infoWindow = this.getInfoWindow(store); if (store.getMarker()) { infoWindow.open(this.getMap(), store.getMarker()); } else { infoWindow.setPosition(store.getLocation()); infoWindow.open(this.getMap()); } if (pan) { this.getMap().panTo(store.getLocation()); } if (this.getMap().getStreetView().getVisible()) { this.getMap().getStreetView().setPosition(store.getLocation()); } } else { infoWindow.close(); } this.set('selectedStore', store); }; /** * Re-triggers the selectedStore_changed event with the store as a parameter. * @this storeLocator.View */ storeLocator.View.prototype.selectedStore_changed = function() { google.maps.event.trigger(this, 'selectedStore_changed', this.get('selectedStore')); }; /** * Fired when the <code>View</code> is loaded. This happens once immediately, * then once more if geolocation is successful. * @name storeLocator.View#event:load * @event */ /** * Fired when the <code>View</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.View#event:featureFilter_changed * @event */ /** * Fired when the <code>View</code>'s <code>updateOnPan</code> property changes. * @name storeLocator.View#event:updateOnPan_changed * @event */ /** * Fired when the <code>View</code>'s <code>stores</code> property changes. * @name storeLocator.View#event:stores_changed * @event */ /** * Fired when the <code>View</code>'s <code>selectedStore</code> property * changes. This happens after <code>highlight()</code> is called. * @name storeLocator.View#event:selectedStore_changed * @param {storeLocator.Store} store * @event */ /** * @example see storeLocator.View * @interface */ storeLocator.ViewOptions = function() {}; /** * Whether the map should update stores in the visible area when the visible * area changes. <code>refreshView()</code> will need to be called * programatically. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.updateOnPan; /** * Whether the store locator should attempt to determine the user's location * for the initial view. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.geolocation; /** * All available store features. Defaults to empty FeatureSet. * @type storeLocator.FeatureSet */ storeLocator.ViewOptions.prototype.features; /** * The icon to use for markers representing stores. * @type string|google.maps.MarkerImage */ storeLocator.ViewOptions.prototype.markerIcon;
JavaScript