code stringlengths 1 2.08M | language stringclasses 1 value |
|---|---|
var theList, theExtraList, toggleWithKeyboard = false, getCount, updateCount, updatePending, dashboardTotals;
(function($) {
setCommentsList = function() {
var totalInput, perPageInput, pageInput, lastConfidentTime = 0, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList;
totalInput = $('input[name="_total"]', '#comments-form');
perPageInput = $('input[name="_per_page"]', '#comments-form');
pageInput = $('input[name="_page"]', '#comments-form');
dimAfter = function( r, settings ) {
var c = $('#' + settings.element), editRow, replyID, replyButton;
editRow = $('#replyrow');
replyID = $('#comment_ID', editRow).val();
replyButton = $('#replybtn', editRow);
if ( c.is('.unapproved') ) {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.replyApprove);
c.find('div.comment_status').html('0');
} else {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.reply);
c.find('div.comment_status').html('1');
}
$('span.pending-count').each( function() {
var a = $(this), n, dif;
n = a.html().replace(/[^0-9]+/g, '');
n = parseInt(n,10);
if ( isNaN(n) ) return;
dif = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
n = n + dif;
if ( n < 0 ) { n = 0; }
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount(a, n);
dashboardTotals();
});
};
// Send current total, page, per_page and url
delBefore = function( settings, list ) {
var cl = $(settings.target).attr('class'), id, el, n, h, a, author, action = false;
settings.data._total = totalInput.val() || 0;
settings.data._per_page = perPageInput.val() || 0;
settings.data._page = pageInput.val() || 0;
settings.data._url = document.location.href;
settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();
if ( cl.indexOf(':trash=1') != -1 )
action = 'trash';
else if ( cl.indexOf(':spam=1') != -1 )
action = 'spam';
if ( action ) {
id = cl.replace(/.*?comment-([0-9]+).*/, '$1');
el = $('#comment-' + id);
note = $('#' + action + '-undo-holder').html();
el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.
if ( el.siblings('#replyrow').length && commentReply.cid == id )
commentReply.close();
if ( el.is('tr') ) {
n = el.children(':visible').length;
author = $('.author strong', el).text();
h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>');
} else {
author = $('.comment-author', el).text();
h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>');
}
el.before(h);
$('strong', '#undo-' + id).text(author + ' ');
a = $('.undo a', '#undo-' + id);
a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
a.attr('class', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1 vim-z vim-destructive');
$('.avatar', el).clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');
a.click(function(){
list.wpList.del(this);
$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
$(this).remove();
$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show() });
});
return false;
});
}
return settings;
};
// Updates the current total (as displayed visibly)
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime )
return;
if ( setConfidentTime )
lastConfidentTime = time;
totalInput.val( total.toString() );
$('span.total-type-count').each( function() {
updateCount( $(this), total );
});
};
dashboardTotals = function(n) {
var dash = $('#dashboard_right_now'), total, appr, totalN, apprN;
n = n || 0;
if ( isNaN(n) || !dash.length )
return;
total = $('span.total-count', dash);
appr = $('span.approved-count', dash);
totalN = getCount(total);
totalN = totalN + n;
apprN = totalN - getCount( $('span.pending-count', dash) ) - getCount( $('span.spam-count', dash) );
updateCount(total, totalN);
updateCount(appr, apprN);
};
getCount = function(el) {
var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
if ( isNaN(n) )
return 0;
return n;
};
updateCount = function(el, n) {
var n1 = '';
if ( isNaN(n) )
return;
n = n < 1 ? '0' : n.toString();
if ( n.length > 3 ) {
while ( n.length > 3 ) {
n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
n = n.substr(0, n.length - 3);
}
n = n + n1;
}
el.html(n);
};
updatePending = function(n) {
$('span.pending-count').each( function() {
var a = $(this);
if ( n < 0 )
n = 0;
a.closest('.awaiting-mod')[ 0 == n ? 'addClass' : 'removeClass' ]('count-0');
updateCount(a, n);
dashboardTotals();
});
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
var total, N, untrash = $(settings.target).parent().is('span.untrash'),
unspam = $(settings.target).parent().is('span.unspam'), spam, trash, pending,
unapproved = $('#' + settings.element).is('.unapproved');
function getUpdate(s) {
if ( $(settings.target).parent().is('span.' + s) )
return 1;
else if ( $('#' + settings.element).is('.' + s) )
return -1;
return 0;
}
spam = getUpdate('spam');
trash = getUpdate('trash');
if ( untrash )
trash = -1;
if ( unspam )
spam = -1;
pending = getCount( $('span.pending-count').eq(0) );
if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) { // we "deleted" an approved comment from the approved list by clicking "Unapprove"
pending = pending + 1;
} else if ( unapproved ) { // we deleted a formerly unapproved comment
pending = pending - 1;
}
updatePending(pending);
$('span.spam-count').each( function() {
var a = $(this), n = getCount(a) + spam;
updateCount(a, n);
});
$('span.trash-count').each( function() {
var a = $(this), n = getCount(a) + trash;
updateCount(a, n);
});
if ( $('#dashboard_right_now').length ) {
N = trash ? -1 * trash : 0;
dashboardTotals(N);
} else {
total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
total = total - spam - trash;
if ( total < 0 )
total = 0;
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || '';
if ( total_items_i18n ) {
$('.displaying-num').text( total_items_i18n );
$('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n );
$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val());
}
updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true );
} else {
updateTotalCount( total, r, false );
}
}
if ( ! theExtraList || theExtraList.size() == 0 || theExtraList.children().size() == 0 || untrash || unspam ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
refillTheExtraList();
};
refillTheExtraList = function(ev) {
var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();
if (! args.paged)
args.paged = 1;
if (args.paged > total_pages) {
return;
}
if (ev) {
theExtraList.empty();
args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
} else {
args.number = 1;
args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
}
args.no_placeholder = true;
args.paged ++;
// $.query.get() needs some correction to be sent into an ajax request
if ( true === args.comment_type )
args.comment_type = '';
args = $.extend(args, {
'action': 'fetch-list',
'list_args': list_args,
'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
});
$.ajax({
url: ajaxurl,
global: false,
dataType: 'json',
data: args,
success: function(response) {
theExtraList.get(0).wpList.add( response.rows );
}
});
};
theExtraList = $('#the-extra-comment-list').wpList( { alt: '', delColor: 'none', addColor: 'none' } );
theList = $('#the-comment-list').wpList( { alt: '', delBefore: delBefore, dimAfter: dimAfter, delAfter: delAfter, addColor: 'none' } )
.bind('wpListDelEnd', function(e, s){
var id = s.element.replace(/[^0-9]+/g, '');
if ( s.target.className.indexOf(':trash=1') != -1 || s.target.className.indexOf(':spam=1') != -1 )
$('#undo-' + id).fadeIn(300, function(){ $(this).show() });
});
};
commentReply = {
cid : '',
act : '',
init : function() {
var row = $('#replyrow');
$('a.cancel', row).click(function() { return commentReply.revert(); });
$('a.save', row).click(function() { return commentReply.send(); });
$('input#author, input#author-email, input#author-url', row).keypress(function(e){
if ( e.which == 13 ) {
commentReply.send();
e.preventDefault();
return false;
}
});
// add events
$('#the-comment-list .column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
$('#doaction, #doaction2, #post-query-submit').click(function(e){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
/* $(listTable).bind('beforeChangePage', function(){
commentReply.close();
}); */
},
addEvents : function(r) {
r.each(function() {
$(this).find('.column-comment > p').dblclick(function(){
commentReply.toggle($(this).parent());
});
});
},
toggle : function(el) {
if ( $(el).css('display') != 'none' )
$(el).find('a.vim-q').click();
},
revert : function() {
if ( $('#the-comment-list #replyrow').length < 1 )
return false;
$('#replyrow').fadeOut('fast', function(){
commentReply.close();
});
return false;
},
close : function() {
var c;
if ( this.cid ) {
c = $('#comment-' + this.cid);
if ( this.act == 'edit-comment' )
c.fadeIn(300, function(){ c.show() }).css('backgroundColor', '');
$('#replyrow').hide();
$('#com-reply').append( $('#replyrow') );
$('#replycontent').val('');
$('input', '#edithead').val('');
$('.error', '#replysubmit').html('').hide();
$('.waiting', '#replysubmit').hide();
if ( $.browser.msie )
$('#replycontainer, #replycontent').css('height', '120px');
else
$('#replycontainer').resizable('destroy').css('height', '120px');
this.cid = '';
}
},
open : function(id, p, a) {
var t = this, editRow, rowData, act, h, c = $('#comment-' + id), replyButton;
t.close();
t.cid = id;
editRow = $('#replyrow');
rowData = $('#inline-'+id);
act = t.act = (a == 'edit') ? 'edit-comment' : 'replyto-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(p);
$('#comment_ID', editRow).val(id);
if ( a == 'edit' ) {
$('#author', editRow).val( $('div.author', rowData).text() );
$('#author-email', editRow).val( $('div.author-email', rowData).text() );
$('#author-url', editRow).val( $('div.author-url', rowData).text() );
$('#status', editRow).val( $('div.comment_status', rowData).text() );
$('#replycontent', editRow).val( $('textarea.comment', rowData).val() );
$('#edithead, #savebtn', editRow).show();
$('#replyhead, #replybtn', editRow).hide();
h = c.height();
if ( h > 220 )
if ( $.browser.msie )
$('#replycontainer, #replycontent', editRow).height(h-105);
else
$('#replycontainer', editRow).height(h-105);
c.after( editRow ).fadeOut('fast', function(){
$('#replyrow').fadeIn(300, function(){ $(this).show() });
});
} else {
replyButton = $('#replybtn', editRow);
$('#edithead, #savebtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
c.after(editRow);
if ( c.hasClass('unapproved') ) {
replyButton.text(adminCommentsL10n.replyApprove);
} else {
replyButton.text(adminCommentsL10n.reply);
}
$('#replyrow').fadeIn(300, function(){ $(this).show() });
}
setTimeout(function() {
var rtop, rbottom, scrollTop, vp, scrollBottom;
rtop = $('#replyrow').offset().top;
rbottom = rtop + $('#replyrow').height();
scrollTop = window.pageYOffset || document.documentElement.scrollTop;
vp = document.documentElement.clientHeight || self.innerHeight || 0;
scrollBottom = scrollTop + vp;
if ( scrollBottom - 20 < rbottom )
window.scroll(0, rbottom - vp + 35);
else if ( rtop - 20 < scrollTop )
window.scroll(0, rtop - 35);
$('#replycontent').focus().keyup(function(e){
if ( e.which == 27 )
commentReply.revert(); // close on Escape
});
}, 600);
return false;
},
send : function() {
var post = {};
$('#replysubmit .error').hide();
$('#replysubmit .waiting').show();
$('#replyrow input').not(':button').each(function() {
post[ $(this).attr('name') ] = $(this).val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
post.p = $('[name="p"]').val();
if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
post.approve_parent = 1;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var t = this, r, c, id, bg, pid;
t.revert();
if ( typeof(xml) == 'string' ) {
t.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
t.error({'responseText': wpAjax.broken});
return false;
}
r = r.responses[0];
c = r.data;
id = '#comment-' + r.id;
if ( 'edit-comment' == t.act )
$(id).remove();
if ( r.supplemental.parent_approved ) {
pid = $('#comment-' + r.supplemental.parent_approved);
updatePending( getCount( $('span.pending-count').eq(0) ) - 1 );
if ( this.comments_listing == 'moderated' ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
pid.fadeOut();
});
return;
}
}
$(c).hide()
$('#replyrow').after(c);
id = $(id);
t.addEvents(id);
bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat').css('backgroundColor');
id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300, function() {
if ( pid && pid.length ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300 )
.removeClass('unapproved').addClass('approved')
.find('div.comment_status').html('1');
}
});
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .waiting').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$(document).delegate('span.delete a.delete', 'click', function(){return false;});
if ( typeof QTags != 'undefined' )
ed_reply = new QTags('ed_reply', 'replycontent', 'replycontainer', 'more,fullscreen');
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
if (l.length)
window.location = l[0].href.replace(/\&hotkeys_highlight_(first|last)=1/g, '')+'&hotkeys_highlight_'+first_last+'=1';
}
};
edit_comment = function(event, current_row) {
window.location = $('span.edit a', current_row).attr('href');
};
toggle_all = function() {
toggleWithKeyboard = true;
$('input:checkbox', '#cb').click().prop('checked', false);
toggleWithKeyboard = false;
};
make_bulk = function(value) {
return function() {
var scope = $('select[name="action"]');
$('option[value="' + value + '"]', scope).prop('selected', true);
$('#doaction').click();
}
};
$.table_hotkeys(
$('table.widefat'),
['a', 'u', 's', 'd', 'r', 'q', 'z', ['e', edit_comment], ['shift+x', toggle_all],
['shift+a', make_bulk('approve')], ['shift+s', make_bulk('spam')],
['shift+d', make_bulk('delete')], ['shift+t', make_bulk('trash')],
['shift+z', make_bulk('untrash')], ['shift+u', make_bulk('unapprove')]],
{ highlight_first: adminCommentsL10n.hotkeys_highlight_first, highlight_last: adminCommentsL10n.hotkeys_highlight_last,
prev_page_link_cb: make_hotkeys_redirect('prev'), next_page_link_cb: make_hotkeys_redirect('next') }
);
}
});
})(jQuery);
| JavaScript |
/* Plugin Browser Thickbox related JS*/
var tb_position;
jQuery(document).ready(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 < width ) ? 720 : width, adminbar_height = 0;
if ( $('body.admin-bar').length )
adminbar_height = 28;
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px','margin-top':'0'});
};
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href )
return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
$('#dashboard_plugins a.thickbox, .plugins a.thickbox').click( function() {
tb_click.call(this);
$('#TB_title').css({'background-color':'#222','color':'#cfcfcf'});
$('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong> ' + $(this).attr('title') );
return false;
});
/* Plugin install related JS*/
$('#plugin-information #sidemenu a').click( function() {
var tab = $(this).attr('name');
//Flip the tab
$('#plugin-information-header a.current').removeClass('current');
$(this).addClass('current');
//Flip the content.
$('#section-holder div.section').hide(); //Hide 'em all
$('#section-' + tab).show();
return false;
});
$('a.install-now').click( function() {
return confirm( plugininstallL10n.ays );
});
});
| JavaScript |
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, sidebars = $('div.widgets-sortables'), isRTL = !! ( 'undefined' != typeof isRtl && isRtl ),
margin = ( isRtl ? 'marginRight' : 'marginLeft' );
$('#widgets-right').children('.widgets-holder-wrap').children('.sidebar-name').click(function(){
var c = $(this).siblings('.widgets-sortables'), p = $(this).parent();
if ( !p.hasClass('closed') ) {
c.sortable('disable');
p.addClass('closed');
} else {
p.removeClass('closed');
c.sortable('enable').sortable('refresh');
}
});
$('#widgets-left').children('.widgets-holder-wrap').children('.sidebar-name').click(function() {
$(this).siblings('.widget-holder').parent().toggleClass('closed');
});
sidebars.not('#wp_inactive_widgets').each(function(){
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
$('a.widget-action').live('click', function(){
var css = {}, widget = $(this).closest('div.widget'), inside = widget.children('.widget-inside'), w = parseInt( widget.find('input.widget-width').val(), 10 );
if ( inside.is(':hidden') ) {
if ( w > 250 && inside.closest('div.widgets-sortables').length ) {
css['width'] = w + 30 + 'px';
if ( inside.closest('div.widget-liquid-right').length )
css[margin] = 235 - w + 'px';
widget.css(css);
}
wpWidgets.fixLabels(widget);
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.css({'width':'', margin:''});
});
}
return false;
});
$('input.widget-control-save').live('click', function(){
wpWidgets.save( $(this).closest('div.widget'), 0, 1, 0 );
return false;
});
$('a.widget-control-remove').live('click', function(){
wpWidgets.save( $(this).closest('div.widget'), 1, 1, 0 );
return false;
});
$('a.widget-control-close').live('click', function(){
wpWidgets.close( $(this).closest('div.widget') );
return false;
});
sidebars.children('.widget').each(function() {
wpWidgets.appendTitle(this);
if ( $('p.widget-error', this).length )
$('a.widget-action', this).click();
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 5,
containment: 'document',
start: function(e,ui) {
wpWidgets.fixWebkit(1);
ui.helper.find('div.widget-description').hide();
},
stop: function(e,ui) {
if ( rem )
$(rem).hide();
rem = '';
wpWidgets.fixWebkit();
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function(e,ui) {
wpWidgets.fixWebkit(1);
ui.item.children('.widget-inside').hide();
ui.item.css({margin:'', 'width':''});
},
stop: function(e,ui) {
if ( ui.item.hasClass('ui-draggable') && ui.item.data('draggable') )
ui.item.draggable('destroy');
if ( ui.item.hasClass('deleting') ) {
wpWidgets.save( ui.item, 1, 0, 1 ); // delete widget
ui.item.remove();
return;
}
var add = ui.item.find('input.add_new').val(),
n = ui.item.find('input.multi_number').val(),
id = ui.item.attr('id'),
sb = $(this).attr('id');
ui.item.css({margin:'', 'width':''});
wpWidgets.fixWebkit();
if ( add ) {
if ( 'multi' == add ) {
ui.item.html( ui.item.html().replace(/<[^<>]+>/g, function(m){ return m.replace(/__i__|%i%/g, n); }) );
ui.item.attr( 'id', id.replace(/__i__|%i%/g, n) );
n++;
$('div#' + id).find('input.multi_number').val(n);
} else if ( 'single' == add ) {
ui.item.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( ui.item, 0, 0, 1 );
ui.item.find('input.add_new').val('');
ui.item.find('a.widget-action').click();
return;
}
wpWidgets.saveOrder(sb);
},
receive: function(e,ui) {
if ( !$(this).is(':visible') )
$(this).sortable('cancel');
}
}).sortable('option', 'connectWith', 'div.widgets-sortables').parent().filter('.closed').children('.widgets-sortables').sortable('disable');
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') != 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') )
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
},
saveOrder : function(sb) {
if ( sb )
$('#' + sb).closest('div.widgets-holder-wrap').find('img.ajax-feedback').css('visibility', 'visible');
var a = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
$('div.widgets-sortables').each( function() {
a['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
});
$.post( ajaxurl, a, function() {
$('img.ajax-feedback').css('visibility', 'hidden');
});
this.resize();
},
save : function(widget, del, animate, order) {
var sb = widget.closest('div.widgets-sortables').attr('id'), data = widget.find('form').serialize(), a;
widget = $(widget);
$('.ajax-feedback', widget).css('visibility', 'visible');
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sb
};
if ( del )
a['delete_widget'] = 1;
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r){
var id;
if ( del ) {
if ( !$('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() == id )
$(this).closest('div.widget').show();
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
wpWidgets.resize();
}
} else {
$('.ajax-feedback').css('visibility', 'hidden');
if ( r && r.length > 2 ) {
$('div.widget-content', widget).html(r);
wpWidgets.appendTitle(widget);
wpWidgets.fixLabels(widget);
}
}
if ( order )
wpWidgets.saveOrder();
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget);
if ( title = title.val() ) {
title = title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(': ' + title);
}
},
resize : function() {
$('div.widgets-sortables').not('#wp_inactive_widgets').each(function(){
var h = 50, H = $(this).children('.widget').length;
h = h + parseInt(H * 48, 10);
$(this).css( 'minHeight', h + 'px' );
});
},
fixWebkit : function(n) {
n = n ? 'none' : '';
$('body').css({
WebkitUserSelect: n,
KhtmlUserSelect: n
});
},
fixLabels : function(widget) {
widget.children('.widget-inside').find('label').each(function(){
var f = $(this).attr('for');
if ( f && f == $('input', this).attr('id') )
$(this).removeAttr('for');
});
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function(){
widget.css({'width':'', margin:''});
});
}
};
$(document).ready(function($){ wpWidgets.init(); });
})(jQuery);
| JavaScript |
jQuery(document).ready(function($){
var h = wpCookies.getHash('TinyMCE_content_size');
if ( getUserSetting( 'editor' ) == 'html' ) {
if ( h )
$('#content').css('height', h.ch - 15 + 'px');
} else {
if ( typeof tinyMCE != 'object' ) {
$('#content').css('color', '#000');
} else {
$('#quicktags').hide();
}
}
});
var switchEditors = {
mode : '',
I : function(e) {
return document.getElementById(e);
},
_wp_Nop : function(content) {
var blocklist1, blocklist2;
// Protect pre|script tags
if ( content.indexOf('<pre') != -1 || content.indexOf('<script') != -1 ) {
content = content.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
a = a.replace(/<br ?\/?>(\r\n|\n)?/g, '<wp_temp>');
return a.replace(/<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp_temp>');
});
}
// Pretty it up for the source editor
blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset';
content = content.replace(new RegExp('\\s*</('+blocklist1+')>\\s*', 'g'), '</$1>\n');
content = content.replace(new RegExp('\\s*<((?:'+blocklist1+')(?: [^>]*)?)>', 'g'), '\n<$1>');
// Mark </p> if it has any attributes.
content = content.replace(/(<p [^>]+>.*?)<\/p>/g, '$1</p#>');
// Sepatate <div> containing <p>
content = content.replace(/<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n');
// Remove <p> and <br />
content = content.replace(/\s*<p>/gi, '');
content = content.replace(/\s*<\/p>\s*/gi, '\n\n');
content = content.replace(/\n[\s\u00a0]+\n/g, '\n\n');
content = content.replace(/\s*<br ?\/?>\s*/gi, '\n');
// Fix some block element newline issues
content = content.replace(/\s*<div/g, '\n<div');
content = content.replace(/<\/div>\s*/g, '</div>\n');
content = content.replace(/\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n');
content = content.replace(/caption\]\n\n+\[caption/g, 'caption]\n\n[caption');
blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset';
content = content.replace(new RegExp('\\s*<((?:'+blocklist2+')(?: [^>]*)?)\\s*>', 'g'), '\n<$1>');
content = content.replace(new RegExp('\\s*</('+blocklist2+')>\\s*', 'g'), '</$1>\n');
content = content.replace(/<li([^>]*)>/g, '\t<li$1>');
if ( content.indexOf('<hr') != -1 ) {
content = content.replace(/\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n');
}
if ( content.indexOf('<object') != -1 ) {
content = content.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
// Unmark special paragraph closing tags
content = content.replace(/<\/p#>/g, '</p>\n');
content = content.replace(/\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1');
// Trim whitespace
content = content.replace(/^\s+/, '');
content = content.replace(/[\s\u00a0]+$/, '');
// put back the line breaks in pre|script
content = content.replace(/<wp_temp>/g, '\n');
return content;
},
go : function(id, mode) {
id = id || 'content';
mode = mode || this.mode || '';
var ed, qt = this.I('quicktags'), H = this.I('edButtonHTML'), P = this.I('edButtonPreview'), ta = this.I(id);
try { ed = tinyMCE.get(id); }
catch(e) { ed = false; }
if ( 'tinymce' == mode ) {
if ( ed && ! ed.isHidden() )
return false;
setUserSetting( 'editor', 'tinymce' );
this.mode = 'html';
P.className = 'active';
H.className = '';
edCloseAllTags(); // :-(
qt.style.display = 'none';
ta.style.color = '#FFF';
ta.value = this.wpautop(ta.value);
try {
if ( ed )
ed.show();
else
tinyMCE.execCommand("mceAddControl", false, id);
} catch(e) {}
ta.style.color = '#000';
} else {
setUserSetting( 'editor', 'html' );
ta.style.color = '#000';
this.mode = 'tinymce';
H.className = 'active';
P.className = '';
if ( ed && !ed.isHidden() ) {
ta.style.height = ed.getContentAreaContainer().offsetHeight + 24 + 'px';
ed.hide();
}
qt.style.display = 'block';
}
return false;
},
_wp_Autop : function(pee) {
var blocklist = 'table|thead|tfoot|tbody|tr|td|th|caption|col|colgroup|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|p|h[1-6]|fieldset|legend|hr|noscript|menu|samp|header|footer|article|section|hgroup|nav|aside|details|summary';
if ( pee.indexOf('<object') != -1 ) {
pee = pee.replace(/<object[\s\S]+?<\/object>/g, function(a){
return a.replace(/[\r\n]+/g, '');
});
}
pee = pee.replace(/<[^<>]+>/g, function(a){
return a.replace(/[\r\n]+/g, ' ');
});
// Protect pre|script tags
if ( pee.indexOf('<pre') != -1 || pee.indexOf('<script') != -1 ) {
pee = pee.replace(/<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function(a) {
return a.replace(/(\r\n|\n)/g, '<wp_temp_br>');
});
}
pee = pee + '\n\n';
pee = pee.replace(/<br \/>\s*<br \/>/gi, '\n\n');
pee = pee.replace(new RegExp('(<(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), '\n$1');
pee = pee.replace(new RegExp('(</(?:'+blocklist+')>)', 'gi'), '$1\n\n');
pee = pee.replace(/<hr( [^>]*)?>/gi, '<hr$1>\n\n'); // hr is self closing block element
pee = pee.replace(/\r\n|\r/g, '\n');
pee = pee.replace(/\n\s*\n+/g, '\n\n');
pee = pee.replace(/([\s\S]+?)\n\n/g, '<p>$1</p>\n');
pee = pee.replace(/<p>\s*?<\/p>/gi, '');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/<p>(<li.+?)<\/p>/gi, '$1');
pee = pee.replace(/<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>');
pee = pee.replace(/<\/blockquote>\s*<\/p>/gi, '</p></blockquote>');
pee = pee.replace(new RegExp('<p>\\s*(</?(?:'+blocklist+')(?: [^>]*)?>)', 'gi'), "$1");
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')(?: [^>]*)?>)\\s*</p>', 'gi'), "$1");
pee = pee.replace(/\s*\n/gi, '<br />\n');
pee = pee.replace(new RegExp('(</?(?:'+blocklist+')[^>]*>)\\s*<br />', 'gi'), "$1");
pee = pee.replace(/<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1');
pee = pee.replace(/(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]');
pee = pee.replace(/(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function(a, b, c) {
if ( c.match(/<p( [^>]*)?>/) )
return a;
return b + '<p>' + c + '</p>';
});
// put back the line breaks in pre|script
pee = pee.replace(/<wp_temp_br>/g, '\n');
return pee;
},
pre_wpautop : function(content) {
var t = this, o = { o: t, data: content, unfiltered: content };
jQuery('body').trigger('beforePreWpautop', [o]);
o.data = t._wp_Nop(o.data);
jQuery('body').trigger('afterPreWpautop', [o]);
return o.data;
},
wpautop : function(pee) {
var t = this, o = { o: t, data: pee, unfiltered: pee };
jQuery('body').trigger('beforeWpautop', [o]);
o.data = t._wp_Autop(o.data);
jQuery('body').trigger('afterWpautop', [o]);
return o.data;
}
};
| JavaScript |
jQuery(document).ready( function($) {
var newCat, noSyncChecks = false, syncChecks, catAddAfter;
$('#link_name').focus();
// postboxes
postboxes.add_postbox_toggles('link');
// category tabs
$('#category-tabs a').click(function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('.tabs-panel').hide();
$(t).show();
if ( '#categories-all' == t )
deleteUserSetting('cats');
else
setUserSetting('cats','pop');
return false;
});
if ( getUserSetting('cats') )
$('#category-tabs a[href="#categories-pop"]').click();
// Ajax Cat
newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ) } );
$('#category-add-submit').click( function() { newCat.focus(); } );
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = $(this), c = th.is(':checked'), id = th.val().toString();
$('#in-link-category-' + id + ', #in-popular-category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddAfter = function( r, s ) {
$(s.what + ' response_data', r).each( function() {
var t = $($(this).text());
t.find( 'label' ).each( function() {
var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o;
$('#' + id).change( syncChecks );
o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name );
} );
} );
};
$('#categorychecklist').wpList( {
alt: '',
what: 'link-category',
response: 'category-ajax-response',
addAfter: catAddAfter
} );
$('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');});
$('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');});
if ( 'pop' == getUserSetting('cats') )
$('a[href="#categories-pop"]').click();
$('#category-add-toggle').click( function() {
$(this).parents('div:first').toggleClass( 'wp-hidden-children' );
$('#category-tabs a[href="#categories-all"]').click();
$('#newcategory').focus();
return false;
} );
$('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change();
});
| JavaScript |
var thickDims, tbWidth, tbHeight;
jQuery(document).ready(function($) {
thickDims = function() {
var tbWindow = $('#TB_window'), H = $(window).height(), W = $(window).width(), w, h;
w = (tbWidth && tbWidth < W - 90) ? tbWidth : W - 90;
h = (tbHeight && tbHeight < H - 60) ? tbHeight : H - 60;
if ( tbWindow.size() ) {
tbWindow.width(w).height(h);
$('#TB_iframeContent').width(w).height(h - 27);
tbWindow.css({'margin-left': '-' + parseInt((w / 2),10) + 'px'});
if ( typeof document.body.style.maxWidth != 'undefined' )
tbWindow.css({'top':'30px','margin-top':'0'});
}
};
thickDims();
$(window).resize( function() { thickDims() } );
$('a.thickbox-preview').click( function() {
tb_click.call(this);
var alink = $(this).parents('.available-theme').find('.activatelink'), link = '', href = $(this).attr('href'), url, text;
if ( tbWidth = href.match(/&tbWidth=[0-9]+/) )
tbWidth = parseInt(tbWidth[0].replace(/[^0-9]+/g, ''), 10);
else
tbWidth = $(window).width() - 90;
if ( tbHeight = href.match(/&tbHeight=[0-9]+/) )
tbHeight = parseInt(tbHeight[0].replace(/[^0-9]+/g, ''), 10);
else
tbHeight = $(window).height() - 60;
if ( alink.length ) {
url = alink.attr('href') || '';
text = alink.attr('title') || '';
link = ' <a href="' + url + '" target="_top" class="tb-theme-preview-link">' + text + '</a>';
} else {
text = $(this).attr('title') || '';
link = ' <span class="tb-theme-preview-link">' + text + '</span>';
}
$('#TB_title').css({'background-color':'#222','color':'#dfdfdf'});
$('#TB_closeAjaxWindow').css({'float':'left'});
$('#TB_ajaxWindowTitle').css({'float':'right'}).html(link);
$('#TB_iframeContent').width('100%');
thickDims();
return false;
} );
// Theme details
$('.theme-detail').click(function () {
$(this).siblings('.themedetaildiv').toggle();
return false;
});
});
| JavaScript |
jQuery(document).ready( function($) {
var before, addBefore, addAfter, delBefore;
before = function() {
var nonce = $('#newmeta [name="_ajax_nonce"]').val(), postId = $('#post_ID').val();
if ( !nonce || !postId ) { return false; }
return [nonce,postId];
}
addBefore = function( s ) {
var b = before();
if ( !b ) { return false; }
s.data = s.data.replace(/_ajax_nonce=[a-f0-9]+/, '_ajax_nonce=' + b[0]) + '&post_id=' + b[1];
return s;
};
addAfter = function( r, s ) {
var postId = $('postid', r).text(), h;
if ( !postId ) { return; }
$('#post_ID').attr( 'name', 'post_ID' ).val( postId );
h = $('#hiddenaction');
if ( 'post' == h.val() ) { h.val( 'postajaxpost' ); }
};
delBefore = function( s ) {
var b = before(); if ( !b ) return false;
s.data._ajax_nonce = b[0]; s.data.post_id = b[1];
return s;
}
$('#the-list')
.wpList( { addBefore: addBefore, addAfter: addAfter, delBefore: delBefore } )
.find('.updatemeta, .deletemeta').attr( 'type', 'button' );
} );
| JavaScript |
// Password strength meter
function passwordStrength(password1, username, password2) {
var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score;
// password 1 != password 2
if ( (password1 != password2) && password2.length > 0)
return mismatch
//password < 4
if ( password1.length < 4 )
return shortPass
//password1 == username
if ( password1.toLowerCase() == username.toLowerCase() )
return badPass;
if ( password1.match(/[0-9]/) )
symbolSize +=10;
if ( password1.match(/[a-z]/) )
symbolSize +=26;
if ( password1.match(/[A-Z]/) )
symbolSize +=26;
if ( password1.match(/[^a-zA-Z0-9]/) )
symbolSize +=31;
natLog = Math.log( Math.pow(symbolSize, password1.length) );
score = natLog / Math.LN2;
if (score < 40 )
return badPass
if (score < 56 )
return goodPass
return strongPass;
}
| JavaScript |
jQuery(document).ready( function($) {
$('#link_rel').prop('readonly', true);
$('#linkxfndiv input').bind('click keyup', function() {
var isMe = $('#me').is(':checked'), inputs = '';
$('input.valinp').each( function() {
if (isMe) {
$(this).prop('disabled', true).parent().addClass('disabled');
} else {
$(this).removeAttr('disabled').parent().removeClass('disabled');
if ( $(this).is(':checked') && $(this).val() != '')
inputs += $(this).val() + ' ';
}
});
$('#link_rel').val( (isMe) ? 'me' : inputs.substr(0,inputs.length - 1) );
});
});
| JavaScript |
jQuery(document).ready(function($) {
var options = false, addAfter, delBefore, delAfter;
if ( document.forms['addcat'].category_parent )
options = document.forms['addcat'].category_parent.options;
addAfter = function( r, settings ) {
var name, id;
name = $("<span>" + $('name', r).text() + "</span>").text();
id = $('cat', r).attr('id');
options[options.length] = new Option(name, id);
}
delAfter = function( r, settings ) {
var id = $('cat', r).attr('id'), o;
for ( o = 0; o < options.length; o++ )
if ( id == options[o].value )
options[o] = null;
}
delBefore = function(s) {
if ( 'undefined' != showNotice )
return showNotice.warn() ? s : false;
return s;
}
if ( options )
$('#the-list').wpList( { addAfter: addAfter, delBefore: delBefore, delAfter: delAfter } );
else
$('#the-list').wpList({ delBefore: delBefore });
$('.delete a[class^="delete"]').live('click', function(){return false;});
});
| JavaScript |
var ThemeViewer;
(function($){
ThemeViewer = function( args ) {
function init() {
$( '#filter-click, #mini-filter-click' ).unbind( 'click' ).click( function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
return false;
});
$( '#filter-box :checkbox' ).unbind( 'click' ).click( function() {
var count = $( '#filter-box :checked' ).length,
text = $( '#filter-click' ).text();
if ( text.indexOf( '(' ) != -1 )
text = text.substr( 0, text.indexOf( '(' ) );
if ( count == 0 )
$( '#filter-click' ).text( text );
else
$( '#filter-click' ).text( text + ' (' + count + ')' );
});
/* $('#filter-box :submit').unbind( 'click' ).click(function() {
var features = [];
$('#filter-box :checked').each(function() {
features.push($(this).val());
});
listTable.update_rows({'features': features}, true, function() {
$( '#filter-click' ).toggleClass( 'current' );
$( '#filter-box' ).slideToggle();
$( '#current-theme' ).slideToggle( 300 );
});
return false;
}); */
}
// These are the functions we expose
var api = {
init: init
};
return api;
}
})(jQuery);
jQuery( document ).ready( function($) {
theme_viewer = new ThemeViewer();
theme_viewer.init();
});
| JavaScript |
var imageEdit;
(function($) {
imageEdit = {
iasapi : {},
hold : {},
postid : '',
intval : function(f) {
return f | 0;
},
setDisabled : function(el, s) {
if ( s ) {
el.removeClass('disabled');
$('input', el).removeAttr('disabled');
} else {
el.addClass('disabled');
$('input', el).prop('disabled', true);
}
},
init : function(postid, nonce) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid != postid && old.length )
t.close(t.postid);
t.hold['w'] = t.hold['ow'] = x;
t.hold['h'] = t.hold['oh'] = y;
t.hold['xy_ratio'] = x / y;
t.hold['sizer'] = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
var k = e.keyCode;
if ( 36 < k && k < 41 )
$(this).blur()
if ( 13 == k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
},
toggleEditor : function(postid, toggle) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle )
wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast');
else
wait.fadeOut('fast');
},
toggleHelp : function(el) {
$(el).siblings('.imgedit-help').slideToggle('fast');
return false;
},
getTarget : function(postid) {
return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
},
scaleChanged : function(postid, x) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
if ( x ) {
h1 = (w.val() != '') ? this.intval( w.val() / this.hold['xy_ratio'] ) : '';
h.val( h1 );
} else {
w1 = (h.val() != '') ? this.intval( h.val() * this.hold['xy_ratio'] ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold['oh'] ) || ( w1 && w1 > this.hold['ow'] ) )
warn.css('visibility', 'visible');
else
warn.css('visibility', 'hidden');
},
getSelRatio : function(postid) {
var x = this.hold['w'], y = this.hold['h'],
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y )
return X + ':' + Y;
if ( x && y )
return x + ':' + y;
return '1:1';
},
filterHistory : function(postid, setSize) {
// apply undo state to history
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history != '' ) {
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
if ( setSize ) {
if ( !history.length ) {
this.hold['w'] = this.hold['ow'];
this.hold['h'] = this.hold['oh'];
return '';
}
// restore
o = history[history.length - 1];
o = o.c || o.r || o.f || false;
if ( o ) {
this.hold['w'] = o.fw;
this.hold['h'] = o.fh;
}
}
// filter the values
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $('<img id="image-preview-' + postid + '" />');
img.load( function() {
var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit;
parent.empty().append(img);
// w, h are the new full size dims
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold['sizer'] = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
t.setCropSelection(postid, 0);
if ( (typeof callback != "unknown") && callback != null )
callback();
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() == 0 )
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
else
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
t.toggleEditor(postid, 0);
}).attr('src', ajaxurl + '?' + $.param(data));
},
action : function(postid, nonce, action) {
var t = this, data, w, h, fw, fh;
if ( t.notsaved(postid) )
return false;
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid
};
if ( 'scale' == action ) {
w = $('#imgedit-scale-width-' + postid),
h = $('#imgedit-scale-height-' + postid),
fw = t.intval(w.val()),
fh = t.intval(h.val());
if ( fw < 1 ) {
w.focus();
return false;
} else if ( fh < 1 ) {
h.focus();
return false;
}
if ( fw == t.hold.ow || fh == t.hold.oh )
return false;
data['do'] = 'scale';
data['fwidth'] = fw;
data['fheight'] = fh;
} else if ( 'restore' == action ) {
data['do'] = 'restore';
} else {
return false;
}
t.toggleEditor(postid, 1);
$.post(ajaxurl, data, function(r) {
$('#image-editor-' + postid).empty().append(r);
t.toggleEditor(postid, 0);
});
},
save : function(postid, nonce) {
var data, target = this.getTarget(postid), history = this.filterHistory(postid, 0);
if ( '' == history )
return false;
this.toggleEditor(postid, 1);
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'history': history,
'target': target,
'do': 'save'
};
$.post(ajaxurl, data, function(r) {
var ret = JSON.parse(r);
if ( ret.error ) {
$('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>');
imageEdit.close(postid);
return;
}
if ( ret.fw && ret.fh )
$('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
if ( ret.thumbnail )
$('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
if ( ret.msg )
$('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
imageEdit.close(postid);
});
},
open : function(postid, nonce) {
var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('img');
btn.prop('disabled', true);
spin.css('visibility', 'visible');
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'do': 'open'
};
elem.load(ajaxurl, data, function() {
elem.fadeIn('fast');
head.fadeOut('fast', function(){
btn.removeAttr('disabled');
spin.css('visibility', 'hidden');
});
});
},
imgLoaded : function(postid) {
var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
this.initCrop(postid, img, parent);
this.setCropSelection(postid, 0);
this.toggleEditor(postid, 0);
},
initCrop : function(postid, image, parent) {
var t = this, selW = $('#imgedit-sel-width-' + postid),
selH = $('#imgedit-sel-height-' + postid);
t.iasapi = $(image).imgAreaSelect({
parent: parent,
instance: true,
handles: true,
keys: true,
minWidth: 3,
minHeight: 3,
onInit: function(img, c) {
parent.children().mousedown(function(e){
var ratio = false, sel, defRatio;
if ( e.shiftKey ) {
sel = t.iasapi.getSelection();
defRatio = t.getSelRatio(postid);
ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
}
t.iasapi.setOptions({
aspectRatio: ratio
});
});
},
onSelectStart: function(img, c) {
imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
},
onSelectEnd: function(img, c) {
imageEdit.setCropSelection(postid, c);
},
onSelectChange: function(img, c) {
var sizer = imageEdit.hold.sizer;
selW.val( imageEdit.round(c.width / sizer) );
selH.val( imageEdit.round(c.height / sizer) );
}
});
},
setCropSelection : function(postid, c) {
var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128',
sizer = this.hold['sizer'];
min = min.split(':');
c = c || 0;
if ( !c || ( c.width < 3 && c.height < 3 ) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-selection-' + postid).val('');
return false;
}
if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
$('#imgedit-selection-' + postid).val('');
return false;
}
sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
$('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
},
close : function(postid, warn) {
warn = warn || false;
if ( warn && this.notsaved(postid) )
return false;
this.iasapi = {};
this.hold = {};
$('#image-editor-' + postid).fadeOut('fast', function() {
$('#media-head-' + postid).fadeIn('fast');
$(this).empty();
});
},
notsaved : function(postid) {
var h = $('#imgedit-history-' + postid).val(),
history = (h != '') ? JSON.parse(h) : new Array(),
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop < history.length ) {
if ( confirm( $('#imgedit-leaving-' + postid).html() ) )
return false;
return true;
}
return false;
},
addStep : function(op, postid, nonce) {
var t = this, elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array(),
undone = $('#imgedit-undone-' + postid),
pop = t.intval(undone.val());
while ( pop > 0 ) {
history.pop();
pop--;
}
undone.val(0); // reset
history.push(op);
elem.val( JSON.stringify(history) );
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled($('#image-redo-' + postid), false);
});
},
rotate : function(angle, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'r': { 'r': angle, 'fw': this.hold['h'], 'fh': this.hold['w'] }}, postid, nonce);
},
flip : function (axis, postid, nonce, t) {
if ( $(t).hasClass('disabled') )
return false;
this.addStep({ 'f': { 'f': axis, 'fw': this.hold['w'], 'fh': this.hold['h'] }}, postid, nonce);
},
crop : function (postid, nonce, t) {
var sel = $('#imgedit-selection-' + postid).val(),
w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
h = this.intval( $('#imgedit-sel-height-' + postid).val() );
if ( $(t).hasClass('disabled') || sel == '' )
return false;
sel = JSON.parse(sel);
if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
sel['fw'] = w;
sel['fh'] = h;
this.addStep({ 'c': sel }, postid, nonce);
}
},
undo : function (postid, nonce) {
var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) + 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
var elem = $('#imgedit-history-' + postid),
history = (elem.val() != '') ? JSON.parse(elem.val()) : new Array();
t.setDisabled($('#image-redo-' + postid), true);
t.setDisabled(button, pop < history.length);
});
},
redo : function(postid, nonce) {
var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) - 1;
if ( button.hasClass('disabled') )
return;
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled(button, pop > 0);
});
},
setNumSelection : function(postid) {
var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
x = this.intval( elX.val() ), y = this.intval( elY.val() ),
img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
sizer = this.hold['sizer'], x1, y1, x2, y2, ias = this.iasapi;
if ( x < 1 ) {
elX.val('');
return false;
}
if ( y < 1 ) {
elY.val('');
return false;
}
if ( x && y && ( sel = ias.getSelection() ) ) {
x2 = sel.x1 + Math.round( x * sizer );
y2 = sel.y1 + Math.round( y * sizer );
x1 = sel.x1;
y1 = sel.y1;
if ( x2 > imgw ) {
x1 = 0;
x2 = imgw;
elX.val( Math.round( x2 / sizer ) );
}
if ( y2 > imgh ) {
y1 = 0;
y2 = imgh;
elY.val( Math.round( y2 / sizer ) );
}
ias.setSelection( x1, y1, x2, y2 );
ias.update();
this.setCropSelection(postid, ias.getSelection());
}
},
round : function(num) {
var s;
num = Math.round(num);
if ( this.hold.sizer > 0.6 )
return num;
s = num.toString().slice(-1);
if ( '1' == s )
return num - 1;
else if ( '9' == s )
return num + 1;
return num;
},
setRatioSelection : function(postid, n, el) {
var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
h = $('#image-preview-' + postid).height();
if ( !this.intval( $(el).val() ) ) {
$(el).val('');
return;
}
if ( x && y ) {
this.iasapi.setOptions({
aspectRatio: x + ':' + y
});
if ( sel = this.iasapi.getSelection(true) ) {
r = Math.ceil( sel.y1 + ((sel.x2 - sel.x1) / (x / y)) );
if ( r > h ) {
r = h;
if ( n )
$('#imgedit-crop-height-' + postid).val('');
else
$('#imgedit-crop-width-' + postid).val('');
}
this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
this.iasapi.update();
}
}
}
}
})(jQuery);
| JavaScript |
jQuery(document).ready(function($) {
$('.delete-tag').live('click', function(e){
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
// Remove the term from the parent box and tag cloud
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
$('#submit').click(function(){
var form = $(this).parents('form');
if ( !validateForm( form ) )
return false;
$.post(ajaxurl, $('#addtag').serialize(), function(r){
$('#ajax-response').empty();
var res = wpAjax.parseAjaxResponse(r, 'ajax-response');
if ( ! res )
return;
var parent = form.find('select#parent').val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$('.tags #tag-' + parent).after( res.responses[0].supplemental['noparents'] ); // As the parent exists, Insert the version with - - - prefixed
else
$('.tags').prepend( res.responses[0].supplemental['parents'] ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
var term = res.responses[1].supplemental;
// Create an indent for the Parent field
var indent = '';
for ( var i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find('select#parent option:selected').after('<option value="' + term['term_id'] + '">' + indent + term['name'] + '</option>');
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| JavaScript |
(function($) {
inlineEditPost = {
init : function(){
var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
t.what = '#post-';
// prepare the edit rows
qeRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
bulkRow.keyup(function(e){
if (e.which == 27)
return inlineEditPost.revert();
});
$('a.cancel', qeRow).click(function(){
return inlineEditPost.revert();
});
$('a.save', qeRow).click(function(){
return inlineEditPost.save(this);
});
$('td', qeRow).keydown(function(e){
if ( e.which == 13 )
return inlineEditPost.save(this);
});
$('a.cancel', bulkRow).click(function(){
return inlineEditPost.revert();
});
$('#inline-edit .inline-edit-private input[value="private"]').click( function(){
var pw = $('input.inline-edit-password-input');
if ( $(this).prop('checked') ) {
pw.val('').prop('disabled', true);
} else {
pw.prop('disabled', false);
}
});
// add events
$('a.editinline').live('click', function(){
inlineEditPost.edit(this);
return false;
});
$('#bulk-title-div').parents('fieldset').after(
$('#inline-edit fieldset.inline-edit-categories').clone()
).siblings( 'fieldset:last' ).prepend(
$('#inline-edit label.inline-edit-tags').clone()
);
// hiearchical taxonomies expandable?
$('span.catshow').click(function(){
$(this).hide().next().show().parent().next().addClass("cat-hover");
});
$('span.cathide').click(function(){
$(this).hide().prev().show().parent().next().removeClass("cat-hover");
});
$('select[name="_status"] option[value="future"]', bulkRow).remove();
$('#doaction, #doaction2').click(function(e){
var n = $(this).attr('id').substr(2);
if ( $('select[name="'+n+'"]').val() == 'edit' ) {
e.preventDefault();
t.setBulk();
} else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
t.revert();
}
});
$('#post-query-submit').mousedown(function(e){
t.revert();
$('select[name^="action"]').val('-1');
});
},
toggle : function(el){
var t = this;
$(t.what+t.getId(el)).css('display') == 'none' ? t.revert() : t.edit(el);
},
setBulk : function(){
var te = '', type = this.type, tax, c = true;
this.revert();
$('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length);
$('table.widefat tbody').prepend( $('#bulk-edit') );
$('#bulk-edit').addClass('inline-editor').show();
$('tbody th.check-column input[type="checkbox"]').each(function(i){
if ( $(this).prop('checked') ) {
c = false;
var id = $(this).val(), theTitle;
theTitle = $('#inline_'+id+' .post_title').text() || inlineEditL10n.notitle;
te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>';
}
});
if ( c )
return this.revert();
$('#bulk-titles').html(te);
$('#bulk-titles a').click(function(){
var id = $(this).attr('id').substr(1);
$('table.widefat input[value="' + id + '"]').prop('checked', false);
$('#ttle'+id).remove();
});
// enable autocomplete for tags
if ( 'post' == type ) {
// support multi taxonomies?
tax = 'post_tag';
$('tr.inline-editor textarea[name="tags_input"]').suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+tax, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } );
}
$('html, body').animate( { scrollTop: 0 }, 'fast' );
},
edit : function(id) {
var t = this, fields, editRow, rowData, cats, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, tax;
t.revert();
if ( typeof(id) == 'object' )
id = t.getId(id);
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password'];
if ( t.type == 'page' )
fields.push('post_parent', 'menu_order', 'page_template');
// add the new blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $(t.what+id).hasClass('alternate') )
$(editRow).addClass('alternate');
$(t.what+id).hide().after(editRow);
// populate the data
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// author no longer has edit caps, so we need to add them to the list of authors
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $(':input[name="post_author"] option', editRow).length == 1 ) {
$('label.inline-edit-author', editRow).hide();
}
for ( var f = 0; f < fields.length; f++ ) {
$(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() );
}
if ( $('.comment_status', rowData).text() == 'open' )
$('input[name="comment_status"]', editRow).prop("checked", true);
if ( $('.ping_status', rowData).text() == 'open' )
$('input[name="ping_status"]', editRow).prop("checked", true);
if ( $('.sticky', rowData).text() == 'sticky' )
$('input[name="sticky"]', editRow).prop("checked", true);
// hierarchical taxonomies
$('.post_category', rowData).each(function(){
var term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
//flat taxonomies
$('.tags_input', rowData).each(function(){
var terms = $(this).text();
if ( terms ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('textarea.tax_input_'+taxname, editRow).val(terms);
$('textarea.tax_input_'+taxname, editRow).suggest( 'admin-ajax.php?action=ajax-tag-search&tax='+taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: ", " } );
}
});
// handle the post status
status = $('._status', rowData).text();
if ( 'future' != status )
$('select[name="_status"] option[value="future"]', editRow).remove();
if ( 'private' == status ) {
$('input[name="keep_private"]', editRow).prop("checked", true);
$('input.inline-edit-password-input').val('').prop('disabled', true);
}
// remove the current page and children from the parent dropdown
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if (nextPage.length == 0) break;
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
},
save : function(id) {
var params, fields, page = $('.post_status_page').val() || '';
if ( typeof(id) == 'object' )
id = this.getId(id);
$('table.widefat .inline-edit-save .waiting').show();
params = {
action: 'inline-save',
post_type: typenow,
post_ID: id,
edit_date: 'true',
post_status: page
};
fields = $('#edit-'+id+' :input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post('admin-ajax.php', params,
function(r) {
$('table.widefat .inline-edit-save .waiting').hide();
if (r) {
if ( -1 != r.indexOf('<tr') ) {
$(inlineEditPost.what+id).remove();
$('#edit-'+id).before(r).remove();
$(inlineEditPost.what+id).hide().fadeIn();
} else {
r = r.replace( /<.[^<>]*?>/g, '' );
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
}
, 'html');
return false;
},
revert : function(){
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .inline-edit-save .waiting').hide();
if ( 'bulk-edit' == id ) {
$('table.widefat #bulk-edit').removeClass('inline-editor').hide();
$('#bulk-titles').html('');
$('#inlineedit').append( $('#bulk-edit') );
} else {
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
}
return false;
},
getId : function(o) {
var id = $(o).closest('tr').attr('id'),
parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditPost.init();});
})(jQuery);
| JavaScript |
var url = window.location.href;
var siteUrl = url.substr(0, url.indexOf('api/manyou/cloud_channel.htm'));
var params = getUrlParams(url);
var action = params['action'];
var identifier = params['identifier'];
setTopFrame();
changPageStatus(identifier);
function changPageStatus(identifier) {
var navText = '';
var cloudText = '';
var menuItem;
try {
var discuzIframe = window.top.window;
menuItem = discuzIframe.document.getElementById('menu_cloud').getElementsByTagName('li');
cloudText = 'Discuz!' + discuzIframe.document.getElementById('header_cloud').innerHTML;
} catch(e) {
return false;
}
for (i=0; i < menuItem.length; i ++) {
if (menuItem[i].innerHTML.indexOf('operation=' + identifier) != -1) {
menuItem[i].getElementsByTagName('a')[0].className = 'tabon';
navText = menuItem[i].innerHTML;
navText = navText.replace(/<em.*<\/em>/i, '');
p = /<a.+?href="(.+?)".+?>(.+?)<\/a>/i;
arr = p.exec(navText);
if (arr) {
link = arr[1];
text = arr[2];
if(discuzIframe.document.getElementById('admincpnav')) {
title = discuzIframe.document.title;
if (title.indexOf(' - ') > 0) {
title = title.substr(0, title.indexOf(' - '));
}
discuzIframe.document.title = title + ' - ' + cloudText + ' - ' + text;
discuzIframe.document.getElementById('admincpnav').innerHTML= cloudText + ' » ' + text + ' <a target="main" title="添加到常用操作" href="' + link + '">[+]</a>';
}
}
} else {
menuItem[i].getElementsByTagName('a')[0].className = '';
}
}
}
function setTopFrame() {
try {
var topUrl = top.location.href;
} catch(e) { }
if (typeof(topUrl) == 'undefined' || topUrl.indexOf(siteUrl) == -1) {
top.location = siteUrl + 'admin.php?frames=yes&action=cloud&operation=' + identifier;
}
}
function getUrlParams(url) {
var pos = url.indexOf('?');
if (pos < 0) {
return false;
}
var query = url.substr(pos + 1);
var arr = query.split('&');
var item = '';
var _params = [];
for (k in arr) {
item = arr[k].split('=');
_params[item[0]] = item[1];
}
return _params;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal.js 21566 2011-03-31 09:00:16Z zhangguosheng $
*/
function block_get_setting(classname, script, bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=setting&bid='+bid+'&classname='+classname+'&script='+script+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_setting'), s);
});
}
function switch_blocktab(type) {
if(type == 'setting') {
$('blockformsetting').style.display = '';
$('blockformdata').style.display = 'none';
$('li_setting').className = 'a';
$('li_data').className = '';
} else {
$('blockformsetting').style.display = 'none';
$('blockformdata').style.display = '';
$('li_setting').className = '';
$('li_data').className = 'a';
}
}
function showpicedit(pre) {
pre = pre ? pre : 'pic';
if($(pre+'way_remote').checked) {
$(pre+'_remote').style.display = "block";
$(pre+'_upload').style.display = "none";
} else {
$(pre+'_remote').style.display = "none";
$(pre+'_upload').style.display = "block";
}
}
function block_show_thumbsetting(classname, styleid, bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=thumbsetting&classname='+classname+'&styleid='+styleid+'&bid='+bid+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_thumbsetting'), s);
});
}
function block_showstyle(stylename) {
var el_span = $('span_'+stylename);
var el_value = $('value_' + stylename);
if (el_value.value == '1'){
el_value.value = '0';
el_span.className = "";
} else {
el_value.value = '1';
el_span.className = "a";
}
}
function block_pushitem(bid, itemid) {
var id = $('push_id').value;
var idtype = $('push_idtype').value;
if(id && idtype) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=push&&bid='+bid+'&itemid='+itemid+'&idtype='+idtype+'&id='+id+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_pushcontent'), s);
});
}
}
function block_delete_item(bid, itemid, itemtype, itemfrom, from) {
var msg = itemtype==1 ? '您确定要删除该数据吗?' : '您确定要屏蔽该数据吗?';
if(confirm(msg)) {
var url = 'portal.php?mod=portalcp&ac=block&op=remove&bid='+bid+'&itemid='+itemid;
if(itemfrom=='ajax') {
var x = new Ajax();
x.get(url+'&inajax=1', function(){
if(succeedhandle_showblock) succeedhandle_showblock('', '', {'bid':bid});
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=data&bid='+bid+'&from='+from+'&tab=data&t='+(+ new Date()), 'get', 0);
});
} else {
location.href = url;
}
}
doane();
}
function portal_comment_requote(cid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=comment&op=requote&cid='+cid+'&inajax=1', function(s){
$('message').focus();
ajaxinnerhtml($('message'), s);
});
}
function insertImage(text) {
text = "\n[img]" + text + "[/img]\n";
insertContent('message', text);
}
function insertContent(target, text) {
var obj = $(target);
selection = document.selection;
checkFocus(target);
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = text;
sel.moveStart('character', -strlen(text));
} else {
obj.value += text;
}
}
function searchblock(from) {
var value = $('searchkey').value;
var targettplname = $('targettplname').value;
value = BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(value) : (value ? value.replace(/#/g,'%23') : '');
var url = 'portal.php?mod=portalcp&ac=portalblock&searchkey='+value+'&from='+from;
url += targettplname != '' ? '&targettplname='+targettplname+'&type=page' : '&type=block';
reloadselection(url);
}
function reloadselection(url) {
ajaxget(url+'&t='+(+ new Date()), 'block_selection');
}
function getColorPalette(colorid, id, background) {
return "<input id=\"c"+colorid+"\" onclick=\"createPalette('"+colorid+"', '"+id+"');\" type=\"button\" class=\"pn colorwd\" value=\"\" style=\"background-color: "+background+"\">";
}
function listblock_bypage(id, idtype) {
var tpl = $('rtargettplname') ? $('rtargettplname').value : '';
var searchkey = $('rsearchkey') ? $('rsearchkey').value.replace('#', '%23') : '';
ajaxget('portal.php?mod=portalcp&ac=portalblock&op=recommend&getdata=yes&searchkey='+searchkey+'&targettplname='+tpl+'&id='+id+'&idtype='+idtype, 'itemeditarea');
}
function recommenditem_check() {
var sel = $('recommend_bid');
if(sel && sel.value) {
document.forms['recommendform'].action = document.forms['recommendform'].action+'&bid='+sel.value;
return true;
} else {
alert("请选择一个模块!");
return false;
}
}
function recommenditem_byblock(bid, id, idtype) {
var editarea = $('itemeditarea');
if(editarea) {
var olditemeditarea = $('olditemeditarea');
ajaxinnerhtml(olditemeditarea, editarea.innerHTML);
if(!$('recommendback')) {
var back = document.createElement('div');
back.innerHTML = '<em id="recommendback" onclick="recommenditem_back()" class="cur1"> «返回</em>';
var return_mods = $('return_mods') || $('return_');
if(return_mods) {
return_mods.parentNode.appendChild(back.childNodes[0]);
}
}
if(bid) {
if($('recommend_bid')) {
$('recommend_bid').value = bid;
}
ajaxget('portal.php?mod=portalcp&ac=block&op=recommend&bid='+bid+'&id='+id+'&idtype='+idtype+'&handlekey=recommenditem', 'itemeditarea');
} else {
ajaxinnerhtml(editarea, '<tr><td> </td><td> </td></tr>');
}
}
}
function recommenditem_back(){
var editarea = $('itemeditarea');
var oldeditarea = $('olditemeditarea');
var recommendback = $('recommendback');
if(oldeditarea){
ajaxinnerhtml(editarea, oldeditarea.innerHTML);
ajaxupdateevents(editarea);
}
if(recommendback) {
recommendback.parentNode.removeChild(recommendback);
}
if($('recommend_bid')) {
$('recommend_bid').value = '';
}
}
function blockBindTips() {
var elems = ($('blockformsetting') || document).getElementsByTagName('img');
var k = 0;
var stamp = (+new Date());
var tips = '';
for(var i = 0; i < elems.length; i++) {
tips = elems[i]['tips'] || elems[i].getAttribute('tips') || '';
if(tips && ! elems[i].isBindTips) {
elems[i].isBindTips = '1';
elems[i].id = elems[i].id ? elems[i].id : ('elem_' + stamp + k.toString());
k++;
showPrompt(elems[i].id, 'mouseover', tips, 1, true);
}
}
}
function blockSetCacheTime(timer) {
$('txt_cachetime').value=timer;
doane();
}
function toggleSettingShow() {
if(!$('tbody_setting').style.display) {
$('tbody_setting').style.display = 'none';
$('a_setting_show').innerHTML = '展开设置项';
} else {
$('tbody_setting').style.display = '';
$('a_setting_show').innerHTML = '收起设置项';
}
doane();
}
function switchSetting() {
var checked = $('isblank').checked;
if(checked) {
$('tbody_setting').style.display = 'none';
$('a_setting_show').innerHTML = '展开设置项';
} else {
$('tbody_setting').style.display = '';
$('a_setting_show').innerHTML = '收起设置项';
}
}
function checkblockname(form) {
if(!(trim(form.name.value) > '')) {
showDialog('模块标识不能为空', 'error', null, function(){form.name.focus();});
return false;
}
if(form.summary && form.summary.value) {
var tag = blockCheckTag(form.summary.value, true);
if(tag) {
showBlockSummary();
form.summary.focus();
showDialog('自定义内容错误,HTML代码:'+tag+' 标签不匹配', 'error', null, function(){form.summary.select();});
return false;
}
}
return true;
}
function blockCheckTag(summary, returnValue) {
var obj = null, fn = null;
if(typeof summary == 'object') {
obj = summary;
summary = summary.value;
fn = function(){obj.focus();obj.select();};
}
if(trim(summary) > '') {
var tags = ['div', 'table', 'tbody', 'tr', 'td', 'th'];
for(var i = 0; i < tags.length; i++) {
var tag = tags[i];
var reg = new RegExp('<'+tag+'', 'gi');
var preTag = [];
var one = [];
while (one = reg.exec(summary)) {
preTag.push(one[0]);
}
reg = new RegExp('</'+tag+'>', 'gi');
var endTag = [];
var one = [];
while (one = reg.exec(summary)) {
endTag.push(one[0]);
}
if(!preTag && !endTag) continue;
if((!preTag && endTag) || (preTag && !endTag) || preTag.length != endTag.length) {
if(returnValue) {
return tag;
} else {
showDialog('HTML代码:'+tag+' 标签不匹配', 'error', null, fn, true, fn);
return false;
}
}
}
}
return false;
}
function showBlockSummary() {
$('block_sumamry_content').style.display='';
$('a_summary_show').style.display='none';
$('a_summary_hide').style.display='';
return false;
}
function hideBlockSummary() {
$('block_sumamry_content').style.display='none';
$('a_summary_hide').style.display='none';
$('a_summary_show').style.display='';
return false;
}
function blockconver(ele,bid) {
if(ele && bid) {
if(confirm('你确定要转换模块的类型从 '+ele.options[0].innerHTML+' 到 '+ele.options[ele.selectedIndex].innerHTML)) {
ajaxget('portal.php?mod=portalcp&ac=block&op=convert&bid='+bid+'&toblockclass='+ele.value,'blockshow');
} else {
ele.selectedIndex = 0;
}
}
}
function blockFavorite(bid){
if(bid) {
ajaxget('portal.php?mod=portalcp&ac=block&op=favorite&bid='+bid,'bfav_'+bid);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tree.js 15149 2010-08-19 08:02:46Z monkey $
*/
var icon = new Object();
icon.root = IMGDIR + '/tree_root.gif';
icon.folder = IMGDIR + '/tree_folder.gif';
icon.folderOpen = IMGDIR + '/tree_folderopen.gif';
icon.file = IMGDIR + '/tree_file.gif';
icon.empty = IMGDIR + '/tree_empty.gif';
icon.line = IMGDIR + '/tree_line.gif';
icon.lineMiddle = IMGDIR + '/tree_linemiddle.gif';
icon.lineBottom = IMGDIR + '/tree_linebottom.gif';
icon.plus = IMGDIR + '/tree_plus.gif';
icon.plusMiddle = IMGDIR + '/tree_plusmiddle.gif';
icon.plusBottom = IMGDIR + '/tree_plusbottom.gif';
icon.minus = IMGDIR + '/tree_minus.gif';
icon.minusMiddle = IMGDIR + '/tree_minusmiddle.gif';
icon.minusBottom = IMGDIR + '/tree_minusbottom.gif';
function treeNode(id, pid, name, url, target, open) {
var obj = new Object();
obj.id = id;
obj.pid = pid;
obj.name = name;
obj.url = url;
obj.target = target;
obj.open = open;
obj._isOpen = open;
obj._lastChildId = 0;
obj._pid = 0;
return obj;
}
function dzTree(treeName) {
this.nodes = new Array();
this.openIds = getcookie('leftmenu_openids');
this.pushNodes = new Array();
this.addNode = function(id, pid, name, url, target, open) {
var theNode = new treeNode(id, pid, name, url, target, open);
this.pushNodes.push(id);
if(!this.nodes[pid]) {
this.nodes[pid] = new Array();
}
this.nodes[pid]._lastChildId = id;
for(k in this.nodes) {
if(this.openIds && this.openIds.indexOf('_' + theNode.id) != -1) {
theNode._isOpen = true;
}
if(this.nodes[k].pid == id) {
theNode._lastChildId = this.nodes[k].id;
}
}
this.nodes[id] = theNode;
};
this.show = function() {
var s = '<div class="tree">';
s += this.createTree(this.nodes[0]);
s += '</div>';
document.write(s);
};
this.createTree = function(node, padding) {
padding = padding ? padding : '';
if(node.id == 0){
var icon1 = '';
} else {
var icon1 = '<img src="' + this.getIcon1(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon1_' + node.id + '" style="cursor: pointer;">';
}
var icon2 = '<img src="' + this.getIcon2(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon2_' + node.id + '" style="cursor: pointer;">';
var s = '<div class="node" id="node_' + node.id + '">' + padding + icon1 + icon2 + this.getName(node) + '</div>';
s += '<div class="nodes" id="nodes_' + node.id + '" style="display:' + (node._isOpen ? '' : 'none') + '">';
for(k in this.pushNodes) {
var id = this.pushNodes[k];
var theNode = this.nodes[id];
if(theNode.pid == node.id) {
if(node.id == 0){
var thePadding = '';
} else {
var thePadding = padding + (node.id == this.nodes[node.pid]._lastChildId ? '<img src="' + icon.empty + '">' : '<img src="' + icon.line + '">');
}
if(!theNode._lastChildId) {
var icon1 = '<img src="' + this.getIcon1(theNode) + '"' + ' id="icon1_' + theNode.id + '">';
var icon2 = '<img src="' + this.getIcon2(theNode) + '" id="icon2_' + theNode.id + '">';
s += '<div class="node" id="node_' + theNode.id + '">' + thePadding + icon1 + icon2 + this.getName(theNode) + '</div>';
} else {
s += this.createTree(theNode, thePadding);
}
}
}
s += '</div>';
return s;
};
this.getIcon1 = function(theNode) {
var parentNode = this.nodes[theNode.pid];
var src = '';
if(theNode._lastChildId) {
if(theNode._isOpen) {
if(theNode.id == 0) {
return icon.minus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.minusBottom;
} else {
src = icon.minusMiddle;
}
} else {
if(theNode.id == 0) {
return icon.plus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.plusBottom;
} else {
src = icon.plusMiddle;
}
}
} else {
if(theNode.id == parentNode._lastChildId) {
src = icon.lineBottom;
} else {
src = icon.lineMiddle;
}
}
return src;
};
this.getIcon2 = function(theNode) {
var src = '';
if(theNode.id == 0 ) {
return icon.root;
}
if(theNode._lastChildId) {
if(theNode._isOpen) {
src = icon.folderOpen;
} else {
src = icon.folder;
}
} else {
src = icon.file;
}
return src;
};
this.getName = function(theNode) {
if(theNode.url) {
return '<a href="'+theNode.url+'" target="' + theNode.target + '"> '+theNode.name+'</a>';
} else {
return theNode.name;
}
};
this.switchDisplay = function(nodeId) {
eval('var theTree = ' + treeName);
var theNode = theTree.nodes[nodeId];
if($('nodes_' + nodeId).style.display == 'none') {
theTree.openIds = updatestring(theTree.openIds, nodeId);
setcookie('leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = true;
$('nodes_' + nodeId).style.display = '';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
} else {
theTree.openIds = updatestring(theTree.openIds, nodeId, true);
setcookie('leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = false;
$('nodes_' + nodeId).style.display = 'none';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
}
};
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: bbcode.js 22924 2011-06-01 07:41:29Z monkey $
*/
var re, DISCUZCODE = [];
DISCUZCODE['num'] = '-1';
DISCUZCODE['html'] = [];
EXTRAFUNC['bbcode2html'] = [];
EXTRAFUNC['html2bbcode'] = [];
function addslashes(str) {
return preg_replace(['\\\\', '\\\'', '\\\/', '\\\(', '\\\)', '\\\[', '\\\]', '\\\{', '\\\}', '\\\^', '\\\$', '\\\?', '\\\.', '\\\*', '\\\+', '\\\|'], ['\\\\', '\\\'', '\\/', '\\(', '\\)', '\\[', '\\]', '\\{', '\\}', '\\^', '\\$', '\\?', '\\.', '\\*', '\\+', '\\|'], str);
}
function atag(aoptions, text) {
if(trim(text) == '') {
return '';
}
var pend = parsestyle(aoptions, '', '');
href = getoptionvalue('href', aoptions);
if(href.substr(0, 11) == 'javascript:') {
return trim(recursion('a', text, 'atag'));
}
return pend['prepend'] + '[url=' + href + ']' + trim(recursion('a', text, 'atag')) + '[/url]' + pend['append'];
}
function bbcode2html(str) {
if(str == '') {
return '';
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = str.replace(/\[code\]([\s\S]+?)\[\/code\]/ig, function($1, $2) {return parsecode($2);});
}
if(fetchCheckbox('allowimgurl')) {
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
}
if(!allowhtml || !fetchCheckbox('htmlon')) {
str = str.replace(/</g, '<');
str = str.replace(/>/g, '>');
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'html', false);
}
}
for(i in EXTRAFUNC['bbcode2html']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['bbcode2html'][i] + '()');
} catch(e) {}
}
if(!fetchCheckbox('smileyoff') && allowsmilies) {
if(typeof smilies_type == 'object') {
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
re = new RegExp(preg_quote(smilies_array[typeid][page][i][1]), "g");
str = str.replace(re, '<img src="' + STATICURL + 'image/smiley/' + smilies_type['_' + typeid][1] + '/' + smilies_array[typeid][page][i][2] + '" border="0" smilieid="' + smilies_array[typeid][page][i][0] + '" alt="' + smilies_array[typeid][page][i][1] + '" />');
}
}
}
}
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = clearcode(str);
str = str.replace(/\[url\]\s*((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.)([^\[\"']+?)\s*\[\/url\]/ig, function($1, $2, $3, $4) {return cuturl($2 + $4);});
str = str.replace(/\[url=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\r\n\[\"']+?)\]([\s\S]+?)\[\/url\]/ig, '<a href="$1$3" target="_blank">$4</a>');
str = str.replace(/\[email\](.*?)\[\/email\]/ig, '<a href="mailto:$1">$1</a>');
str = str.replace(/\[email=(.[^\[]*)\](.*?)\[\/email\]/ig, '<a href="mailto:$1" target="_blank">$2</a>');
str = str.replace(/\[color=([^\[\<]+?)\]/ig, '<font color="$1">');
str = str.replace(/\[backcolor=([^\[\<]+?)\]/ig, '<font style="background-color:$1">');
str = str.replace(/\[size=(\d+?)\]/ig, '<font size="$1">');
str = str.replace(/\[size=(\d+(\.\d+)?(px|pt)+?)\]/ig, '<font style="font-size: $1">');
str = str.replace(/\[font=([^\[\<]+?)\]/ig, '<font face="$1">');
str = str.replace(/\[align=([^\[\<]+?)\]/ig, '<p align="$1">');
str = str.replace(/\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]/ig, '<p style="line-height: $1px; text-indent: $2em; text-align: $3;">');
str = str.replace(/\[float=left\]/ig, '<br style="clear: both"><span style="float: left; margin-right: 5px;">');
str = str.replace(/\[float=right\]/ig, '<br style="clear: both"><span style="float: right; margin-left: 5px;">');
str = str.replace(/\[quote]([\s\S]*?)\[\/quote\]\s?\s?/ig, '<div class="quote"><blockquote>$1</blockquote></div>\n');
re = /\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*([\s\S]+?)\s*\[\/table\]/ig;
for (i = 0; i < 4; i++) {
str = str.replace(re, function($1, $2, $3, $4) {return parsetable($2, $3, $4);});
}
str = preg_replace([
'\\\[\\\/color\\\]', '\\\[\\\/backcolor\\\]', '\\\[\\\/size\\\]', '\\\[\\\/font\\\]', '\\\[\\\/align\\\]', '\\\[\\\/p\\\]', '\\\[b\\\]', '\\\[\\\/b\\\]',
'\\\[i\\\]', '\\\[\\\/i\\\]', '\\\[u\\\]', '\\\[\\\/u\\\]', '\\\[s\\\]', '\\\[\\\/s\\\]', '\\\[hr\\\]', '\\\[list\\\]', '\\\[list=1\\\]', '\\\[list=a\\\]',
'\\\[list=A\\\]', '\\s?\\\[\\\*\\\]', '\\\[\\\/list\\\]', '\\\[indent\\\]', '\\\[\\\/indent\\\]', '\\\[\\\/float\\\]'
], [
'</font>', '</font>', '</font>', '</font>', '</p>', '</p>', '<b>', '</b>', '<i>',
'</i>', '<u>', '</u>', '<strike>', '</strike>', '<hr class="l" />', '<ul>', '<ul type=1 class="litype_1">', '<ul type=a class="litype_2">',
'<ul type=A class="litype_3">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
], str, 'g');
}
if(!fetchCheckbox('bbcodeoff')) {
if(allowimgcode) {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img src="$1" border="0" alt="" style="max-width:400px" />');
str = str.replace(/\[attachimg\](\d+)\[\/attachimg\]/ig, function ($1, $2) {
if(!$('image_' + $2)) {
return '';
}
width = $('image_' + $2).getAttribute('cwidth');
if(!width) {
re = /cwidth=(["']?)(\d+)(\1)/i;
var matches = re.exec($('image_' + $2).outerHTML);
if(matches != null) {
width = matches[2];
}
}
return '<img src="' + $('image_' + $2).src + '" border="0" aid="attachimg_' + $2 + '" width="' + width + '" alt="" style="max-width:400px" />';
});
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, function ($1, $2, $3, $4) {return '<img' + ($2 > 0 ? ' width="' + $2 + '"' : '') + ($3 > 0 ? ' height="' + $3 + '"' : '') + ' src="' + $4 + '" border="0" alt="" style="max-width:400px" />'});
} else {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
}
}
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
if(!allowhtml || !fetchCheckbox('htmlon')) {
str = str.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
return $2 + preg_replace(['\t', ' ', ' ', '(\r\n|\n|\r)'], [' ', ' ', ' ', '<br />'], $3);
});
}
return str;
}
function clearcode(str) {
str= str.replace(/\[url\]\[\/url\]/ig, '', str);
str= str.replace(/\[url=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\s\[\"']+?)\]\[\/url\]/ig, '', str);
str= str.replace(/\[email\]\[\/email\]/ig, '', str);
str= str.replace(/\[email=(.[^\[]*)\]\[\/email\]/ig, '', str);
str= str.replace(/\[color=([^\[\<]+?)\]\[\/color\]/ig, '', str);
str= str.replace(/\[size=(\d+?)\]\[\/size\]/ig, '', str);
str= str.replace(/\[size=(\d+(\.\d+)?(px|pt)+?)\]\[\/size\]/ig, '', str);
str= str.replace(/\[font=([^\[\<]+?)\]\[\/font\]/ig, '', str);
str= str.replace(/\[align=([^\[\<]+?)\]\[\/align\]/ig, '', str);
str= str.replace(/\[p=(\d{1,2}), (\d{1,2}), (left|center|right)\]\[\/p\]/ig, '', str);
str= str.replace(/\[float=([^\[\<]+?)\]\[\/float\]/ig, '', str);
str= str.replace(/\[quote\]\[\/quote\]/ig, '', str);
str= str.replace(/\[code\]\[\/code\]/ig, '', str);
str= str.replace(/\[table\]\[\/table\]/ig, '', str);
str= str.replace(/\[free\]\[\/free\]/ig, '', str);
str= str.replace(/\[b\]\[\/b]/ig, '', str);
str= str.replace(/\[u\]\[\/u]/ig, '', str);
str= str.replace(/\[i\]\[\/i]/ig, '', str);
str= str.replace(/\[s\]\[\/s]/ig, '', str);
return str;
}
function cuturl(url) {
var length = 65;
var urllink = '<a href="' + (url.toLowerCase().substr(0, 4) == 'www.' ? 'http://' + url : url) + '" target="_blank">';
if(url.length > length) {
url = url.substr(0, parseInt(length * 0.5)) + ' ... ' + url.substr(url.length - parseInt(length * 0.3));
}
urllink += url + '</a>';
return urllink;
}
function dstag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
var pend = parsestyle(options, '', '');
var prepend = pend['prepend'];
var append = pend['append'];
if(in_array(tagname, ['div', 'p'])) {
align = getoptionvalue('align', options);
if(in_array(align, ['left', 'center', 'right'])) {
prepend = '[align=' + align + ']' + prepend;
append += '[/align]';
} else {
append += '\n';
}
}
return prepend + recursion(tagname, text, 'dstag') + append;
}
function ptag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
if(trim(options) == '') {
return text + '\n';
}
var lineHeight = null;
var textIndent = null;
var align, re, matches;
re = /line-height\s?:\s?(\d{1,3})px/i;
matches = re.exec(options);
if(matches != null) {
lineHeight = matches[1];
}
re = /text-indent\s?:\s?(\d{1,3})em/i;
matches = re.exec(options);
if(matches != null) {
textIndent = matches[1];
}
re = /text-align\s?:\s?(left|center|right)/i;
matches = re.exec(options);
if(matches != null) {
align = matches[1];
} else {
align = getoptionvalue('align', options);
}
align = in_array(align, ['left', 'center', 'right']) ? align : 'left';
style = getoptionvalue('style', options);
style = preg_replace(['line-height\\\s?:\\\s?(\\\d{1,3})px', 'text-indent\\\s?:\\\s?(\\\d{1,3})em', 'text-align\\\s?:\\\s?(left|center|right)'], '', style);
if(lineHeight === null && textIndent === null) {
return '[align=' + align + ']' + (style ? '<span style="' + style + '">' : '') + text + (style ? '</span>' : '') + '[/align]';
} else {
return '[p=' + lineHeight + ', ' + textIndent + ', ' + align + ']' + (style ? '<span style="' + style + '">' : '') + text + (style ? '</span>' : '') + '[/p]';
}
}
function fetchCheckbox(cbn) {
return $(cbn) && $(cbn).checked == true ? 1 : 0;
}
function fetchoptionvalue(option, text) {
if((position = strpos(text, option)) !== false) {
delimiter = position + option.length;
if(text.charAt(delimiter) == '"') {
delimchar = '"';
} else if(text.charAt(delimiter) == '\'') {
delimchar = '\'';
} else {
delimchar = ' ';
}
delimloc = strpos(text, delimchar, delimiter + 1);
if(delimloc === false) {
delimloc = text.length;
} else if(delimchar == '"' || delimchar == '\'') {
delimiter++;
}
return trim(text.substr(delimiter, delimloc - delimiter));
} else {
return '';
}
}
function fonttag(fontoptions, text) {
var prepend = '';
var append = '';
var tags = new Array();
tags = {'font' : 'face=', 'size' : 'size=', 'color' : 'color='};
for(bbcode in tags) {
optionvalue = fetchoptionvalue(tags[bbcode], fontoptions);
if(optionvalue) {
prepend += '[' + bbcode + '=' + optionvalue + ']';
append = '[/' + bbcode + ']' + append;
}
}
var pend = parsestyle(fontoptions, prepend, append);
return pend['prepend'] + recursion('font', text, 'fonttag') + pend['append'];
}
function getoptionvalue(option, text) {
re = new RegExp(option + "(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)", "ig");
var matches = re.exec(text);
if(matches != null) {
return trim(matches[3]);
}
return '';
}
function html2bbcode(str) {
if((allowhtml && fetchCheckbox('htmlon')) || trim(str) == '') {
for(i in EXTRAFUNC['html2bbcode']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['html2bbcode'][i] + '()');
} catch(e) {}
}
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
str = str.replace(/<img([^>]*aid=[^>]*)>/ig, function($1, $2) {return imgtag($2);});
return str;
}
str = str.replace(/<div\sclass=["']?blockcode["']?>[\s\S]*?<blockquote>([\s\S]+?)<\/blockquote>[\s\S]*?<\/div>/ig, function($1, $2) {return codetag($2);});
str = preg_replace(['<style.*?>[\\\s\\\S]*?<\/style>', '<script.*?>[\\\s\\\S]*?<\/script>', '<noscript.*?>[\\\s\\\S]*?<\/noscript>', '<select.*?>[\s\S]*?<\/select>', '<object.*?>[\s\S]*?<\/object>', '<!--[\\\s\\\S]*?-->', ' on[a-zA-Z]{3,16}\\\s?=\\\s?"[\\\s\\\S]*?"'], '', str);
str= str.replace(/(\r\n|\n|\r)/ig, '');
str= str.replace(/&((#(32|127|160|173))|shy|nbsp);/ig, ' ');
if(fetchCheckbox('allowimgurl')) {
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
}
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'bbcode', false);
}
for(i in EXTRAFUNC['html2bbcode']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['html2bbcode'][i] + '()');
} catch(e) {}
}
str = str.replace(/<br\s+?style=(["']?)clear: both;?(\1)[^\>]*>/ig, '');
str = str.replace(/<br[^\>]*>/ig, "\n");
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = preg_replace([
'<table[^>]*float:\\\s*(left|right)[^>]*><tbody><tr><td>\\\s*([\\\s\\\S]+?)\\\s*<\/td><\/tr></tbody><\/table>',
'<table([^>]*(width|background|background-color|backcolor)[^>]*)>',
'<table[^>]*>',
'<tr[^>]*(?:background|background-color|backcolor)[:=]\\\s*(["\']?)([\(\)\\\s%,#\\\w]+)(\\1)[^>]*>',
'<tr[^>]*>',
'(<t[dh]([^>]*(left|center|right)[^>]*)>)\\\s*([\\\s\\\S]+?)\\\s*(<\/t[dh]>)',
'<t[dh]([^>]*(width|colspan|rowspan)[^>]*)>',
'<t[dh][^>]*>',
'<\/t[dh]>',
'<\/tr>',
'<\/table>',
'<h\\\d[^>]*>',
'<\/h\\\d>'
], [
function($1, $2, $3) {return '[float=' + $2 + ']' + $3 + '[/float]';},
function($1, $2) {return tabletag($2);},
'[table]\n',
function($1, $2, $3) {return '[tr=' + $3 + ']';},
'[tr]',
function($1, $2, $3, $4, $5, $6) {return $2 + '[align=' + $4 + ']' + $5 + '[/align]' + $6},
function($1, $2) {return tdtag($2);},
'[td]',
'[/td]',
'[/tr]\n',
'[/table]',
'[b]',
'[/b]'
], str);
str = str.replace(/<h([0-9]+)[^>]*>(.*)<\/h\\1>/ig, "[size=$1]$2[/size]\n\n");
str = str.replace(/<hr[^>]*>/ig, "[hr]");
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
str = str.replace(/<img([^>]*src[^>]*)>/ig, function($1, $2) {return imgtag($2);});
str = str.replace(/<a\s+?name=(["']?)(.+?)(\1)[\s\S]*?>([\s\S]*?)<\/a>/ig, '$4');
str = str.replace(/<div[^>]*quote[^>]*><blockquote>([\s\S]*?)<\/blockquote><\/div>([\s\S]*?)(<br[^>]*>)?/ig, "[quote]$1[/quote]");
str = str.replace(/<div[^>]*blockcode[^>]*><blockquote>([\s\S]*?)<\/blockquote><\/div>([\s\S]*?)(<br[^>]*>)?/ig, "[code]$1[/code]");
str = recursion('b', str, 'simpletag', 'b');
str = recursion('strong', str, 'simpletag', 'b');
str = recursion('i', str, 'simpletag', 'i');
str = recursion('em', str, 'simpletag', 'i');
str = recursion('u', str, 'simpletag', 'u');
str = recursion('strike', str, 'simpletag', 's');
str = recursion('a', str, 'atag');
str = recursion('font', str, 'fonttag');
str = recursion('blockquote', str, 'simpletag', 'indent');
str = recursion('ol', str, 'listtag');
str = recursion('ul', str, 'listtag');
str = recursion('div', str, 'dstag');
str = recursion('p', str, 'ptag');
str = recursion('span', str, 'fonttag');
}
str = str.replace(/<[\/\!]*?[^<>]*?>/ig, '');
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
str = clearcode(str);
return preg_replace([' ', '<', '>', '&'], [' ', '<', '>', '&'], str);
}
function tablesimple(s, table, str) {
if(strpos(str, '[tr=') || strpos(str, '[td=')) {
return s;
} else {
return '[table=' + table + ']\n' + preg_replace(['\\\[tr\\\]', '\\\[\\\/td\\\]\\\s?\\\[td\\\]', '\\\[\\\/tr\\\]\s?', '\\\[td\\\]', '\\\[\\\/td\\\]', '\\\[\\\/td\\\]\\\[\\\/tr\\\]'], ['', '|', '', '', '', '', ''], str) + '[/table]';
}
}
function imgtag(attributes) {
var width = '';
var height = '';
re = /src=(["']?)([\s\S]*?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
var src = matches[2];
} else {
return '';
}
re = /(max-)?width\s?:\s?(\d{1,4})(px)?/i;
var matches = re.exec(attributes);
if(matches != null && !matches[1]) {
width = matches[2];
}
re = /height\s?:\s?(\d{1,4})(px)?/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[1];
}
if(!width) {
re = /width=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
}
if(!height) {
re = /height=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[2];
}
}
re = /aid=(["']?)attachimg_(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
return '[attachimg]' + matches[2] + '[/attachimg]';
}
width = width > 0 ? width : 0;
height = height > 0 ? height : 0;
return width > 0 || height > 0 ?
'[img=' + width + ',' + height + ']' + src + '[/img]' :
'[img]' + src + '[/img]';
}
function listtag(listoptions, text, tagname) {
text = text.replace(/<li>(([\s\S](?!<\/li))*?)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/ig, '<li>$1</li>') + (BROWSER.opera ? '</li>' : '');
text = recursion('li', text, 'litag');
var opentag = '[list]';
var listtype = fetchoptionvalue('type=', listoptions);
listtype = listtype != '' ? listtype : (tagname == 'ol' ? '1' : '');
if(in_array(listtype, ['1', 'a', 'A'])) {
opentag = '[list=' + listtype + ']';
}
return text ? opentag + '\n' + recursion(tagname, text, 'listtag') + '[/list]' : '';
}
function litag(listoptions, text) {
return '[*]' + text.replace(/(\s+)$/g, '') + '\n';
}
function parsecode(text) {
DISCUZCODE['num']++;
DISCUZCODE['html'][DISCUZCODE['num']] = '<div class="blockcode"><blockquote>' + htmlspecialchars(text) + '</blockquote></div>';
return "[\tDISCUZ_CODE_" + DISCUZCODE['num'] + "\t]";
}
function parsestyle(tagoptions, prepend, append) {
var searchlist = [
['align', true, 'text-align:\\s*(left|center|right);?', 1],
['float', true, 'float:\\s*(left|right);?', 1],
['color', true, '(^|[;\\s])color:\\s*([^;]+);?', 2],
['backcolor', true, '(^|[;\\s])background-color:\\s*([^;]+);?', 2],
['font', true, 'font-family:\\s*([^;]+);?', 1],
['size', true, 'font-size:\\s*(\\d+(\\.\\d+)?(px|pt|in|cm|mm|pc|em|ex|%|));?', 1],
['size', true, 'font-size:\\s*(x\\-small|small|medium|large|x\\-large|xx\\-large|\\-webkit\\-xxx\\-large);?', 1, 'size'],
['b', false, 'font-weight:\\s*(bold);?'],
['i', false, 'font-style:\\s*(italic);?'],
['u', false, 'text-decoration:\\s*(underline);?'],
['s', false, 'text-decoration:\\s*(line-through);?']
];
var sizealias = {'x-small':1,'small':2,'medium':3,'large':4,'x-large':5,'xx-large':6,'-webkit-xxx-large':7};
var style = getoptionvalue('style', tagoptions);
re = /^(?:\s|)color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/i;
style = style.replace(re, function($1, $2, $3, $4, $5) {return("color:#" + parseInt($2).toString(16) + parseInt($3).toString(16) + parseInt($4).toString(16) + $5);});
var len = searchlist.length;
for(var i = 0; i < len; i++) {
searchlist[i][4] = !searchlist[i][4] ? '' : searchlist[i][4];
re = new RegExp(searchlist[i][2], "ig");
match = re.exec(style);
if(match != null) {
opnvalue = match[searchlist[i][3]];
if(searchlist[i][4] == 'size') {
opnvalue = sizealias[opnvalue];
}
prepend += '[' + searchlist[i][0] + (searchlist[i][1] == true ? '=' + opnvalue + ']' : ']');
append = '[/' + searchlist[i][0] + ']' + append;
}
}
return {'prepend' : prepend, 'append' : append};
}
function parsetable(width, bgcolor, str) {
if(isUndefined(width)) {
var width = '';
} else {
try {
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
} catch(e) { width = ''; }
}
if(isUndefined(str)) {
return;
}
if(strpos(str, '[/tr]') === false && strpos(str, '[/td]') === false) {
var rows = str.split('\n');
var s = '';
for(i = 0;i < rows.length;i++) {
s += '<tr><td>' + preg_replace(['\r', '\\\\\\\|', '\\\|', '\\\\n'], ['', '|', '</td><td>', '\n'], rows[i]) + '</td></tr>';
}
str = s;
simple = ' simpletable';
} else {
simple = '';
str = str.replace(/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,4}%?))?\]/ig, function($1, $2, $3) {
return '<tr' + ($2 ? ' style="background-color: ' + $2 + '"' : '') + '><td' + ($3 ? ' width="' + $3 + '"' : '') + '>';
});
str = str.replace(/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4, $5) {
return '<tr' + ($2 ? ' style="background-color: ' + $2 + '"' : '') + '><td' + ($3 ? ' colspan="' + $3 + '"' : '') + ($4 ? ' rowspan="' + $4 + '"' : '') + ($5 ? ' width="' + $5 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,4}%?))?\]/ig, function($1, $2) {
return '</td><td' + ($2 ? ' width="' + $2 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4) {
return '</td><td' + ($2 ? ' colspan="' + $2 + '"' : '') + ($3 ? ' rowspan="' + $3 + '"' : '') + ($4 ? ' width="' + $4 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[\/tr\]\s*/ig, '</td></tr>');
str = str.replace(/<td> <\/td>/ig, '<td> </td>');
}
return '<table ' + (width == '' ? '' : 'width="' + width + '" ') + 'class="t_table"' + (isUndefined(bgcolor) ? '' : ' style="background-color: ' + bgcolor + '"') + simple +'>' + str + '</table>';
}
function preg_quote(str) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, "\\$1");
}
function recursion(tagname, text, dofunction, extraargs) {
if(extraargs == null) {
extraargs = '';
}
tagname = tagname.toLowerCase();
var open_tag = '<' + tagname;
var open_tag_len = open_tag.length;
var close_tag = '</' + tagname + '>';
var close_tag_len = close_tag.length;
var beginsearchpos = 0;
do {
var textlower = text.toLowerCase();
var tagbegin = textlower.indexOf(open_tag, beginsearchpos);
if(tagbegin == -1) {
break;
}
var strlen = text.length;
var inquote = '';
var found = false;
var tagnameend = false;
var optionend = 0;
var t_char = '';
for(optionend = tagbegin; optionend <= strlen; optionend++) {
t_char = text.charAt(optionend);
if((t_char == '"' || t_char == "'") && inquote == '') {
inquote = t_char;
} else if((t_char == '"' || t_char == "'") && inquote == t_char) {
inquote = '';
} else if(t_char == '>' && !inquote) {
found = true;
break;
} else if((t_char == '=' || t_char == ' ') && !tagnameend) {
tagnameend = optionend;
}
}
if(!found) {
break;
}
if(!tagnameend) {
tagnameend = optionend;
}
var offset = optionend - (tagbegin + open_tag_len);
var tagoptions = text.substr(tagbegin + open_tag_len, offset);
var acttagname = textlower.substr(tagbegin * 1 + 1, tagnameend - tagbegin - 1);
if(acttagname != tagname) {
beginsearchpos = optionend;
continue;
}
var tagend = textlower.indexOf(close_tag, optionend);
if(tagend == -1) {
break;
}
var nestedopenpos = textlower.indexOf(open_tag, optionend);
while(nestedopenpos != -1 && tagend != -1) {
if(nestedopenpos > tagend) {
break;
}
tagend = textlower.indexOf(close_tag, tagend + close_tag_len);
nestedopenpos = textlower.indexOf(open_tag, nestedopenpos + open_tag_len);
}
if(tagend == -1) {
beginsearchpos = optionend;
continue;
}
var localbegin = optionend + 1;
var localtext = eval(dofunction)(tagoptions, text.substr(localbegin, tagend - localbegin), tagname, extraargs);
text = text.substring(0, tagbegin) + localtext + text.substring(tagend + close_tag_len);
beginsearchpos = tagbegin + localtext.length;
} while(tagbegin != -1);
return text;
}
function simpletag(options, text, tagname, parseto) {
if(trim(text) == '') {
return '';
}
text = recursion(tagname, text, 'simpletag', parseto);
return '[' + parseto + ']' + text + '[/' + parseto + ']';
}
function smileycode(smileyid) {
if(typeof smilies_type != 'object') return;
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
if(smilies_array[typeid][page][i][0] == smileyid) {
return smilies_array[typeid][page][i][1];
break;
}
}
}
}
}
function strpos(haystack, needle, _offset) {
if(isUndefined(_offset)) {
_offset = 0;
}
var _index = haystack.toLowerCase().indexOf(needle.toLowerCase(), _offset);
return _index == -1 ? false : _index;
}
function tabletag(attributes) {
var width = '';
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2].substr(matches[2].length - 1, matches[2].length) == '%' ?
(matches[2].substr(0, matches[2].length - 1) <= 98 ? matches[2] : '98%') :
(matches[2] <= 560 ? matches[2] : '98%');
} else {
re = /width\s?:\s?(\d{1,4})([px|%])/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2] == '%' ? (matches[1] <= 98 ? matches[1] + '%' : '98%') : (matches[1] <= 560 ? matches[1] : '98%');
}
}
var bgcolor = '';
re = /(?:background|background-color|bgcolor)[:=]\s*(["']?)((rgb\(\d{1,3}%?,\s*\d{1,3}%?,\s*\d{1,3}%?\))|(#[0-9a-fA-F]{3,6})|([a-zA-Z]{1,20}))(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
bgcolor = matches[2];
width = width ? width : '98%';
}
return bgcolor ? '[table=' + width + ',' + bgcolor + ']\n' : (width ? '[table=' + width + ']\n' : '[table]\n');
}
function tdtag(attributes) {
var colspan = 1;
var rowspan = 1;
var width = '';
re = /colspan=(["']?)(\d{1,2})(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
colspan = matches[2];
}
re = /rowspan=(["']?)(\d{1,2})(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
rowspan = matches[2];
}
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
return in_array(width, ['', '0', '100%']) ?
(colspan == 1 && rowspan == 1 ? '[td]' : '[td=' + colspan + ',' + rowspan + ']') :
(colspan == 1 && rowspan == 1 ? '[td=' + width + ']' : '[td=' + colspan + ',' + rowspan + ',' + width + ']');
}
if(typeof jsloaded == 'function') {
jsloaded('bbcode');
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_post.js 22843 2011-05-25 09:39:50Z monkey $
*/
var postSubmited = false;
var AID = {0:1,1:1};
var UPLOADSTATUS = -1;
var UPLOADFAILED = UPLOADCOMPLETE = AUTOPOST = 0;
var CURRENTATTACH = '0';
var FAILEDATTACHS = '';
var UPLOADWINRECALL = null;
var imgexts = typeof imgexts == 'undefined' ? 'jpg, jpeg, gif, png, bmp' : imgexts;
var ATTACHORIMAGE = '0';
var STATUSMSG = {
'-1' : '内部服务器错误',
'0' : '上传成功',
'1' : '不支持此类扩展名',
'2' : '服务器限制无法上传那么大的附件',
'3' : '用户组限制无法上传那么大的附件',
'4' : '不支持此类扩展名',
'5' : '文件类型限制无法上传那么大的附件',
'6' : '今日你已无法上传更多的附件',
'7' : '请选择图片文件(' + imgexts + ')',
'8' : '附件文件无法保存',
'9' : '没有合法的文件被上传',
'10' : '非法操作',
'11' : '今日你已无法上传那么大的附件'
};
EXTRAFUNC['validator'] = [];
function checkFocus() {
var obj = wysiwyg ? editwin : textobj;
if(!obj.hasfocus) {
obj.focus();
}
}
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && $('postsubmit')) {
if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit', 'editsubmit']) && !validate($('postform'))) {
doane(event);
return;
}
postSubmited = true;
$('postsubmit').disabled = true;
$('postform').submit();
}
if(event.keyCode == 9) {
doane(event);
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
showDialog('当前长度: ' + mb_strlen(message) + ' 字节,' + (postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节。' : ''), 'notice', '字数检查');
}
if(!tradepost) {
var tradepost = 0;
}
function validate(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
if(($('postsubmit').name != 'replysubmit' && !($('postsubmit').name == 'editsubmit' && !isfirstpost) && theform.subject.value == "") || !sortid && !special && trim(message) == "") {
showError('抱歉,您尚未输入标题或内容');
return false;
} else if(mb_strlen(theform.subject.value) > 80) {
showError('您的标题超过 80 个字符的限制');
return false;
}
if(ispicstyleforum == 1 && ATTACHORIMAGE == 0 && isfirstpost) {
showError('帖图版块至少应上传一张图片作为封面');
return false;
}
if(in_array($('postsubmit').name, ['topicsubmit', 'editsubmit'])) {
if(theform.typeid && (theform.typeid.options && theform.typeid.options[theform.typeid.selectedIndex].value == 0) && typerequired) {
showError('请选择主题对应的分类');
return false;
}
if(theform.sortid && (theform.sortid.options && theform.sortid.options[theform.sortid.selectedIndex].value == 0) && sortrequired) {
showError('请选择主题对应的分类信息');
return false;
}
}
for(i in EXTRAFUNC['validator']) {
try {
eval('var v = ' + EXTRAFUNC['validator'][i] + '()');
if(!v) {
return false;
}
} catch(e) {}
}
if(!disablepostctrl && !sortid && !special && ((postminchars != 0 && mb_strlen(message) < postminchars) || (postmaxchars != 0 && mb_strlen(message) > postmaxchars))) {
showError('您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(message) + ' 字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节');
return false;
}
if(UPLOADSTATUS == 0) {
if(!confirm('您有等待上传的附件,确认不上传这些附件吗?')) {
return false;
}
} else if(UPLOADSTATUS == 1) {
showDialog('您有正在上传的附件,请稍候,上传完成后帖子将会自动发表...', 'notice');
AUTOPOST = 1;
return false;
}
if($(editorid + '_attachlist')) {
$('postbox').appendChild($(editorid + '_attachlist'));
$(editorid + '_attachlist').style.display = 'none';
}
if($(editorid + '_imgattachlist')) {
$('postbox').appendChild($(editorid + '_imgattachlist'));
$(editorid + '_imgattachlist').style.display = 'none';
}
hideMenu();
theform.message.value = message;
if($('postsubmit').name == 'editsubmit') {
return true;
} else if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit'])) {
if(seccodecheck || secqaacheck) {
var chk = 1, chkv = '';
if(secqaacheck) {
chkv = $('checksecqaaverify_' + theform.sechash.value).innerHTML;
if(chkv.indexOf('loading') != -1) {
setTimeout(function () { validate(theform); }, 100);
chk = 0;
} else if(chkv.indexOf('check_right') == -1) {
showError('验证问答错误,请重新填写');
chk = 0;
}
}
if(seccodecheck) {
chkv = $('checkseccodeverify_' + theform.sechash.value).innerHTML;
if(chkv.indexOf('loading') !== -1) {
setTimeout(function () { validate(theform); }, 100);
chk = 0;
} else if(chkv.indexOf('check_right') === -1) {
showError('验证码错误,请重新填写');
chk = 0;
}
}
if(chk) {
postsubmit(theform);
}
} else {
postsubmit(theform);
}
return false;
}
}
function postsubmit(theform) {
theform.replysubmit ? theform.replysubmit.disabled = true : (theform.editsubmit ? theform.editsubmit.disabled = true : theform.topicsubmit.disabled = true);
theform.submit();
}
function relatekw(subject, message) {
if(isUndefined(subject) || subject == -1) {
subject = $('subject').value;
subject = subject.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
subject = subject.replace(/\s{2,}/ig, ' ');
}
if(isUndefined(message) || message == -1) {
message = getEditorContents();
message = message.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
message = message.replace(/\s{2,}/ig, ' ');
}
subject = (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(subject) : subject);
message = (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(message) : message);
message = message.replace(/&/ig, '', message).substr(0, 500);
ajaxget('forum.php?mod=relatekw&subjectenc=' + subject + '&messageenc=' + message, 'tagselect');
}
function switchicon(iconid, obj) {
$('iconid').value = iconid;
$('icon_img').src = obj.src;
hideMenu();
}
function clearContent() {
if(wysiwyg) {
editdoc.body.innerHTML = BROWSER.firefox ? '<br />' : '';
} else {
textobj.value = '';
}
}
function uploadNextAttach() {
var str = $('attachframe').contentWindow.document.body.innerHTML;
if(str == '') return;
var arr = str.split('|');
var att = CURRENTATTACH.split('|');
var sizelimit = '';
if(arr[4] == 'ban') {
sizelimit = '(附件类型被禁止)';
} else if(arr[4] == 'perday') {
sizelimit = '(不能超过 ' + arr[5] + ' 字节)';
} else if(arr[4] > 0) {
sizelimit = '(不能超过 ' + arr[4] + ' 字节)';
}
uploadAttach(parseInt(att[0]), arr[0] == 'DISCUZUPLOAD' ? parseInt(arr[1]) : -1, att[1], sizelimit);
}
function uploadAttach(curId, statusid, prefix, sizelimit) {
prefix = isUndefined(prefix) ? '' : prefix;
var nextId = 0;
for(var i = 0; i < AID[prefix ? 1 : 0] - 1; i++) {
if($(prefix + 'attachform_' + i)) {
nextId = i;
if(curId == 0) {
break;
} else {
if(i > curId) {
break;
}
}
}
}
if(nextId == 0) {
return;
}
CURRENTATTACH = nextId + '|' + prefix;
if(curId > 0) {
if(statusid == 0) {
UPLOADCOMPLETE++;
} else {
FAILEDATTACHS += '<br />' + mb_cutstr($(prefix + 'attachnew_' + curId).value.substr($(prefix + 'attachnew_' + curId).value.replace(/\\/g, '/').lastIndexOf('/') + 1), 25) + ': ' + STATUSMSG[statusid] + sizelimit;
UPLOADFAILED++;
}
$(prefix + 'cpdel_' + curId).innerHTML = '<img src="' + IMGDIR + '/check_' + (statusid == 0 ? 'right' : 'error') + '.gif" alt="' + STATUSMSG[statusid] + '" />';
if(nextId == curId || in_array(statusid, [6, 8])) {
if(prefix == 'img') {
updateImageList();
} else {
updateAttachList();
}
if(UPLOADFAILED > 0) {
showDialog('附件上传完成!成功 ' + UPLOADCOMPLETE + ' 个,失败 ' + UPLOADFAILED + ' 个:' + FAILEDATTACHS);
FAILEDATTACHS = '';
}
UPLOADSTATUS = 2;
for(var i = 0; i < AID[prefix ? 1 : 0] - 1; i++) {
if($(prefix + 'attachform_' + i)) {
reAddAttach(prefix, i)
}
}
$(prefix + 'uploadbtn').style.display = '';
$(prefix + 'uploading').style.display = 'none';
if(AUTOPOST) {
hideMenu();
validate($('postform'));
} else if(UPLOADFAILED == 0 && (prefix == 'img' || prefix == '')) {
showDialog('附件上传完成!', 'right', null, null, 0, null, null, null, null, 3);
}
UPLOADFAILED = UPLOADCOMPLETE = 0;
CURRENTATTACH = '0';
FAILEDATTACHS = '';
return;
}
} else {
$(prefix + 'uploadbtn').style.display = 'none';
$(prefix + 'uploading').style.display = '';
}
$(prefix + 'cpdel_' + nextId).innerHTML = '<img src="' + IMGDIR + '/loading.gif" alt="上传中..." />';
UPLOADSTATUS = 1;
$(prefix + 'attachform_' + nextId).submit();
}
function addAttach(prefix) {
var id = AID[prefix ? 1 : 0];
var tags, newnode, i;
prefix = isUndefined(prefix) ? '' : prefix;
newnode = $(prefix + 'attachbtnhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'Filedata') {
tags[i].id = prefix + 'attachnew_' + id;
tags[i].onchange = function() {insertAttach(prefix, id)};
tags[i].unselectable = 'on';
} else if(tags[i].name == 'attachid') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('form');
tags[0].name = tags[0].id = prefix + 'attachform_' + id;
$(prefix + 'attachbtn').appendChild(newnode);
newnode = $(prefix + 'attachbodyhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == prefix + 'localid[]') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == prefix + 'localfile[]') {
tags[i].id = prefix + 'localfile_' + id;
} else if(tags[i].id == prefix + 'cpdel[]') {
tags[i].id = prefix + 'cpdel_' + id;
} else if(tags[i].id == prefix + 'localno[]') {
tags[i].id = prefix + 'localno_' + id;
} else if(tags[i].id == prefix + 'deschidden[]') {
tags[i].id = prefix + 'deschidden_' + id;
}
}
AID[prefix ? 1 : 0]++;
newnode.style.display = 'none';
$(prefix + 'attachbody').appendChild(newnode);
}
function insertAttach(prefix, id) {
var localimgpreview = '';
var path = $(prefix + 'attachnew_' + id).value;
var extpos = path.lastIndexOf('.');
var ext = extpos == -1 ? '' : path.substr(extpos + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $(prefix + 'attachnew_' + id).value.substr($(prefix + 'attachnew_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
var filename = mb_cutstr(localfile, 30);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
reAddAttach(prefix, id);
showError('对不起,不支持上传此类扩展名的附件。');
return;
}
if(prefix == 'img' && imgexts.indexOf(ext) == -1) {
reAddAttach(prefix, id);
showError('请选择图片文件(' + imgexts + ')');
return;
}
$(prefix + 'cpdel_' + id).innerHTML = '<a href="javascript:;" class="d" onclick="reAddAttach(\'' + prefix + '\', ' + id + ')">删除</a>';
$(prefix + 'localfile_' + id).innerHTML = '<span>' + filename + '</span>';
$(prefix + 'attachnew_' + id).style.display = 'none';
$(prefix + 'deschidden_' + id).style.display = '';
$(prefix + 'deschidden_' + id).title = localfile;
$(prefix + 'localno_' + id).parentNode.parentNode.style.display = '';
addAttach(prefix);
UPLOADSTATUS = 0;
}
function reAddAttach(prefix, id) {
$(prefix + 'attachbody').removeChild($(prefix + 'localno_' + id).parentNode.parentNode);
$(prefix + 'attachbtn').removeChild($(prefix + 'attachnew_' + id).parentNode.parentNode);
$(prefix + 'attachbody').innerHTML == '' && addAttach(prefix);
$('localimgpreview_' + id) ? document.body.removeChild($('localimgpreview_' + id)) : null;
}
function delAttach(id, type) {
var ids = {};
if(typeof id == 'number') {
ids[id] = id;
} else {
ids = id;
}
for(id in ids) {
if($('attach_' + id)) {
$('attach_' + id).style.display = 'none';
ATTACHNUM['attach' + (type ? 'un' : '') + 'used']--;
updateattachnum('attach');
}
}
appendAttachDel(ids);
}
function delImgAttach(id, type) {
var ids = {};
if(typeof id == 'number') {
ids[id] = id;
} else {
ids = id;
}
for(id in ids) {
if($('image_td_' + id)) {
$('image_td_' + id).className = 'imgdeleted';
$('image_' + id).onclick = null;
$('image_desc_' + id).disabled = true;
ATTACHNUM['image' + (type ? 'un' : '') + 'used']--;
updateattachnum('image');
}
}
appendAttachDel(ids);
}
function appendAttachDel(ids) {
if(!ids) {
return;
}
var aids = '';
for(id in ids) {
aids += '&aids[]=' + id;
}
var x = new Ajax();
x.get('forum.php?mod=ajax&action=deleteattach&inajax=yes&tid=' + (typeof tid == 'undefined' ? 0 : tid) + '&pid=' + (typeof pid == 'undefined' ? 0 : pid) + aids, function() {});
if($('delattachop')) {
$('delattachop').value = 1;
}
}
function updateAttach(aid) {
objupdate = $('attachupdate'+aid);
obj = $('attach' + aid);
if(!objupdate.innerHTML) {
obj.style.display = 'none';
objupdate.innerHTML = '<input type="file" name="attachupdate[paid' + aid + ']"><a href="javascript:;" onclick="updateAttach(' + aid + ')">取消</a>';
} else {
obj.style.display = '';
objupdate.innerHTML = '';
}
}
function updateattachnum(type) {
ATTACHNUM[type + 'used'] = ATTACHNUM[type + 'used'] >= 0 ? ATTACHNUM[type + 'used'] : 0;
ATTACHNUM[type + 'unused'] = ATTACHNUM[type + 'unused'] >= 0 ? ATTACHNUM[type + 'unused'] : 0;
var num = ATTACHNUM[type + 'used'] + ATTACHNUM[type + 'unused'];
if(num) {
if($(editorid + '_' + type)) {
$(editorid + '_' + type).title = '包含 ' + num + (type == 'image' ? ' 个图片附件' : ' 个附件');
}
if($(editorid + '_' + type + 'n')) {
$(editorid + '_' + type + 'n').style.display = '';
}
ATTACHORIMAGE = 1;
} else {
if($(editorid + '_' + type)) {
$(editorid + '_' + type).title = type == 'image' ? '图片' : '附件';
}
if($(editorid + '_' + type + 'n')) {
$(editorid + '_' + type + 'n').style.display = 'none';
}
}
}
function swfHandler(action, type) {
if(action == 2) {
if(type == 'image') {
updateImageList();
} else {
updateAttachList();
}
}
}
function updateAttachList(action, aids) {
ajaxget('forum.php?mod=ajax&action=attachlist' + (!action ? '&posttime=' + $('posttime').value : (!aids ? '' : '&aids=' + aids)) + (!fid ? '' : '&fid=' + fid), 'attachlist');
switchAttachbutton('attachlist');$('attach_tblheader').style.display = $('attach_notice').style.display = '';
}
function updateImageList(action, aids) {
ajaxget('forum.php?mod=ajax&action=imagelist' + (!action ? '&pid=' + pid + '&posttime=' + $('posttime').value : (!aids ? '' : '&aids=' + aids)) + (!fid ? '' : '&fid=' + fid), 'imgattachlist');
switchImagebutton('imgattachlist');$('imgattach_notice').style.display = '';
}
function updateDownImageList(msg) {
if(msg == '') {
showError('抱歉,暂无远程附件');
} else {
ajaxget('forum.php?mod=ajax&action=imagelist&pid=' + pid + '&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'imgattachlist', null, null, null, function(){if(wysiwyg) {editdoc.body.innerHTML = msg;switchEditor(0);switchEditor(1)} else {textobj.value = msg;}});
switchImagebutton('imgattachlist');$('imgattach_notice').style.display = '';
showDialog('远程附件下载完成!', 'right', null, null, 0, null, null, null, null, 3);
}
}
function switchButton(btn, type) {
var btnpre = editorid + '_btn_';
if(!$(btnpre + btn) || !$(editorid + '_' + btn)) {
return;
}
var tabs = $(editorid + '_' + type + '_ctrl').getElementsByTagName('LI');
$(btnpre + btn).style.display = '';
$(editorid + '_' + btn).style.display = '';
$(btnpre + btn).className = 'current';
var btni = '';
for(i = 0;i < tabs.length;i++) {
if(tabs[i].id.indexOf(btnpre) !== -1) {
btni = tabs[i].id.substr(btnpre.length);
}
if(btni != btn) {
if(!$(editorid + '_' + btni) || !$(editorid + '_btn_' + btni)) {
continue;
}
$(editorid + '_' + btni).style.display = 'none';
$(editorid + '_btn_' + btni).className = '';
}
}
}
function uploadWindowstart() {
$('uploadwindowing').style.visibility = 'visible';
}
function uploadWindowload() {
$('uploadwindowing').style.visibility = 'hidden';
var str = $('uploadattachframe').contentWindow.document.body.innerHTML;
if(str == '') return;
var arr = str.split('|');
if(arr[0] == 'DISCUZUPLOAD' && arr[2] == 0) {
UPLOADWINRECALL(arr[3], arr[5], arr[6]);
hideWindow('upload', 0);
} else {
var sizelimit = '';
if(arr[7] == 'ban') {
sizelimit = '(附件类型被禁止)';
} else if(arr[7] == 'perday') {
sizelimit = '(不能超过 ' + arr[8] + ' 字节)';
} else if(arr[7] > 0) {
sizelimit = '(不能超过 ' + arr[7] + ' 字节)';
}
showError(STATUSMSG[arr[2]] + sizelimit);
}
if($('attachlimitnotice')) {
ajaxget('forum.php?mod=ajax&action=updateattachlimit&fid=' + fid, 'attachlimitnotice');
}
}
function uploadWindow(recall, type) {
var type = isUndefined(type) ? 'image' : type;
UPLOADWINRECALL = recall;
showWindow('upload', 'forum.php?mod=misc&action=upload&fid=' + fid + '&type=' + type, 'get', 0, {'zindex':601});
}
function updatetradeattach(aid, url, attachurl) {
$('tradeaid').value = aid;
$('tradeattach_image').innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function updateactivityattach(aid, url, attachurl) {
$('activityaid').value = aid;
$('activityattach_image').innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function updatesortattach(aid, url, attachurl, identifier) {
$('sortaid_' + identifier).value = aid;
$('sortattachurl_' + identifier).value = attachurl + '/' + url;
$('sortattach_image_' + identifier).innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function switchpollm(swt) {
t = $('pollchecked').checked && swt ? 2 : 1;
var v = '';
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption')) {
if(t == 2 && e.tagName == 'INPUT') {
v += e.value + '\n';
} else if(t == 1 && e.tagName == 'TEXTAREA') {
v += e.value;
}
}
}
}
if(t == 1) {
var a = v.split('\n');
var pcount = 0;
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption')) {
pcount++;
if(e.tagName == 'INPUT') e.value = '';
}
}
}
for(var i = 0; i < a.length - pcount + 2; i++) {
addpolloption();
}
var ii = 0;
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption') && e.tagName == 'INPUT' && a[ii]) {
e.value = a[ii++];
}
}
}
} else if(t == 2) {
$('postform').polloptions.value = trim(v);
}
$('postform').tpolloption.value = t;
if(swt) {
display('pollm_c_1');
display('pollm_c_2');
}
}
function addpolloption() {
if(curoptions < maxoptions) {
$('polloption_new').outerHTML = '<p>' + $('polloption_hidden').innerHTML + '</p>' + $('polloption_new').outerHTML;
curoptions++;
} else {
$('polloption_new').outerHTML = '<span>已达到最大投票数'+maxoptions+'</span>';
}
}
function delpolloption(obj) {
obj.parentNode.parentNode.removeChild(obj.parentNode);
curoptions--;
}
function insertsave(pid) {
var x = new Ajax();
x.get('forum.php?mod=misc&action=loadsave&inajax=yes&pid=' + pid + '&type=' + wysiwyg, function(str, x) {
insertText(str, str.length, 0);
});
}
function userdataoption(op) {
if(!op) {
saveUserdata('forum', '');
display('rstnotice');
} else {
loadData();
checkFocus();
}
doane();
}
function attachoption(type, op) {
if(!op) {
if(type == 'attach') {
delAttach(ATTACHUNUSEDAID, 1);
ATTACHNUM['attachunused'] = 0;
display('attachnotice_attach');
} else {
delImgAttach(IMGUNUSEDAID, 1);
ATTACHNUM['imageunused'] = 0;
display('attachnotice_img');
}
} else if(op == 1) {
var obj = $('unusedwin') ? $('unusedwin') : $('unusedlist_' + type);
list = obj.getElementsByTagName('INPUT'), aids = '';
for(i = 0;i < list.length;i++) {
if(list[i].name.match('unused') && list[i].checked) {
aids += '|' + list[i].value;
}
}
if(aids) {
if(type == 'attach') {
updateAttachList(1, aids);
} else {
updateImageList(1, aids);
}
}
display('attachnotice_' + type);
} else if(op == 2) {
showDialog('<div id="unusedwin" class="c altw" style="overflow:auto;height:100px;">' + $('unusedlist_' + type).innerHTML + '</div>' +
'<p class="o pns"><span class="z xg1"><label for="unusedwinchkall"><input id="unusedwinchkall" type="checkbox" onclick="attachoption(\'' + type + '\', 3)" checked="checked" />全选</label></span>' +
'<button onclick="attachoption(\'' + type + '\', 1);hideMenu(\'fwin_dialog\', \'dialog\')" class="pn pnc"><strong>确定</strong></button></p>', 'info', '未使用的' + (type == 'attach' ? '附件' : '图片'));
} else if(op == 3) {
list = $('unusedwin').getElementsByTagName('INPUT');
for(i = 0;i < list.length;i++) {
if(list[i].name.match('unused')) {
list[i].checked = $('unusedwinchkall').checked;
}
}
return;
}
doane();
}
function insertAttachTag(aid) {
var txt = '[attach]' + aid + '[/attach]';
seditor_insertunit('fastpost', txt);
}
function insertAttachimgTag(aid) {
var txt = '[attachimg]' + aid + '[/attachimg]';
seditor_insertunit('fastpost', txt);
}
function insertText(str) {
seditor_insertunit('fastpost', str);
}
function insertAllAttachTag() {
var attachListObj = $('e_attachlist').getElementsByTagName("tbody");
for(var i in attachListObj) {
if(typeof attachListObj[i] == "object") {
var attach = attachListObj[i];
var ids = attach.id.split('_');
if(ids[0] == 'attach') {
if($('attachname'+ids[1])) {
if(parseInt($('attachname'+ids[1]).getAttribute('isimage'))) {
insertAttachimgTag(ids[1]);
} else {
insertAttachTag(ids[1]);
}
var txt = wysiwyg ? '\r\n<br/><br/>\r\n' : '\r\n\r\n';
insertText(txt, strlen(txt), 0);
}
}
}
}
doane();
}
function selectAllSaveImg(state) {
var inputListObj = $('imgattachlist').getElementsByTagName("input");
for(i in inputListObj) {
if(typeof inputListObj[i] == "object" && inputListObj[i].id) {
var inputObj = inputListObj[i];
var ids = inputObj.id.split('_');
if(ids[0] == 'albumaidchk' && $('image_td_' + ids[1]).className != 'imgdeleted' && inputObj.checked != state) {
inputObj.click();
}
}
}
}
function showExtra(id) {
if ($(id+'_c').style.display == 'block') {
$(id+'_b').className = 'pn z';
$(id+'_c').style.display = 'none';
} else {
var extraButton = $('post_extra_tb').getElementsByTagName('label');
var extraForm = $('post_extra_c').getElementsByTagName('div');
for (i=0;i<extraButton.length;i++) {
extraButton[i].className = '';
}
for (i=0;i<extraForm.length;i++) {
if(hasClass(extraForm[i],'exfm')) {
extraForm[i].style.display = 'none';
}
}
for (i=0;i<extraForm.length;i++) {
if(hasClass(extraForm[i],'exfm')) {
extraForm[i].style.display = 'none';
}
}
$(id+'_b').className = 'a';
$(id+'_c').style.display = 'block';
}
}
function extraCheck(op) {
if(!op && $('extra_replycredit_chk')) {
$('extra_replycredit_chk').className = $('replycredit_extcredits').value > 0 && $('replycredit_times').value > 0 ? 'a' : '';
} else if(op == 1 && $('readperm')) {
$('extra_readperm_chk').className = $('readperm').value !== '' ? 'a' : '';
} else if(op == 2 && $('price')) {
$('extra_price_chk').className = $('price').value > 0 ? 'a' : '';
} else if(op == 3 && $('rushreply')) {
$('extra_rushreplyset_chk').className = $('rushreply').checked ? 'a' : '';
} else if(op == 4 && $('tags')) {
$('extra_tag_chk').className = $('tags').value !== '' ? 'a' : '';
}
}
function getreplycredit() {
var replycredit_extcredits = $('replycredit_extcredits');
var replycredit_times = $('replycredit_times');
var credit_once = parseInt(replycredit_extcredits.value) > 0 ? parseInt(replycredit_extcredits.value) : 0;
var times = parseInt(replycredit_times.value) > 0 ? parseInt(replycredit_times.value) : 0;
if(parseInt(credit_once * times) - have_replycredit > 0) {
var real_reply_credit = Math.ceil(parseInt(credit_once * times) - have_replycredit + ((parseInt(credit_once * times) - have_replycredit) * creditstax));
} else {
var real_reply_credit = Math.ceil(parseInt(credit_once * times) - have_replycredit);
}
var reply_credits_sum = Math.ceil(parseInt(credit_once * times));
if(real_reply_credit > userextcredit) {
$('replycredit').innerHTML = '<b class="xi1">回帖奖励积分总额过大('+real_reply_credit+')</b>';
} else {
if(have_replycredit > 0 && real_reply_credit < 0) {
$('replycredit').innerHTML = "<font class='xi1'>返还"+Math.abs(real_reply_credit)+"</font>";
} else {
$('replycredit').innerHTML = replycredit_result_lang + (real_reply_credit > 0 ? real_reply_credit : 0 );
}
$('replycredit_sum').innerHTML = reply_credits_sum > 0 ? reply_credits_sum : 0 ;
}
}
function extraCheckall() {
for(i = 0;i < 5;i++) {
extraCheck(i);
}
}
function deleteThread() {
if(confirm('确定要删除该帖子吗?') != 0){
$('delete').value = '1';
$('postform').submit();
}
}
function hideAttachMenu(id) {
if($(editorid + '_' + id + '_menu')) {
$(editorid + '_' + id + '_menu').style.visibility = 'hidden';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: admincp.js 22381 2011-05-05 03:05:16Z monkey $
*/
function redirect(url) {
window.location.replace(url);
}
function scrollTopBody() {
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkAll(type, form, value, checkall, changestyle) {
var checkall = checkall ? checkall : 'chkall';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(type == 'option' && e.type == 'radio' && e.value == value && e.disabled != true) {
e.checked = true;
} else if(type == 'value' && e.type == 'checkbox' && e.getAttribute('chkvalue') == value) {
e.checked = form.elements[checkall].checked;
if(changestyle) {
multiupdate(e);
}
} else if(type == 'prefix' && e.name && e.name != checkall && (!value || (value && e.name.match(value)))) {
e.checked = form.elements[checkall].checked;
if(changestyle) {
if(e.parentNode && e.parentNode.tagName.toLowerCase() == 'li') {
e.parentNode.className = e.checked ? 'checked' : '';
}
if(e.parentNode.parentNode && e.parentNode.parentNode.tagName.toLowerCase() == 'div') {
e.parentNode.parentNode.className = e.checked ? 'item checked' : 'item';
}
}
}
}
}
function altStyle(obj, disabled) {
function altStyleClear(obj) {
var input, lis, i;
lis = obj.parentNode.getElementsByTagName('li');
for(i=0; i < lis.length; i++){
lis[i].className = '';
}
}
var disabled = !disabled ? 0 : disabled;
if(disabled) {
return;
}
var input, lis, i, cc, o;
cc = 0;
lis = obj.getElementsByTagName('li');
for(i=0; i < lis.length; i++){
lis[i].onclick = function(e) {
o = BROWSER.ie ? event.srcElement.tagName : e.target.tagName;
altKey = BROWSER.ie ? window.event.altKey : e.altKey;
if(cc) {
return;
}
cc = 1;
input = this.getElementsByTagName('input')[0];
if(input.getAttribute('type') == 'checkbox' || input.getAttribute('type') == 'radio') {
if(input.getAttribute('type') == 'radio') {
altStyleClear(this);
}
if(BROWSER.ie || o != 'INPUT' && input.onclick) {
input.click();
}
if(this.className != 'checked') {
this.className = 'checked';
input.checked = true;
} else {
this.className = '';
input.checked = false;
}
if(altKey && input.name.match(/^multinew\[\d+\]/)) {
miid = input.id.split('|');
mi = 0;
while($(miid[0] + '|' + mi)) {
$(miid[0] + '|' + mi).checked = input.checked;
if(input.getAttribute('type') == 'radio') {
altStyleClear($(miid[0] + '|' + mi).parentNode);
}
$(miid[0] + '|' + mi).parentNode.className = input.checked ? 'checked' : '';
mi++;
}
}
}
};
lis[i].onmouseup = function(e) {
cc = 0;
}
}
}
var addrowdirect = 0;
function addrow(obj, type) {
var table = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
if(!addrowdirect) {
var row = table.insertRow(obj.parentNode.parentNode.parentNode.rowIndex);
} else {
var row = table.insertRow(obj.parentNode.parentNode.parentNode.rowIndex + 1);
}
var typedata = rowtypedata[type];
for(var i = 0; i <= typedata.length - 1; i++) {
var cell = row.insertCell(i);
cell.colSpan = typedata[i][0];
var tmp = typedata[i][1];
if(typedata[i][2]) {
cell.className = typedata[i][2];
}
tmp = tmp.replace(/\{(\d+)\}/g, function($1, $2) {return addrow.arguments[parseInt($2) + 1];});
cell.innerHTML = tmp;
}
addrowdirect = 0;
}
function deleterow(obj) {
var table = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
var tr = obj.parentNode.parentNode.parentNode;
table.deleteRow(tr.rowIndex);
}
function dropmenu(obj){
showMenu({'ctrlid':obj.id, 'menuid':obj.id + 'child', 'evt':'mouseover'});
$(obj.id + 'child').style.top = (parseInt($(obj.id + 'child').style.top) - Math.max(document.body.scrollTop, document.documentElement.scrollTop)) + 'px';
if(BROWSER.ie > 6 || !BROWSER.ie) {
$(obj.id + 'child').style.left = (parseInt($(obj.id + 'child').style.left) - Math.max(document.body.scrollLeft, document.documentElement.scrollLeft)) + 'px';
}
}
var heightag = BROWSER.chrome ? 4 : 0;
function textareasize(obj, op) {
if(!op) {
if(obj.scrollHeight > 70) {
obj.style.height = (obj.scrollHeight < 300 ? obj.scrollHeight - heightag: 300) + 'px';
if(obj.style.position == 'absolute') {
obj.parentNode.style.height = (parseInt(obj.style.height) + 20) + 'px';
}
}
} else {
if(obj.style.position == 'absolute') {
obj.style.position = '';
obj.style.width = '';
obj.parentNode.style.height = '';
} else {
obj.parentNode.style.height = obj.parentNode.offsetHeight + 'px';
obj.style.width = BROWSER.ie > 6 || !BROWSER.ie ? '90%' : '600px';
obj.style.position = 'absolute';
}
}
}
function showanchor(obj) {
var navs = $('submenu').getElementsByTagName('li');
for(var i = 0; i < navs.length; i++) {
if(navs[i].id.substr(0, 4) == 'nav_' && navs[i].id != obj.id) {
if($(navs[i].id.substr(4))) {
navs[i].className = '';
$(navs[i].id.substr(4)).style.display = 'none';
if($(navs[i].id.substr(4) + '_tips')) $(navs[i].id.substr(4) + '_tips').style.display = 'none';
}
}
}
obj.className = 'current';
currentAnchor = obj.id.substr(4);
$(currentAnchor).style.display = '';
if($(currentAnchor + '_tips')) $(currentAnchor + '_tips').style.display = '';
if($(currentAnchor + 'form')) {
$(currentAnchor + 'form').anchor.value = currentAnchor;
} else if($('cpform')) {
$('cpform').anchor.value = currentAnchor;
}
}
function updatecolorpreview(obj) {
$(obj).style.background = $(obj + '_v').value;
}
function entersubmit(e, name) {
var e = e ? e : event;
if(e.keyCode != 13) {
return;
}
var tag = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tag != 'TEXTAREA') {
doane(e);
if($('submit_' + name).offsetWidth) {
$('formscrolltop').value = document.documentElement.scrollTop;
$('submit_' + name).click();
}
}
}
function parsetag(tag) {
var parse = function (tds) {
for(var i = 0; i < tds.length; i++) {
if(tds[i].getAttribute('s') == '1') {
var str = tds[i].innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
if(tag && $3.indexOf(tag) != -1) {
re = new RegExp(tag, "g");
$3 = $3.replace(re, '<h_>');
}
return $2 + $3;
});
tds[i].innerHTML = str.replace(/<h_>/ig, function($1, $2) {
return '<font class="highlight">' + tag + '</font>';
});
}
}
}
parse(document.body.getElementsByTagName('td'));
parse(document.body.getElementsByTagName('span'));
}
function sdisplay(id, obj) {
obj.innerHTML = $(id).style.display == 'none' ? '<img src="static/image/admincp/desc.gif" style="vertical-align:middle" />' : '<img src="static/image/admincp/add.gif" style="vertical-align:middle" />'
display(id);
}
if(ISFRAME) {
try {
_attachEvent(document.documentElement, 'keydown', parent.resetEscAndF5);
} catch(e) {}
}
var multiids = new Array();
function multiupdate(obj) {
v = obj.value;
if(obj.checked) {
multiids[v] = v;
} else {
multiids[v] = null;
}
}
function getmultiids() {
var ids = '', comma = '';
for(i in multiids) {
if(multiids[i] != null) {
ids += comma + multiids[i];
comma = ',';
}
}
return ids;
}
function toggle_group(oid, obj, conf) {
obj = obj ? obj : $('a_'+oid);
if(!conf) {
var conf = {'show':'[-]','hide':'[+]'};
}
var obody = $(oid);
if(obody.style.display == 'none') {
obody.style.display = '';
obj.innerHTML = conf.show;
} else {
obody.style.display = 'none';
obj.innerHTML = conf.hide;
}
}
function show_all() {
var tbodys = $("cpform").getElementsByTagName('tbody');
for(var i = 0; i < tbodys.length; i++) {
var re = /^group_(\d+)$/;
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = '';
$('a_group_' + matches[1]).innerHTML = '[-]';
}
}
}
function hide_all() {
var tbodys = $("cpform").getElementsByTagName('tbody');
for(var i = 0; i < tbodys.length; i++) {
var re = /^group_(\d+)$/;
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = 'none';
$('a_group_' + matches[1]).innerHTML = '[+]';
}
}
}
function srchforum() {
var fname = $('srchforumipt').value;
if(!fname) return false;
var inputs = $("cpform").getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.match(/^name\[\d+\]$/)) {
if(inputs[i].value.substr(0, fname.length).toLowerCase() == fname.toLowerCase()) {
inputs[i].parentNode.parentNode.parentNode.parentNode.style.display = '';
inputs[i].parentNode.parentNode.parentNode.style.background = '#eee';
window.scrollTo(0, fetchOffset(inputs[i]).top - 100);
return false;
}
}
}
return false;
}
function setfaq(obj, id) {
if(!$(id)) {
return;
}
$(id).style.display = '';
if(!obj.onmouseout) {
obj.onmouseout = function () {
$(id).style.display = 'none';
}
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common.js 22634 2011-05-16 05:52:08Z monkey $
*/
var BROWSER = {};
var USERAGENT = navigator.userAgent.toLowerCase();
browserVersion({'ie':'msie','firefox':'','chrome':'','opera':'','safari':'','mozilla':'','webkit':'','maxthon':'','qq':'qqbrowser'});
if(BROWSER.safari) {
BROWSER.firefox = true;
}
BROWSER.opera = BROWSER.opera ? opera.version() : 0;
HTMLNODE = document.getElementsByTagName('head')[0].parentNode;
if(BROWSER.ie) {
BROWSER.iemode = parseInt(typeof document.documentMode != 'undefined' ? document.documentMode : BROWSER.ie);
HTMLNODE.className = 'ie_all ie' + BROWSER.iemode;
}
var CSSLOADED = [];
var JSLOADED = [];
var JSMENU = [];
JSMENU['active'] = [];
JSMENU['timer'] = [];
JSMENU['drag'] = [];
JSMENU['layer'] = 0;
JSMENU['zIndex'] = {'win':200,'menu':300,'dialog':400,'prompt':500};
JSMENU['float'] = '';
var AJAX = [];
AJAX['url'] = [];
AJAX['stack'] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var CURRENTSTYPE = null;
var discuz_uid = isUndefined(discuz_uid) ? 0 : discuz_uid;
var creditnotice = isUndefined(creditnotice) ? '' : creditnotice;
var cookiedomain = isUndefined(cookiedomain) ? '' : cookiedomain;
var cookiepath = isUndefined(cookiepath) ? '' : cookiepath;
var EXTRAFUNC = [], EXTRASTR = '';
EXTRAFUNC['showmenu'] = [];
var DISCUZCODE = [];
DISCUZCODE['num'] = '-1';
DISCUZCODE['html'] = [];
var USERABOUT_BOX = true;
var USERCARDST = null;
var CLIPBOARDSWFDATA = '';
var NOTICETITLE = [];
if(BROWSER.firefox && window.HTMLElement) {
HTMLElement.prototype.__defineSetter__('outerHTML', function(sHTML) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r.createContextualFragment(sHTML);
this.parentNode.replaceChild(df,this);
return sHTML;
});
HTMLElement.prototype.__defineGetter__('outerHTML', function() {
var attr;
var attrs = this.attributes;
var str = '<' + this.tagName.toLowerCase();
for(var i = 0;i < attrs.length;i++){
attr = attrs[i];
if(attr.specified)
str += ' ' + attr.name + '="' + attr.value + '"';
}
if(!this.canHaveChildren) {
return str + '>';
}
return str + '>' + this.innerHTML + '</' + this.tagName.toLowerCase() + '>';
});
HTMLElement.prototype.__defineGetter__('canHaveChildren', function() {
switch(this.tagName.toLowerCase()) {
case 'area':case 'base':case 'basefont':case 'col':case 'frame':case 'hr':case 'img':case 'br':case 'input':case 'isindex':case 'link':case 'meta':case 'param':
return false;
}
return true;
});
}
function $(id) {
return !id ? null : document.getElementById(id);
}
function $C(classname, ele, tag) {
var returns = [];
ele = ele || document;
tag = tag || '*';
if(ele.getElementsByClassName) {
var eles = ele.getElementsByClassName(classname);
if(tag != '*') {
for (var i = 0, L = eles.length; i < L; i++) {
if (eles[i].tagName.toLowerCase() == tag.toLowerCase()) {
returns.push(eles[i]);
}
}
} else {
returns = eles;
}
}else {
eles = ele.getElementsByTagName(tag);
var pattern = new RegExp("(^|\\s)"+classname+"(\\s|$)");
for (i = 0, L = eles.length; i < L; i++) {
if (pattern.test(eles[i].className)) {
returns.push(eles[i]);
}
}
}
return returns;
}
function _attachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(eventobj.attachEvent) {
obj.attachEvent('on' + evt, func);
}
}
function _detachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.removeEventListener) {
obj.removeEventListener(evt, func, false);
} else if(eventobj.detachEvent) {
obj.detachEvent('on' + evt, func);
}
}
function browserVersion(types) {
var other = 1;
for(i in types) {
var v = types[i] ? types[i] : i;
if(USERAGENT.indexOf(v) != -1) {
var re = new RegExp(v + '(\\/|\\s)([\\d\\.]+)', 'ig');
var matches = re.exec(USERAGENT);
var ver = matches != null ? matches[2] : 0;
other = ver !== 0 && v != 'mozilla' ? 0 : other;
}else {
var ver = 0;
}
eval('BROWSER.' + i + '= ver');
}
BROWSER.other = other;
}
function getEvent() {
if(document.all) return window.event;
func = getEvent.caller;
while(func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
return arg0;
}
}
func=func.caller;
}
return null;
}
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function in_array(needle, haystack) {
if(typeof needle == 'string' || typeof needle == 'number') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function trim(str) {
return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function strlen(str) {
return (BROWSER.ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
function mb_strlen(str) {
var len = 0;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
}
return len;
}
function mb_cutstr(str, maxlen, dot) {
var len = 0;
var ret = '';
var dot = !dot ? '...' : '';
maxlen = maxlen - dot.length;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
if(len > maxlen) {
ret += dot;
break;
}
ret += str.substr(i, 1);
}
return ret;
}
function preg_replace(search, replace, str, regswitch) {
var regswitch = !regswitch ? 'ig' : regswitch;
var len = search.length;
for(var i = 0; i < len; i++) {
re = new RegExp(search[i], regswitch);
str = str.replace(re, typeof replace == 'string' ? replace : (replace[i] ? replace[i] : replace[0]));
}
return str;
}
function htmlspecialchars(str) {
return preg_replace(['&', '<', '>', '"'], ['&', '<', '>', '"'], str);
}
function display(id) {
var obj = $(id);
if(obj.style.visibility) {
obj.style.visibility = obj.style.visibility == 'visible' ? 'hidden' : 'visible';
} else {
obj.style.display = obj.style.display == '' ? 'none' : '';
}
}
function checkall(form, prefix, checkall) {
var checkall = checkall ? checkall : 'chkall';
count = 0;
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name && e.name != checkall && (!prefix || (prefix && e.name.match(prefix)))) {
e.checked = form.elements[checkall].checked;
if(e.checked) {
count++;
}
}
}
return count;
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
var expires = new Date();
if(cookieValue == '' || seconds < 0) {
cookieValue = '';
seconds = -2592000;
}
expires.setTime(expires.getTime() + seconds * 1000);
domain = !domain ? cookiedomain : domain;
path = !path ? cookiepath : path;
document.cookie = escape(cookiepre + cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function getcookie(name, nounescape) {
name = cookiepre + name;
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
if(cookie_start == -1) {
return '';
} else {
var v = document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length));
return !nounescape ? unescape(v) : v;
}
}
function Ajax(recvType, waitId) {
for(var stackId = 0; stackId < AJAX['stack'].length && AJAX['stack'][stackId] != 0; stackId++);
AJAX['stack'][stackId] = 1;
var aj = new Object();
aj.loading = '请稍候...';
aj.recvType = recvType ? recvType : 'XML';
aj.waitId = waitId ? $(waitId) : null;
aj.resultHandle = null;
aj.sendString = '';
aj.targetUrl = '';
aj.stackId = 0;
aj.stackId = stackId;
aj.setLoading = function(loading) {
if(typeof loading !== 'undefined' && loading !== null) aj.loading = loading;
};
aj.setRecvType = function(recvtype) {
aj.recvType = recvtype;
};
aj.setWaitId = function(waitid) {
aj.waitId = typeof waitid == 'object' ? waitid : $(waitid);
};
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) {
request.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) {
return request;
}
} catch(e) {}
}
}
return request;
};
aj.XMLHttpRequest = aj.createXMLHttpRequest();
aj.showLoading = function() {
if(aj.waitId && (aj.XMLHttpRequest.readyState != 4 || aj.XMLHttpRequest.status != 200)) {
aj.waitId.style.display = '';
aj.waitId.innerHTML = '<span><img src="' + IMGDIR + '/loading.gif" class="vm"> ' + aj.loading + '</span>';
}
};
aj.processHandle = function() {
if(aj.XMLHttpRequest.readyState == 4 && aj.XMLHttpRequest.status == 200) {
for(k in AJAX['url']) {
if(AJAX['url'][k] == aj.targetUrl) {
AJAX['url'][k] = null;
}
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
}
if(aj.recvType == 'HTML') {
aj.resultHandle(aj.XMLHttpRequest.responseText, aj);
} else if(aj.recvType == 'XML') {
if(!aj.XMLHttpRequest.responseXML || !aj.XMLHttpRequest.responseXML.lastChild || aj.XMLHttpRequest.responseXML.lastChild.localName == 'parsererror') {
aj.resultHandle('<a href="' + aj.targetUrl + '" target="_blank" style="color:red">内部错误,无法显示此内容</a>' , aj);
} else {
aj.resultHandle(aj.XMLHttpRequest.responseXML.lastChild.firstChild.nodeValue, aj);
}
}
AJAX['stack'][aj.stackId] = 0;
}
};
aj.get = function(targetUrl, resultHandle) {
targetUrl = hostconvert(targetUrl);
setTimeout(function(){aj.showLoading()}, 250);
if(in_array(targetUrl, AJAX['url'])) {
return false;
} else {
AJAX['url'].push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
var attackevasive = isUndefined(attackevasive) ? 0 : attackevasive;
var delay = attackevasive & 1 ? (aj.stackId + 1) * 1001 : 100;
if(window.XMLHttpRequest) {
setTimeout(function(){
aj.XMLHttpRequest.open('GET', aj.targetUrl);
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send(null);}, delay);
} else {
setTimeout(function(){
aj.XMLHttpRequest.open("GET", targetUrl, true);
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send();}, delay);
}
};
aj.post = function(targetUrl, sendString, resultHandle) {
targetUrl = hostconvert(targetUrl);
setTimeout(function(){aj.showLoading()}, 250);
if(in_array(targetUrl, AJAX['url'])) {
return false;
} else {
AJAX['url'].push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.XMLHttpRequest.open('POST', targetUrl);
aj.XMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send(aj.sendString);
};
return aj;
}
function getHost(url) {
var host = "null";
if(typeof url == "undefined"|| null == url) {
url = window.location.href;
}
var regex = /^\w+\:\/\/([^\/]*).*/;
var match = url.match(regex);
if(typeof match != "undefined" && null != match) {
host = match[1];
}
return host;
}
function hostconvert(url) {
if(!url.match(/^https?:\/\//)) url = SITEURL + url;
var url_host = getHost(url);
var cur_host = getHost().toLowerCase();
if(url_host && cur_host != url_host) {
url = url.replace(url_host, cur_host);
}
return url;
}
function newfunction(func) {
var args = [];
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(event) {
doane(event);
window[func].apply(window, args);
return false;
}
}
function evalscript(s) {
if(s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
var arr = [];
while(arr = p.exec(s)) {
var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
var arr1 = [];
arr1 = p1.exec(arr[0]);
if(arr1) {
appendscript(arr1[1], '', arr1[2], arr1[3]);
} else {
p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
arr1 = p1.exec(arr[0]);
appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
}
}
return s;
}
var safescripts = {}, evalscripts = [];
function safescript(id, call, seconds, times, timeoutcall, endcall, index) {
seconds = seconds || 1000;
times = times || 0;
var checked = true;
try {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
} catch(e) {
checked = false;
}
if(!checked) {
if(!safescripts[id] || !index) {
safescripts[id] = safescripts[id] || [];
safescripts[id].push({
'times':0,
'si':setInterval(function () {
safescript(id, call, seconds, times, timeoutcall, endcall, safescripts[id].length);
}, seconds)
});
} else {
index = (index || 1) - 1;
safescripts[id][index]['times']++;
if(safescripts[id][index]['times'] >= times) {
clearInterval(safescripts[id][index]['si']);
if(typeof timeoutcall == 'function') {
timeoutcall();
} else {
eval(timeoutcall);
}
}
}
} else {
try {
index = (index || 1) - 1;
if(safescripts[id][index]['si']) {
clearInterval(safescripts[id][index]['si']);
}
if(typeof endcall == 'function') {
endcall();
} else {
eval(endcall);
}
} catch(e) {}
}
}
function $F(func, args, script) {
var run = function () {
var argc = args.length, s = '';
for(i = 0;i < argc;i++) {
s += ',args[' + i + ']';
}
eval('var check = typeof ' + func + ' == \'function\'');
if(check) {
eval(func + '(' + s.substr(1) + ')');
} else {
setTimeout(function () { checkrun(); }, 50);
}
};
var checkrun = function () {
if(JSLOADED[src]) {
run();
} else {
setTimeout(function () { checkrun(); }, 50);
}
};
script = script || 'common_extra';
src = JSPATH + script + '.js?' + VERHASH;
if(!JSLOADED[src]) {
appendscript(src);
}
checkrun();
}
function appendscript(src, text, reload, charset) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
try {
if(src) {
scriptNode.src = src;
scriptNode.onloadDone = false;
scriptNode.onload = function () {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
};
scriptNode.onreadystatechange = function () {
if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode.onloadDone) {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
}
};
} else if(text){
scriptNode.text = text;
}
document.getElementsByTagName('head')[0].appendChild(scriptNode);
} catch(e) {}
}
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}
function ajaxupdateevents(obj, tagName) {
tagName = tagName ? tagName : 'A';
var objs = obj.getElementsByTagName(tagName);
for(k in objs) {
var o = objs[k];
ajaxupdateevent(o);
}
}
function ajaxupdateevent(o) {
if(typeof o == 'object' && o.getAttribute) {
if(o.getAttribute('ajaxtarget')) {
if(!o.id) o.id = Math.random();
var ajaxevent = o.getAttribute('ajaxevent') ? o.getAttribute('ajaxevent') : 'click';
var ajaxurl = o.getAttribute('ajaxurl') ? o.getAttribute('ajaxurl') : o.href;
_attachEvent(o, ajaxevent, newfunction('ajaxget', ajaxurl, o.getAttribute('ajaxtarget'), o.getAttribute('ajaxwaitid'), o.getAttribute('ajaxloading'), o.getAttribute('ajaxdisplay')));
if(o.getAttribute('ajaxfunc')) {
o.getAttribute('ajaxfunc').match(/(\w+)\((.+?)\)/);
_attachEvent(o, ajaxevent, newfunction(RegExp.$1, RegExp.$2));
}
}
}
}
function ajaxget(url, showid, waitid, loading, display, recall) {
waitid = typeof waitid == 'undefined' || waitid === null ? showid : waitid;
var x = new Ajax();
x.setLoading(loading);
x.setWaitId(waitid);
x.display = typeof display == 'undefined' || display == null ? '' : display;
x.showId = $(showid);
if(url.substr(strlen(url) - 1) == '#') {
url = url.substr(0, strlen(url) - 1);
x.autogoto = 1;
}
var url = url + '&inajax=1&ajaxtarget=' + showid;
x.get(url, function(s, x) {
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
x.showId.style.display = x.display;
ajaxinnerhtml(x.showId, s);
ajaxupdateevents(x.showId);
if(x.autogoto) scroll(0, x.showId.offsetTop);
}
}
ajaxerror = null;
if(recall && typeof recall == 'function') {
recall();
} else if(recall) {
eval(recall);
}
if(!evaled) evalscript(s);
});
}
function ajaxpost(formid, showid, waitid, showidclass, submitbtn, recall) {
var waitid = typeof waitid == 'undefined' || waitid === null ? showid : (waitid !== '' ? waitid : '');
var showidclass = !showidclass ? '' : showidclass;
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
var formtarget = $(formid).target;
var handleResult = function() {
var s = '';
var evaled = false;
showloading('none');
try {
s = $(ajaxframeid).contentWindow.document.XMLDocument.text;
} catch(e) {
try {
s = $(ajaxframeid).contentWindow.document.documentElement.firstChild.wholeText;
} catch(e) {
try {
s = $(ajaxframeid).contentWindow.document.documentElement.firstChild.nodeValue;
} catch(e) {
s = '内部错误,无法显示此内容';
}
}
}
if(s != '' && s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(showidclass) {
if(showidclass != 'onerror') {
$(showid).className = showidclass;
} else {
showError(s);
ajaxerror = true;
}
}
if(submitbtn) {
submitbtn.disabled = false;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
ajaxinnerhtml($(showid), s);
}
ajaxerror = null;
if($(formid)) $(formid).target = formtarget;
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
if(!evaled) evalscript(s);
ajaxframe.loading = 0;
$('append_parent').removeChild(ajaxframe.parentNode);
};
if(!ajaxframe) {
var div = document.createElement('div');
div.style.display = 'none';
div.innerHTML = '<iframe name="' + ajaxframeid + '" id="' + ajaxframeid + '" loading="1"></iframe>';
$('append_parent').appendChild(div);
ajaxframe = $(ajaxframeid);
} else if(ajaxframe.loading) {
return false;
}
_attachEvent(ajaxframe, 'load', handleResult);
showloading();
$(formid).target = ajaxframeid;
var action = $(formid).getAttribute('action');
action = hostconvert(action);
$(formid).action = action.replace(/\&inajax\=1/g, '')+'&inajax=1';
$(formid).submit();
if(submitbtn) {
submitbtn.disabled = true;
}
doane();
return false;
}
function ajaxmenu(ctrlObj, timeout, cache, duration, pos, recall, idclass, contentclass) {
if(!ctrlObj.getAttribute('mid')) {
var ctrlid = ctrlObj.id;
if(!ctrlid) {
ctrlObj.id = 'ajaxid_' + Math.random();
}
} else {
var ctrlid = ctrlObj.getAttribute('mid');
if(!ctrlObj.id) {
ctrlObj.id = 'ajaxid_' + Math.random();
}
}
var menuid = ctrlid + '_menu';
var menu = $(menuid);
if(isUndefined(timeout)) timeout = 3000;
if(isUndefined(cache)) cache = 1;
if(isUndefined(pos)) pos = '43';
if(isUndefined(duration)) duration = timeout > 0 ? 0 : 3;
if(isUndefined(idclass)) idclass = 'p_pop';
if(isUndefined(contentclass)) contentclass = 'p_opt';
var func = function() {
showMenu({'ctrlid':ctrlObj.id,'menuid':menuid,'duration':duration,'timeout':timeout,'pos':pos,'cache':cache,'layer':2});
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
};
if(menu) {
if(menu.style.display == '') {
hideMenu(menuid);
} else {
func();
}
} else {
menu = document.createElement('div');
menu.id = menuid;
menu.style.display = 'none';
menu.className = idclass;
menu.innerHTML = '<div class="' + contentclass + '" id="' + menuid + '_content"></div>';
$('append_parent').appendChild(menu);
var url = (!isUndefined(ctrlObj.href) ? ctrlObj.href : ctrlObj.attributes['href'].value);
url += (url.indexOf('?') != -1 ? '&' :'?') + 'ajaxmenu=1';
ajaxget(url, menuid + '_content', 'ajaxwaitid', '', '', func);
}
doane();
}
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function showPreview(val, id) {
var showObj = $(id);
if(showObj) {
showObj.innerHTML = val.replace(/\n/ig, "<bupdateseccoder />");
}
}
function showloading(display, waiting) {
var display = display ? display : 'block';
var waiting = waiting ? waiting : '请稍候...';
$('ajaxwaitid').innerHTML = waiting;
$('ajaxwaitid').style.display = display;
}
function ajaxinnerhtml(showid, s) {
if(showid.tagName != 'TBODY') {
showid.innerHTML = s;
} else {
while(showid.firstChild) {
showid.firstChild.parentNode.removeChild(showid.firstChild);
}
var div1 = document.createElement('DIV');
div1.id = showid.id+'_div';
div1.innerHTML = '<table><tbody id="'+showid.id+'_tbody">'+s+'</tbody></table>';
$('append_parent').appendChild(div1);
var trs = div1.getElementsByTagName('TR');
var l = trs.length;
for(var i=0; i<l; i++) {
showid.appendChild(trs[0]);
}
var inputs = div1.getElementsByTagName('INPUT');
var l = inputs.length;
for(var i=0; i<l; i++) {
showid.appendChild(inputs[0]);
}
div1.parentNode.removeChild(div1);
}
}
function doane(event, preventDefault, stopPropagation) {
var preventDefault = isUndefined(preventDefault) ? 1 : preventDefault;
var stopPropagation = isUndefined(stopPropagation) ? 1 : stopPropagation;
e = event ? event : window.event;
if(!e) {
e = getEvent();
}
if(!e) {
return null;
}
if(preventDefault) {
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
if(stopPropagation) {
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
return e;
}
function loadcss(cssname) {
if(!CSSLOADED[cssname]) {
if(!$('css_' + cssname)) {
css = document.createElement('link');
css.id = 'css_' + cssname,
css.type = 'text/css';
css.rel = 'stylesheet';
css.href = 'data/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
var headNode = document.getElementsByTagName("head")[0];
headNode.appendChild(css);
} else {
$('css_' + cssname).href = 'data/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
}
CSSLOADED[cssname] = 1;
}
}
function showMenu(v) {
var ctrlid = isUndefined(v['ctrlid']) ? v : v['ctrlid'];
var showid = isUndefined(v['showid']) ? ctrlid : v['showid'];
var menuid = isUndefined(v['menuid']) ? showid + '_menu' : v['menuid'];
var ctrlObj = $(ctrlid);
var menuObj = $(menuid);
if(!menuObj) return;
var mtype = isUndefined(v['mtype']) ? 'menu' : v['mtype'];
var evt = isUndefined(v['evt']) ? 'mouseover' : v['evt'];
var pos = isUndefined(v['pos']) ? '43' : v['pos'];
var layer = isUndefined(v['layer']) ? 1 : v['layer'];
var duration = isUndefined(v['duration']) ? 2 : v['duration'];
var timeout = isUndefined(v['timeout']) ? 250 : v['timeout'];
var maxh = isUndefined(v['maxh']) ? 600 : v['maxh'];
var cache = isUndefined(v['cache']) ? 1 : v['cache'];
var drag = isUndefined(v['drag']) ? '' : v['drag'];
var dragobj = drag && $(drag) ? $(drag) : menuObj;
var fade = isUndefined(v['fade']) ? 0 : v['fade'];
var cover = isUndefined(v['cover']) ? 0 : v['cover'];
var zindex = isUndefined(v['zindex']) ? JSMENU['zIndex']['menu'] : v['zindex'];
var ctrlclass = isUndefined(v['ctrlclass']) ? '' : v['ctrlclass'];
var winhandlekey = isUndefined(v['win']) ? '' : v['win'];
zindex = cover ? zindex + 500 : zindex;
if(typeof JSMENU['active'][layer] == 'undefined') {
JSMENU['active'][layer] = [];
}
for(i in EXTRAFUNC['showmenu']) {
try {
eval(EXTRAFUNC['showmenu'][i] + '()');
} catch(e) {}
}
if(evt == 'click' && in_array(menuid, JSMENU['active'][layer]) && mtype != 'win') {
hideMenu(menuid, mtype);
return;
}
if(mtype == 'menu') {
hideMenu(layer, mtype);
}
if(ctrlObj) {
if(!ctrlObj.getAttribute('initialized')) {
ctrlObj.setAttribute('initialized', true);
ctrlObj.unselectable = true;
ctrlObj.outfunc = typeof ctrlObj.onmouseout == 'function' ? ctrlObj.onmouseout : null;
ctrlObj.onmouseout = function() {
if(this.outfunc) this.outfunc();
if(duration < 3 && !JSMENU['timer'][menuid]) {
JSMENU['timer'][menuid] = setTimeout(function () {
hideMenu(menuid, mtype);
}, timeout);
}
};
ctrlObj.overfunc = typeof ctrlObj.onmouseover == 'function' ? ctrlObj.onmouseover : null;
ctrlObj.onmouseover = function(e) {
doane(e);
if(this.overfunc) this.overfunc();
if(evt == 'click') {
clearTimeout(JSMENU['timer'][menuid]);
JSMENU['timer'][menuid] = null;
} else {
for(var i in JSMENU['timer']) {
if(JSMENU['timer'][i]) {
clearTimeout(JSMENU['timer'][i]);
JSMENU['timer'][i] = null;
}
}
}
};
}
}
if(!menuObj.getAttribute('initialized')) {
menuObj.setAttribute('initialized', true);
menuObj.ctrlkey = ctrlid;
menuObj.mtype = mtype;
menuObj.layer = layer;
menuObj.cover = cover;
if(ctrlObj && ctrlObj.getAttribute('fwin')) {menuObj.scrolly = true;}
menuObj.style.position = 'absolute';
menuObj.style.zIndex = zindex + layer;
menuObj.onclick = function(e) {
return doane(e, 0, 1);
};
if(duration < 3) {
if(duration > 1) {
menuObj.onmouseover = function() {
clearTimeout(JSMENU['timer'][menuid]);
JSMENU['timer'][menuid] = null;
};
}
if(duration != 1) {
menuObj.onmouseout = function() {
JSMENU['timer'][menuid] = setTimeout(function () {
hideMenu(menuid, mtype);
}, timeout);
};
}
}
if(cover) {
var coverObj = document.createElement('div');
coverObj.id = menuid + '_cover';
coverObj.style.position = 'absolute';
coverObj.style.zIndex = menuObj.style.zIndex - 1;
coverObj.style.left = coverObj.style.top = '0px';
coverObj.style.width = '100%';
coverObj.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
coverObj.style.backgroundColor = '#000';
coverObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=50)';
coverObj.style.opacity = 0.5;
coverObj.onclick = function () { hideMenu(); };
$('append_parent').appendChild(coverObj);
_attachEvent(window, 'load', function () {
coverObj.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
}, document);
}
}
if(drag) {
dragobj.style.cursor = 'move';
dragobj.onmousedown = function(event) {try{dragMenu(menuObj, event, 1);}catch(e){}};
}
if(cover) $(menuid + '_cover').style.display = '';
if(fade) {
var O = 0;
var fadeIn = function(O) {
if(O > 100) {
clearTimeout(fadeInTimer);
return;
}
menuObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + O + ')';
menuObj.style.opacity = O / 100;
O += 20;
var fadeInTimer = setTimeout(function () {
fadeIn(O);
}, 40);
};
fadeIn(O);
menuObj.fade = true;
} else {
menuObj.fade = false;
}
menuObj.style.display = '';
if(ctrlObj && ctrlclass) {
ctrlObj.className += ' ' + ctrlclass;
menuObj.setAttribute('ctrlid', ctrlid);
menuObj.setAttribute('ctrlclass', ctrlclass);
}
if(pos != '*') {
setMenuPosition(showid, menuid, pos);
}
if(BROWSER.ie && BROWSER.ie < 7 && winhandlekey && $('fwin_' + winhandlekey)) {
$(menuid).style.left = (parseInt($(menuid).style.left) - parseInt($('fwin_' + winhandlekey).style.left)) + 'px';
$(menuid).style.top = (parseInt($(menuid).style.top) - parseInt($('fwin_' + winhandlekey).style.top)) + 'px';
}
if(maxh && menuObj.scrollHeight > maxh) {
menuObj.style.height = maxh + 'px';
if(BROWSER.opera) {
menuObj.style.overflow = 'auto';
} else {
menuObj.style.overflowY = 'auto';
}
}
if(!duration) {
setTimeout('hideMenu(\'' + menuid + '\', \'' + mtype + '\')', timeout);
}
if(!in_array(menuid, JSMENU['active'][layer])) JSMENU['active'][layer].push(menuid);
menuObj.cache = cache;
if(layer > JSMENU['layer']) {
JSMENU['layer'] = layer;
}
}
var delayShowST = null;
function delayShow(ctrlObj, call, time) {
if(typeof ctrlObj == 'object') {
var ctrlid = ctrlObj.id;
call = call || function () { showMenu(ctrlid); };
}
var time = isUndefined(time) ? 500 : time;
delayShowST = setTimeout(function () {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
}, time);
if(!ctrlObj.delayinit) {
_attachEvent(ctrlObj, 'mouseout', function() {clearTimeout(delayShowST);});
ctrlObj.delayinit = 1;
}
}
var dragMenuDisabled = false;
function dragMenu(menuObj, e, op) {
e = e ? e : window.event;
if(op == 1) {
if(dragMenuDisabled || in_array(e.target ? e.target.tagName : e.srcElement.tagName, ['TEXTAREA', 'INPUT', 'BUTTON', 'SELECT'])) {
return;
}
JSMENU['drag'] = [e.clientX, e.clientY];
JSMENU['drag'][2] = parseInt(menuObj.style.left);
JSMENU['drag'][3] = parseInt(menuObj.style.top);
document.onmousemove = function(e) {try{dragMenu(menuObj, e, 2);}catch(err){}};
document.onmouseup = function(e) {try{dragMenu(menuObj, e, 3);}catch(err){}};
doane(e);
}else if(op == 2 && JSMENU['drag'][0]) {
var menudragnow = [e.clientX, e.clientY];
menuObj.style.left = (JSMENU['drag'][2] + menudragnow[0] - JSMENU['drag'][0]) + 'px';
menuObj.style.top = (JSMENU['drag'][3] + menudragnow[1] - JSMENU['drag'][1]) + 'px';
doane(e);
}else if(op == 3) {
JSMENU['drag'] = [];
document.onmousemove = null;
document.onmouseup = null;
}
}
function setMenuPosition(showid, menuid, pos) {
var showObj = $(showid);
var menuObj = menuid ? $(menuid) : $(showid + '_menu');
if(isUndefined(pos) || !pos) pos = '43';
var basePoint = parseInt(pos.substr(0, 1));
var direction = parseInt(pos.substr(1, 1));
var important = pos.indexOf('!') != -1 ? 1 : 0;
var sxy = 0, sx = 0, sy = 0, sw = 0, sh = 0, ml = 0, mt = 0, mw = 0, mcw = 0, mh = 0, mch = 0, bpl = 0, bpt = 0;
if(!menuObj || (basePoint > 0 && !showObj)) return;
if(showObj) {
sxy = fetchOffset(showObj);
sx = sxy['left'];
sy = sxy['top'];
sw = showObj.offsetWidth;
sh = showObj.offsetHeight;
}
mw = menuObj.offsetWidth;
mcw = menuObj.clientWidth;
mh = menuObj.offsetHeight;
mch = menuObj.clientHeight;
switch(basePoint) {
case 1:
bpl = sx;
bpt = sy;
break;
case 2:
bpl = sx + sw;
bpt = sy;
break;
case 3:
bpl = sx + sw;
bpt = sy + sh;
break;
case 4:
bpl = sx;
bpt = sy + sh;
break;
}
switch(direction) {
case 0:
menuObj.style.left = (document.body.clientWidth - menuObj.clientWidth) / 2 + 'px';
mt = (document.documentElement.clientHeight - menuObj.clientHeight) / 2;
break;
case 1:
ml = bpl - mw;
mt = bpt - mh;
break;
case 2:
ml = bpl;
mt = bpt - mh;
break;
case 3:
ml = bpl;
mt = bpt;
break;
case 4:
ml = bpl - mw;
mt = bpt;
break;
}
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
if(!important) {
if(in_array(direction, [1, 4]) && ml < 0) {
ml = bpl;
if(in_array(basePoint, [1, 4])) ml += sw;
} else if(ml + mw > scrollLeft + document.body.clientWidth && sx >= mw) {
ml = bpl - mw;
if(in_array(basePoint, [2, 3])) {
ml -= sw;
} else if(basePoint == 4) {
ml += sw;
}
}
if(in_array(direction, [1, 2]) && mt < 0) {
mt = bpt;
if(in_array(basePoint, [1, 2])) mt += sh;
} else if(mt + mh > scrollTop + document.documentElement.clientHeight && sy >= mh) {
mt = bpt - mh;
if(in_array(basePoint, [3, 4])) mt -= sh;
}
}
if(pos.substr(0, 3) == '210') {
ml += 69 - sw / 2;
mt -= 5;
if(showObj.tagName == 'TEXTAREA') {
ml -= sw / 2;
mt += sh / 2;
}
}
if(direction == 0 || menuObj.scrolly) {
if(BROWSER.ie && BROWSER.ie < 7) {
if(direction == 0) mt += scrollTop;
} else {
if(menuObj.scrolly) mt -= scrollTop;
menuObj.style.position = 'fixed';
}
}
if(ml) menuObj.style.left = ml + 'px';
if(mt) menuObj.style.top = mt + 'px';
if(direction == 0 && BROWSER.ie && !document.documentElement.clientHeight) {
menuObj.style.position = 'absolute';
menuObj.style.top = (document.body.clientHeight - menuObj.clientHeight) / 2 + 'px';
}
if(menuObj.style.clip && !BROWSER.opera) {
menuObj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
function hideMenu(attr, mtype) {
attr = isUndefined(attr) ? '' : attr;
mtype = isUndefined(mtype) ? 'menu' : mtype;
if(attr == '') {
for(var i = 1; i <= JSMENU['layer']; i++) {
hideMenu(i, mtype);
}
return;
} else if(typeof attr == 'number') {
for(var j in JSMENU['active'][attr]) {
hideMenu(JSMENU['active'][attr][j], mtype);
}
return;
}else if(typeof attr == 'string') {
var menuObj = $(attr);
if(!menuObj || (mtype && menuObj.mtype != mtype)) return;
var ctrlObj = '', ctrlclass = '';
if((ctrlObj = $(menuObj.getAttribute('ctrlid'))) && (ctrlclass = menuObj.getAttribute('ctrlclass'))) {
var reg = new RegExp(' ' + ctrlclass);
ctrlObj.className = ctrlObj.className.replace(reg, '');
}
clearTimeout(JSMENU['timer'][attr]);
var hide = function() {
if(menuObj.cache) {
if(menuObj.style.visibility != 'hidden') {
menuObj.style.display = 'none';
if(menuObj.cover) $(attr + '_cover').style.display = 'none';
}
}else {
menuObj.parentNode.removeChild(menuObj);
if(menuObj.cover) $(attr + '_cover').parentNode.removeChild($(attr + '_cover'));
}
var tmp = [];
for(var k in JSMENU['active'][menuObj.layer]) {
if(attr != JSMENU['active'][menuObj.layer][k]) tmp.push(JSMENU['active'][menuObj.layer][k]);
}
JSMENU['active'][menuObj.layer] = tmp;
};
if(menuObj.fade) {
var O = 100;
var fadeOut = function(O) {
if(O == 0) {
clearTimeout(fadeOutTimer);
hide();
return;
}
menuObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + O + ')';
menuObj.style.opacity = O / 100;
O -= 20;
var fadeOutTimer = setTimeout(function () {
fadeOut(O);
}, 40);
};
fadeOut(O);
} else {
hide();
}
}
}
function getCurrentStyle(obj, cssproperty, csspropertyNS) {
if(obj.style[cssproperty]){
return obj.style[cssproperty];
}
if (obj.currentStyle) {
return obj.currentStyle[cssproperty];
} else if (document.defaultView.getComputedStyle(obj, null)) {
var currentStyle = document.defaultView.getComputedStyle(obj, null);
var value = currentStyle.getPropertyValue(csspropertyNS);
if(!value){
value = currentStyle[cssproperty];
}
return value;
} else if (window.getComputedStyle) {
var currentStyle = window.getComputedStyle(obj, "");
return currentStyle.getPropertyValue(csspropertyNS);
}
}
function fetchOffset(obj, mode) {
var left_offset = 0, top_offset = 0, mode = !mode ? 0 : mode;
if(obj.getBoundingClientRect && !mode) {
var rect = obj.getBoundingClientRect();
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
if(document.documentElement.dir == 'rtl') {
scrollLeft = scrollLeft + document.documentElement.clientWidth - document.documentElement.scrollWidth;
}
left_offset = rect.left + scrollLeft - document.documentElement.clientLeft;
top_offset = rect.top + scrollTop - document.documentElement.clientTop;
}
if(left_offset <= 0 || top_offset <= 0) {
left_offset = obj.offsetLeft;
top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
position = getCurrentStyle(obj, 'position', 'position');
if(position == 'relative') {
continue;
}
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
}
return {'left' : left_offset, 'top' : top_offset};
}
function showTip(ctrlobj) {
$F('_showTip', arguments);
}
function showPrompt(ctrlid, evt, msg, timeout) {
$F('_showPrompt', arguments);
}
function showCreditPrompt() {
$F('_showCreditPrompt', []);
}
var showDialogST = null;
function showDialog(msg, mode, t, func, cover, funccancel, leftmsg, confirmtxt, canceltxt, closetime, locationtime) {
clearTimeout(showDialogST);
cover = isUndefined(cover) ? (mode == 'info' ? 0 : 1) : cover;
leftmsg = isUndefined(leftmsg) ? '' : leftmsg;
mode = in_array(mode, ['confirm', 'notice', 'info', 'right']) ? mode : 'alert';
var menuid = 'fwin_dialog';
var menuObj = $(menuid);
confirmtxtdefault = '确定';
closetime = isUndefined(closetime) ? '' : closetime;
closefunc = function () {
if(typeof func == 'function') func();
else eval(func);
hideMenu(menuid, 'dialog');
};
if(closetime) {
leftmsg = closetime + ' 秒后窗口关闭';
showDialogST = setTimeout(closefunc, closetime * 1000);
}
locationtime = isUndefined(locationtime) ? '' : locationtime;
if(locationtime) {
leftmsg = locationtime + ' 秒后页面跳转';
showDialogST = setTimeout(closefunc, locationtime * 1000);
confirmtxtdefault = '立即跳转';
}
confirmtxt = confirmtxt ? confirmtxt : confirmtxtdefault;
canceltxt = canceltxt ? canceltxt : '取消';
if(menuObj) hideMenu('fwin_dialog', 'dialog');
menuObj = document.createElement('div');
menuObj.style.display = 'none';
menuObj.className = 'fwinmask';
menuObj.id = menuid;
$('append_parent').appendChild(menuObj);
var hidedom = '';
if(!BROWSER.ie) {
hidedom = '<style type="text/css">object{visibility:hidden;}</style>';
}
var s = hidedom + '<table cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"></td><td class="t_r"></td></tr><tr><td class="m_l"> </td><td class="m_c"><h3 class="flb"><em>';
s += t ? t : '提示信息';
s += '</em><span><a href="javascript:;" id="fwin_dialog_close" class="flbc" onclick="hideMenu(\'' + menuid + '\', \'dialog\')" title="关闭">关闭</a></span></h3>';
if(mode == 'info') {
s += msg ? msg : '';
} else {
s += '<div class="c altw"><div class="' + (mode == 'alert' ? 'alert_error' : (mode == 'right' ? 'alert_right' : 'alert_info')) + '"><p>' + msg + '</p></div></div>';
s += '<p class="o pns">' + (leftmsg ? '<span class="z xg1">' + leftmsg + '</span>' : '') + '<button id="fwin_dialog_submit" value="true" class="pn pnc"><strong>'+confirmtxt+'</strong></button>';
s += mode == 'confirm' ? '<button id="fwin_dialog_cancel" value="true" class="pn" onclick="hideMenu(\'' + menuid + '\', \'dialog\')"><strong>'+canceltxt+'</strong></button>' : '';
s += '</p>';
}
s += '</td><td class="m_r"></td></tr><tr><td class="b_l"></td><td class="b_c"></td><td class="b_r"></td></tr></table>';
menuObj.innerHTML = s;
if($('fwin_dialog_submit')) $('fwin_dialog_submit').onclick = function() {
if(typeof func == 'function') func();
else eval(func);
hideMenu(menuid, 'dialog');
};
if($('fwin_dialog_cancel')) {
$('fwin_dialog_cancel').onclick = function() {
if(typeof funccancel == 'function') funccancel();
else eval(funccancel);
hideMenu(menuid, 'dialog');
};
$('fwin_dialog_close').onclick = $('fwin_dialog_cancel').onclick;
}
showMenu({'mtype':'dialog','menuid':menuid,'duration':3,'pos':'00','zindex':JSMENU['zIndex']['dialog'],'cache':0,'cover':cover});
try {
if($('fwin_dialog_submit')) $('fwin_dialog_submit').focus();
} catch(e) {}
}
function showWindow(k, url, mode, cache, menuv) {
mode = isUndefined(mode) ? 'get' : mode;
cache = isUndefined(cache) ? 1 : cache;
var menuid = 'fwin_' + k;
var menuObj = $(menuid);
var drag = null;
var loadingst = null;
var hidedom = '';
if(disallowfloat && disallowfloat.indexOf(k) != -1) {
if(BROWSER.ie) url += (url.indexOf('?') != -1 ? '&' : '?') + 'referer=' + escape(location.href);
location.href = url;
doane();
return;
}
var fetchContent = function() {
if(mode == 'get') {
menuObj.url = url;
url += (url.search(/\?/) > 0 ? '&' : '?') + 'infloat=yes&handlekey=' + k;
url += cache == -1 ? '&t='+(+ new Date()) : '';
ajaxget(url, 'fwin_content_' + k, null, '', '', function() {initMenu();show();});
} else if(mode == 'post') {
menuObj.act = $(url).action;
ajaxpost(url, 'fwin_content_' + k, '', '', '', function() {initMenu();show();});
}
if(parseInt(BROWSER.ie) != 6) {
loadingst = setTimeout(function() {showDialog('', 'info', '<img src="' + IMGDIR + '/loading.gif"> 请稍候...')}, 500);
}
};
var initMenu = function() {
clearTimeout(loadingst);
var objs = menuObj.getElementsByTagName('*');
var fctrlidinit = false;
for(var i = 0; i < objs.length; i++) {
if(objs[i].id) {
objs[i].setAttribute('fwin', k);
}
if(objs[i].className == 'flb' && !fctrlidinit) {
if(!objs[i].id) objs[i].id = 'fctrl_' + k;
drag = objs[i].id;
fctrlidinit = true;
}
}
};
var show = function() {
hideMenu('fwin_dialog', 'dialog');
v = {'mtype':'win','menuid':menuid,'duration':3,'pos':'00','zindex':JSMENU['zIndex']['win'],'drag':typeof drag == null ? '' : drag,'cache':cache};
for(k in menuv) {
v[k] = menuv[k];
}
showMenu(v);
};
if(!menuObj) {
menuObj = document.createElement('div');
menuObj.id = menuid;
menuObj.className = 'fwinmask';
menuObj.style.display = 'none';
$('append_parent').appendChild(menuObj);
evt = ' style="cursor:move" onmousedown="dragMenu($(\'' + menuid + '\'), event, 1)" ondblclick="hideWindow(\'' + k + '\')"';
if(!BROWSER.ie) {
hidedom = '<style type="text/css">object{visibility:hidden;}</style>';
}
menuObj.innerHTML = hidedom + '<table cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"' + evt + '></td><td class="t_r"></td></tr><tr><td class="m_l"' + evt + ')"> </td><td class="m_c" id="fwin_content_' + k + '">'
+ '</td><td class="m_r"' + evt + '"></td></tr><tr><td class="b_l"></td><td class="b_c"' + evt + '></td><td class="b_r"></td></tr></table>';
if(mode == 'html') {
$('fwin_content_' + k).innerHTML = url;
initMenu();
show();
} else {
fetchContent();
}
} else if((mode == 'get' && (url != menuObj.url || cache != 1)) || (mode == 'post' && $(url).action != menuObj.act)) {
fetchContent();
} else {
show();
}
doane();
}
function showError(msg) {
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
msg = msg.replace(p, '');
if(msg !== '') {
showDialog(msg, 'alert', '错误信息', null, true, null, '', '', '', 3);
}
}
function hideWindow(k, all, clear) {
all = isUndefined(all) ? 1 : all;
clear = isUndefined(clear) ? 1 : clear;
hideMenu('fwin_' + k, 'win');
if(clear && $('fwin_' + k)) {
$('append_parent').removeChild($('fwin_' + k));
}
if(all) {
hideMenu();
}
}
function AC_FL_RunContent() {
var str = '';
var ret = AC_GetArgs(arguments, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
if(BROWSER.ie && !BROWSER.opera) {
str += '<object ';
for (var i in ret.objAttrs) {
str += i + '="' + ret.objAttrs[i] + '" ';
}
str += '>';
for (var i in ret.params) {
str += '<param name="' + i + '" value="' + ret.params[i] + '" /> ';
}
str += '</object>';
} else {
str += '<embed ';
for (var i in ret.embedAttrs) {
str += i + '="' + ret.embedAttrs[i] + '" ';
}
str += '></embed>';
}
return str;
}
function AC_GetArgs(args, classid, mimeType) {
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i = 0; i < args.length; i = i + 2){
var currArg = args[i].toLowerCase();
switch (currArg){
case "classid":break;
case "pluginspage":ret.embedAttrs[args[i]] = 'http://www.macromedia.com/go/getflashplayer';break;
case "src":ret.embedAttrs[args[i]] = args[i+1];ret.params["movie"] = args[i+1];break;
case "codebase":ret.objAttrs[args[i]] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0';break;
case "onafterupdate":case "onbeforeupdate":case "onblur":case "oncellchange":case "onclick":case "ondblclick":case "ondrag":case "ondragend":
case "ondragenter":case "ondragleave":case "ondragover":case "ondrop":case "onfinish":case "onfocus":case "onhelp":case "onmousedown":
case "onmouseup":case "onmouseover":case "onmousemove":case "onmouseout":case "onkeypress":case "onkeydown":case "onkeyup":case "onload":
case "onlosecapture":case "onpropertychange":case "onreadystatechange":case "onrowsdelete":case "onrowenter":case "onrowexit":case "onrowsinserted":case "onstart":
case "onscroll":case "onbeforeeditfocus":case "onactivate":case "onbeforedeactivate":case "ondeactivate":case "type":
case "id":ret.objAttrs[args[i]] = args[i+1];break;
case "width":case "height":case "align":case "vspace": case "hspace":case "class":case "title":case "accesskey":case "name":
case "tabindex":ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];break;
default:ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
}
}
ret.objAttrs["classid"] = classid;
if(mimeType) {
ret.embedAttrs["type"] = mimeType;
}
return ret;
}
function simulateSelect(selectId, widthvalue) {
var selectObj = $(selectId);
if(!selectObj) return;
if(BROWSER.other) {
if(selectObj.getAttribute('change')) {
selectObj.onchange = function () {eval(selectObj.getAttribute('change'));}
}
return;
}
var widthvalue = widthvalue ? widthvalue : 70;
var defaultopt = selectObj.options[0] ? selectObj.options[0].innerHTML : '';
var defaultv = '';
var menuObj = document.createElement('div');
var ul = document.createElement('ul');
var handleKeyDown = function(e) {
e = BROWSER.ie ? event : e;
if(e.keyCode == 40 || e.keyCode == 38) doane(e);
};
var selectwidth = (selectObj.getAttribute('width', i) ? selectObj.getAttribute('width', i) : widthvalue) + 'px';
var tabindex = selectObj.getAttribute('tabindex', i) ? selectObj.getAttribute('tabindex', i) : 1;
for(var i = 0; i < selectObj.options.length; i++) {
var li = document.createElement('li');
li.innerHTML = selectObj.options[i].innerHTML;
li.k_id = i;
li.k_value = selectObj.options[i].value;
if(selectObj.options[i].selected) {
defaultopt = selectObj.options[i].innerHTML;
defaultv = selectObj.options[i].value;
li.className = 'current';
selectObj.setAttribute('selecti', i);
}
li.onclick = function() {
if($(selectId + '_ctrl').innerHTML != this.innerHTML) {
var lis = menuObj.getElementsByTagName('li');
lis[$(selectId).getAttribute('selecti')].className = '';
this.className = 'current';
$(selectId + '_ctrl').innerHTML = this.innerHTML;
$(selectId).setAttribute('selecti', this.k_id);
$(selectId).options.length = 0;
$(selectId).options[0] = new Option('', this.k_value);
eval(selectObj.getAttribute('change'));
}
hideMenu(menuObj.id);
return false;
};
ul.appendChild(li);
}
selectObj.options.length = 0;
selectObj.options[0]= new Option('', defaultv);
selectObj.style.display = 'none';
selectObj.outerHTML += '<a href="javascript:;" id="' + selectId + '_ctrl" style="width:' + selectwidth + '" tabindex="' + tabindex + '">' + defaultopt + '</a>';
menuObj.id = selectId + '_ctrl_menu';
menuObj.className = 'sltm';
menuObj.style.display = 'none';
menuObj.style.width = selectwidth;
menuObj.appendChild(ul);
$('append_parent').appendChild(menuObj);
$(selectId + '_ctrl').onclick = function(e) {
$(selectId + '_ctrl_menu').style.width = selectwidth;
showMenu({'ctrlid':(selectId == 'loginfield' ? 'account' : selectId + '_ctrl'),'menuid':selectId + '_ctrl_menu','evt':'click','pos':'43'});
doane(e);
};
$(selectId + '_ctrl').onfocus = menuObj.onfocus = function() {
_attachEvent(document.body, 'keydown', handleKeyDown);
};
$(selectId + '_ctrl').onblur = menuObj.onblur = function() {
_detachEvent(document.body, 'keydown', handleKeyDown);
};
$(selectId + '_ctrl').onkeyup = function(e) {
e = e ? e : window.event;
value = e.keyCode;
if(value == 40 || value == 38) {
if(menuObj.style.display == 'none') {
$(selectId + '_ctrl').onclick();
} else {
lis = menuObj.getElementsByTagName('li');
selecti = selectObj.getAttribute('selecti');
lis[selecti].className = '';
if(value == 40) {
selecti = parseInt(selecti) + 1;
} else if(value == 38) {
selecti = parseInt(selecti) - 1;
}
if(selecti < 0) {
selecti = lis.length - 1
} else if(selecti > lis.length - 1) {
selecti = 0;
}
lis[selecti].className = 'current';
selectObj.setAttribute('selecti', selecti);
lis[selecti].parentNode.scrollTop = lis[selecti].offsetTop;
}
} else if(value == 13) {
var lis = menuObj.getElementsByTagName('li');
lis[selectObj.getAttribute('selecti')].onclick();
} else if(value == 27) {
hideMenu(menuObj.id);
}
};
}
function switchTab(prefix, current, total, activeclass) {
$F('_switchTab', arguments);
}
function imageRotate(imgid, direct) {
$F('_imageRotate', arguments);
}
function thumbImg(obj, method) {
if(!obj) {
return;
}
obj.onload = null;
file = obj.src;
zw = obj.offsetWidth;
zh = obj.offsetHeight;
if(zw < 2) {
if(!obj.id) {
obj.id = 'img_' + Math.random();
}
setTimeout("thumbImg($('" + obj.id + "'), " + method + ")", 100);
return;
}
zr = zw / zh;
method = !method ? 0 : 1;
if(method) {
fixw = obj.getAttribute('_width');
fixh = obj.getAttribute('_height');
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
}
if(zh > fixh) {
zh = fixh;
zw = zh * zr;
}
} else {
fixw = typeof imagemaxwidth == 'undefined' ? '600' : imagemaxwidth;
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
obj.style.cursor = 'pointer';
if(!obj.onclick) {
obj.onclick = function() {
zoom(obj, obj.src);
};
}
}
}
obj.width = zw;
obj.height = zh;
}
var zoomstatus = 1;
function zoom(obj, zimg, nocover, pn) {
$F('_zoom', arguments);
}
function showselect(obj, inpid, t, rettype) {
$F('_showselect', arguments);
}
function showColorBox(ctrlid, layer, k, bgcolor) {
$F('_showColorBox', arguments);
}
function ctrlEnter(event, btnId, onlyEnter) {
if(isUndefined(onlyEnter)) onlyEnter = 0;
if((event.ctrlKey || onlyEnter) && event.keyCode == 13) {
$(btnId).click();
return false;
}
return true;
}
function parseurl(str, mode, parsecode) {
if(isUndefined(parsecode)) parsecode = true;
if(parsecode) str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});
str = str.replace(/([^>=\]"'\/@]|^)((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|qqdl|synacast):\/\/))([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&;~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w>=\]"'\/@]|^)((www\.)([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&;~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w->=\]:"'\.\/]|^)(([\-\.\w]+@[\.\-\w]+(\.\w+)+))/ig, mode == 'html' ? '$1<a href="mailto:$2">$2</a>' : '$1[email]$2[/email]');
if(parsecode) {
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
}
return str;
}
function codetag(text) {
DISCUZCODE['num']++;
if(typeof wysiwyg != 'undefined' && wysiwyg) text = text.replace(/<br[^\>]*>/ig, '\n').replace(/<(\/|)[A-Za-z].*?>/ig, '');
DISCUZCODE['html'][DISCUZCODE['num']] = '[code]' + text + '[/code]';
return '[\tDISCUZ_CODE_' + DISCUZCODE['num'] + '\t]';
}
function saveUserdata(name, data) {
if(BROWSER.ie){
if(data.length < 54889) {
with(document.documentElement) {
setAttribute("value", data);
save('Discuz_' + name);
}
}
} else if(window.localStorage){
localStorage.setItem('Discuz_' + name, data);
} else if(window.sessionStorage){
sessionStorage.setItem('Discuz_' + name, data);
}
setcookie('clearUserdata', '', -1);
}
function loadUserdata(name) {
if(BROWSER.ie){
with(document.documentElement) {
load('Discuz_' + name);
return getAttribute("value");
}
} else if(window.localStorage){
return localStorage.getItem('Discuz_' + name);
} else if(window.sessionStorage){
return sessionStorage.getItem('Discuz_' + name);
}
}
function initTab(frameId, type) {
$F('_initTab', arguments);
}
function openDiy(){
window.location.href = ((window.location.href + '').replace(/[\?\&]diy=yes/g, '').split('#')[0] + ( window.location.search && window.location.search.indexOf('?diy=yes') < 0 ? '&diy=yes' : '?diy=yes'));
}
function hasClass(elem, className) {
return elem.className && (" " + elem.className + " ").indexOf(" " + className + " ") != -1;
}
function runslideshow() {
$F('_runslideshow', []);
}
function toggle_collapse(objname, noimg, complex, lang) {
$F('_toggle_collapse', arguments);
}
function updatestring(str1, str2, clear) {
str2 = '_' + str2 + '_';
return clear ? str1.replace(str2, '') : (str1.indexOf(str2) == -1 ? str1 + str2 : str1);
}
function getClipboardData() {
window.document.clipboardswf.SetVariable('str', CLIPBOARDSWFDATA);
}
function setCopy(text, msg) {
$F('_setCopy', arguments);
}
function copycode(obj) {
$F('_copycode', arguments);
}
function showdistrict(container, elems, totallevel, changelevel) {
$F('_showdistrict', arguments);
}
function setDoodle(fid, oid, url, tid, from) {
$F('_setDoodle', arguments);
}
function initSearchmenu(searchform) {
var searchtxt = $(searchform + '_txt');
if(!searchtxt) {
searchtxt = $(searchform);
}
var tclass = searchtxt.className;
searchtxt.className = tclass + ' xg1';
searchtxt.onfocus = function () {
if(searchtxt.value == '请输入搜索内容') {
searchtxt.value = '';
searchtxt.className = tclass;
}
};
searchtxt.onblur = function () {
if(searchtxt.value == '' ) {
searchtxt.value = '请输入搜索内容';
searchtxt.className = tclass + ' xg1';
}
};
if(!$(searchform + '_type_menu')) return false;
var o = $(searchform + '_type');
var a = $(searchform + '_type_menu').getElementsByTagName('a');
for(var i=0; i<a.length; i++){
if(a[i].className == 'curtype'){
o.innerHTML = a[i].innerHTML;
$(searchform + '_mod').value = a[i].rel;
}
a[i].onclick = function(){
o.innerHTML = this.innerHTML;
$(searchform + '_mod').value = this.rel;
};
}
}
function searchFocus(obj) {
if(obj.value == '请输入搜索内容') {
obj.value = '';
}
}
function extstyle(css) {
$F('_extstyle', arguments);
}
function widthauto(obj) {
$F('_widthauto', arguments);
}
var secST = new Array();
function updatesecqaa(idhash) {
$F('_updatesecqaa', arguments);
}
function updateseccode(idhash, play) {
$F('_updateseccode', arguments);
}
function checksec(type, idhash, showmsg, recall) {
$F('_checksec', arguments);
}
function createPalette(colorid, id, func) {
$F('_createPalette', arguments);
}
function cardInit() {
var cardShow = function (obj) {
if(BROWSER.ie && BROWSER.ie < 7 && obj.href.indexOf('username') != -1) {
return;
}
pos = obj.getAttribute('c') == '1' ? '43' : obj.getAttribute('c');
USERCARDST = setTimeout(function() {ajaxmenu(obj, 500, 1, 2, pos, null, 'p_pop card');}, 250);
};
var a = document.body.getElementsByTagName('a');
for(var i = 0;i < a.length;i++){
if(a[i].getAttribute('c')) {
a[i].setAttribute('mid', hash(a[i].href));
a[i].onmouseover = function() {cardShow(this)};
a[i].onmouseout = function() {clearTimeout(USERCARDST);};
}
}
}
function navShow(id) {
var mnobj = $('snav_mn_' + id);
if(!mnobj) {
return;
}
var uls = $('mu').getElementsByTagName('ul');
for(i = 0;i < uls.length;i++) {
if(uls[i].className != 'cl current') {
uls[i].style.display = 'none';
}
}
if(mnobj.className != 'cl current') {
showMenu({'ctrlid':'mn_' + id,'menuid':'snav_mn_' + id,'pos':'*'});
mnobj.className = 'cl floatmu';
mnobj.style.width = ($('nv').clientWidth) + 'px';
mnobj.style.display = '';
}
}
function strLenCalc(obj, checklen, maxlen) {
var v = obj.value, charlen = 0, maxlen = !maxlen ? 200 : maxlen, curlen = maxlen, len = strlen(v);
for(var i = 0; i < v.length; i++) {
if(v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
curlen -= charset == 'utf-8' ? 2 : 1;
}
}
if(curlen >= len) {
$(checklen).innerHTML = curlen - len;
} else {
obj.value = mb_cutstr(v, maxlen, true);
}
}
function noticeTitle() {
NOTICETITLE = {'State':0, 'oldTitle':document.title, flashNumber:0, sleep:15};
if(!getcookie('noticeTitle')) {
window.setInterval('noticeTitleFlash();', 500);
} else {
window.setTimeout('noticeTitleFlash();', 500);
}
setcookie('noticeTitle', 1, 600);
}
function noticeTitleFlash() {
if(NOTICETITLE.flashNumber < 5 || NOTICETITLE.flashNumber > 4 && !NOTICETITLE['State']) {
document.title = (NOTICETITLE['State'] ? '【 】' : '【新提醒】') + NOTICETITLE['oldTitle'];
NOTICETITLE['State'] = !NOTICETITLE['State'];
}
NOTICETITLE.flashNumber = NOTICETITLE.flashNumber < NOTICETITLE.sleep ? ++NOTICETITLE.flashNumber : 0;
}
function relatedlinks(rlinkmsgid) {
$F('_relatedlinks', arguments);
}
function con_handle_response(response) {
return response;
}
function showTopLink() {
if($('ft')){
var viewPortHeight = parseInt(document.documentElement.clientHeight);
var scrollHeight = parseInt(document.body.getBoundingClientRect().top);
var basew = parseInt($('ft').clientWidth);
var sw = $('scrolltop').clientWidth;
if (basew < 1000) {
var left = parseInt(fetchOffset($('ft'))['left']);
left = left < sw ? left * 2 - sw : left;
$('scrolltop').style.left = ( basew + left ) + 'px';
} else {
$('scrolltop').style.left = 'auto';
$('scrolltop').style.right = 0;
}
if (BROWSER.ie && BROWSER.ie < 7) {
$('scrolltop').style.top = viewPortHeight - scrollHeight - 150 + 'px';
}
if (scrollHeight < -100) {
$('scrolltop').style.visibility = 'visible';
} else {
$('scrolltop').style.visibility = 'hidden';
}
}
}
function showCreditmenu() {
$F('_showCreditmenu', []);
}
function showUpgradeinfo() {
showMenu({'ctrlid':'g_upmine', 'pos':'21'});
}
function addFavorite(url, title) {
try {
window.external.addFavorite(url, title);
} catch (e){
try {
window.sidebar.addPanel(title, url, '');
} catch (e) {
showDialog("请按 Ctrl+D 键添加到收藏夹", 'notice');
}
}
}
function setHomepage(sURL) {
if(BROWSER.ie){
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage(sURL);
} else {
showDialog("非 IE 浏览器请手动将本站设为首页", 'notice');
doane();
}
}
function smilies_show(id, smcols, seditorkey) {
$F('_smilies_show', arguments, 'smilies');
}
if(typeof IN_ADMINCP == 'undefined') {
if(creditnotice != '' && getcookie('creditnotice')) {
_attachEvent(window, 'load', showCreditPrompt, document);
}
if(typeof showusercard != 'undefined' && showusercard == 1) {
_attachEvent(window, 'load', cardInit, document);
}
}
if(BROWSER.ie) {
document.documentElement.addBehavior("#default#userdata");
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_blog.js 15155 2010-08-19 08:16:19Z monkey $
*/
function validate_ajax(obj) {
var subject = $('subject');
if (subject) {
var slen = strlen(subject.value);
if (slen < 1 || slen > 80) {
alert("标题长度(1~80字符)不符合要求");
subject.focus();
return false;
}
}
if($('seccode')) {
var code = $('seccode').value;
var x = new Ajax();
x.get('cp.php?ac=common&op=seccode&code=' + code, function(s){
s = trim(s);
if(s.indexOf('succeed') == -1) {
alert(s);
$('seccode').focus();
return false;
} else {
edit_save();
obj.form.submit();
return true;
}
});
} else {
edit_save();
obj.form.submit();
return true;
}
}
function edit_album_show(id) {
var obj = $('uchome-edit-'+id);
if(id == 'album') {
$('uchome-edit-pic').style.display = 'none';
}
if(id == 'pic') {
$('uchome-edit-album').style.display = 'none';
}
if(obj.style.display == '') {
obj.style.display = 'none';
} else {
obj.style.display = '';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_uploadpic.js 17964 2010-11-09 01:11:24Z monkey $
*/
var attachexts = new Array();
var attachwh = new Array();
var insertType = 1;
var thumbwidth = parseInt(60);
var thumbheight = parseInt(60);
var extensions = 'jpg,jpeg,gif,png';
var forms;
var nowUid = 0;
var albumid = 0;
var uploadStat = 0;
var picid = 0;
var nowid = 0;
var mainForm;
var successState = false;
function delAttach(id) {
$('attachbody').removeChild($('attach_' + id).parentNode.parentNode.parentNode);
if($('attachbody').innerHTML == '') {
addAttach();
}
$('localimgpreview_' + id + '_menu') ? document.body.removeChild($('localimgpreview_' + id + '_menu')) : null;
}
function addAttach() {
newnode = $('attachbodyhidden').rows[0].cloneNode(true);
var id = nowid;
var tags;
tags = newnode.getElementsByTagName('form');
for(i in tags) {
if(tags[i].id == 'upload') {
tags[i].id = 'upload_' + id;
}
}
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach') {
tags[i].id = 'attach_' + id;
tags[i].name = 'attach';
tags[i].onchange = function() {insertAttach(id)};
tags[i].unselectable = 'on';
}
if(tags[i].id == 'albumid') {
tags[i].id = 'albumid_' + id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile') {
tags[i].id = 'localfile_' + id;
}
}
nowid++;
$('attachbody').appendChild(newnode);
}
addAttach();
function insertAttach(id) {
var localimgpreview = '';
var path = $('attach_' + id).value;
var ext = getExt(path);
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类扩展名的图片');
return;
}
attachexts[id] = inArray(ext, ['gif', 'jpg', 'jpeg', 'png']) ? 2 : 1;
var inhtml = '<table cellspacing="0" cellpadding="0" class="up_row"><tr>';
if(typeof no_insert=='undefined') {
localfile += ' <a href="javascript:;" class="xi2" title="点击这里插入内容中当前光标的位置" onclick="insertAttachimgTag(' + id + ');return false;">[插入]</a>';
}
inhtml += '<td><strong>' + localfile +'</strong>';
inhtml += '</td><td class="d">图片描述<br/><textarea name="pic_title" cols="40" rows="2" class="pt"></textarea>';
inhtml += '</td><td class="o"><span id="showmsg' + id + '"><a href="javascript:;" onclick="delAttach(' + id + ');return false;" class="xi2">[删除]</a></span>';
inhtml += '</td></tr></table>';
$('localfile_' + id).innerHTML = inhtml;
$('attach_' + id).style.display = 'none';
addAttach();
}
function getPath(obj){
if (obj) {
if (BROWSER.ie && BROWSER.ie < 7) {
obj.select();
return document.selection.createRange().text;
} else if(BROWSER.firefox) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
} else {
return '';
}
return obj.value;
}
}
function inArray(needle, haystack) {
if(typeof needle == 'string') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function insertAttachimgTag(id) {
edit_insert('[imgid=' + id + ']');
}
function uploadSubmit(obj) {
obj.disabled = true;
mainForm = obj.form;
forms = $('attachbody').getElementsByTagName("FORM");
albumid = $('uploadalbum').value;
upload();
}
function start_upload() {
$('btnupload').disabled = true;
mainForm = $('albumresultform');
forms = $('attachbody').getElementsByTagName("FORM");
upload();
}
function upload() {
if(typeof(forms[nowUid]) == 'undefined') return false;
var nid = forms[nowUid].id.split('_');
nid = nid[1];
if(nowUid>0) {
var upobj = $('showmsg'+nowid);
if(uploadStat==1) {
upobj.innerHTML = '上传成功';
successState = true;
var InputNode;
try {
var InputNode = document.createElement("<input type=\"hidden\" id=\"picid_" + picid + "\" value=\""+ nowid +"\" name=\"picids["+picid+"]\">");
} catch(e) {
var InputNode = document.createElement("input");
InputNode.setAttribute("name", "picids["+picid+"]");
InputNode.setAttribute("type", "hidden");
InputNode.setAttribute("id", "picid_" + picid);
InputNode.setAttribute("value", nowid);
}
mainForm.appendChild(InputNode);
} else {
upobj.style.color = "#f00";
upobj.innerHTML = '上传失败 '+uploadStat;
}
}
if($('showmsg'+nid) != null) {
$('showmsg'+nid).innerHTML = '上传中,请等待(<a href="javascript:;" onclick="forms[nowUid].submit();">重试</a>)';
$('albumid_'+nid).value = albumid;
forms[nowUid].submit();
} else if(nowUid+1 == forms.length) {
if(typeof (no_insert) != 'undefined') {
var albumidcheck = parseInt(parent.albumid);
$('opalbumid').value = isNaN(albumidcheck)? 0 : albumid;
if(!successState) return false;
}
window.onbeforeunload = null;
mainForm.submit();
}
nowid = nid;
nowUid++;
uploadStat = 0;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_upload.js 18682 2010-12-01 03:35:10Z zhangguosheng $
*/
var nowid = 0;
var extensions = '';
function addAttach() {
var newnode = $('upload').cloneNode(true);
var id = nowid;
var tags;
newnode.id = 'upload_' + id;
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach') {
tags[i].id = 'attach_' + id;
tags[i].name = 'attach';
tags[i].onchange = function() {this.form.action = this.form.action.replace(/catid\=\d/, 'catid='+$('catid').value);insertAttach(id)};
tags[i].unselectable = 'on';
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile') {
tags[i].id = 'localfile_' + id;
}
}
nowid++;
$('attachbody').appendChild(newnode);
}
function insertAttach(id) {
var path = $('attach_' + id).value;
if(path == '') {
return;
}
var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类文件');
return;
}
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
$('localfile_' + id).innerHTML = localfile + ' 上传中...';
$('attach_' + id).style.display = 'none';
$('upload_' + id).action += '&attach_target_id=' + id;
$('upload_' + id).submit();
addAttach();
}
function deleteAttach(attachid, url) {
ajaxget(url);
$('attach_list_' + attachid).style.display = 'none';
}
function setConver(attach) {
$('conver').value = attach;
}
addAttach(); | JavaScript |
function xmlobj() {
var obj = new Object();
obj.createXMLDoc = function(xmlstring) {
var xmlobj = false;
if(window.DOMParser && document.implementation && document.implementation.createDocument) {
try{
var domparser = new DOMParser();
xmlobj = domparser.parseFromString(xmlstring, 'text/xml');
} catch(e) {
}
} else if(window.ActiveXObject) {
var versions = ["MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XmlDom"];
for(var i=0; i<versions.length; i++) {
try {
xmlobj = new ActiveXObject(versions[i]);
if(xmlobj) {
xmlobj.async = false;
xmlobj.loadXML(xmlstring);
}
} catch(e) {}
}
}
return xmlobj;
};
obj.xml2json = function(xmlobj, node) {
var nodeattr = node.attributes;
if(nodeattr != null) {
if(nodeattr.length && xmlobj == null) {
xmlobj = new Object();
}
for(var i = 0;i < nodeattr.length;i++) {
xmlobj[nodeattr[i].name] = nodeattr[i].value;
}
}
var nodetext = "text";
if(node.text == null) {
nodetext = "textContent";
}
var nodechilds = node.childNodes;
if(nodechilds != null) {
if(nodechilds.length && xmlobj == null) {
xmlobj = new Object();
}
for(var i = 0;i < nodechilds.length;i++) {
if(nodechilds[i].tagName != null) {
if(nodechilds[i].childNodes[0] != null && nodechilds[i].childNodes.length <= 1 && (nodechilds[i].childNodes[0].nodeType == 3 || nodechilds[i].childNodes[0].nodeType == 4)) {
if(xmlobj[nodechilds[i].tagName] == null) {
xmlobj[nodechilds[i].tagName] = nodechilds[i][nodetext];
} else {
if(typeof(xmlobj[nodechilds[i].tagName]) == "object" && xmlobj[nodechilds[i].tagName].length) {
xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length] = nodechilds[i][nodetext];
} else {
xmlobj[nodechilds[i].tagName] = [xmlobj[nodechilds[i].tagName]];
xmlobj[nodechilds[i].tagName][1] = nodechilds[i][nodetext];
}
}
} else {
if(nodechilds[i].childNodes.length) {
if(xmlobj[nodechilds[i].tagName] == null) {
xmlobj[nodechilds[i].tagName] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName], nodechilds[i]);
} else {
if(xmlobj[nodechilds[i].tagName].length) {
xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length-1], nodechilds[i]);
} else {
xmlobj[nodechilds[i].tagName] = [xmlobj[nodechilds[i].tagName]];
xmlobj[nodechilds[i].tagName][1] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName][1], nodechilds[i]);
}
}
} else {
xmlobj[nodechilds[i].tagName] = nodechilds[i][nodetext];
}
}
}
}
}
};
return obj;
}
var xml = new xmlobj();
var xmlpar = xml.createXMLDoc(forum_optionlist);
var forum_optionlist_obj = new Object();
xml.xml2json(forum_optionlist_obj, xmlpar);
function changeselectthreadsort(selectchoiceoptionid, optionid, type) {
if(selectchoiceoptionid == '0') {
return;
}
var soptionid = 's' + optionid;
var sselectchoiceoptionid = 's' + selectchoiceoptionid;
forum_optionlist = forum_optionlist_obj['forum_optionlist'];
var choicesarr = forum_optionlist[soptionid]['schoices'];
var lastcount = 1;
var name = issearch = id = nameid = '';
if(type == 'search') {
issearch = ', \'search\'';
name = ' name="searchoption[' + optionid + '][value]"';
id = 'id="' + forum_optionlist[soptionid]['sidentifier'] + '"';
} else {
name = ' name="typeoption[' + forum_optionlist[soptionid]['sidentifier'] + ']"';
id = 'id="typeoption_' + forum_optionlist[soptionid]['sidentifier'] + '"';
}
if((choicesarr[sselectchoiceoptionid]['slevel'] == 1 || type == 'search') && choicesarr[sselectchoiceoptionid]['scount'] == 1) {
nameid = name + ' ' + id;
}
var selectoption = '<select' + nameid + ' class="ps vm" onchange="changeselectthreadsort(this.value, \'' + optionid + '\'' + issearch + ');checkoption(\'' + forum_optionlist[soptionid]['sidentifier'] + '\', \'' + forum_optionlist[soptionid]['srequired'] + '\', \'' + forum_optionlist[soptionid]['stype'] + '\')"><option value="0">请选择</option>';
for(var i in choicesarr) {
nameid = '';
if((choicesarr[sselectchoiceoptionid]['slevel'] == 1 || type == 'search') && choicesarr[i]['scount'] == choicesarr[sselectchoiceoptionid]['scount']) {
nameid = name + ' ' + id;
}
if(choicesarr[i]['sfoptionid'] != '0') {
var patrn1 = new RegExp("^" + choicesarr[i]['sfoptionid'] + "\\.", 'i');
var patrn2 = new RegExp("^" + choicesarr[i]['sfoptionid'] + "$", 'i');
if(selectchoiceoptionid.match(patrn1) == null && selectchoiceoptionid.match(patrn2) == null) {
continue;
}
}
if(choicesarr[i]['scount'] != lastcount) {
if(parseInt(choicesarr[i]['scount']) >= (parseInt(choicesarr[sselectchoiceoptionid]['scount']) + parseInt(choicesarr[sselectchoiceoptionid]['slevel']))) {
break;
}
selectoption += '</select>' + "\r\n" + '<select' + nameid + ' class="ps vm" onchange="changeselectthreadsort(this.value, \'' + optionid + '\'' + issearch + ');checkoption(\'' + forum_optionlist[soptionid]['sidentifier'] + '\', \'' + forum_optionlist[soptionid]['srequired'] + '\', \'' + forum_optionlist[soptionid]['stype'] + '\')"><option value="0">请选择</option>';
lastcount = parseInt(choicesarr[i]['scount']);
}
var patrn1 = new RegExp("^" + choicesarr[i]['soptionid'] + "\\.", 'i');
var patrn2 = new RegExp("^" + choicesarr[i]['soptionid'] + "$", 'i');
var isnext = '';
if(parseInt(choicesarr[i]['slevel']) != 1) {
isnext = '»';
}
if(selectchoiceoptionid.match(patrn1) != null || selectchoiceoptionid.match(patrn2) != null) {
selectoption += "\r\n" + '<option value="' + choicesarr[i]['soptionid'] + '" selected="selected">' + choicesarr[i]['scontent'] + isnext + '</option>';
} else {
selectoption += "\r\n" + '<option value="' + choicesarr[i]['soptionid'] + '">' + choicesarr[i]['scontent'] + isnext + '</option>';
}
}
selectoption += '</select>';
if(type == 'search') {
selectoption += "\r\n" + '<input type="hidden" name="searchoption[' + optionid + '][type]" value="select">';
}
$('select_' + forum_optionlist[soptionid]['sidentifier']).innerHTML = selectoption;
}
function checkoption(identifier, required, checktype, checkmaxnum, checkminnum, checkmaxlength) {
if(checktype != 'image' && checktype != 'select' && !$('typeoption_' + identifier) || !$('check' + identifier)) {
return true;
}
var ce = $('check' + identifier);
ce.innerHTML = '';
if(checktype == 'select') {
if(required != '0' && $('typeoption_' + identifier) == null) {
warning(ce, '必填项目没有填写');
return false;
} else if(required == '0' && ($('typeoption_' + identifier) == null || $('typeoption_' + identifier).value == '0')) {
ce.innerHTML = '<img src="' + IMGDIR + '/check_error.gif" width="16" height="16" class="vm" /> 请选择下一级';
ce.className = "warning";
return true;
}
}
if(checktype == 'image') {
var checkvalue = $('sortaid_' + identifier).value;
} else {
var checkvalue = $('typeoption_' + identifier).value;
}
if(required != '0') {
if(checkvalue == '' || checkvalue == '0') {
warning(ce, '必填项目没有填写');
return false;
} else {
ce.innerHTML = '<img src="' + IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
}
}
if(checkvalue) {
if((checktype == 'number' || checktype == 'range') && isNaN(checkvalue)) {
warning(ce, '数字填写不正确');
return false;
} else if(checktype == 'email' && !(/^[\-\.\w]+@[\.\-\w]+(\.\w+)+$/.test(checkvalue))) {
warning(ce, '邮件地址不正确');
return false;
} else if((checktype == 'text' || checktype == 'textarea') && checkmaxlength != '0' && mb_strlen(checkvalue) > checkmaxlength) {
warning(ce, '填写项目长度过长');
return false;
} else if((checktype == 'number' || checktype == 'range')) {
if(checkmaxnum != '0' && parseInt(checkvalue) > parseInt(checkmaxnum)) {
warning(ce, '大于设置最大值');
return false;
} else if(checkminnum != '0' && parseInt(checkvalue) < parseInt(checkminnum)) {
warning(ce, '小于设置最小值');
return false;
}
} else {
ce.innerHTML = '<img src="' + IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
}
}
return true;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_slide.js 4479 2010-02-27 10:40:20Z liyulong $
*/
if(isUndefined(sliderun)) {
var sliderun = 1;
function slide() {
var s = new Object();
s.slideId = Math.random();
s.slideSpeed = slideSpeed;
s.size = slideImgsize;
s.imgs = slideImgs;
s.imgLoad = new Array();
s.imgnum = slideImgs.length;
s.imgLinks = slideImgLinks;
s.imgTexts = slideImgTexts;
s.slideBorderColor = slideBorderColor;
s.slideBgColor = slideBgColor;
s.slideSwitchColor = slideSwitchColor;
s.slideSwitchbgColor = slideSwitchbgColor;
s.slideSwitchHiColor = slideSwitchHiColor;
s.currentImg = 0;
s.prevImg = 0;
s.imgLoaded = 0;
s.st = null;
s.loadImage = function () {
if(!s.imgnum) {
return;
}
s.size[0] = parseInt(s.size[0]);
s.size[1] = parseInt(s.size[1]);
document.write('<div class="slideouter" id="outer_'+s.slideId+'" style="cursor:pointer;position:absolute;width:'+(s.size[0]-2)+'px;height:'+(s.size[1]-2)+'px;border:1px solid '+s.slideBorderColor+'"></div>');
document.write('<table cellspacing="0" cellpadding="0" style="cursor:pointer;width:'+s.size[0]+'px;height:'+s.size[1]+'px;table-layout:fixed;overflow:hidden;background:'+s.slideBgColor+';text-align:center"><tr><td valign="middle" style="padding:0" id="slide_'+s.slideId+'">');
document.write((typeof IMGDIR == 'undefined' ? '' : '<img src="'+IMGDIR+'/loading.gif" />') + '<br /><span id="percent_'+s.slideId+'">0%</span></td></tr></table>');
document.write('<div id="switch_'+s.slideId+'" style="position:absolute;margin-left:1px;margin-top:-18px"></div>');
$('outer_' + s.slideId).onclick = s.imageLink;
for(i = 1;i < s.imgnum;i++) {
switchdiv = document.createElement('div');
switchdiv.id = 'switch_' + i + '_' + s.slideId;
switchdiv.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=70)';
switchdiv.style.opacity = 0.7;
switchdiv.style.styleFloat = 'left';
switchdiv.style.cssFloat = 'left';
switchdiv.style.cursor = 'pointer';
switchdiv.style.width = '17px';
switchdiv.style.height = '17px';
switchdiv.style.overflow = 'hidden';
switchdiv.style.fontWeight = 'bold';
switchdiv.style.textAlign = 'center';
switchdiv.style.fontSize = '9px';
switchdiv.style.color = s.slideSwitchColor;
switchdiv.style.borderRight = '1px solid ' + s.slideBorderColor;
switchdiv.style.borderTop = '1px solid ' + s.slideBorderColor;
switchdiv.style.backgroundColor = s.slideSwitchbgColor;
switchdiv.className = 'slideswitch';
switchdiv.i = i;
switchdiv.onclick = function () {
s.switchImage(this);
};
switchdiv.innerHTML = i;
$('switch_'+s.slideId).appendChild(switchdiv);
s.imgLoad[i] = new Image();
s.imgLoad[i].src = s.imgs[i];
s.imgLoad[i].onerror = function () { s.imgLoaded++; };
}
s.loadCheck();
};
s.imageLink = function () {
window.open(s.imgLinks[s.currentImg]);
};
s.switchImage = function (obj) {
s.showImage(obj.i);
s.interval();
};
s.loadCheck = function () {
for(i = 1;i < s.imgnum;i++) {
if(s.imgLoad[i].complete && !s.imgLoad[i].status) {
s.imgLoaded++;
s.imgLoad[i].status = 1;
if(s.imgLoad[i].width > s.size[0] || s.imgLoad[i].height > s.size[1]) {
zr = s.imgLoad[i].width / s.imgLoad[i].height;
if(zr > 1) {
s.imgLoad[i].height = s.size[1];
s.imgLoad[i].width = s.size[1] * zr;
} else {
s.imgLoad[i].width = s.size[0];
s.imgLoad[i].height = s.size[0] / zr;
if(s.imgLoad[i].height > s.size[1]) {
s.imgLoad[i].height = s.size[1];
s.imgLoad[i].width = s.size[1] * zr;
}
}
}
}
}
if(s.imgLoaded < s.imgnum - 1) {
$('percent_' + s.slideId).innerHTML = (parseInt(s.imgLoad.length / s.imgnum * 100)) + '%';
setTimeout(function () { s.loadCheck(); }, 100);
} else {
for(i = 1;i < s.imgnum;i++) {
s.imgLoad[i].onclick = s.imageLink;
s.imgLoad[i].title = s.imgTexts[i];
}
s.showImage();
s.interval();
}
};
s.interval = function () {
clearInterval(s.st);
s.st = setInterval(function () { s.showImage(); }, s.slideSpeed);
};
s.showImage = function (i) {
if(!i) {
s.currentImg++;
s.currentImg = s.currentImg < s.imgnum ? s.currentImg : 1;
} else {
s.currentImg = i;
}
if(s.prevImg) {
$('switch_' + s.prevImg + '_' + s.slideId).style.backgroundColor = s.slideSwitchbgColor;
}
$('switch_' + s.currentImg + '_' + s.slideId).style.backgroundColor = s.slideSwitchHiColor;
$('slide_' + s.slideId).innerHTML = '';
$('slide_' + s.slideId).appendChild(s.imgLoad[s.currentImg]);
s.prevImg = s.currentImg;
};
s.loadImage();
}
}
slide(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_friendselector.js 22000 2011-04-19 14:35:46Z svn_project_zhangjie $
*/
(function() {
friendSelector = function(parameter) {
this.dataSource = {};
this.selectUser = {};
this.prompterUser = [];
this.showObj = $(isUndefined(parameter['showId']) ? 'selectorBox' : parameter['showId']);
if(!this.showObj) return;
this.handleObj = $(isUndefined(parameter['searchId']) ? 'valueId' : parameter['searchId']);
this.showType = isUndefined(parameter['showType']) ? 0 : parameter['showType'];
this.searchStr = null;
this.selectNumber = 0;
this.maxSelectNumber = isUndefined(parameter['maxSelectNumber']) ? 0 : parseInt(parameter['maxSelectNumber']);
this.allNumber = 0;
this.handleKey = isUndefined(parameter['handleKey']) ? 'this' : parameter['handleKey'];
this.selectTabId = isUndefined(parameter['selectTabId']) ? 'selectTabId' : parameter['selectTabId'];
this.unSelectTabId = isUndefined(parameter['unSelectTabId']) ? 'unSelectTabId' : parameter['unSelectTabId'];
this.maxSelectTabId = isUndefined(parameter['maxSelectTabId']) ? 'maxSelectTabId' : parameter['maxSelectTabId'];
this.formId = isUndefined(parameter['formId']) ? '' : parameter['formId'];
this.filterUser = isUndefined(parameter['filterUser']) ? {} : parameter['filterUser'];
this.showAll = true;
this.newPMUser = {};
this.interlaced = true;
this.handover = true;
this.parentKeyCode = 0;
this.pmSelBoxState = 0;
this.selBoxObj = isUndefined(parameter['selBox']) ? null : $(parameter['selBox']);
this.containerBoxObj = isUndefined(parameter['selBoxMenu']) ? null : $(parameter['selBoxMenu']);
this.imgBtn = null;
this.initialize();
return this;
};
friendSelector.prototype = {
addDataSource : function(data, clear) {
if(typeof data == 'object') {
var userData = data['userdata'];
clear = isUndefined(clear) ? 0: clear;
if(clear) {
this.showObj.innerHTML = "";
if(this.showType == 3) {
this.selBoxObj.innerHTML = '';
}
this.allNumber = 0;
this.dataSource = {};
}
for(var i in userData) {
if(typeof this.filterUser[i] != 'undefined') {
continue;
}
var append = clear ? true : false;
if(typeof this.dataSource[i] == 'undefined') {
this.dataSource[i] = userData[i];
append = true;
this.allNumber++;
}
if(append) {
this.interlaced = !this.interlaced;
if(this.showType == 3) {
this.append(i, 0, 1);
} else {
this.append(i);
}
}
}
if(this.showType == 1) {
this.showSelectNumber();
} else if(this.showType == 2) {
if(this.newPMUser) {
window.setInterval(this.handleKey+".handoverCSS()", 400);
}
}
}
},
addFilterUser : function(data) {
var filterData = {};
if(typeof data != 'object') {
filterData[data] = data;
} else if(typeof data == 'object') {
filterData = data;
} else {
return false;
}
for(var id in filterData) {
this.filterUser[filterData[id]] = filterData[id];
}
return true;
},
handoverCSS : function() {
for(var uid in this.newPMUser) {
$('avt_'+uid).className = this.handover ? 'avt newpm' : 'avt';
}
this.handover = !this.handover;
},
handleEvent : function(key, event) {
var username = '';
this.searchStr = '';
if(key != '') {
if(event.keyCode == 188 || event.keyCode == 13 || event.keyCode == 59) {
if(this.showType == 3) {
if(event.keyCode == 13) {
var currentnum = this.getCurrentPrompterUser();
if(currentnum != -1) {
key = this.dataSource[this.prompterUser[currentnum]]['username'];
}
}
if(this.parentKeyCode != 229) {
this.selectUserName(this.trim(key));
this.showObj.style.display = 'none';
$(this.handleObj.id+'_menu').style.display = 'none';
this.showObj.innerHTML = "";
}
}
} else if(event.keyCode == 38 || event.keyCode == 40) {
} else {
if(this.showType == 3) {
this.showObj.innerHTML = "";
var result = false;
var reg = new RegExp(key, "ig");
this.searchStr = key;
this.prompterUser = [];
for(var uid in this.dataSource) {
username = this.dataSource[uid]['username'];
if(username.match(reg)) {
this.prompterUser.push(uid);
this.append(uid, 1);
result = true;
}
}
if(!result) {
$(this.handleObj.id+'_menu').style.display = 'none';
} else {
showMenu({'showid':this.showObj.id, 'duration':3, 'pos':'43'});
showMenu({'showid':this.handleObj.id, 'duration':3, 'pos':'43'});
}
}
}
} else if(this.showType != 3) {
this.showObj.innerHTML = "";
for(var uid in this.dataSource) {
this.append(uid);
}
} else {
$(this.handleObj.id+'_menu').style.display = 'none';
this.showObj.innerHTML = "";
}
},
selectUserName:function(userName) {
this.handleObj.value = '';
if(userName != '') {
var uid = this.isFriend(userName);
if(uid && typeof this.selectUser[uid] == 'undefined' || uid === 0 && typeof this.selectUser[userName] == 'undefined') {
var spanObj = document.createElement("span");
if(uid) {
this.selectUser[uid] = this.dataSource[uid];
spanObj.id = 'uid' + uid;
if($('chk'+uid) != null) {
$('chk'+uid).checked = true;
}
} else {
var id = 'str' + Math.floor(Math.random() * 10000);
spanObj.id = id;
this.selectUser[userName] = userName;
}
this.selectNumber++;
spanObj.innerHTML= '<a href="javascript:;" class="x" onclick="'+this.handleKey+'.delSelUser(\''+(spanObj.id)+'\');">删除</a><em class="z" title="' + userName + '">' + userName + '</em><input type="hidden" name="users[]" value="'+userName+'" uid="uid'+uid+'" />';
this.handleObj.parentNode.insertBefore(spanObj, this.handleObj);
this.showObj.style.display = 'none';
} else {
alert('已经存在'+userName);
}
}
},
delSelUser:function(id) {
id = isUndefined(id) ? 0 : id;
var uid = id.substring(0, 3) == 'uid' ? parseInt(id.substring(3)) : 0;
var spanObj;
if(uid) {
spanObj = $(id);
delete this.selectUser[uid];
if($('chk'+uid) != null) {
$('chk'+uid).checked = false;
}
} else if(id.substring(0, 3) == 'str') {
spanObj = $(id);
delete this.selectUser[spanObj.getElementsByTagName('input')[0].value];
}
if(spanObj != null) {
this.selectNumber--;
spanObj.parentNode.removeChild(spanObj);
}
},
trim:function(str) {
return str.replace(/\s|,|;/g, '');
},
isFriend:function(userName) {
var id = 0;
for(var uid in this.dataSource) {
if(this.dataSource[uid]['username'] === userName) {
id = uid;
break;
}
}
return id;
},
directionKeyDown : function(event) {},
clearDataSource : function() {
this.dataSource = {};
this.selectUser = {};
},
showUser : function(type) {
this.showObj.innerHTML = '';
type = isUndefined(type) ? 0 : parseInt(type);
this.showAll = true;
if(type == 1) {
for(var uid in this.selectUser) {
this.append(uid);
}
this.showAll = false;
} else {
for(var uid in this.dataSource) {
if(type == 2) {
if(typeof this.selectUser[uid] != 'undefined') {
continue;
}
this.showAll = false;
}
this.append(uid);
}
}
if(this.showType == 1) {
for(var i = 0; i < 3; i++) {
$('showUser_'+i).className = '';
}
$('showUser_'+type).className = 'a brs';
}
},
append : function(uid, filtrate, form) {
filtrate = isUndefined(filtrate) ? 0 : filtrate;
form = isUndefined(form) ? 0 : form;
var liObj = document.createElement("li");
var username = this.dataSource[uid]['username'];
liObj.userid = this.dataSource[uid]['uid'];
if(typeof this.selectUser[uid] != 'undefined') {
liObj.className = "a";
}
if(filtrate) {
var reg = new RegExp("(" + this.searchStr + ")","ig");
username = username.replace(reg , "<strong>$1</strong>");
}
if(this.showType == 1) {
liObj.innerHTML = '<a href="javascript:;" id="' + liObj.userid + '" onclick="' + this.handleKey + '.select(this.id)" class="cl"><span class="avt brs" style="background-image: url(' + this.dataSource[uid]['avatar'] + ');"><span></span></span><span class="d">' + username + '</span></a>';
} else if(this.showType == 2) {
if(this.dataSource[uid]['new'] && typeof this.newPMUser[uid] == 'undefined') {
this.newPMUser[uid] = uid;
}
liObj.className = this.interlaced ? 'alt' : '';
liObj.innerHTML = '<div id="avt_' + liObj.userid + '" class="avt"><a href="home.php?mod=spacecp&ac=pm&op=showmsg&handlekey=showmsg_' + liObj.userid + '&touid=' + liObj.userid + '&pmid='+this.dataSource[uid]['pmid']+'&daterange='+this.dataSource[uid]['daterange']+'" title="'+username+'" id="avatarmsg_' + liObj.userid + '" onclick="'+this.handleKey+'.delNewFlag(' + liObj.userid + ');showWindow(\'showMsgBox\', this.href, \'get\', 0);"><img src="' + this.dataSource[uid]['avatar'] + '" alt="'+username+'" /></a></div><p><a class="xg1" href="home.php?mod=spacecp&ac=pm&op=showmsg&handlekey=showmsg_' + liObj.userid + '&touid=' + liObj.userid + '&pmid='+this.dataSource[uid]['pmid']+'&daterange='+this.dataSource[uid]['daterange']+'" title="'+username+'" id="usernamemsg_' + liObj.userid + '" onclick="'+this.handleKey+'.delNewFlag(' + liObj.userid + ');showWindow(\'showMsgBox\', this.href, \'get\', 0);">'+username+'</a></p>';
} else {
if(form) {
var checkstate = typeof this.selectUser[uid] == 'undefined' ? '' : ' checked="checked" ';
liObj.innerHTML = '<label><input type="checkbox" name="selUsers[]" id="chk'+uid+'" value="'+ this.dataSource[uid]['username'] +'" onclick="if(this.checked) {' + this.handleKey + '.selectUserName(this.value);} else {' + this.handleKey + '.delSelUser(\'uid'+uid+'\');}" '+checkstate+' class="pc" /> <span class="xi2">' + username + '</span></label>';
this.selBoxObj.appendChild(liObj);
return true;
} else {
liObj.innerHTML = '<a href="javascript:;" username="' + this.dataSource[uid]['username'] + '" onmouseover="' + this.handleKey + '.mouseOverPrompter(this);" onclick="' + this.handleKey + '.selectUserName(this.getAttribute(\'username\'));$(\'username\').focus();" class="cl" id="prompter_' + uid + '">' + username + '</a>';
}
}
this.showObj.appendChild(liObj);
},
select : function(uid) {
uid = parseInt(uid);
if(uid){
var select = false;
if(typeof this.selectUser[uid] == 'undefined') {
if(this.maxSelectNumber && this.selectNumber >= this.maxSelectNumber) {
alert('最多只允许选择'+this.maxSelectNumber+'个用户');
return false;
}
this.selectUser[uid] = this.dataSource[uid];
this.selectNumber++;
if(this.showType == '1') {
$(uid).parentNode.className = 'a';
}
select = true;
} else {
delete this.selectUser[uid];
this.selectNumber--;
$(uid).parentNode.className = '';
}
if(this.formId != '') {
var formObj = $(this.formId);
var opId = 'selUids_' + uid;
if(select) {
var inputObj = document.createElement("input");
inputObj.type = 'hidden';
inputObj.id = opId;
inputObj.name = 'uids[]';
inputObj.value = uid;
formObj.appendChild(inputObj);
} else {
formObj.removeChild($(opId));
}
}
if(this.showType == 1) {
this.showSelectNumber();
}
}
},
delNewFlag : function(uid) {
delete this.newPMUser[uid];
},
showSelectNumber:function() {
if($(this.selectTabId) != null && typeof $(this.selectTabId) != 'undefined') {
$(this.selectTabId).innerHTML = this.selectNumber;
}
if($(this.unSelectTabId) != null && typeof $(this.unSelectTabId) != 'undefined') {
$(this.unSelectTabId).innerHTML = this.allNumber - this.selectNumber;
}
if($(this.maxSelectTabId) != null && this.maxSelectNumber && typeof $(this.maxSelectTabId) != 'undefined') {
$(this.maxSelectTabId).innerHTML = this.maxSelectNumber -this.selectNumber;
}
},
getCurrentPrompterUser:function() {
var len = this.prompterUser.length;
var selectnum = -1;
if(len) {
for(var i = 0; i < len; i++) {
var obj = $('prompter_' + this.prompterUser[i]);
if(obj != null && obj.className == 'a') {
selectnum = i;
}
}
}
return selectnum;
},
mouseOverPrompter:function(obj) {
var len = this.prompterUser.length;
if(len) {
for(var i = 0; i < len; i++) {
$('prompter_' + this.prompterUser[i]).className = 'cl';
}
obj.className = 'a';
}
},
initialize:function() {
var instance = this;
this.handleObj.onkeyup = function(event) {
event = event ? event : window.event;
instance.handleEvent(this.value, event);
};
if(this.showType == 3) {
this.handleObj.onkeydown = function(event) {
event = event ? event : window.event;
instance.parentKeyCode = event.keyCode;
instance.showObj.style.display = '';
if(event.keyCode == 8 && this.value == '') {
var preNode = this.previousSibling;
if(preNode.tagName == 'SPAN') {
var uid = preNode.getElementsByTagName('input')[0].getAttribute('uid');
if(parseInt(uid.substring(3))) {
instance.delSelUser(uid);
} else {
delete instance.selectUser[preNode.getElementsByTagName('input')[0].value];
instance.selectNumber--;
this.parentNode.removeChild(preNode);
}
}
} else if(event.keyCode == 38) {
if(!instance.prompterUser.length) {
doane(event);
}
var currentnum = instance.getCurrentPrompterUser();
if(currentnum != -1) {
var nextnum = (currentnum == 0) ? (instance.prompterUser.length-1) : currentnum - 1;
$('prompter_' + instance.prompterUser[currentnum]).className = "cl";
$('prompter_' + instance.prompterUser[nextnum]).className = "a";
} else {
$('prompter_' + instance.prompterUser[0]).className = "a";
}
} else if(event.keyCode == 40) {
if(!instance.prompterUser.length) {
doane(event);
}
var currentnum = instance.getCurrentPrompterUser();
if(currentnum != -1) {
var nextnum = (currentnum == (instance.prompterUser.length - 1)) ? 0 : currentnum + 1;
$('prompter_' + instance.prompterUser[currentnum]).className = "cl";
$('prompter_' + instance.prompterUser[nextnum]).className = "a";
} else {
$('prompter_' + instance.prompterUser[0]).className = "a";
}
} else if(event.keyCode == 13) {
doane(event);
}
if(typeof instance != "undefined" && instance.pmSelBoxState) {
instance.pmSelBoxState = 0;
instance.changePMBoxImg(instance.imgBtn);
instance.containerBoxObj.style.display = 'none';
}
};
}
},
changePMBoxImg:function(obj) {
var btnImg = new Image();
btnImg.src = IMGDIR + '/' + (this.pmSelBoxState ? 'icon_top.gif' : 'icon_down.gif');
if(obj != null) {
obj.src = btnImg.src;
}
},
showPMFriend:function(boxId, listId, obj) {
this.pmSelBoxState = !this.pmSelBoxState;
this.imgBtn = obj;
this.changePMBoxImg(obj);
if(this.pmSelBoxState) {
this.selBoxObj.innerHTML = '';
for(var uid in this.dataSource) {
this.append(uid, 0, 1);
}
}
this.containerBoxObj.style.display = this.pmSelBoxState ? '' : 'none';
this.showObj.innerHTML = "";
},
showPMBoxUser:function() {
this.selBoxObj.innerHTML = '';
for(var uid in this.dataSource) {
this.append(uid, 0, 1);
}
},
extend:function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_viewthread.js 22866 2011-05-27 06:23:56Z zhangguosheng $
*/
var replyreload = '', attachimgST = new Array(), zoomgroup = new Array(), zoomgroupinit = new Array();
function attachimggroup(pid) {
if(!zoomgroupinit[pid]) {
for(i = 0;i < aimgcount[pid].length;i++) {
zoomgroup['aimg_' + aimgcount[pid][i]] = pid;
}
zoomgroupinit[pid] = true;
}
}
function attachimgshow(pid, onlyinpost) {
onlyinpost = !onlyinpost ? false : onlyinpost;
aimgs = aimgcount[pid];
aimgcomplete = 0;
loadingcount = 0;
for(i = 0;i < aimgs.length;i++) {
obj = $('aimg_' + aimgs[i]);
if(!obj) {
aimgcomplete++;
continue;
}
if(onlyinpost && obj.getAttribute('inpost') || !onlyinpost) {
if(!obj.status) {
obj.status = 1;
if(obj.getAttribute('file')) obj.src = obj.getAttribute('file');
loadingcount++;
} else if(obj.status == 1) {
if(obj.complete) {
obj.status = 2;
} else {
loadingcount++;
}
} else if(obj.status == 2) {
aimgcomplete++;
if(obj.getAttribute('thumbImg')) {
thumbImg(obj);
}
}
if(loadingcount >= 10) {
break;
}
}
}
if(aimgcomplete < aimgs.length) {
setTimeout(function () {
attachimgshow(pid, onlyinpost);
}, 100);
}
}
function attachimglstshow(pid, islazy) {
var aimgs = aimgcount[pid];
if(typeof aimgcount == 'object' && $('imagelistthumb_' + pid)) {
for(pid in aimgcount) {
var imagelist = '';
for(i = 0;i < aimgcount[pid].length;i++) {
if(!$('aimg_' + aimgcount[pid][i]) || $('aimg_' + aimgcount[pid][i]).getAttribute('inpost')) {
continue;
}
imagelist += '<div class="pattimg">' +
'<a class="pattimg_zoom" href="javascript:;" onclick="zoom($(\'aimg_' + aimgcount[pid][i] + '\'), attachimggetsrc(\'aimg_' + aimgcount[pid][i] + '\'))" title="点击放大">点击放大</a>' +
'<img ' + (islazy ? 'file' : 'src') + '="forum.php?mod=image&aid=' + aimgcount[pid][i] + '&size=100x100&key=' + imagelistkey + '&atid=' + tid + '" width="100" height="100" /></div>';
}
if($('imagelistthumb_' + pid)) {
$('imagelistthumb_' + pid).innerHTML = imagelist;
}
}
}
}
function attachimggetsrc(img) {
return $(img).getAttribute('zoomfile') ? $(img).getAttribute('zoomfile') : $(img).getAttribute('file');
}
function attachimglst(pid, op, islazy) {
if(!op) {
$('imagelist_' + pid).style.display = 'none';
$('imagelistthumb_' + pid).style.display = '';
} else {
$('imagelistthumb_' + pid).style.display = 'none';
$('imagelist_' + pid).style.display = '';
if(islazy) {
o = new lazyload();
o.showImage();
} else {
attachimgshow(pid);
}
}
doane();
}
function attachimginfo(obj, infoobj, show, event) {
objinfo = fetchOffset(obj);
if(show) {
$(infoobj).style.left = objinfo['left'] + 'px';
$(infoobj).style.top = obj.offsetHeight < 40 ? (objinfo['top'] + obj.offsetHeight) + 'px' : objinfo['top'] + 'px';
$(infoobj).style.display = '';
} else {
if(BROWSER.ie) {
$(infoobj).style.display = 'none';
return;
} else {
var mousex = document.body.scrollLeft + event.clientX;
var mousey = document.documentElement.scrollTop + event.clientY;
if(mousex < objinfo['left'] || mousex > objinfo['left'] + objinfo['width'] || mousey < objinfo['top'] || mousey > objinfo['top'] + objinfo['height']) {
$(infoobj).style.display = 'none';
}
}
}
}
function signature(obj) {
if(obj.style.maxHeightIE != '') {
var height = (obj.scrollHeight > parseInt(obj.style.maxHeightIE)) ? obj.style.maxHeightIE : obj.scrollHeight + 'px';
if(obj.innerHTML.indexOf('<IMG ') == -1) {
obj.style.maxHeightIE = '';
}
return height;
}
}
function tagshow(event) {
var obj = BROWSER.ie ? event.srcElement : event.target;
ajaxmenu(obj, 0, 1, 2);
}
function parsetag(pid) {
if(!$('postmessage_'+pid) || $('postmessage_'+pid).innerHTML.match(/<script[^\>]*?>/i)) {
return;
}
var havetag = false;
var tagfindarray = new Array();
var str = $('postmessage_'+pid).innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3, $4) {
for(i in tagarray) {
if(tagarray[i] && $3.indexOf(tagarray[i]) != -1) {
havetag = true;
$3 = $3.replace(tagarray[i], '<h_ ' + i + '>');
tmp = $3.replace(/&[a-z]*?<h_ \d+>[a-z]*?;/ig, '');
if(tmp != $3) {
$3 = tmp;
} else {
tagfindarray[i] = tagarray[i];
tagarray[i] = '';
}
}
}
return $2 + $3;
});
if(havetag) {
$('postmessage_'+pid).innerHTML = str.replace(/<h_ (\d+)>/ig, function($1, $2) {
return '<span href=\"forum.php?mod=tag&name=' + tagencarray[$2] + '\" onclick=\"tagshow(event)\" class=\"t_tag\">' + tagfindarray[$2] + '</span>';
});
}
}
function setanswer(pid, from){
if(confirm('您确认要把该回复选为“最佳答案”吗?')){
if(BROWSER.ie) {
doane(event);
}
$('modactions').action='forum.php?mod=misc&action=bestanswer&tid=' + tid + '&pid=' + pid + '&from=' + from + '&bestanswersubmit=yes';
$('modactions').submit();
}
}
var authort;
function showauthor(ctrlObj, menuid) {
authort = setTimeout(function () {
showMenu({'menuid':menuid});
if($(menuid + '_ma').innerHTML == '') $(menuid + '_ma').innerHTML = ctrlObj.innerHTML;
}, 500);
if(!ctrlObj.onmouseout) {
ctrlObj.onmouseout = function() {
clearTimeout(authort);
}
}
}
function fastpostappendreply() {
if($('fastpostrefresh') != null) {
setcookie('fastpostrefresh', $('fastpostrefresh').checked ? 1 : 0, 2592000);
if($('fastpostrefresh').checked) {
location.href = 'forum.php?mod=redirect&tid='+tid+'&goto=lastpost&random=' + Math.random() + '#lastpost';
return;
}
}
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
$('fastpostsubmit').disabled = false;
if($('fastpostmessage')) {
$('fastpostmessage').value = '';
} else {
editdoc.body.innerHTML = BROWSER.firefox ? '<br />' : '';
}
if($('secanswer3')) {
$('checksecanswer3').innerHTML = '<img src="' + STATICURL + 'image/common/none.gif" width="17" height="17">';
$('secanswer3').value = '';
secclick3['secanswer3'] = 0;
}
if($('seccodeverify3')) {
$('checkseccodeverify3').innerHTML = '<img src="' + STATICURL + 'image/common/none.gif" width="17" height="17">';
$('seccodeverify3').value = '';
secclick3['seccodeverify3'] = 0;
}
showCreditPrompt();
}
function succeedhandle_fastpost(locationhref, message, param) {
var pid = param['pid'];
var tid = param['tid'];
var from = param['from'];
if(pid) {
ajaxget('forum.php?mod=viewthread&tid=' + tid + '&viewpid=' + pid + '&from=' + from, 'post_new', 'ajaxwaitid', '', null, 'fastpostappendreply()');
if(replyreload) {
var reloadpids = replyreload.split(',');
for(i = 1;i < reloadpids.length;i++) {
ajaxget('forum.php?mod=viewthread&tid=' + tid + '&viewpid=' + reloadpids[i] + '&from=' + from, 'post_' + reloadpids[i]);
}
}
$('fastpostreturn').className = '';
} else {
if(!message) {
message = '本版回帖需要审核,您的帖子将在通过审核后显示';
}
$('post_new').style.display = $('fastpostmessage').value = $('fastpostreturn').className = '';
$('fastpostreturn').innerHTML = message;
}
if(param['sechash']) {
updatesecqaa(param['sechash']);
updateseccode(param['sechash']);
}
if($('attach_tblheader')) {
$('attach_tblheader').style.display = 'none';
}
if($('attachlist')) {
$('attachlist').innerHTML = '';
}
}
function errorhandle_fastpost() {
$('fastpostsubmit').disabled = false;
}
function succeedhandle_comment(locationhref, message, param) {
ajaxget('forum.php?mod=misc&action=commentmore&tid=' + param['tid'] + '&pid=' + param['pid'], 'comment_' + param['pid']);
hideWindow('comment');
showCreditPrompt();
}
function succeedhandle_postappend(locationhref, message, param) {
ajaxget('forum.php?mod=viewthread&tid=' + param['tid'] + '&viewpid=' + param['pid'], 'post_' + param['pid']);
hideWindow('postappend');
}
function recommendupdate(n) {
if(getcookie('recommend')) {
var objv = n > 0 ? $('recommendv_add') : $('recommendv_subtract');
objv.innerHTML = parseInt(objv.innerHTML) + 1;
setTimeout(function () {
$('recommentc').innerHTML = parseInt($('recommentc').innerHTML) + n;
$('recommentv').style.display = 'none';
}, 1000);
setcookie('recommend', '');
}
}
function favoriteupdate() {
var obj = $('favoritenumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function shareupdate() {
var obj = $('sharenumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function switchrecommendv() {
display('recommendv');
display('recommendav');
}
function appendreply() {
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
if($('postform')) {
$('postform').replysubmit.disabled = false;
}
showCreditPrompt();
}
function poll_checkbox(obj) {
if(obj.checked) {
p++;
for (var i = 0; i < $('poll').elements.length; i++) {
var e = $('poll').elements[i];
if(p == max_obj) {
if(e.name.match('pollanswers') && !e.checked) {
e.disabled = true;
}
}
}
} else {
p--;
for (var i = 0; i < $('poll').elements.length; i++) {
var e = $('poll').elements[i];
if(e.name.match('pollanswers') && e.disabled) {
e.disabled = false;
}
}
}
$('pollsubmit').disabled = p <= max_obj && p > 0 ? false : true;
}
function itemdisable(i) {
if($('itemt_' + i).className == 'z') {
$('itemt_' + i).className = 'z xg1';
$('itemc_' + i).value = '';
itemset(i);
} else {
$('itemt_' + i).className = 'z';
$('itemc_' + i).value = $('itemc_' + i).value > 0 ? $('itemc_' + i).value : 0;
}
}
function itemop(i, v) {
var h = v > 0 ? '-' + (v * 16) + 'px' : '0';
$('item_' + i).style.backgroundPosition = '10px ' + h;
}
function itemclk(i, v) {
$('itemc_' + i).value = v;
$('itemt_' + i).className = 'z';
}
function itemset(i) {
var v = $('itemc_' + i).value;
var h = v > 0 ? '-' + (v * 16) + 'px' : '0';
$('item_' + i).style.backgroundPosition = '10px ' + h;
}
function checkmgcmn(id) {
if($('mgc_' + id) && !$('mgc_' + id + '_menu').getElementsByTagName('li').length) {
$('mgc_' + id).innerHTML = '';
$('mgc_' + id).style.display = 'none';
}
}
function toggleRatelogCollapse(tarId, ctrlObj) {
if($(tarId).className == 'rate') {
$(tarId).className = 'rate rate_collapse';
setcookie('ratecollapse', 1, 2592000);
ctrlObj.innerHTML = '展开';
} else {
$(tarId).className = 'rate';
setcookie('ratecollapse', 0, -2592000);
ctrlObj.innerHTML = '收起';
}
}
function copyThreadUrl(obj) {
setCopy($('thread_subject').innerHTML.replace(/&/g, '&') + '\n' + obj.href + '\n', '帖子地址已经复制到剪贴板');
return false;
}
function replyNotice() {
var newurl = 'forum.php?mod=misc&action=replynotice&tid=' + tid + '&op=';
var replynotice = $('replynotice');
var status = replynotice.getAttribute("status");
if(status == 1) {
replynotice.href = newurl + 'receive';
replynotice.innerHTML = '接收回复通知';
replynotice.setAttribute("status", 0);
} else {
replynotice.href = newurl + 'ignore';
replynotice.innerHTML = '取消回复通知';
replynotice.setAttribute("status", 1);
}
}
var connect_share_loaded = 0;
function connect_share(connect_share_url, connect_uin) {
if(parseInt(discuz_uid) <= 0) {
return true;
} else {
if(connect_uin) {
setTimeout(function () {
if(!connect_share_loaded) {
showDialog('分享服务连接失败,请稍后再试。', 'notice');
$('append_parent').removeChild($('connect_load_js'));
}
}, 5000);
connect_load(connect_share_url);
} else {
showDialog($('connect_share_unbind').innerHTML, 'info', '请先绑定QQ账号');
}
return false;
}
}
function connect_load(src) {
var e = document.createElement('script');
e.type = "text/javascript";
e.id = 'connect_load_js';
e.src = src + '&_r=' + Math.random();
e.async = true;
$('append_parent').appendChild(e);
}
function connect_show_dialog(title, html, type) {
var type = type ? type : 'info';
showDialog(html, type, title, null, 0);
}
function connect_get_thread() {
connect_thread_info.subject = $('connect_thread_title').value;
if ($('postmessage_' + connect_thread_info.post_id)) {
connect_thread_info.html_content = preg_replace(["'"], ['%27'], encodeURIComponent(preg_replace(['本帖最后由 .*? 于 .*? 编辑',' ','<em onclick="copycode\\(\\$\\(\'code0\'\\)\\);">复制代码</em>'], ['',' ', ''], $('postmessage_' + connect_thread_info.post_id).innerHTML)));
}
return connect_thread_info;
}
function lazyload(className) {
var obj = this;
lazyload.className = className;
this.getOffset = function (el, isLeft) {
var retValue = 0 ;
while (el != null ) {
retValue += el["offset" + (isLeft ? "Left" : "Top" )];
el = el.offsetParent;
}
return retValue;
};
this.initImages = function (ele) {
lazyload.imgs = [];
var eles = lazyload.className ? $C(lazyload.className, ele) : [document.body];
for (var i = 0; i < eles.length; i++) {
var imgs = eles[i].getElementsByTagName('IMG');
for(var j = 0; j < imgs.length; j++) {
if(imgs[j].getAttribute('file') && !imgs[j].getAttribute('lazyloaded')) {
if(this.getOffset(imgs[j]) > document.documentElement.clientHeight) {
lazyload.imgs.push(imgs[j]);
} else {
imgs[j].setAttribute('src', imgs[j].getAttribute('file'));
}
}
}
}
};
this.showImage = function() {
this.initImages();
if(!lazyload.imgs.length) return false;
var imgs = [];
var scrollTop = Math.max(document.documentElement.scrollTop , document.body.scrollTop);
for (var i=0; i<lazyload.imgs.length; i++) {
var img = lazyload.imgs[i];
var offsetTop = this.getOffset(img);
if (offsetTop > document.documentElement.clientHeight && (offsetTop - scrollTop < document.documentElement.clientHeight)) {
img.setAttribute('src', img.getAttribute('file') ? img.getAttribute('file') : img.getAttribute('src'));
img.setAttribute('lazyloaded', true);
} else {
imgs.push(img);
}
}
lazyload.imgs = imgs;
return true;
};
this.initImages();
_attachEvent(window, 'scroll', function(){obj.showImage();});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common_diy.js 22487 2011-05-10 03:46:05Z zhangguosheng $
*/
String.prototype.property2js = function(){
var t = this.replace(/-([a-z])/g, function($0, $1) {return $1.toUpperCase();});
return t;
};
function styleCss(n) {
if(typeof n == "number") {
var _s = document.styleSheets[n];
} else {
return false;
}
this.sheet = _s;
this.rules = _s.cssRules ? _s.cssRules : _s.rules;
};
styleCss.prototype.indexOf = function(selector) {
for(var i = 0; i < this.rules.length; i++) {
if (typeof(this.rules[i].selectorText) == 'undefined') continue;
if(this.rules[i].selectorText == selector) {
return i;
}
}
return -1;
};
styleCss.prototype.removeRule = function(n) {
if(typeof n == "number") {
if(n < this.rules.length) {
this.sheet.removeRule ? this.sheet.removeRule(n) : this.sheet.deleteRule(n);
}
} else {
var i = this.indexOf(n);
if (i>0) this.sheet.removeRule ? this.sheet.removeRule(i) : this.sheet.deleteRule(i);
}
};
styleCss.prototype.addRule = function(selector, styles, n, porperty) {
var i = this.indexOf(selector);
var s = '';
var reg = '';
if (i != -1) {
reg = new RegExp('^'+porperty+'.*;','i');
s = this.getRule(selector);
if (s) {
s = s.replace(selector,'').replace('{', '').replace('}', '').replace(/ /g, ' ').replace(/^ | $/g,'');
s = (s != '' && s.substr(-1,1) != ';') ? s+ ';' : s;
s = s.toLowerCase().replace(reg, '');
if (s.length == 1) s = '';
}
this.removeRule(i);
}
s = s.indexOf('!important') > -1 || s.indexOf('! important') > -1 ? s : s.replace(/;/g,' !important;');
s = s + styles;
if (typeof n == 'undefined' || !isNaN(n)) {
n = this.rules.length;
}
if (this.sheet.insertRule) {
this.sheet.insertRule(selector+'{'+s+'}', n);
} else {
if (s) this.sheet.addRule(selector, s, n);
}
};
styleCss.prototype.setRule = function(selector, attribute, value) {
var i = this.indexOf(selector);
if(-1 == i) return false;
this.rules[i].style[attribute] = value;
return true;
};
styleCss.prototype.getRule = function(selector, attribute) {
var i = this.indexOf(selector);
if(-1 == i) return '';
var value = '';
if (typeof attribute == 'undefined') {
value = typeof this.rules[i].cssText != 'undefined' ? this.rules[i].cssText : this.rules[i].style['cssText'];
} else {
value = this.rules[i].style[attribute];
}
return typeof value != 'undefined' ? value : '';
};
styleCss.prototype.removeAllRule = function(noSearch) {
var num = this.rules.length;
var j = 0;
for(var i = 0; i < num; i ++) {
var selector = this.rules[this.rules.length - 1 - j].selectorText;
if(noSearch == 1) {
this.sheet.removeRule ? this.sheet.removeRule(this.rules.length - 1 - j) : this.sheet.deleteRule(this.rules.length - 1 - j);
} else {
j++;
}
}
};
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (element, index) {
var length = this.length;
if (index == null) {
index = 0;
} else {
index = (!isNaN(index) ? index : parseInt(index));
if (index < 0) index = length + index;
if (index < 0) index = 0;
}
for (var i = index; i < length; i++) {
var current = this[i];
if (!(typeof(current) === 'undefined') || i in this) {
if (current === element) return i;
}
}
return -1;
};
}
if (!Array.prototype.filter){
Array.prototype.filter = function(fun , thisp){
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++){
if (i in this){
var val = this[i];
if (fun.call(thisp, val, i, this)) res.push(val);
}
}
return res;
};
}
var Util = {
event: function(event){
Util.e = event || window.event;
Util.e.aim = Util.e.target || Util.e.srcElement;
if (!Util.e.preventDefault) {
Util.e.preventDefault = function(){
Util.e.returnValue = false;
};
}
if (!Util.e.stopPropagation) {
Util.e.stopPropagation = function(){
Util.e.cancelBubble = true;
};
}
if (typeof Util.e.layerX == "undefined") {
Util.e.layerX = Util.e.offsetX;
}
if (typeof Util.e.layerY == "undefined") {
Util.e.layerY = Util.e.offsetY;
}
if (typeof Util.e.which == "undefined") {
Util.e.which = Util.e.button;
}
return Util.e;
},
url: function(s){
var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
if (/\\\\$/.test(s2)) {
s2 += ' ';
}
return "url('" + s2 + "')";
},
trimUrl : function(s){
var s2 = s.toLowerCase().replace(/url\(|\"|\'|\)/g,'');
return s2;
},
swapDomNodes: function(a, b){
var afterA = a.nextSibling;
if (afterA == b) {
swapDomNodes(b, a);
return;
}
var aParent = a.parentNode;
b.parentNode.replaceChild(a, b);
aParent.insertBefore(b, afterA);
},
hasClass: function(el, name){
return el && el.nodeType == 1 && el.className.split(/\s+/).indexOf(name) != -1;
},
addClass: function(el, name){
el.className += this.hasClass(el, name) ? '' : ' ' + name;
},
removeClass: function(el, name){
var names = el.className.split(/\s+/);
el.className = names.filter(function(n){
return name != n;
}).join(' ');
},
getTarget: function(e, attributeName, value){
var target = e.target || e.srcElement;
while (target != null) {
if (attributeName == 'className') {
if (this.hasClass(target, value)) {
return target;
}
}else if (target[attributeName] == value) {
return target;
}
target = target.parentNode;
}
return false;
},
getOffset:function (el, isLeft) {
var retValue = 0 ;
while (el != null ) {
retValue += el["offset" + (isLeft ? "Left" : "Top" )];
el = el.offsetParent;
}
return retValue;
},
insertBefore: function (newNode, targetNode) {
var parentNode = targetNode.parentNode;
var next = targetNode.nextSibling;
if (targetNode.id && targetNode.id.indexOf('temp')>-1) {
parentNode.insertBefore(newNode,targetNode);
} else if (!next) {
parentNode.appendChild(newNode);
} else {
parentNode.insertBefore(newNode,targetNode);
}
},
insertAfter : function (newNode, targetNode) {
var parentNode = targetNode.parentNode;
var next = targetNode.nextSibling;
if (next) {
parentNode.insertBefore(newNode,next);
} else {
parentNode.appendChild(newNode);
}
},
getScroll: function () {
var t, l, w, h;
if (document.documentElement && document.documentElement.scrollTop) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
return {t: t, l: l, w: w, h: h};
},
hide:function (ele){
if (typeof ele == 'string') {ele = $(ele);}
if (ele){ele.style.display = 'none';}
},
show:function (ele){
if (typeof ele == 'string') {ele = $(ele);}
if (ele) {
this.removeClass(ele, 'hide');
ele.style.display = '';
}
},
cancelSelect : function () {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
},
getSelectText : function () {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
} else {
t = '';
}
return t;
},
toggleEle : function (ele) {
ele = (typeof ele !='object') ? $(ele) : ele;
if (!ele) return false;
var value = this.getFinallyStyle(ele,'display');
if (value =='none') {
this.show(ele);
this.hide($('uploadmsg_button'));
} else {
this.hide(ele);
this.show($('uploadmsg_button'));
}
},
getFinallyStyle : function (ele,property) {
ele = (typeof ele !='object') ? $(ele) : ele;
var style = (typeof(ele['currentStyle']) == 'undefined') ? window.getComputedStyle(ele,null)[property] : ele['currentStyle'][property];
if (typeof style == 'undefined' && property == 'backgroundPosition') {
style = ele['currentStyle']['backgroundPositionX'] + ' ' +ele['currentStyle']['backgroundPositionY'];
}
return style;
},
recolored:function (){
var b = document.body;
b.style.zoom = b.style.zoom=="1"?"100%":"1";
},
getRandom : function (len,type) {
len = len < 0 ? 0 : len;
type = type && type<=3? type : 3;
var str = '';
for (var i = 0; i < len; i++) {
var j = Math.ceil(Math.random()*type);
if (j == 1) {
str += Math.ceil(Math.random()*9);
} else if (j == 2) {
str += String.fromCharCode(Math.ceil(Math.random()*25+65));
} else {
str += String.fromCharCode(Math.ceil(Math.random()*25+97));
}
}
return str;
},
fade : function(obj,timer,ftype,cur,fn) {
if (this.stack == undefined) {this.stack = [];}
obj = typeof obj == 'string' ? $(obj) : obj;
if (!obj) return false;
for (var i=0;i<this.stack.length;i++) {
if (this.stack[i] == obj && (cur == 0 || cur == 100)) return false;
}
if (cur == 0 || cur == 100) {this.stack.push(obj);}
ftype = ftype != 'in' && ftype != 'out' ? 'out' : ftype;
timer = timer || 400;
var step = 100/(timer/20);
obj.style.filter = 'Alpha(opacity=' + cur + ')';
obj.style.opacity = cur / 100;
cur = ftype == 'in' ? cur + step : cur - step ;
var fadeTimer = (function(){
return setTimeout(function () {
Util.fade(obj, timer, ftype, cur, fn);
}, 20);
})();
this[ftype == 'in' ? 'show' : 'hide'](obj);
if(ftype == 'in' && cur >= 100 || ftype == 'out' && cur <= 0) {
clearTimeout(fadeTimer);
for (i=0;i<this.stack.length;i++) {
if (this.stack[i] == obj ) {
this.stack.splice(i,1);break;
}
}
fn = fn || function(){};
fn(obj);
}
return obj;
},
fadeIn : function (obj,timer,fn) {
return this.fade(obj, timer, 'in', 0, fn);
},
fadeOut : function (obj,timer,fn) {
return this.fade(obj, timer, 'out', 100, fn);
},
getStyle : function (ele) {
if (ele) {
var s = ele.getAttribute('style') || '';
return typeof s == 'object' ? s.cssText : s;
}
return false;
},
setStyle : function (ele,cssText) {
if (ele) {
var s = ele.getAttribute('style') || '';
return typeof s == 'object' ? s.cssText = cssText : ele.setAttribute('style',cssText);
}
return false;
},
getText : function (ele) {
var t = ele.innerText ? ele.innerText : ele.textContent;
return !t ? '' : t;
},
rgb2hex : function (color) {
if (!color) return '';
var reg = new RegExp('(\\d+)[, ]+(\\d+)[, ]+(\\d+)','g');
var rgb = reg.exec(color);
if (rgb == null) rgb = [0,0,0,0];
var red = rgb[1], green = rgb[2], blue = rgb[3];
var decColor = 65536 * parseInt(red) + 256 * parseInt(green) + parseInt(blue);
var hex = decColor.toString(16).toUpperCase();
var pre = new Array(6 - hex.length + 1).join('0');
hex = pre + hex;
return hex;
},
formatColor : function (color) {
return color == '' || color.indexOf('#')>-1 || color.toLowerCase() == 'transparent' ? color : '#'+Util.rgb2hex(color);
}
};
(function(){
Frame = function(name, className, top, left, moveable){
this.name = name;
this.top = top;
this.left = left;
this.moveable = moveable ? true : false;
this.columns = [];
this.className = className;
this.titles = [];
if (typeof Frame._init == 'undefined') {
Frame.prototype.addColumn = function (column) {
if (column instanceof Column) {
this.columns[column.name] = column;
}
};
Frame.prototype.addFrame = function(columnId, frame) {
if (frame instanceof Frame || frame instanceof Tab){
this.columns[columnId].children.push(frame);
}
};
Frame.prototype.addBlock = function(columnId, block) {
if (block instanceof Block){
this.columns[columnId].children.push(block);
}
};
}
Frame._init = true;
};
Column = function (name, className) {
this.name = name;
this.className = className;
this.children = [];
};
Tab = function (name, className, top, left, moveable) {
Frame.apply(this, arguments);
};
Tab.prototype = new Frame();
Block = function(name, className, top, left) {
this.name = name;
this.top = top;
this.left = left;
this.className = className;
this.titles = [];
};
Drag = function () {
this.data = [];
this.scroll = {};
this.menu = [];
this.data = [];
this.allBlocks = [];
this.overObj = '';
this.dragObj = '';
this.dragObjFrame = '';
this.overObjFrame = '';
this.isDragging = false;
this.layout = 2;
this.frameClass = 'frame';
this.blockClass = 'block';
this.areaClass = 'area';
this.moveableArea = [];
this.moveableColumn = 'column';
this.moveableObject = 'move-span';
this.titleClass = 'title';
this.hideClass = 'hide';
this.titleTextClass = 'titletext';
this.frameTitleClass = 'frame-title',
this.tabClass = 'frame-tab';
this.tabActivityClass = 'tabactivity';
this.tabTitleClass = 'tab-title';
this.tabContentClass = 'tb-c';
this.moving = 'moving';
this.contentClass = 'dxb_bc';
this.tmpBoxElement = null ;
this.dargRelative = {};
this.scroll = {};
this.menu = [];
this.rein = [];
this.newFlag = false;
this.isChange = false;
this.fn = '';
this._replaceFlag = false;
this.sampleMode = false;
this.sampleBlocks = null;
this.advancedStyleSheet = null;
};
Drag.prototype = {
getTmpBoxElement : function () {
if (!this.tmpBoxElement) {
this.tmpBoxElement = document.createElement("div");
this.tmpBoxElement.id = 'tmpbox';
this.tmpBoxElement.className = "tmpbox" ;
this.tmpBoxElement.style.width = this.overObj.offsetWidth-4+"px";
this.tmpBoxElement.style.height = this.overObj.offsetHeight-4+"px";
} else if (this.overObj && this.overObj.offsetWidth > 0) {
this.tmpBoxElement.style.width = this.overObj.offsetWidth-4+"px";
}
return this.tmpBoxElement;
},
getPositionStr : function (){
this.initPosition();
var start = '<?xml version="1.0" encoding="ISO-8859-1"?><root>';
var end ="</root>";
var str = "";
for (var i in this.data) {
if (typeof this.data[i] == 'function') continue;
str += '<item id="' + i + '">';
for (var j in this.data[i]) {
if (!(this.data[i][j] instanceof Frame || this.data[i][j] instanceof Tab)) continue;
str += this._getFrameXML(this.data[i][j]);
}
str += '</item>';
}
return start + str + end;
},
_getFrameXML : function (frame) {
if (!(frame instanceof Frame || frame instanceof Tab) || frame.name.indexOf('temp') > 0) return '';
var itemId = frame instanceof Tab ? 'tab' : 'frame';
var Cstr = "";
var name = frame.name;
var frameAttr = this._getAttrXML(frame);
var columns = frame['columns'];
for (var j in columns) {
if (columns[j] instanceof Column) {
var Bstr = '';
var colChildren = columns[j].children;
for (var k in colChildren) {
if (k == 'attr' || typeof colChildren[k] == 'function' || colChildren[k].name.indexOf('temp') > 0) continue;
if (colChildren[k] instanceof Block) {
Bstr += '<item id="block`' + colChildren[k]['name'] + '">';
Bstr += this._getAttrXML(colChildren[k]);
Bstr += '</item>';
} else if (colChildren[k] instanceof Frame || colChildren[k] instanceof Tab) {
Bstr += this._getFrameXML(colChildren[k]);
}
}
var columnAttr = this._getAttrXML(columns[j]);
Cstr += '<item id="column`' + j + '">' + columnAttr + Bstr + '</item>';
}
}
return '<item id="' + itemId + '`' + name + '">' + frameAttr + Cstr + '</item>';
},
_getAttrXML : function (obj) {
var attrXml = '<item id="attr">';
var trimAttr = ['left', 'top'];
var xml = '';
if (obj instanceof Frame || obj instanceof Tab || obj instanceof Block || obj instanceof Column) {
for (var i in obj) {
if (i == 'titles') {
xml += this._getTitlesXML(obj[i]);
}
if (!(typeof obj[i] == 'object' || typeof obj[i] == 'function')) {
if (trimAttr.indexOf(i) >= 0) continue;
xml += '<item id="' + i + '"><![CDATA[' + obj[i] + ']]></item>';
}
}
}else {
xml += '';
}
return attrXml + xml + '</item>';
},
_getTitlesXML : function (titles) {
var xml = '<item id="titles">';
for (var i in titles) {
if (typeof titles[i] == 'function') continue;
xml += '<item id="'+i+'">';
for (var j in titles[i]) {
if (typeof titles[i][j] == 'function') continue;
xml += '<item id="'+j+'"><![CDATA[' + titles[i][j] + ']]></item>';
}
xml += '</item>';
}
xml += '</item>';
return xml;
},
getCurrentOverObj : function (e) {
var _clientX = parseInt(this.dragObj.style.left);
var _clientY = parseInt(this.dragObj.style.top);
var max = 10000000;
for (var i in this.data) {
for (var j in this.data[i]) {
if (!(this.data[i][j] instanceof Frame || this.data[i][j] instanceof Tab)) continue;
var min = this._getMinDistance(this.data[i][j], max);
if (min.distance < max) {
var id = min.id;
max = min.distance;
}
}
}
return $(id);
},
_getMinDistance : function (ele, max) {
if(ele.name==this.dragObj.id) return {"id":ele.name, "distance":max};
var _clientX = parseInt(this.dragObj.style.left);
var _clientY = parseInt(this.dragObj.style.top);
var id;
var isTabInTab = Util.hasClass(this.dragObj, this.tabClass) && Util.hasClass($(ele.name).parentNode.parentNode, this.tabClass);
if (ele instanceof Frame || ele instanceof Tab) {
if (ele.moveable && !isTabInTab) {
var isTab = Util.hasClass(this.dragObj, this.tabClass);
var isFrame = Util.hasClass(this.dragObj, this.frameClass);
var isBlock = Util.hasClass(this.dragObj, this.blockClass) && Util.hasClass($(ele.name).parentNode, this.moveableColumn);
if ( isTab || isFrame || isBlock) {
var _Y = ele['top'] - _clientY;
var _X = ele['left'] - _clientX;
var distance = Math.sqrt(Math.pow(_X, 2) + Math.pow(_Y, 2));
if (distance < max) {
max = distance;
id = ele.name;
}
}
}
for (var i in ele['columns']) {
var column = ele['columns'][i];
if (column instanceof Column) {
for (var j in column['children']) {
if ((column['children'][j] instanceof Tab || column['children'][j] instanceof Frame || column['children'][j] instanceof Block)) {
var min = this._getMinDistance(column['children'][j], max);
if (min.distance < max) {
id = min.id;
max = min.distance;
}
}
}
}
}
return {"id":id, "distance":max};
} else {
if (isTabInTab) return {'id': ele['name'], 'distance': max};
var _Y = ele['top'] - _clientY;
var _X = ele['left'] - _clientX;
var distance = Math.sqrt(Math.pow(_X, 2) + Math.pow(_Y, 2));
if (distance < max) {
return {'id': ele['name'], 'distance': distance};
} else {
return {'id': ele['name'], 'distance': max};
}
}
},
getObjByName : function (name, data) {
if (!name) return false;
data = data || this.data;
if ( data instanceof Frame) {
if (data.name == name) {
return data;
} else {
var d = this.getObjByName(name,data['columns']);
if (name == d.name) return d;
}
} else if (data instanceof Block) {
if (data.name == name) return data;
} else if (typeof data == 'object') {
for (var i in data) {
var d = this.getObjByName(name, data[i]);
if (name == d.name) return d;
}
}
return false;
},
initPosition : function () {
this.data = [],this.allBlocks = [];
var blocks = $C(this.blockClass);
for(var i = 0; i < blocks.length; i++) {
if (blocks[i]['id'].indexOf('temp') < 0) {
this.checkEdit(blocks[i]);
this.allBlocks.push(blocks[i]['id'].replace('portal_block_',''));
}
}
var areaLen = this.moveableArea.length;
for (var j = 0; j < areaLen; j++ ) {
var area = this.moveableArea[j];
var areaData = [];
if (typeof area == 'object') {
this.checkTempDiv(area.id);
var frames = area.childNodes;
for (var i in frames) {
if (typeof(frames[i]) != 'object') continue;
if (Util.hasClass(frames[i], this.frameClass) || Util.hasClass(frames[i], this.blockClass)
|| Util.hasClass(frames[i], this.tabClass) || Util.hasClass(frames[i], this.moveableObject)) {
areaData.push(this.initFrame(frames[i]));
}
}
this.data[area.id] = areaData;
}
}
this._replaceFlag = true;
},
removeBlockPointer : function(e) {this.removeBlock(e);},
toggleContent : function (e) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('_edit_toggle','');
} else {
id = e;
}
var obj = this.getObjByName(id);
var display = '';
if (obj instanceof Block || obj instanceof Tab) {
display = $(id+'_content').style.display;
Util.toggleEle(id+'_content');
} else {
var col = obj.columns;
for (var i in col) {
display = $(i).style.display;
Util.toggleEle($(i));
}
}
if(display != '') {
e.aim.src=STATICURL+'/image/common/fl_collapsed_no.gif';
} else {
e.aim.src=STATICURL+'/image/common/fl_collapsed_yes.gif';
}
},
checkEdit : function (ele) {
if (!ele || Util.hasClass(ele, 'temp') || ele.getAttribute('noedit')) return false;
var id = ele.id;
var _method = this;
if (!$(id+'_edit')) {
var _method = this;
var dom = document.createElement('div');
dom.className = 'edit hide';
dom.id = id+'_edit';
dom.innerHTML = '<span id="'+id+'_edit_menu">编辑</span>';
ele.appendChild(dom);
$(id+'_edit_menu').onclick = function (e){Drag.prototype.toggleMenu.call(_method, e, this);};
}
ele.onmouseover = function (e) {Drag.prototype.showEdit.call(_method,e);};
ele.onmouseout = function (e) {Drag.prototype.hideEdit.call(_method,e);};
},
initFrame : function (frameEle) {
if (typeof(frameEle) != 'object') return '';
var frameId = frameEle.id;
if(!this.sampleMode) {
this.checkEdit(frameEle);
}
var moveable = Util.hasClass(frameEle, this.moveableObject);
var frameObj = '';
if (Util.hasClass(frameEle, this.tabClass)) {
this._initTabActivity(frameEle);
frameObj = new Tab(frameId, frameEle.className, Util.getOffset(frameEle,false), Util.getOffset(frameEle,true), moveable);
} else if (Util.hasClass(frameEle, this.frameClass) || Util.hasClass(frameEle, this.moveableObject)) {
if (Util.hasClass(frameEle, this.frameClass) && !this._replaceFlag) this._replaceFrameColumn(frameEle);
frameObj = new Frame(frameId, frameEle.className, Util.getOffset(frameEle,false), Util.getOffset(frameEle,true), moveable);
}
this._initColumn(frameObj, frameEle);
return frameObj;
},
_initColumn : function (frameObj,frameEle) {
var columns = frameEle.children;
if (Util.hasClass(frameEle.parentNode.parentNode,this.tabClass)) {
var col2 = $(frameEle.id+'_content').children;
var len = columns.length;
for (var i in col2) {
if (typeof(col2[i]) == 'object') columns[len+i] = col2[i];
}
}
for (var i in columns) {
if (typeof(columns[i]) != 'object') continue;
if (Util.hasClass(columns[i], this.titleClass)) {
this._initTitle(frameObj, columns[i]);
}
this._initEleTitle(frameObj, frameEle);
if (Util.hasClass(columns[i], this.moveableColumn)) {
var columnId = columns[i].id;
var column = new Column(columnId, columns[i].className);
frameObj.addColumn(column);
this.checkTempDiv(columnId);
var elements = columns[i].children;
var eleLen = elements.length;
for (var j = 0; j < eleLen; j++) {
var ele = elements[j];
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
var frameObj2 = this.initFrame(ele);
frameObj.addFrame(columnId, frameObj2);
} else if (Util.hasClass(ele, this.blockClass) || Util.hasClass(ele, this.moveableObject)) {
var block = new Block(ele.id, ele.className, Util.getOffset(ele, false), Util.getOffset(ele, true));
for (var k in ele.children) {
if (Util.hasClass(ele.children[k], this.titleClass)) this._initTitle(block, ele.children[k]);
}
this._initEleTitle(block, ele);
frameObj.addBlock(columnId, block);
}
}
}
}
},
_initTitle : function (obj, ele) {
if (Util.hasClass(ele, this.titleClass)) {
obj.titles['className'] = [ele.className];
obj.titles['style'] = {};
if (ele.style.backgroundImage) obj.titles['style']['background-image'] = ele.style.backgroundImage;
if (ele.style.backgroundRepeat) obj.titles['style']['background-repeat'] = ele.style.backgroundRepeat;
if (ele.style.backgroundColor) obj.titles['style']['background-color'] = ele.style.backgroundColor;
if (obj instanceof Tab) {
obj.titles['switchType'] = [];
obj.titles['switchType'][0] = ele.getAttribute('switchtype') ? ele.getAttribute('switchtype') : 'click';
}
var ch = ele.children;
for (var k in ch) {
if (Util.hasClass(ch[k], this.titleTextClass)){
this._getTitleData(obj, ch[k], 'first');
} else if (typeof ch[k] == 'object' && !Util.hasClass(ch[k], this.moveableObject)) {
this._getTitleData(obj, ch[k]);
}
}
}
},
_getTitleData : function (obj, ele, i) {
var shref = '',ssize = '',sfloat = '',scolor = '',smargin = '',stext = '', src = '';
var collection = ele.getElementsByTagName('a');
if (collection.length > 0) {
shref = collection[0]['href'];
scolor = collection[0].style['color'];
}
collection = ele.getElementsByTagName('img');
if (collection.length > 0) {
src = collection[0]['src'];
}
stext = Util.getText(ele);
if (stext || src) {
scolor = scolor ? scolor : ele.style['color'];
sfloat = ele.style['styleFloat'] ? ele.style['styleFloat'] : ele.style['cssFloat'] ;
sfloat = sfloat == undefined ? '' : sfloat;
var margin_ = sfloat == '' ? 'left' : sfloat;
smargin = parseInt(ele.style[('margin-'+margin_).property2js()]);
smargin = smargin ? smargin : '';
ssize = parseInt(ele.style['fontSize']);
ssize = ssize ? ssize : '';
var data = {'text':stext, 'href':shref,'color':scolor, 'float':sfloat, 'margin':smargin, 'font-size':ssize, 'className':ele.className, 'src':src};
if (i) {
obj.titles[i] = data;
} else {
obj.titles.push(data);
}
}
},
_initEleTitle : function (obj,ele) {
if (Util.hasClass(ele, this.moveableObject)) {
if (obj.titles['first'] && obj.titles['first']['text']) {
var title = obj.titles['first']['text'];
} else {
var title = obj.name;
}
}
},
showEdit : function (e) {
e = Util.event(e);
var targetObject = Util.getTarget(e,'className',this.moveableObject);
if (targetObject) {
Util.show(targetObject.id + '_edit');
targetObject.style.backgroundColor="#fffacd";
} else {
var targetFrame = Util.getTarget(e,'className',this.frameClass);
if (typeof targetFrame == 'object') {
Util.show(targetFrame.id + '_edit');
targetFrame.style.backgroundColor="#fffacd";
}
}
},
hideEdit : function (e) {
e = Util.event(e);
var targetObject = Util.getTarget(e,'className',this.moveableObject);
var targetFrame = Util.getTarget(e,'className',this.frameClass);
if (typeof targetFrame == 'object') {
Util.hide(targetFrame.id + '_edit');
targetFrame.style.backgroundColor = '';
}
if (typeof targetObject == 'object') {
Util.hide(targetObject.id + '_edit');
targetObject.style.backgroundColor = '';
}
},
toggleMenu : function (e, obj) {
e = Util.event(e);
e.stopPropagation();
var objPara = {'top' : Util.getOffset( obj, false),'left' : Util.getOffset( obj, true),
'width' : obj['offsetWidth'], 'height' : obj['offsetHeight']};
var dom = $('edit_menu');
if (dom) {
if (objPara.top + objPara.height == Util.getOffset(dom, false) && objPara.left == Util.getOffset(dom, true)) {
dom.parentNode.removeChild(dom);
} else {
dom.style.top = objPara.top + objPara.height + 'px';
dom.style.left = objPara.left + 'px';
dom.innerHTML = this._getMenuHtml(e, obj);
}
} else {
var html = this._getMenuHtml(e, obj);
if (html != '') {
dom = document.createElement('div');
dom.id = 'edit_menu';
dom.className = 'edit-menu';
dom.style.top = objPara.top + objPara.height + 'px';
dom.style.left = objPara.left + 'px';
dom.innerHTML = html;
document.body.appendChild(dom);
var _method = this;
document.body.onclick = function(e){Drag.prototype.removeMenu.call(_method, e);};
}
}
},
_getMenuHtml : function (e,obj) {
var id = obj.id.replace('_edit_menu','');
var html = '<ul>';
if (typeof this.menu[id] == 'object') html += this._getMenuHtmlLi(id, this.menu[id]);
if (Util.hasClass($(id),this.tabClass) && typeof this.menu['tab'] == 'object') html += this._getMenuHtmlLi(id, this.menu['tab']);
if (Util.hasClass($(id),this.frameClass) && typeof this.menu['frame'] == 'object') html += this._getMenuHtmlLi(id, this.menu['frame']);
if (Util.hasClass($(id),this.blockClass) && typeof this.menu['block'] == 'object') html += this._getMenuHtmlLi(id, this.menu['block']);
if (typeof this.menu['default'] == 'object' && this.getObjByName(id)) html += this._getMenuHtmlLi(id, this.menu['default']);
html += '</ul>';
return html == '<ul></ul>' ? '' : html;
},
_getMenuHtmlLi : function (id, cmds) {
var li = '';
var len = cmds.length;
for (var i=0; i<len; i++) {
li += '<li class="mitem" id="cmd_'+id+'" onclick='+"'"+cmds[i]['cmd']+"'"+'>'+cmds[i]['cmdName']+'</li>';
}
return li;
},
removeMenu : function (e) {
var dom = $('edit_menu');
if (dom) dom.parentNode.removeChild(dom);
document.body.onclick = '';
},
addMenu : function (objId,cmdName,cmd) {
if (typeof this.menu[objId] == 'undefined') this.menu[objId] = [];
this.menu[objId].push({'cmdName':cmdName, 'cmd':cmd});
},
setDefalutMenu : function () {},
setSampleMenu : function () {},
getPositionKey : function (n) {
this.initPosition();
n = parseInt(n);
var i = 0;
for (var k in this.position) {
if (i++ >= n) break;
}
return k;
},
checkTempDiv : function (_id) {
if(_id) {
var id = _id+'_temp';
var dom = $(id);
if (dom == null || typeof dom == 'undefined') {
dom = document.createElement("div");
dom.className = this.moveableObject+' temp';
dom.id = id;
$(_id).appendChild(dom);
}
}
},
_setCssPosition : function (ele, value) {
while (ele && ele.parentNode && ele.id != 'ct') {
if (Util.hasClass(ele,this.frameClass) || Util.hasClass(ele,this.tabClass)) ele.style.position = value;
ele = ele.parentNode;
}
},
initDragObj : function (e) {
e = Util.event(e);
var target = Util.getTarget(e,'className',this.moveableObject);
if (!target) {return false;}
if (this.overObj != target && target.id !='tmpbox') {
this.overObj = target;
this.overObj.style.cursor = 'move';
}
},
dragStart : function (e) {
e = Util.event(e);
if (e.aim['id'] && e.aim['id'].indexOf && e.aim['id'].indexOf('_edit') > 0) return false;
if(e.which != 1 ) {return false;}
this.overObj = this.dragObj = Util.getTarget(e,'className',this.moveableObject);
if (!this.dragObj || Util.hasClass(this.dragObj,'temp')) {return false;}
if (!this.getTmpBoxElement()) return false;
this.getRelative();
this._setCssPosition(this.dragObj.parentNode.parentNode, "static");
var offLeft = Util.getOffset( this.dragObj, true );
var offTop = Util.getOffset( this.dragObj, false );
var offWidth = this.dragObj['offsetWidth'];
this.dragObj.style.position = 'absolute';
this.dragObj.style.left = offLeft + "px";
this.dragObj.style.top = offTop - 3 + "px";
this.dragObj.style.width = offWidth + 'px';
this.dragObj.lastMouseX = e.clientX;
this.dragObj.lastMouseY = e.clientY;
Util.insertBefore(this.tmpBoxElement,this.overObj);
Util.addClass(this.dragObj,this.moving);
this.dragObj.style.zIndex = 500 ;
this.scroll = Util.getScroll();
var _method = this;
document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);};
},
getRelative : function () {
this.dargRelative = {'up': this.dragObj.previousSibling, 'down': this.dragObj.nextSibling};
},
resetObj : function (e) {
if (this.dragObj){
e = Util.event(e);
var p = Util.getScroll();
var _t = p.t - this.scroll.t;
var _l = p.l - this.scroll.l;
var t = parseInt(this.dragObj.style.top);
var l = parseInt(this.dragObj.style.left);
t += _t;
l += _l;
this.dragObj.style.top =t+'px';
this.dragObj.style.left =l+'px';
this.scroll = Util.getScroll();
}
},
drag : function (e) {
e = Util.event(e);
if(!this.isDragging) {
this.dragObj.style.filter = "alpha(opacity=60)" ;
this.dragObj.style.opacity = 0.6 ;
this.isDragging = true ;
}
var _clientX = e.clientX;
var _clientY = e.clientY;
if (this.dragObj.lastMouseX == _clientX && this.dragObj.lastMouseY == _clientY) return false ;
var _lastY = parseInt(this.dragObj.style.top);
var _lastX = parseInt(this.dragObj.style.left);
_lastX = isNaN(_lastX) ? 0 :_lastX;
_lastY = isNaN(_lastY) ? 0 :_lastY;
var newX, newY;
newY = _lastY + _clientY - this.dragObj.lastMouseY;
newX = _lastX + _clientX - this.dragObj.lastMouseX;
this.dragObj.style.left = newX +"px ";
this.dragObj.style.top = newY + "px ";
this.dragObj.lastMouseX = _clientX;
this.dragObj.lastMouseY = _clientY;
var obj = this.getCurrentOverObj(e);
if (obj && this.overObj != obj) {
this.overObj = obj;
this.getTmpBoxElement();
Util.insertBefore(this.tmpBoxElement, this.overObj);
this.dragObjFrame = this.dragObj.parentNode.parentNode;
this.overObjFrame = this.overObj.parentNode.parentNode;
}
Util.cancelSelect();
},
_pushTabContent : function (tab, ele){
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
var dom = $(ele.id+'_content');
if (!dom) {
dom = document.createElement('div');
dom.id = ele.id+'_content';
dom.className = Util.hasClass(ele, this.frameClass) ? this.contentClass+' cl '+ele.className.substr(ele.className.lastIndexOf(' ')+1) : this.contentClass+' cl';
}
var frame = this.getObjByName(ele.id);
if (frame) {
for (var i in frame['columns']) {
if (frame['columns'][i] instanceof Column) dom.appendChild($(i));
}
} else {
var children = ele.childNodes;
var arrDom = [];
for (var i in children) {
if (typeof children[i] != 'object') continue;
if (Util.hasClass(children[i],this.moveableColumn) || Util.hasClass(children[i],this.tabContentClass)) {
arrDom.push(children[i]);
}
}
var len = arrDom.length;
for (var i = 0; i < len; i++) {
dom.appendChild(arrDom[i]);
}
}
$(tab.id+'_content').appendChild(dom);
} else if (Util.hasClass(ele, this.blockClass)) {
if ($(ele.id+'_content')) $(tab.id+'_content').appendChild($(ele.id+'_content'));
}
},
_popTabContent : function (tab, ele){
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
Util.removeClass(ele, this.tabActivityClass);
var eleContent = $(ele.id+'_content');
if (!eleContent) return false;
var children = eleContent.childNodes;
var arrEle = [];
for (var i in children) {
if (typeof children[i] == 'object') arrEle.push(children[i]);
}
var len = arrEle.length;
for (var i = 0; i < len; i++) {
ele.appendChild(arrEle[i]);
}
children = '';
$(tab.id+'_content').removeChild(eleContent);
} else if (Util.hasClass(ele, this.blockClass)) {
if ($(ele.id+'_content')) Util.show($(ele.id+'_content'));
if ($(ele.id+'_content')) ele.appendChild($(ele.id+'_content'));
}
},
_initTabActivity : function (ele) {
if (!Util.hasClass(ele,this.tabClass)) return false;
var tabs = $(ele.id+'_title').childNodes;
var arrTab = [];
for (var i in tabs) {
if (typeof tabs[i] != 'object') continue;
var tabId = tabs[i].id;
if (Util.hasClass(tabs[i],this.frameClass) || Util.hasClass(tabs[i],this.tabClass)) {
if (!this._replaceFlag) this._replaceFrameColumn(tabs[i]);
if (!$(tabId + '_content')) {
var arrColumn = [];
for (var j in tabs[i].childNodes) {
if (Util.hasClass(tabs[i].childNodes[j], this.moveableColumn)) arrColumn.push(tabs[i].childNodes[j]);
}
var frameContent = document.createElement('div');
frameContent.id = tabId + '_content';
frameContent.className = Util.hasClass(tabs[i], this.frameClass) ? this.contentClass+' cl '+tabs[i].className.substr(tabs[i].className.lastIndexOf(' ')+1) : this.contentClass+' cl';
var colLen = arrColumn.length;
for (var k = 0; k < colLen; k++) {
frameContent.appendChild(arrColumn[k]);
}
}
arrTab.push(tabs[i]);
} else if (Util.hasClass(tabs[i],this.blockClass)) {
var frameContent = $(tabId+'_content');
if (frameContent) {
frameContent = Util.hasClass(frameContent.parentNode,this.blockClass) ? frameContent : '';
} else {
frameContent = document.createElement('div');
frameContent.id = tabId+'_content';
}
arrTab.push(tabs[i]);
}
if (frameContent) $(ele.id + '_content').appendChild(frameContent);
}
var len = arrTab.length;
for (var i = 0; i < len; i++) {
Util[i > 0 ? 'hide' : 'show']($(arrTab[i].id+'_content'));
}
},
dragEnd : function (e) {
e = Util.event(e);
if(!this.dragObj) {return false;}
document.onscroll = function(){};
window.onscroll = function(){};
document.onmousemove = function(e){};
document.onmouseup = '';
if (this.tmpBoxElement.parentNode) {
if (this.tmpBoxElement.parentNode == document.body) {
document.body.removeChild(this.tmpBoxElement);
document.body.removeChild(this.dragObj);
this.fn = '';
} else {
Util.removeClass(this.dragObj,this.moving);
this.dragObj.style.display = 'none';
this.dragObj.style.width = '' ;
this.dragObj.style.top = '';
this.dragObj.style.left = '';
this.dragObj.style.zIndex = '';
this.dragObj.style.position = 'relative';
this.dragObj.style.backgroundColor = '';
this.isDragging = false ;
this.tmpBoxElement.parentNode.replaceChild(this.dragObj, this.tmpBoxElement);
Util.fadeIn(this.dragObj);
this.tmpBoxElement='';
this._setCssPosition(this.dragObjFrame, 'relative');
this.doEndDrag();
this.initPosition();
if (!(this.dargRelative.up == this.dragObj.previousSibling && this.dargRelative.down == this.dragObj.nextSibling)) {
this.setClose();
}
this.dragObjFrame = this.overObjFrame = null;
}
}
this.newFlag = false;
if (typeof this.fn == 'function') {this.fn();}
},
doEndDrag : function () {
if (!Util.hasClass(this.dragObjFrame, this.tabClass) && Util.hasClass(this.overObjFrame, this.tabClass)) {
this._pushTabContent(this.overObjFrame, this.dragObj);
}else if (Util.hasClass(this.dragObjFrame, this.tabClass) && !Util.hasClass(this.overObjFrame, this.tabClass)) {
this._popTabContent(this.dragObjFrame, this.dragObj);
}else if (Util.hasClass(this.dragObjFrame, this.tabClass) && Util.hasClass(this.overObjFrame, this.tabClass)) {
if (this.dragObjFrame != this.overObjFrame) {
this._popTabContent(this.dragObjFrame, this.dragObj);
this._pushTabContent(this.overObjFrame, this.dragObj);
}
} else {
}
},
_replaceFrameColumn : function (ele,flag) {
var children = ele.childNodes;
var fcn = ele.className.match(/(frame-[\w-]*)/);
if (!fcn) return false;
var frameClassName = fcn[1];
for (var i in children) {
if (Util.hasClass(children[i], this.moveableColumn)) {
var className = children[i].className;
className = className.replace(' col-l', ' '+frameClassName+'-l');
className = className.replace(' col-r', ' '+frameClassName+'-r');
className = className.replace(' col-c', ' '+frameClassName+'-c');
className = className.replace(' mn', ' '+frameClassName+'-l');
className = className.replace(' sd', ' '+frameClassName+'-r');
children[i].className = className;
}
}
},
stopCmd : function () {
this.rein.length > 0 ? this.rein.pop()() : '';
},
setClose : function () {
if (!this.isChange) {
window.onbeforeunload = function() {
return '您的数据已经修改,退出将无法保存您的修改。';
};
}
this.isChange = true;
},
clearClose : function () {
this.isChange = false;
window.onbeforeunload = function () {};
},
_getMoveableArea : function (ele) {
ele = ele ? ele : document.body;
this.moveableArea = $C(this.areaClass, ele, 'div');
},
initMoveableArea : function () {
var _method = this;
this._getMoveableArea();
var len = this.moveableArea.length;
for (var i = 0; i < len; i++) {
var el = this.moveableArea[i];
if (el == null || typeof el == 'undefined') return false;
el.ondragstart = function (e) {return false;};
el.onmouseover = function (e) {Drag.prototype.initDragObj.call(_method, e);};
el.onmousedown = function (e) {Drag.prototype.dragStart.call(_method, e);};
el.onmouseup = function (e) {Drag.prototype.dragEnd.call(_method, e);};
el.onclick = function (e) {e = Util.event(e);e.preventDefault();};
}
if ($('contentframe')) $('contentframe').ondragstart = function (e) {return false;};
},
disableAdvancedStyleSheet : function () {
if(this.advancedStyleSheet) {
this.advancedStyleSheet.disabled = true;
}
},
enableAdvancedStyleSheet : function () {
if(this.advancedStyleSheet) {
this.advancedStyleSheet.disabled = false;
}
},
getStyleSheetIndex : function (name) {
var index = -1;
var all = document.styleSheets;
for (var i=0;i<all.length;i++) {
var ownerNode = all[i].ownerNode || all[i].owningElement;
if (ownerNode.id && ownerNode.id == name) {
index = i;
break;
}
}
return index;
},
init : function (sampleMode) {
this.initCommon();
this.setSampleMode(sampleMode);
if(!this.sampleMode) {
this.initAdvanced();
} else {
this.initSample();
}
return true;
},
initAdvanced : function () {
this.initMoveableArea();
this.initPosition();
this.setDefalutMenu();
this.enableAdvancedStyleSheet();
this.showControlPanel();
this.initTips();
if(this.goonDIY) this.goonDIY();
this.openfn();
},
openfn : function () {
var openfn = loadUserdata('openfn');
if(openfn) {
if(typeof openfn == 'function') {
openfn();
} else {
eval(openfn);
}
saveUserdata('openfn', '');
}
},
initCommon : function () {
var index = this.getStyleSheetIndex('diy_common');
this.advancedStyleSheet = index != -1 ? document.styleSheets[index] : null;
this.menu = [];
},
initSample : function () {
this._getMoveableArea();
this.initPosition();
this.sampleBlocks = $C(this.blockClass);
this.initSampleBlocks();
this.disableAdvancedStyleSheet('diy_common');
this.setSampleMenu();
this.disableAdvancedStyleSheet();
this.hideControlPanel();
},
initSampleBlocks : function () {
if(this.sampleBlocks) {
for(var i = 0; i < this.sampleBlocks.length; i++){
this.checkEdit(this.sampleBlocks[i]);
}
}
},
setSampleMode : function (sampleMode) {
if(loadUserdata('diy_advance_mode')) {
this.sampleMode = '';
} else {
this.sampleMode = sampleMode;
saveUserdata('diy_advance_mode', sampleMode ? '' : '1');
}
},
hideControlPanel : function() {
Util.show('samplepanel');
Util.hide('controlpanel');
Util.hide('diy-tg');
},
showControlPanel : function() {
Util.hide('samplepanel');
Util.show('controlpanel');
Util.show('diy-tg');
},
checkHasFrame : function (obj) {
obj = !obj ? this.data : obj;
for (var i in obj) {
if (obj[i] instanceof Frame && obj[i].className.indexOf('temp') < 0 ) {
return true;
} else if (typeof obj[i] == 'object') {
if (this.checkHasFrame(obj[i])) return true;
}
}
return false;
},
deleteFrame : function (name) {
if (typeof name == 'string') {
if (typeof window['c'+name+'_frame'] == 'object' && !BROWSER.ie) delete window['c'+name+'_frame'];
} else {
for(var i = 0,L = name.length;i < L;i++) {
if (typeof window['c'+name[i]+'_frame'] == 'object' && !BROWSER.ie) delete window['c'+name[i]+'_frame'];
}
}
},
saveViewTip : function (tipname) {
if(tipname) {
saveUserdata(tipname, '1');
Util.hide(tipname);
}
doane();
},
initTips : function () {
var tips = ['diy_backup_tip'];
for(var i = 0; i < tips.length; i++) {
if(tips[i] && !loadUserdata(tips[i])) {
Util.show(tips[i]);
}
}
},
extend : function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
DIY = function() {
this.frames = [];
this.isChange = false;
this.spacecss = [];
this.style = 't1';
this.currentDiy = 'body';
this.opSet = [];
this.opPointer = 0;
this.backFlag = false;
this.styleSheet = {} ;
this.scrollHeight = 0 ;
};
DIY.prototype = {
init : function (mod) {
drag.init(mod);
this.style = document.diyform.style.value;
if (this.style == '') {
var reg = RegExp('topic\(.*)\/style\.css');
var href = $('style_css') ? $('style_css').href : '';
var arr = reg.exec(href);
this.style = arr && arr.length > 1 ? arr[1] : '';
}
this.currentLayout = typeof document.diyform.currentlayout == 'undefined' ? '' : document.diyform.currentlayout.value;
this.initStyleSheet();
if (this.styleSheet.rules) this.initDiyStyle();
},
initStyleSheet : function () {
var all = document.styleSheets;
for (var i=0;i<all.length;i++) {
var ownerNode = all[i].ownerNode || all[i].owningElement;
if (ownerNode.id == 'diy_style') {
this.styleSheet = new styleCss(i);
return true;
}
}
},
initDiyStyle : function (css) {
var allCssText = css || $('diy_style').innerHTML;
allCssText = allCssText ? allCssText.replace(/\n|\r|\t| /g,'') : '';
var random = Math.random(), rules = '';
var reg = new RegExp('(.*?) ?\{(.*?)\}','g');
while((rules = reg.exec(allCssText))) {
var selector = this.checkSelector(rules[1]);
var cssText = rules[2];
var cssarr = cssText.split(';');
var l = cssarr.length;
for (var k = 0; k < l; k++) {
var attribute = trim(cssarr[k].substr(0, cssarr[k].indexOf(':')).toLowerCase());
var value = cssarr[k].substr(cssarr[k].indexOf(':')+1).toLowerCase();
if (!attribute || !value) continue;
if (!this.spacecss[selector]) this.spacecss[selector] = [];
this.spacecss[selector][attribute] = value;
if (css) this.setStyle(selector, attribute, value, random);
}
}
},
checkSelector : function (selector) {
var s = selector.toLowerCase();
if (s.toLowerCase().indexOf('body') > -1) {
var body = BROWSER.ie ? 'BODY' : 'body';
selector = selector.replace(/body/i,body);
}
if (s.indexOf(' a') > -1) {
selector = BROWSER.ie ? selector.replace(/ [aA]/,' A') : selector.replace(/ [aA]/,' a');
}
return selector;
},
initPalette : function (id) {
var bgcolor = '',selector = '',bgimg = '',bgrepeat = '', bgposition = '', bgattachment = '', bgfontColor = '', bglinkColor = '', i = 0;
var repeat = ['repeat','no-repeat','repeat-x','repeat-y'];
var attachment = ['scroll','fixed'];
var position = ['left top','center top','right top','left center','center center','right center','left bottom','center bottom','right bottom'];
var position_ = ['0% 0%','50% 0%','100% 0%','0% 50%','50% 50%','100% 50%','0% 100%','50% 100%','100% 100%'];
selector = this.getSelector(id);
bgcolor = Util.formatColor(this.styleSheet.getRule(selector,'backgroundColor'));
bgimg = this.styleSheet.getRule(selector,'backgroundImage');
bgrepeat = this.styleSheet.getRule(selector,'backgroundRepeat');
bgposition = this.styleSheet.getRule(selector,'backgroundPosition');
bgattachment = this.styleSheet.getRule(selector,'backgroundAttachment');
bgfontColor = Util.formatColor(this.styleSheet.getRule(selector,'color'));
bglinkColor = Util.formatColor(this.styleSheet.getRule(this.getSelector(selector+' a'),'color'));
var selectedIndex = 0;
for (i=0;i<repeat.length;i++) {
if (bgrepeat == repeat[i]) selectedIndex= i;
}
$('repeat_mode').selectedIndex = selectedIndex;
for (i=0;i<attachment.length;i++) {
$('rabga'+i).checked = (bgattachment == attachment[i] ? true : false);
}
var flag = '';
for (i=0;i<position.length;i++) {
var className = bgposition == position[i] ? 'red' : '';
$('bgimgposition'+i).className = className;
flag = flag ? flag : className;
}
if (flag != 'red') {
for (i=0;i<position_.length;i++) {
className = bgposition == position_[i] ? 'red' : '';
$('bgimgposition'+i).className = className;
}
}
$('colorValue').value = bgcolor;
if ($('cbpb')) $('cbpb').style.backgroundColor = bgcolor;
$('textColorValue').value = bgfontColor;
if ($('ctpb')) $('ctpb').style.backgroundColor = bgfontColor;
$('linkColorValue').value = bglinkColor;
if ($('clpb')) $('clpb').style.backgroundColor = bglinkColor;
Util.show($('currentimgdiv'));
Util.hide($('diyimages'));
if ($('selectalbum')) $('selectalbum').disabled = 'disabled';
bgimg = bgimg != '' && bgimg != 'none' ? bgimg.replace(/url\(['|"]{0,1}/,'').replace(/['|"]{0,1}\)/,'') : 'static/image/common/nophotosmall.gif';
$('currentimg').src = bgimg;
},
changeBgImgDiv : function () {
Util.hide($('currentimgdiv'));
Util.show($('diyimages'));
if ($('selectalbum')) $('selectalbum').disabled = '';
},
getSpacecssStr : function() {
var css = '';
var selectors = ['body', '#hd','#ct', 'BODY'];
for (var i in this.spacecss) {
var name = i.split(' ')[0];
if(selectors.indexOf(name) == -1 && !drag.getObjByName(name.substr(1))) {
for(var k in this.spacecss) {
if (k.indexOf(i) > -1) {
this.spacecss[k] = [];
}
}
continue;
}
var rule = this.spacecss[i];
if (typeof rule == "function") continue;
var one = '';
rule = this.formatCssRule(rule);
for (var j in rule) {
var content = this.spacecss[i][j];
if (content && typeof content == "string" && content.length > 0) {
content = this.trimCssImportant(content);
content = content ? content + ' !important;' : ';';
one += j + ":" + content;
}
}
if (one == '') continue;
css += i + " {" + one + "}";
}
return css;
},
formatCssRule : function (rule) {
var arr = ['top', 'right', 'bottom', 'left'], i = 0;
if (typeof rule['margin-top'] != 'undefined') {
var margin = rule['margin-bottom'];
if (margin && margin == rule['margin-top'] && margin == rule['margin-right'] && margin == rule['margin-left']) {
rule['margin'] = margin;
for(i=0;i<arr.length;i++) {
delete rule['margin-'+arr[i]];
}
} else {
delete rule['margin'];
}
}
var border = '', borderb = '', borderr = '', borderl = '';
if (typeof rule['border-top-color'] != 'undefined' || typeof rule['border-top-width'] != 'undefined' || typeof rule['border-top-style'] != 'undefined') {
var format = function (css) {
css = css.join(' ').replace(/!( ?)important/g,'').replace(/ /g,' ').replace(/^ | $/g,'');
return css ? css + ' !important' : '';
};
border = format([rule['border-top-color'], rule['border-top-width'], rule['border-top-style']]);
borderr = format([rule['border-right-color'], rule['border-right-width'], rule['border-right-style']]);
borderb = format([rule['border-bottom-color'], rule['border-bottom-width'], rule['border-bottom-style']]);
borderl = format([rule['border-left-color'], rule['border-left-width'], rule['border-left-style']]);
} else if (typeof rule['border-top'] != 'undefined') {
border = rule['border-top'];borderr = rule['border-right'];borderb = rule['border-bottom'];borderl = rule['border-left'];
}
if (border) {
if (border == borderb && border == borderr && border == borderl) {
rule['border'] = border;
for(i=0;i<arr.length;i++) {
delete rule['border-'+arr[i]];
}
} else {
rule['border-top'] = border;rule['border-right'] = borderr;rule['border-bottom'] = borderb;rule['border-left'] = borderl;
delete rule['border'];
}
for(i=0;i<arr.length;i++) {
delete rule['border-'+arr[i]+'-color'];delete rule['border-'+arr[i]+'-width'];delete rule['border-'+arr[i]+'-style'];
}
}
return rule;
},
changeLayout : function (newLayout) {
if (this.currentLayout == newLayout) return false;
var data = $('layout'+newLayout).getAttribute('data');
var dataArr = data.split(' ');
var currentLayoutLength = this.currentLayout.length;
var newLayoutLength = newLayout.length;
if (newLayoutLength == currentLayoutLength){
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
if (typeof(dataArr[2]) != 'undefined') $('frame1_right').style.width = dataArr[2]+'px';
} else if (newLayoutLength > currentLayoutLength) {
var block = this.getRandomBlockName();
var dom = document.createElement('div');
dom.id = 'frame1_right';
dom.className = drag.moveableColumn + ' z';
dom.appendChild($(block));
$('frame1').appendChild(dom);
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
dom.style.width = dataArr[2]+'px';
} else if (newLayoutLength < currentLayoutLength) {
var _length = drag.data['diypage'][0]['columns']['frame1_right']['children'].length;
var tobj = $('frame1_center_temp');
for (var i = 0; i < _length; i++) {
var name = drag.data['diypage'][0]['columns']['frame1_right']['children'][i].name;
if (name.indexOf('temp') < 0) $('frame1_center').insertBefore($(name),tobj);
}
$('frame1').removeChild($('frame1_right'));
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
}
var className = $('layout'+this.currentLayout).className;
$('layout'+this.currentLayout).className = '';
$('layout'+newLayout).className = className;
this.currentLayout = newLayout;
drag.initPosition();
drag.setClose();
},
getRandomBlockName : function () {
var left = drag.data['diypage'][0]['columns']['frame1_left']['children'];
if (left.length > 2) {
var block = left[0];
} else {
var block = drag.data['diypage'][0]['columns']['frame1_center']['children'][0];
}
return block.name;
},
changeStyle : function (t) {
if (t == '') return false;
$('style_css').href=STATICURL+t+"/style.css";
if (!this.backFlag) {
var oldData = [this.style];
var newData = [t];
var random = Math.random();
this.addOpRecord ('this.changeStyle', newData, oldData, random);
}
var arr = t.split("/");
this.style = arr[arr.length-1];
drag.setClose();
},
setCurrentDiy : function (type) {
if (type) {
$('diy_tag_'+this.currentDiy).className = '';
this.currentDiy = type;
$('diy_tag_'+this.currentDiy).className = 'activity';
this.initPalette(this.currentDiy);
}
},
hideBg : function () {
var random = Math.random();
this.setStyle(this.currentDiy, 'background-image', '', random);
this.setStyle(this.currentDiy, 'background-color', '', random);
if (this.currentDiy == 'hd') this.setStyle(this.currentDiy, 'height', '', random);
this.initPalette(this.currentDiy);
},
toggleHeader : function () {
var random = Math.random();
if ($('header_hide_cb').checked) {
this.setStyle('#hd', 'height', '260px', random);
this.setStyle('#hd', 'background-image', 'none', random);
this.setStyle('#hd', 'border-width', '0px', random);
} else {
this.setStyle('#hd', 'height', '', random);
this.setStyle('#hd', 'background-image', '', random);
this.setStyle('#hd', 'border-width', '', random);
}
},
setBgImage : function (value) {
var path = typeof value == "string" ? value : value.src;
if (path.indexOf('.thumb') > 0) {
path = path.substring(0,path.indexOf('.thumb'));
}
if (path == '' || path == 'undefined') return false;
var random = Math.random();
this.setStyle(this.currentDiy, 'background-image', Util.url(path), random);
this.setStyle(this.currentDiy, 'background-repeat', 'repeat', random);
if (this.currentDiy == 'hd') {
var _method = this;
var img = new Image();
img.onload = function () {
if (parseInt(img.height) < 140) {
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'background-repeat', 'repeat', random);
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'height', '', random);
} else {
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'height', img.height+"px", random);
}
};
img.src = path;
}
},
setBgRepeat : function (value) {
var repeat = ['repeat','no-repeat','repeat-x','repeat-y'];
if (typeof repeat[value] == 'undefined') {return false;}
this.setStyle(this.currentDiy, 'background-repeat', repeat[value]);
},
setBgAttachment : function (value) {
var attachment = ['scroll','fixed'];
if (typeof attachment[value] == 'undefined') {return false;}
this.setStyle(this.currentDiy, 'background-attachment', attachment[value]);
},
setBgColor : function (color) {
this.setStyle(this.currentDiy, 'background-color', color);
},
setTextColor : function (color) {
this.setStyle(this.currentDiy, 'color', color);
},
setLinkColor : function (color) {
this.setStyle(this.currentDiy + ' a', 'color', color);
},
setBgPosition : function (id) {
var td = $(id);
var i = id.substr(id.length-1);
var position = ['left top','center top','right top','left center','center center','right center','left bottom','center bottom','right bottom'];
td.className = 'red';
for (var j=0;j<9;j++) {
if (i != j) {
$('bgimgposition'+j).className = '';
}
}
this.setStyle(this.currentDiy, 'background-position', position[i]);
},
getSelector : function (currentDiv) {
var arr = currentDiv.split(' ');
currentDiv = arr[0];
var link = '';
if (arr.length > 1) {
link = (arr[arr.length-1].toLowerCase() == 'a') ? link = ' '+arr.pop() : '';
currentDiv = arr.join(' ');
}
var selector = '';
switch(currentDiv) {
case 'blocktitle' :
selector = '#ct .move-span .blocktitle';
break;
case 'body' :
case 'BODY' :
selector = BROWSER.ie ? 'BODY' : 'body';
break;
default :
selector = currentDiv.indexOf("#")>-1 ? currentDiv : "#"+currentDiv;
}
var rega = BROWSER.ie ? ' A' : ' a';
selector = (selector+link).replace(/ a/i,rega);
return selector;
},
setStyle : function (currentDiv, property, value, random, num){
property = trim(property).toLowerCase();
var propertyJs = property.property2js();
if (typeof value == 'undefined') value = '';
var selector = this.getSelector(currentDiv);
if (!this.backFlag) {
var rule = this.styleSheet.getRule(selector,propertyJs);
rule = rule.replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
var oldData = [currentDiv, property, rule];
var newData = [currentDiv, property, value];
if (typeof random == 'undefined') random = Math.random();
this.addOpRecord ('this.setStyle', newData, oldData, random);
}
value = this.trimCssImportant(value);
value = value ? value + ' !important' : '';
var pvalue = value ? property+':'+value : '';
this.styleSheet.addRule(selector,pvalue,num,property);
Util.recolored();
if (typeof this.spacecss[selector] == 'undefined') {
this.spacecss[selector] = [];
}
this.spacecss[selector][property] = value;
drag.setClose();
},
trimCssImportant : function (value) {
if (value instanceof Array) value = value.join(' ');
return value ? value.replace(/!( ?)important/g,'').replace(/ /g,' ').replace(/^ | $/g,'') : '';
},
removeCssSelector : function (selector) {
for (var i in this.spacecss) {
if (typeof this.spacecss[i] == "function") continue;
if (i.indexOf(selector) > -1) {
this.styleSheet.removeRule(i);
this.spacecss[i] = [];
}
}
},
undo : function () {
if (this.opSet.length == 0) return false;
var oldData = '';
if (this.opPointer <= 0) {return '';}
var step = this.opSet[--this.opPointer];
var random = step['random'];
var cmd = step['cmd'].split(',');
var cmdNum = cmd.length;
if (cmdNum >1) {
for (var i=0; i<cmdNum; i++) {
oldData = typeof step['oldData'][i] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['oldData'][i].join('","') + '"';
this.backFlag = true;
eval(cmd[i]+'('+oldData+')');
this.backFlag = false;
}
} else {
oldData = typeof step['oldData'] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['oldData'].join('","') + '"';
this.backFlag = true;
eval(cmd+'('+oldData+')');
this.backFlag = false;
}
$('button_redo').className = '';
if (this.opPointer == 0) {
$('button_undo').className = 'unusable';
drag.isChange = false;
drag.clearClose();
return '';
} else if (random == this.opSet[this.opPointer-1]['random']) {
this.undo();
return '';
} else {
return '';
}
},
redo : function () {
if (this.opSet.length == 0) return false;
var newData = '',random = '';
if (this.opPointer >= this.opSet.length) return '';
var step = this.opSet[this.opPointer++];
random = step['random'];
var cmd = step['cmd'].split(',');
var cmdNum = cmd.length;
if (cmdNum >1) {
for (var i=0; i<cmdNum; i++) {
newData = typeof step['newData'][i] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['newData'][i].join('","') + '"';
this.backFlag = true;
eval(cmd[i]+'('+newData+')');
this.backFlag = false;
}
}else {
newData = typeof step['newData'] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['newData'].join('","') + '"';
this.backFlag = true;
eval(cmd+'('+newData+')');
this.backFlag = false;
}
$('button_undo').className = '';
if (this.opPointer == this.opSet.length) {
$('button_redo').className = 'unusable';
return '';
} else if(random == this.opSet[this.opPointer]['random']){
this.redo();
}
},
addOpRecord : function (cmd, newData, oldData, random) {
if (this.opPointer == 0) this.opSet = [];
this.opSet[this.opPointer++] = {'cmd':cmd, 'newData':newData, 'oldData':oldData, 'random':random};
$('button_undo').className = '';
$('button_redo').className = 'unusable';
Util.show('recover_button');
},
recoverStyle : function () {
var random = Math.random();
for (var selector in this.spacecss){
var style = this.spacecss[selector];
if (typeof style == "function") {continue;}
for (var attribute in style) {
if (typeof style[attribute] == "function") {continue;}
this.setStyle(selector,attribute,'',random);
}
}
Util.hide('recover_button');
drag.setClose();
this.initPalette(this.currentDiy);
},
uploadSubmit : function (){
if (document.uploadpic.attach.value.length<3) {
alert('请选择您要上传的图片');
return false;
}
if (document.uploadpic.albumid != null) document.uploadpic.albumid.value = $('selectalbum').value;
return true;
},
save : function () {
return false;
},
cancel : function () {
var flag = false;
if (this.isChange) {
flag = confirm(this.cancelConfirm ? this.cancelConfirm : '退出将不会保存您刚才的设置。是否确认退出?');
}
if (!this.isChange || flag) {
location.href = location.href.replace(/[\?|\&]diy\=yes/g,'');
}
},
extend : function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_drag.js 17522 2010-10-20 13:57:03Z monkey $
*/
var Drags = [];
var nDrags = 1;
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;
var dragObject = null;
var DragDrops = [];
var curTarget = null;
var lastTarget = null;
var dragHelper = null;
var tempDiv = null;
var rootParent = null;
var rootSibling = null;
var D1Target = null;
Number.prototype.NaN0=function(){return isNaN(this)?0:this;};
function CreateDragContainer(){
var cDrag = DragDrops.length;
DragDrops[cDrag] = [];
for(var i=0; i<arguments.length; i++){
var cObj = arguments[i];
DragDrops[cDrag].push(cObj);
cObj.setAttribute('DropObj', cDrag);
for(var j=0; j<cObj.childNodes.length; j++){
if(cObj.childNodes[j].nodeName=='#text') continue;
cObj.childNodes[j].setAttribute('DragObj', cDrag);
}
}
}
function getPosition(e){
var left = 0;
var top = 0;
while (e.offsetParent){
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
e = e.offsetParent;
}
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
return {x:left, y:top};
}
function mouseCoords(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
};
}
function writeHistory(object, message){
if(!object || !object.parentNode || typeof object.parentNode.getAttribute == 'unknown' || !object.parentNode.getAttribute) return;
var historyDiv = object.parentNode.getAttribute('history');
if(historyDiv){
historyDiv = document.getElementById(historyDiv);
historyDiv.appendChild(document.createTextNode(object.id+': '+message));
historyDiv.appendChild(document.createElement('BR'));
historyDiv.scrollTop += 50;
}
}
function getMouseOffset(target, ev){
ev = ev || window.event;
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}
function mouseMove(ev){
ev = ev || window.event;
var target = ev.target || ev.srcElement;
var mousePos = mouseCoords(ev);
if(Drags[0]){
if(lastTarget && (target!==lastTarget)){
writeHistory(lastTarget, 'Mouse Out Fired');
var origClass = lastTarget.getAttribute('origClass');
if(origClass) lastTarget.className = origClass;
}
var dragObj = target.getAttribute('DragObj');
if(dragObj!=null){
if(target!=lastTarget){
writeHistory(target, 'Mouse Over Fired');
var oClass = target.getAttribute('overClass');
if(oClass){
target.setAttribute('origClass', target.className);
target.className = oClass;
}
}
if(iMouseDown && !lMouseState){
writeHistory(target, 'Start Dragging');
curTarget = target;
rootParent = curTarget.parentNode;
rootSibling = curTarget.nextSibling;
mouseOffset = getMouseOffset(target, ev);
for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);
dragHelper.appendChild(curTarget.cloneNode(true));
dragHelper.style.display = 'block';
var dragClass = curTarget.getAttribute('dragClass');
if(dragClass){
dragHelper.firstChild.className = dragClass;
}
dragHelper.firstChild.removeAttribute('DragObj');
var dragConts = DragDrops[dragObj];
curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth));
curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
curTarget.style.display = 'none';
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
var pos = getPosition(dragConts[i]);
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
for(var j=0; j<dragConts[i].childNodes.length; j++){
with(dragConts[i].childNodes[j]){
if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;
var pos = getPosition(dragConts[i].childNodes[j]);
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
}
}
}
}
if(curTarget){
dragHelper.style.top = (mousePos.y - mouseOffset.y)+"px";
dragHelper.style.left = (mousePos.x - mouseOffset.x)+"px";
var dragConts = DragDrops[curTarget.getAttribute('DragObj')];
var activeCont = null;
var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
if((parseInt(getAttribute('startLeft')) < xPos) &&
(parseInt(getAttribute('startTop')) < yPos) &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
activeCont = dragConts[i];
break;
}
}
}
if(activeCont){
if(activeCont!=curTarget.parentNode){
writeHistory(curTarget, 'Moved into '+activeCont.id);
}
var beforeNode = null;
for(var i=activeCont.childNodes.length-1; i>=0; i--){
with(activeCont.childNodes[i]){
if(nodeName=='#text') continue;
if(curTarget != activeCont.childNodes[i] &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
beforeNode = activeCont.childNodes[i];
}
}
}
if(beforeNode){
if(beforeNode!=curTarget.nextSibling){
writeHistory(curTarget, 'Inserted Before '+beforeNode.id);
activeCont.insertBefore(curTarget, beforeNode);
}
} else {
if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
writeHistory(curTarget, 'Inserted at end of '+activeCont.id);
activeCont.appendChild(curTarget);
}
}
setTimeout(function(){
var contPos = getPosition(activeCont);
activeCont.setAttribute('startWidth', parseInt(activeCont.offsetWidth));
activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
activeCont.setAttribute('startLeft', contPos.x);
activeCont.setAttribute('startTop', contPos.y);}, 5);
if(curTarget.style.display!=''){
writeHistory(curTarget, 'Made Visible');
curTarget.style.display = '';
curTarget.style.visibility = 'hidden';
}
} else {
if(curTarget.style.display!='none'){
writeHistory(curTarget, 'Hidden');
curTarget.style.display = 'none';
}
}
}
lMouseState = iMouseDown;
lastTarget = target;
}
if(dragObject){
dragObject.style.position = 'absolute';
dragObject.style.top = mousePos.y - mouseOffset.y;
dragObject.style.left = mousePos.x - mouseOffset.x;
}
lMouseState = iMouseDown;
if(curTarget || dragObject) return false;
}
function mouseUp(ev){
if(Drags[0]){
if(curTarget){
writeHistory(curTarget, 'Mouse Up Fired');
dragHelper.style.display = 'none';
if(curTarget.style.display == 'none'){
if(rootSibling){
rootParent.insertBefore(curTarget, rootSibling);
} else {
rootParent.appendChild(curTarget);
}
}
curTarget.style.display = '';
curTarget.style.visibility = 'visible';
}
curTarget = null;
}
dragObject = null;
iMouseDown = false;
}
function mouseDown(ev){
mousedown(ev);
ev = ev || window.event;
var target = ev.target || ev.srcElement;
iMouseDown = true;
if(Drags[0]){
if(lastTarget){
writeHistory(lastTarget, 'Mouse Down Fired');
}
}
if(target.onmousedown || target.getAttribute('DragObj')){
return false;
}
}
function makeDraggable(item){
if(!item) return;
item.onmousedown = function(ev){
dragObject = this;
mouseOffset = getMouseOffset(this, ev);
return false;
}
}
function init_drag2(){
document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup = mouseUp;
Drags[0] = $('Drags0');
if(Drags[0]){
CreateDragContainer($('DragContainer0'));
}
if(Drags[0]){
var cObj = $('applistcontent');
dragHelper = document.createElement('div');
dragHelper.style.cssName = "apps dragable";
dragHelper.style.cssText = 'position:absolute;display:none;width:374px;';
cObj.parentNode.insertBefore(dragHelper, cObj);
}
}
function mousedown(evnt){
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: smilies.js 21444 2011-03-25 10:12:35Z lifangming $
*/
function _smilies_show(id, smcols, seditorkey) {
if(seditorkey && !$(seditorkey + 'sml_menu')) {
var div = document.createElement("div");
div.id = seditorkey + 'sml_menu';
div.style.display = 'none';
div.className = 'sllt';
$('append_parent').appendChild(div);
var div = document.createElement("div");
div.id = id;
div.style.overflow = 'hidden';
$(seditorkey + 'sml_menu').appendChild(div);
}
if(typeof smilies_type == 'undefined') {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
scriptNode.src = 'data/cache/common_smilies_var.js?' + VERHASH;
$('append_parent').appendChild(scriptNode);
if(BROWSER.ie) {
scriptNode.onreadystatechange = function() {
smilies_onload(id, smcols, seditorkey);
};
} else {
scriptNode.onload = function() {
smilies_onload(id, smcols, seditorkey);
};
}
} else {
smilies_onload(id, smcols, seditorkey);
}
}
function smilies_onload(id, smcols, seditorkey) {
seditorkey = !seditorkey ? '' : seditorkey;
smile = getcookie('smile').split('D');
if(typeof smilies_type == 'object') {
if(smile[0] && smilies_array[smile[0]]) {
CURRENTSTYPE = smile[0];
} else {
for(i in smilies_array) {
CURRENTSTYPE = i;break;
}
}
smiliestype = '<div id="'+id+'_tb" class="tb tb_s cl"><ul>';
for(i in smilies_type) {
key = i.substring(1);
if(smilies_type[i][0]) {
smiliestype += '<li ' + (CURRENTSTYPE == key ? 'class="current"' : '') + ' id="'+seditorkey+'stype_'+key+'" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', '+key+', 1, \'' + seditorkey + '\');if(CURRENTSTYPE) {$(\''+seditorkey+'stype_\'+CURRENTSTYPE).className=\'\';}this.className=\'current\';CURRENTSTYPE='+key+';doane(event);"><a href="javascript:;" hidefocus="true">'+smilies_type[i][0]+'</a></li>';
}
}
smiliestype += '</ul></div>';
$(id).innerHTML = smiliestype + '<div id="' + id + '_data"></div><div class="sllt_p" id="' + id + '_page"></div>';
smilies_switch(id, smcols, CURRENTSTYPE, smile[1], seditorkey);
smilies_fastdata = '';
if(seditorkey == 'fastpost' && $('fastsmilies') && smilies_fast) {
var j = 0;
for(i = 0;i < smilies_fast.length; i++) {
if(j == 0) {
smilies_fastdata += '<tr>';
}
j = ++j > 3 ? 0 : j;
s = smilies_array[smilies_fast[i][0]][smilies_fast[i][1]][smilies_fast[i][2]];
smilieimg = STATICURL + 'image/smiley/' + smilies_type['_' + smilies_fast[i][0]][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smilies_fastdata += s ? '<td onmouseover="smilies_preview(\'' + seditorkey + '\', \'fastsmiliesdiv\', this, ' + s[5] + ')" onmouseout="$(\'smilies_preview\').style.display = \'none\'" onclick="' + (typeof wysiwyg != 'undefined' ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'" id="' + seditorkey + 'smilie_' + s[0] + '_td"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
}
$('fastsmilies').innerHTML = '<table cellspacing="0" cellpadding="0"><tr>' + smilies_fastdata + '</tr></table>';
}
}
}
function smilies_switch(id, smcols, type, page, seditorkey) {
page = page ? page : 1;
if(!smilies_array[type] || !smilies_array[type][page]) return;
setcookie('smile', type + 'D' + page, 31536000);
smiliesdata = '<table id="' + id + '_table" cellpadding="0" cellspacing="0"><tr>';
j = k = 0;
img = [];
for(i in smilies_array[type][page]) {
if(j >= smcols) {
smiliesdata += '<tr>';
j = 0;
}
s = smilies_array[type][page][i];
smilieimg = STATICURL + 'image/smiley/' + smilies_type['_' + type][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smiliesdata += s && s[0] ? '<td onmouseover="smilies_preview(\'' + seditorkey + '\', \'' + id + '\', this, ' + s[5] + ')" onclick="' + (typeof wysiwyg != 'undefined' ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'" id="' + seditorkey + 'smilie_' + s[0] + '_td"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
j++;k++;
}
smiliesdata += '</table>';
smiliespage = '';
if(smilies_array[type].length > 2) {
prevpage = ((prevpage = parseInt(page) - 1) < 1) ? smilies_array[type].length - 1 : prevpage;
nextpage = ((nextpage = parseInt(page) + 1) == smilies_array[type].length) ? 1 : nextpage;
smiliespage = '<div class="z"><a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + prevpage + ', \'' + seditorkey + '\');doane(event);">上页</a>' +
'<a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + nextpage + ', \'' + seditorkey + '\');doane(event);">下页</a></div>' +
page + '/' + (smilies_array[type].length - 1);
}
$(id + '_data').innerHTML = smiliesdata;
$(id + '_page').innerHTML = smiliespage;
$(id + '_tb').style.width = smcols*(16+parseInt(s[3])) + 'px';
}
function smilies_preview(seditorkey, id, obj, w) {
var menu = $('smilies_preview');
if(!menu) {
menu = document.createElement('div');
menu.id = 'smilies_preview';
menu.className = 'sl_pv';
menu.style.display = 'none';
$('append_parent').appendChild(menu);
}
menu.innerHTML = '<img width="' + w + '" src="' + obj.childNodes[0].src + '" />';
mpos = fetchOffset($(id + '_data'));
spos = fetchOffset(obj);
pos = spos['left'] >= mpos['left'] + $(id + '_data').offsetWidth / 2 ? '13' : '24';
showMenu({'ctrlid':obj.id,'showid':id + '_data','menuid':menu.id,'pos':pos,'layer':3});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: register.js 22639 2011-05-16 07:05:16Z lifangming $
*/
var lastusername = '', lastpassword = '', lastemail = '', lastinvitecode = '', stmp = new Array();
function errormessage(id, msg) {
if($(id)) {
showInputTip();
msg = !msg ? '' : msg;
if($('tip_' + id)) {
if(msg == 'succeed') {
msg = '';
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
$('tip_' + id).parentNode.className += ' p_right';
} else if(msg !== '') {
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
}
}
if($('chk_' + id)) {
$('chk_' + id).innerHTML = msg;
}
$(id).className = !msg ? $(id).className.replace(/ er/, '') : $(id).className + ' er';
}
}
function addFormEvent(formid, focus){
var si = 0;
var formNode = $(formid).getElementsByTagName('input');
for(i = 0;i < formNode.length;i++) {
if(formNode[i].name == '') {
formNode[i].name = formNode[i].id;
stmp[si] = i;
si++;
}
if(formNode[i].type == 'text' || formNode[i].type == 'password'){
formNode[i].onfocus = function(){
showInputTip(!this.id ? this.name : this.id);
}
}
}
if(!si) {
return;
}
formNode[stmp[0]].onblur = function () {
checkusername(formNode[stmp[0]].id);
};
formNode[stmp[1]].onblur = function () {
if(formNode[stmp[1]].value == '') {
errormessage(formNode[stmp[1]].id, '请填写密码');
}else{
errormessage(formNode[stmp[1]].id, 'succeed');
}
checkpassword(formNode[stmp[1]].id, formNode[stmp[2]].id);
};
formNode[stmp[2]].onblur = function () {
if(formNode[stmp[2]].value == '') {
errormessage(formNode[stmp[2]].id, '请再次输入密码');
}
checkpassword(formNode[stmp[1]].id, formNode[stmp[2]].id);
};
formNode[stmp[3]].onclick = function (event) {
emailMenu(event, formNode[stmp[3]].id);
};
formNode[stmp[3]].onkeyup = function (event) {
emailMenu(event, formNode[stmp[3]].id);
};
formNode[stmp[3]].onkeydown = function (event) {
emailMenuOp(4, event, formNode[stmp[3]].id);
};
formNode[stmp[3]].onblur = function () {
if(formNode[stmp[3]].value == '') {
errormessage(formNode[stmp[3]].id, '请输入邮箱地址');
}
emailMenuOp(3, null, formNode[stmp[3]].id);
};
stmp['email'] = formNode[stmp[3]].id;
try {
if(focus) {
$('invitecode').focus();
} else {
formNode[stmp[0]].focus();
}
} catch(e) {}
}
function showInputTip(id) {
var p_tips = $('registerform').getElementsByTagName('i');
for(i = 0;i < p_tips.length;i++){
if(p_tips[i].className == 'p_tip'){
p_tips[i].style.display = 'none';
}
}
if($('tip_' + id)) {
$('tip_' + id).style.display = 'block';
}
}
function showbirthday(){
var el = $('birthday');
var birthday = el.value;
el.length=0;
el.options.add(new Option('日', ''));
for(var i=0;i<28;i++){
el.options.add(new Option(i+1, i+1));
}
if($('birthmonth').value!="2"){
el.options.add(new Option(29, 29));
el.options.add(new Option(30, 30));
switch($('birthmonth').value){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":{
el.options.add(new Option(31, 31));
}
}
} else if($('birthyear').value!="") {
var nbirthyear=$('birthyear').value;
if(nbirthyear%400==0 || (nbirthyear%4==0 && nbirthyear%100!=0)) el.options.add(new Option(29, 29));
}
el.value = birthday;
}
function trim(str) {
return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1');
}
var emailMenuST = null, emailMenui = 0, emaildomains = ['qq.com', '163.com', 'sina.com', 'sohu.com', 'yahoo.cn', 'gmail.com', 'hotmail.com'];
function emailMenuOp(op, e, id) {
if(op == 3 && BROWSER.ie && BROWSER.ie < 7) {
checkemail(id);
}
if(!$('emailmore_menu')) {
return;
}
if(op == 1) {
$('emailmore_menu').style.display = 'none';
} else if(op == 2) {
showMenu({'ctrlid':'emailmore','pos': '13!'});
} else if(op == 3) {
emailMenuST = setTimeout(function () {
emailMenuOp(1, id);
checkemail(id);
}, 500);
} else if(op == 4) {
e = e ? e : window.event;
var obj = $(id);
if(e.keyCode == 13) {
var v = obj.value.indexOf('@') != -1 ? obj.value.substring(0, obj.value.indexOf('@')) : obj.value;
obj.value = v + '@' + emaildomains[emailMenui];
doane(e);
}
} else if(op == 5) {
var as = $('emailmore_menu').getElementsByTagName('a');
for(i = 0;i < as.length;i++){
as[i].className = '';
}
}
}
function emailMenu(e, id) {
if(BROWSER.ie && BROWSER.ie < 7) {
return;
}
e = e ? e : window.event;
var obj = $(id);
if(obj.value.indexOf('@') != -1) {
$('emailmore_menu').style.display = 'none';
return;
}
var value = e.keyCode;
var v = obj.value;
if(!obj.value.length) {
emailMenuOp(1);
return;
}
if(value == 40) {
emailMenui++;
if(emailMenui >= emaildomains.length) {
emailMenui = 0;
}
} else if(value == 38) {
emailMenui--;
if(emailMenui < 0) {
emailMenui = emaildomains.length - 1;
}
} else if(value == 13) {
$('emailmore_menu').style.display = 'none';
return;
}
if(!$('emailmore_menu')) {
menu = document.createElement('div');
menu.id = 'emailmore_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
$('append_parent').appendChild(menu);
}
var s = '<ul>';
for(var i = 0; i < emaildomains.length; i++) {
s += '<li><a href="javascript:;" onmouseover="emailMenuOp(5)" ' + (emailMenui == i ? 'class="a" ' : '') + 'onclick="$(stmp[\'email\']).value=this.innerHTML;display(\'emailmore_menu\');checkemail(stmp[\'email\']);">' + v + '@' + emaildomains[i] + '</a></li>';
}
s += '</ul>';
$('emailmore_menu').innerHTML = s;
emailMenuOp(2);
}
function checksubmit() {
var p_chks = $('registerform').getElementsByTagName('kbd');
for(i = 0;i < p_chks.length;i++){
if(p_chks[i].className == 'p_chk'){
p_chks[i].innerHTML = '';
}
}
ajaxpost('registerform', 'returnmessage4', 'returnmessage4', 'onerror');
return;
}
function checkusername(id) {
errormessage(id);
var username = trim($(id).value);
if($('tip_' + id).parentNode.className.match(/ p_right/) && (username == '' || username == lastusername)) {
return;
} else {
lastusername = username;
}
if(username.match(/<|"/ig)) {
errormessage(id, '用户名包含敏感字符');
return;
}
var unlen = username.replace(/[^\x00-\xff]/g, "**").length;
if(unlen < 3 || unlen > 15) {
errormessage(id, unlen < 3 ? '用户名小于 3 个字符' : '用户名超过 15 个字符');
return;
}
var x = new Ajax();
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkusername&username=' + (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(username) : username), function(s) {
errormessage(id, s);
});
}
function checkpassword(id1, id2) {
if(!$(id1).value && !$(id2).value) {
return;
}
errormessage(id2);
if($(id1).value != $(id2).value) {
errormessage(id2, '两次输入的密码不一致');
} else {
errormessage(id2, 'succeed');
}
}
function checkemail(id) {
errormessage(id);
var email = trim($(id).value);
if($(id).parentNode.className.match(/ p_right/) && (email == '' || email == lastemail)) {
return;
} else {
lastemail = email;
}
if(email.match(/<|"/ig)) {
errormessage(id, 'Email 包含敏感字符');
return;
}
var x = new Ajax();
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkemail&email=' + email, function(s) {
errormessage(id, s);
});
}
function checkinvite() {
errormessage('invitecode');
var invitecode = trim($('invitecode').value);
if(invitecode == '' || invitecode == lastinvitecode) {
return;
} else {
lastinvitecode = invitecode;
}
if(invitecode.match(/<|"/ig)) {
errormessage('invitecode', '邀请码包含敏感字符');
return;
}
var x = new Ajax();
$('tip_invitecode').parentNode.className = $('tip_invitecode').parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkinvitecode&invitecode=' + invitecode, function(s) {
errormessage('invitecode', s);
});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: md5.js 15149 2010-08-19 08:02:46Z monkey $
*/
var hexcase = 0;
var chrsz = 8;
function hex_md5(s){
return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}
function core_md5(x, len) {
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
return bin;
}
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 22522 2011-05-11 03:12:47Z monkey $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum', data);
}
function switchFullMode() {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
}
ajaxget('forum.php?mod=ajax&action=editor&cedit=yes' + (!fid ? '' : '&fid=' + fid), 'fastposteditor');
return false;
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('您确认要把此主题从热点主题中移除么?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['展开', '收起'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' && theform.subject.value == '') {
s = '抱歉,您尚未输入标题或内容';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = '您的标题超过 80 个字符的限制';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = '您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(theform.message.value) + ' ' + '字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v ? 0 : 1);};
setcookie('atarget', v, (v ? 2592000 : -1));
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum');
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('没有可以恢复的数据!', 'info');
}
return;
}
if(!quiet && !confirm('此操作将覆盖当前帖子内容,确定要恢复数据吗?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
if($('separatorline')) {
var table = $('separatorline').parentNode;
} else {
var table = $('forum_' + fid);
}
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">有新回复的主题,点击查看', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: calendar.js 21580 2011-04-01 02:22:19Z svn_project_zhangjie $
*/
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute; z-index:100000;" onclick="doane(event)">';
s += '<div style="width: 210px;"><table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;">';
s += '<tr align="center" id="calendar_week"><td><a href="javascript:;" onclick="refreshcalendar(yy, mm-1)" title="上一月">«</a></td><td colspan="5" style="text-align: center"><a href="javascript:;" onclick="showdiv(\'year\');doane(event)" class="dropmenu" title="点击选择年份" id="year"></a> - <a id="month" class="dropmenu" title="点击选择月份" href="javascript:;" onclick="showdiv(\'month\');doane(event)"></a></td><td><A href="javascript:;" onclick="refreshcalendar(yy, mm+1)" title="下一月">»</A></td></tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute" class="pns"><td colspan="4" align="left"><input type="text" size="1" value="" id="hour" class="px vm" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'> 点 <input type="text" size="1" value="" id="minute" class="px vm" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'> 分</td><td align="right" colspan="3"><button class="pn" onclick="confirmcalendar();"><em>确定</em></button></td></tr>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="doane(event)" style="display: none;z-index:100001;"><div class="col">';
for(var k = 2020; k >= 1931; k--) {
s += k != 2020 && k % 10 == 0 ? '</div><div class="col">' : '';
s += '<a href="javascript:;" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="calendar_today"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="doane(event)" style="display: none;z-index:100001;">';
for(var k = 1; k <= 12; k++) {
s += '<a href="javascript:;" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'"><span' + (today.getMonth()+1 == k ? ' class="calendar_today"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
if(BROWSER.ie && BROWSER.ie < 7) {
s += '<iframe id="calendariframe" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_year" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_month" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
}
var div = document.createElement('div');
div.innerHTML = s;
$('append_parent').appendChild(div);
document.onclick = function(event) {
closecalendar(event);
};
$('calendar').onclick = function(event) {
doane(event);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
};
}
function closecalendar(event) {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.display = 'none';
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
if(!addtime) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.display = 'none';
}
}
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
}
function confirmcalendar() {
if(addtime && controlid.value === '') {
controlid.value = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value);
}
closecalendar();
}
function initclosecalendar() {
var e = getEvent();
var aim = e.target || e.srcElement;
while (aim.parentNode != document.body) {
if (aim.parentNode.id == 'append_parent') {
aim.onclick = function () {closecalendar(e);};
}
aim = aim.parentNode;
}
}
function showcalendar(event, controlid1, addtime1, startdate1, enddate1) {
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
var p = fetchOffset(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['left']+'px';
$('calendar').style.top = (p['top'] + 20)+'px';
doane(event);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = 'calendar_default';
$('calendar_year_' + today.getFullYear()).className = 'calendar_today';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = 'calendar_default';
$('calendar_month_' + (today.getMonth() + 1)).className = 'calendar_today';
}
$('calendar_year_' + currday.getFullYear()).className = 'calendar_checked';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'calendar_checked';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.top = $('calendar').style.top;
$('calendariframe').style.left = $('calendar').style.left;
$('calendariframe').style.width = $('calendar').offsetWidth;
$('calendariframe').style.height = $('calendar').offsetHeight;
$('calendariframe').style.display = 'block';
}
initclosecalendar();
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.innerHTML = '<a href="javascript:;" onclick="settime(' + d + ');return false">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'calendar_expire';
} else {
dd.className = 'calendar_default';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'calendar_today';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'calendar_checked';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = fetchOffset($(id));
$('calendar_' + id).style.left = p['left']+'px';
$('calendar_' + id).style.top = (p['top'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe_' + id).style.top = $('calendar_' + id).style.top;
$('calendariframe_' + id).style.left = $('calendar_' + id).style.left;
$('calendariframe_' + id).style.width = $('calendar_' + id).offsetWidth;
$('calendariframe_' + id ).style.height = $('calendar_' + id).offsetHeight;
$('calendariframe_' + id).style.display = 'block';
}
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
if(!BROWSER.other) {
loadcss('forum_calendar');
loadcalendar();
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home.js 22765 2011-05-20 03:06:12Z zhengqingpeng $
*/
var note_step = 0;
var note_oldtitle = document.title;
var note_timer;
function addSort(obj) {
if (obj.value == 'addoption') {
showWindow('addoption', 'home.php?mod=spacecp&ac=blog&op=addoption&handlekey=addoption&oid='+obj.id);
}
}
function addOption(sid, aid) {
var obj = $(aid);
var newOption = $(sid).value;
$(sid).value = "";
if (newOption!=null && newOption!='') {
var newOptionTag=document.createElement('option');
newOptionTag.text=newOption;
newOptionTag.value="new:" + newOption;
try {
obj.add(newOptionTag, obj.options[0]);
} catch(ex) {
obj.add(newOptionTag, obj.selecedIndex);
}
obj.value="new:" + newOption;
} else {
obj.value=obj.options[0].value;
}
}
function blogAddOption(sid, aid) {
var obj = $(aid);
var newOption = $(sid).value;
newOption = newOption.replace(/^\s+|\s+$/g,"");
$(sid).value = "";
if (newOption!=null && newOption!='') {
var newOptionTag=document.createElement('option');
newOptionTag.text=newOption;
newOptionTag.value="new:" + newOption;
try {
obj.add(newOptionTag, obj.options[0]);
} catch(ex) {
obj.add(newOptionTag, obj.selecedIndex);
}
obj.value="new:" + newOption;
return true;
} else {
alert('分类名不能为空!');
return false;
}
}
function blogCancelAddOption(aid) {
var obj = $(aid);
obj.value=obj.options[0].value;
}
function checkAll(form, name) {
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name.match(name)) {
e.checked = form.elements['chkall'].checked;
}
}
}
function cnCode(str) {
str = str.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
str = str.replace(/\s{2,}/ig, ' ');
return BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(str) : str;
}
function getExt(path) {
return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function resizeImg(id,size) {
var theImages = $(id).getElementsByTagName('img');
for (i=0; i<theImages.length; i++) {
theImages[i].onload = function() {
if (this.width > size) {
this.style.width = size + 'px';
if (this.parentNode.tagName.toLowerCase() != 'a') {
var zoomDiv = document.createElement('div');
this.parentNode.insertBefore(zoomDiv,this);
zoomDiv.appendChild(this);
zoomDiv.style.position = 'relative';
zoomDiv.style.cursor = 'pointer';
this.title = '点击图片,在新窗口显示原始尺寸';
var zoom = document.createElement('img');
zoom.src = 'image/zoom.gif';
zoom.style.position = 'absolute';
zoom.style.marginLeft = size -28 + 'px';
zoom.style.marginTop = '5px';
this.parentNode.insertBefore(zoom,this);
zoomDiv.onmouseover = function() {
zoom.src = 'image/zoom_h.gif';
};
zoomDiv.onmouseout = function() {
zoom.src = 'image/zoom.gif';
};
zoomDiv.onclick = function() {
window.open(this.childNodes[1].src);
};
}
}
}
}
}
function zoomTextarea(id, zoom) {
zoomSize = zoom ? 10 : -10;
obj = $(id);
if(obj.rows + zoomSize > 0 && obj.cols + zoomSize * 3 > 0) {
obj.rows += zoomSize;
obj.cols += zoomSize * 3;
}
}
function ischeck(id, prefix) {
form = document.getElementById(id);
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name.match(prefix) && e.checked) {
if(confirm("您确定要执行本操作吗?")) {
return true;
} else {
return false;
}
}
}
alert('请选择要操作的对象');
return false;
}
function copyRow(tbody) {
var add = false;
var newnode;
if($(tbody).rows.length == 1 && $(tbody).rows[0].style.display == 'none') {
$(tbody).rows[0].style.display = '';
newnode = $(tbody).rows[0];
} else {
newnode = $(tbody).rows[0].cloneNode(true);
add = true;
}
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
if(add) {
$(tbody).appendChild(newnode);
}
}
function delRow(obj, tbody) {
if($(tbody).rows.length == 1) {
var trobj = obj.parentNode.parentNode;
tags = trobj.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
trobj.style.display='none';
} else {
$(tbody).removeChild(obj.parentNode.parentNode);
}
}
function insertWebImg(obj) {
if(checkImage(obj.value)) {
insertImage(obj.value);
obj.value = 'http://';
} else {
alert('图片地址不正确');
}
}
function checkFocus(target) {
var obj = $(target);
if(!obj.hasfocus) {
obj.focus();
}
}
function insertImage(text) {
text = "\n[img]" + text + "[/img]\n";
insertContent('message', text);
}
function insertContent(target, text) {
var obj = $(target);
selection = document.selection;
checkFocus(target);
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = text;
sel.moveStart('character', -strlen(text));
} else {
obj.value += text;
}
}
function checkImage(url) {
var re = /^http\:\/\/.{5,200}\.(jpg|gif|png)$/i;
return url.match(re);
}
function quick_validate(obj) {
if($('seccode')) {
var code = $('seccode').value;
var x = new Ajax();
x.get('cp.php?ac=common&op=seccode&code=' + code, function(s){
s = trim(s);
if(s != 'succeed') {
alert(s);
$('seccode').focus();
return false;
} else {
obj.form.submit();
return true;
}
});
} else {
obj.form.submit();
return true;
}
}
function stopMusic(preID, playerID) {
var musicFlash = preID.toString() + '_' + playerID.toString();
if($(musicFlash)) {
$(musicFlash).SetVariable('closePlayer', 1);
}
}
function showFlash(host, flashvar, obj, shareid) {
var flashAddr = {
'youku.com' : 'http://player.youku.com/player.php/sid/FLASHVAR=/v.swf',
'ku6.com' : 'http://player.ku6.com/refer/FLASHVAR/v.swf',
'youtube.com' : 'http://www.youtube.com/v/FLASHVAR',
'5show.com' : 'http://www.5show.com/swf/5show_player.swf?flv_id=FLASHVAR',
'sina.com.cn' : 'http://vhead.blog.sina.com.cn/player/outer_player.swf?vid=FLASHVAR',
'sohu.com' : 'http://v.blog.sohu.com/fo/v4/FLASHVAR',
'mofile.com' : 'http://tv.mofile.com/cn/xplayer.swf?v=FLASHVAR',
'music' : 'FLASHVAR',
'flash' : 'FLASHVAR'
};
var flash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="480" height="400">'
+ '<param name="movie" value="FLASHADDR" />'
+ '<param name="quality" value="high" />'
+ '<param name="bgcolor" value="#FFFFFF" />'
+ '<param name="allowScriptAccess" value="none" />'
+ '<param name="allowNetworking" value="internal" />'
+ '<embed width="480" height="400" menu="false" quality="high" src="FLASHADDR" type="application/x-shockwave-flash" />'
+ '</object>';
var videoFlash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="450">'
+ '<param value="transparent" name="wmode"/>'
+ '<param value="FLASHADDR" name="movie" />'
+ '<embed src="FLASHADDR" wmode="transparent" allowfullscreen="true" type="application/x-shockwave-flash" width="480" height="450"></embed>'
+ '</object>';
var musicFlash = '<object id="audioplayer_SHAREID" height="24" width="290" data="' + STATICURL + 'image/common/player.swf" type="application/x-shockwave-flash">'
+ '<param value="' + STATICURL + 'image/common/player.swf" name="movie"/>'
+ '<param value="autostart=yes&bg=0xCDDFF3&leftbg=0x357DCE&lefticon=0xF2F2F2&rightbg=0xF06A51&rightbghover=0xAF2910&righticon=0xF2F2F2&righticonhover=0xFFFFFF&text=0x357DCE&slider=0x357DCE&track=0xFFFFFF&border=0xFFFFFF&loader=0xAF2910&soundFile=FLASHADDR" name="FlashVars"/>'
+ '<param value="high" name="quality"/>'
+ '<param value="false" name="menu"/>'
+ '<param value="#FFFFFF" name="bgcolor"/>'
+ '</object>';
var musicMedia = '<object height="64" width="290" data="FLASHADDR" type="audio/x-ms-wma">'
+ '<param value="FLASHADDR" name="src"/>'
+ '<param value="1" name="autostart"/>'
+ '<param value="true" name="controller"/>'
+ '</object>';
var flashHtml = videoFlash;
var videoMp3 = true;
if('' == flashvar) {
alert('音乐地址错误,不能为空');
return false;
}
if('music' == host) {
var mp3Reg = new RegExp('.mp3$', 'ig');
var flashReg = new RegExp('.swf$', 'ig');
flashHtml = musicMedia;
videoMp3 = false;
if(mp3Reg.test(flashvar)) {
videoMp3 = true;
flashHtml = musicFlash;
} else if(flashReg.test(flashvar)) {
videoMp3 = true;
flashHtml = flash;
}
}
flashvar = encodeURI(flashvar);
if(flashAddr[host]) {
var flash = flashAddr[host].replace('FLASHVAR', flashvar);
flashHtml = flashHtml.replace(/FLASHADDR/g, flash);
flashHtml = flashHtml.replace(/SHAREID/g, shareid);
}
if(!obj) {
$('flash_div_' + shareid).innerHTML = flashHtml;
return true;
}
if($('flash_div_' + shareid)) {
$('flash_div_' + shareid).style.display = '';
$('flash_hide_' + shareid).style.display = '';
obj.style.display = 'none';
return true;
}
if(flashAddr[host]) {
var flashObj = document.createElement('div');
flashObj.id = 'flash_div_' + shareid;
obj.parentNode.insertBefore(flashObj, obj);
flashObj.innerHTML = flashHtml;
obj.style.display = 'none';
var hideObj = document.createElement('div');
hideObj.id = 'flash_hide_' + shareid;
var nodetxt = document.createTextNode("收起");
hideObj.appendChild(nodetxt);
obj.parentNode.insertBefore(hideObj, obj);
hideObj.style.cursor = 'pointer';
hideObj.onclick = function() {
if(true == videoMp3) {
stopMusic('audioplayer', shareid);
flashObj.parentNode.removeChild(flashObj);
hideObj.parentNode.removeChild(hideObj);
} else {
flashObj.style.display = 'none';
hideObj.style.display = 'none';
}
obj.style.display = '';
};
}
}
function userapp_open() {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=common&op=getuserapp&inajax=1', function(s){
$('my_userapp').innerHTML = s;
$('a_app_more').className = 'fold';
$('a_app_more').innerHTML = '收起';
$('a_app_more').onclick = function() {
userapp_close();
};
});
}
function userapp_close() {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=common&op=getuserapp&subop=off&inajax=1', function(s){
$('my_userapp').innerHTML = s;
$('a_app_more').className = 'unfold';
$('a_app_more').innerHTML = '展开';
$('a_app_more').onclick = function() {
userapp_open();
};
});
}
function startMarquee(h, speed, delay, sid) {
var t = null;
var p = false;
var o = $(sid);
o.innerHTML += o.innerHTML;
o.onmouseover = function() {p = true};
o.onmouseout = function() {p = false};
o.scrollTop = 0;
function start() {
t = setInterval(scrolling, speed);
if(!p) {
o.scrollTop += 2;
}
}
function scrolling() {
if(p) return;
if(o.scrollTop % h != 0) {
o.scrollTop += 2;
if(o.scrollTop >= o.scrollHeight/2) o.scrollTop = 0;
} else {
clearInterval(t);
setTimeout(start, delay);
}
}
setTimeout(start, delay);
}
function readfeed(obj, id) {
if(Cookie.get("read_feed_ids")) {
var fcookie = Cookie.get("read_feed_ids");
fcookie = id + ',' + fcookie;
} else {
var fcookie = id;
}
Cookie.set("read_feed_ids", fcookie, 48);
obj.className = 'feedread';
}
function showreward() {
if(Cookie.get('reward_notice_disable')) {
return false;
}
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getreward', function(s){
if(s) {
msgwin(s, 2000);
}
});
}
function msgwin(s, t) {
var msgWinObj = $('msgwin');
if(!msgWinObj) {
var msgWinObj = document.createElement("div");
msgWinObj.id = 'msgwin';
msgWinObj.style.display = 'none';
msgWinObj.style.position = 'absolute';
msgWinObj.style.zIndex = '100000';
$('append_parent').appendChild(msgWinObj);
}
msgWinObj.innerHTML = s;
msgWinObj.style.display = '';
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
msgWinObj.style.opacity = 0;
var sTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
pbegin = sTop + (document.documentElement.clientHeight / 2);
pend = sTop + (document.documentElement.clientHeight / 5);
setTimeout(function () {showmsgwin(pbegin, pend, 0, t)}, 10);
msgWinObj.style.left = ((document.documentElement.clientWidth - msgWinObj.clientWidth) / 2) + 'px';
msgWinObj.style.top = pbegin + 'px';
}
function showmsgwin(b, e, a, t) {
step = (b - e) / 10;
var msgWinObj = $('msgwin');
newp = (parseInt(msgWinObj.style.top) - step);
if(newp > e) {
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + a + ')';
msgWinObj.style.opacity = a / 100;
msgWinObj.style.top = newp + 'px';
setTimeout(function () {showmsgwin(b, e, a += 10, t)}, 10);
} else {
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
msgWinObj.style.opacity = 1;
setTimeout('displayOpacity(\'msgwin\', 100)', t);
}
}
function displayOpacity(id, n) {
if(!$(id)) {
return;
}
if(n >= 0) {
n -= 10;
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + n + ')';
$(id).style.opacity = n / 100;
setTimeout('displayOpacity(\'' + id + '\',' + n + ')', 50);
} else {
$(id).style.display = 'none';
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
$(id).style.opacity = 1;
}
}
function urlto(url) {
window.location.href = url;
}
function explode(sep, string) {
return string.split(sep);
}
function selector(pattern, context) {
var re = new RegExp('([a-z0-9]*)([\.#:]*)(.*|$)', 'ig');
var match = re.exec(pattern);
var conditions = cc = [];
if (match[2] == '#') conditions.push(['id', '=', match[3]]);
else if(match[2] == '.') conditions.push(['className', '~=', match[3]]);
else if(match[2] == ':') conditions.push(['type', '=', match[3]]);
var s = match[3].replace(/\[(.*)\]/g,'$1').split('@');
for(var i=0; i<s.length; i++) {
if (cc = /([\w]+)([=^%!$~]+)(.*)$/.exec(s[i]))
conditions.push([cc[1], cc[2], cc[3]]);
}
var list = conditions[0] && conditions[0][0] == 'id' ? [document.getElementById(conditions[0][2])] : (context || document).getElementsByTagName(match[1] || "*");
if(!list || !list.length) return [];
if(conditions) {
var elements = [];
var attrMapping = {'for': 'htmlFor', 'class': 'className'};
for(var i=0; i<list.length; i++) {
var pass = true;
for(var j=0; j<conditions.length; j++) {
var attr = attrMapping[conditions[j][0]] || conditions[j][0];
var val = list[i][attr] || (list[i].getAttribute ? list[i].getAttribute(attr) : '');
var pattern = null;
if(conditions[j][1] == '=') {
pattern = new RegExp('^'+conditions[j][2]+'$', 'i');
} else if(conditions[j][1] == '^=') {
pattern = new RegExp('^' + conditions[j][2], 'i');
} else if(conditions[j][1] == '$=') {
pattern = new RegExp(conditions[j][2] + '$', 'i');
} else if(conditions[j][1] == '%=') {
pattern = new RegExp(conditions[j][2], 'i');
} else if(conditions[j][1] == '~=') {
pattern = new RegExp('(^|[ ])' + conditions[j][2] + '([ ]|$)', 'i');
}
if(pattern && !pattern.test(val)) {
pass = false;
break;
}
}
if(pass) elements.push(list[i]);
}
return elements;
} else {
return list;
}
}
function showBlock(cid, oid) {
if(parseInt(cid)) {
var listObj = $(oid);
var x = new Ajax();
x.get('portal.php?mod=cp&ac=block&operation=getblock&classid='+cid, function(s){
listObj.innerHTML = s;
})
}
}
function resizeTx(obj){
var oid = obj.id + '_limit';
if(!BROWSER.ie) obj.style.height = 0;
obj.style.height = obj.scrollHeight + 'px';
if($(oid)) $(oid).style.display = obj.scrollHeight > 30 ? '':'none';
}
function showFace(showid, target, dropstr) {
if($(showid + '_menu') != null) {
$(showid+'_menu').style.display = '';
} else {
var faceDiv = document.createElement("div");
faceDiv.id = showid+'_menu';
faceDiv.className = 'p_pop facel';
faceDiv.style.position = 'absolute';
faceDiv.style.zIndex = 1001;
var faceul = document.createElement("ul");
for(i=1; i<31; i++) {
var faceli = document.createElement("li");
faceli.innerHTML = '<img src="' + STATICURL + 'image/smiley/comcom/'+i+'.gif" onclick="insertFace(\''+showid+'\','+i+', \''+ target +'\', \''+dropstr+'\')" style="cursor:pointer; position:relative;" />';
faceul.appendChild(faceli);
}
faceDiv.appendChild(faceul);
$('append_parent').appendChild(faceDiv)
}
setMenuPosition(showid, 0);
doane();
_attachEvent(document.body, 'click', function(){if($(showid+'_menu')) $(showid+'_menu').style.display = 'none';});
}
function insertFace(showid, id, target, dropstr) {
var faceText = '[em:'+id+':]';
if($(target) != null) {
insertContent(target, faceText);
if(dropstr) {
$(target).value = $(target).value.replace(dropstr, "");
}
}
}
function wall_add(id) {
var obj = $('comment_ul');
var newdl = document.createElement("dl");
newdl.id = 'comment_'+id+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+id, function(s){
newdl.innerHTML = s;
});
obj.insertBefore(newdl, obj.firstChild);
if($('comment_message')) {
$('comment_message').value= '';
}
showCreditPrompt();
}
function share_add(sid) {
var obj = $('share_ul');
var newli = document.createElement("li");
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=share&inajax=1&sid='+sid, function(s){
newli.innerHTML = s;
});
obj.insertBefore(newli, obj.firstChild);
$('share_link').value = 'http://';
$('share_general').value = '';
showCreditPrompt();
}
function comment_add(id) {
var obj = $('comment_ul');
var newdl = document.createElement("dl");
newdl.id = 'comment_'+id+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+id, function(s){
newdl.innerHTML = s;
});
if($('comment_prepend')){
obj = obj.firstChild;
while (obj && obj.nodeType != 1){
obj = obj.nextSibling;
}
obj.parentNode.insertBefore(newdl, obj);
} else {
obj.appendChild(newdl);
}
if($('comment_message')) {
$('comment_message').value= '';
}
if($('comment_replynum')) {
var a = parseInt($('comment_replynum').innerHTML);
var b = a + 1;
$('comment_replynum').innerHTML = b + '';
}
showCreditPrompt();
}
function comment_edit(cid) {
var obj = $('comment_'+ cid +'_li');
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+ cid, function(s){
obj.innerHTML = s;
});
}
function comment_delete(cid) {
var obj = $('comment_'+ cid +'_li');
obj.style.display = "none";
if($('comment_replynum')) {
var a = parseInt($('comment_replynum').innerHTML);
var b = a - 1;
$('comment_replynum').innerHTML = b + '';
}
}
function share_delete(sid) {
var obj = $('share_'+ sid +'_li');
obj.style.display = "none";
}
function friend_delete(uid) {
var obj = $('friend_'+ uid +'_li');
if(obj != null) obj.style.display = "none";
var obj2 = $('friend_tbody_'+uid);
if(obj2 != null) obj2.style.display = "none";
}
function friend_changegroup(id, result) {
if(result) {
var ids = explode('_', id);
var uid = ids[1];
var obj = $('friend_group_'+ uid);
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getfriendgroup&uid='+uid, function(s){
obj.innerHTML = s;
});
}
}
function friend_changegroupname(group) {
var obj = $('friend_groupname_'+ group);
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getfriendname&inajax=1&group='+group, function(s){
obj.innerHTML = s;
});
}
function post_add(pid, result) {
if(result) {
var obj = $('post_ul');
var newli = document.createElement("div");
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=post', function(s){
newli.innerHTML = s;
});
obj.appendChild(newli);
if($('message')) {
$('message').value= '';
newnode = $('quickpostimg').rows[0].cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
var allRows = $('quickpostimg').rows;
while(allRows.length) {
$('quickpostimg').removeChild(allRows[0]);
}
$('quickpostimg').appendChild(newnode);
}
if($('post_replynum')) {
var a = parseInt($('post_replynum').innerHTML);
var b = a + 1;
$('post_replynum').innerHTML = b + '';
}
showCreditPrompt();
}
}
function post_edit(id, result) {
if(result) {
var ids = explode('_', id);
var pid = ids[1];
var obj = $('post_'+ pid +'_li');
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=post&pid='+ pid, function(s){
obj.innerHTML = s;
});
}
}
function post_delete(id, result) {
if(result) {
var ids = explode('_', id);
var pid = ids[1];
var obj = $('post_'+ pid +'_li');
obj.style.display = "none";
if($('post_replynum')) {
var a = parseInt($('post_replynum').innerHTML);
var b = a - 1;
$('post_replynum').innerHTML = b + '';
}
}
}
function poke_send(id, result) {
if(result) {
var ids = explode('_', id);
var uid = ids[1];
if($('poke_'+ uid)) {
$('poke_'+ uid).style.display = "none";
}
showCreditPrompt();
}
}
function myfriend_post(uid) {
if($('friend_'+uid)) {
$('friend_'+uid).innerHTML = '<p>你们现在是好友了,接下来,您还可以:<a href="home.php?mod=space&do=wall&uid='+uid+'" class="xi2" target="_blank">给TA留言</a> ,或者 <a href="home.php?mod=spacecp&ac=poke&op=send&uid='+uid+'&handlekey=propokehk_'+uid+'" id="a_poke_'+uid+'" class="xi2" onclick="showWindow(this.id, this.href, \'get\', 0, {\'ctrlid\':this.id,\'pos\':\'13\'});">打个招呼</a></p>';
}
showCreditPrompt();
}
function myfriend_ignore(id) {
var ids = explode('_', id);
var uid = ids[1];
$('friend_tbody_'+uid).style.display = "none";
}
function mtag_join(tagid, result) {
if(result) {
location.reload();
}
}
function picView(albumid) {
if(albumid == 'none') {
$('albumpic_body').innerHTML = '';
} else {
ajaxget('home.php?mod=misc&ac=ajax&op=album&id='+albumid+'&ajaxdiv=albumpic_body', 'albumpic_body');
}
}
function resend_mail(mid) {
if(mid) {
var obj = $('sendmail_'+ mid +'_li');
obj.style.display = "none";
}
}
function userapp_delete(id, result) {
if(result) {
var ids = explode('_', id);
var appid = ids[1];
$('space_app_'+appid).style.display = "none";
}
}
function docomment_get(doid, key) {
var showid = key + '_' + doid;
var opid = key + '_do_a_op_'+doid;
$(showid).style.display = '';
$(showid).className = 'cmt brm';
ajaxget('home.php?mod=spacecp&ac=doing&op=getcomment&handlekey=msg_'+doid+'&doid='+doid+'&key='+key, showid);
if($(opid)) {
$(opid).innerHTML = '收起';
$(opid).onclick = function() {
docomment_colse(doid, key);
}
}
showCreditPrompt();
}
function docomment_colse(doid, key) {
var showid = key + '_' + doid;
var opid = key + '_do_a_op_'+doid;
$(showid).style.display = 'none';
$(showid).style.className = '';
$(opid).innerHTML = '回复';
$(opid).onclick = function() {
docomment_get(doid, key);
}
}
function docomment_form(doid, id, key) {
var showid = key + '_form_'+doid+'_'+id;
var divid = key +'_'+ doid;
var url = 'home.php?mod=spacecp&ac=doing&op=docomment&handlekey=msg_'+id+'&doid='+doid+'&id='+id+'&key='+key;
if(parseInt(discuz_uid)) {
ajaxget(url, showid);
if($(divid)) {
$(divid).style.display = '';
}
} else {
showWindow(divid, url);
}
}
function docomment_form_close(doid, id, key) {
var showid = key + '_form_' + doid + '_' + id;
var opid = key + '_do_a_op_' + doid;
$(showid).innerHTML = '';
$(showid).style.display = 'none';
var liObj = $(key+'_'+doid).getElementsByTagName('li');
if(!liObj.length) {
$(key+'_'+doid).style.display = 'none';
if($(opid)) {
$(opid).innerHTML = '回复';
$(opid).onclick = function () {
docomment_get(doid, key);
}
}
}
}
function feedcomment_get(feedid) {
var showid = 'feedcomment_'+feedid;
var opid = 'feedcomment_a_op_'+feedid;
$(showid).style.display = '';
ajaxget('home.php?mod=spacecp&ac=feed&op=getcomment&feedid='+feedid+'&handlekey=feedhk_'+feedid, showid);
if($(opid) != null) {
$(opid).innerHTML = '收起';
$(opid).onclick = function() {
feedcomment_close(feedid);
}
}
}
function feedcomment_add(cid, feedid) {
var obj = $('comment_ol_'+feedid);
var newdl = document.createElement("dl");
newdl.id = 'comment_'+cid+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+cid, function(s){
newdl.innerHTML = s;
});
obj.appendChild(newdl);
$('feedmessage_'+feedid).value= '';
showCreditPrompt();
}
function feedcomment_close(feedid) {
var showid = 'feedcomment_'+feedid;
var opid = 'feedcomment_a_op_'+feedid;
$(showid).style.display = 'none';
$(showid).style.className = '';
$(opid).innerHTML = '评论';
$(opid).onclick = function() {
feedcomment_get(feedid);
}
}
function feed_post_result(feedid, result) {
if(result) {
location.reload();
}
}
function feed_more_show(feedid) {
var showid = 'feed_more_'+feedid;
var opid = 'feed_a_more_'+feedid;
$(showid).style.display = '';
$(showid).className = 'sub_doing';
$(opid).innerHTML = '« 收起列表';
$(opid).onclick = function() {
feed_more_close(feedid);
}
}
function feed_more_close(feedid) {
var showid = 'feed_more_'+feedid;
var opid = 'feed_a_more_'+feedid;
$(showid).style.display = 'none';
$(opid).innerHTML = '» 更多动态';
$(opid).onclick = function() {
feed_more_show(feedid);
}
}
function poll_post_result(id, result) {
if(result) {
var aObj = $('__'+id).getElementsByTagName("a");
window.location.href = aObj[0].href;
}
}
function show_click(idtype, id, clickid) {
ajaxget('home.php?mod=spacecp&ac=click&op=show&clickid='+clickid+'&idtype='+idtype+'&id='+id, 'click_div');
showCreditPrompt();
}
function feed_menu(feedid, show) {
var obj = $('a_feed_menu_'+feedid);
if(obj) {
if(show) {
obj.style.display='block';
} else {
obj.style.display='none';
}
}
var obj = $('feedmagic_'+feedid);
if(obj) {
if(show) {
obj.style.display='block';
} else {
obj.style.display='none';
}
}
}
function showbirthday(){
var el = $('birthday');
var birthday = el.value;
el.length=0;
el.options.add(new Option('日', ''));
for(var i=0;i<28;i++){
el.options.add(new Option(i+1, i+1));
}
if($('birthmonth').value!="2"){
el.options.add(new Option(29, 29));
el.options.add(new Option(30, 30));
switch($('birthmonth').value){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":{
el.options.add(new Option(31, 31));
}
}
} else if($('birthyear').value!="") {
var nbirthyear=$('birthyear').value;
if(nbirthyear%400==0 || (nbirthyear%4==0 && nbirthyear%100!=0)) el.options.add(new Option(29, 29));
}
el.value = birthday;
}
function magicColor(elem, t) {
t = t || 10;
elem = (elem && elem.constructor == String) ? $(elem) : elem;
if(!elem){
setTimeout(function(){magicColor(elem, t-1);}, 400);
return;
}
if(window.mcHandler == undefined) {
window.mcHandler = {elements:[]};
window.mcHandler.colorIndex = 0;
window.mcHandler.run = function(){
var color = ["#CC0000","#CC6D00","#CCCC00","#00CC00","#0000CC","#00CCCC","#CC00CC"][(window.mcHandler.colorIndex++) % 7];
for(var i = 0, L=window.mcHandler.elements.length; i<L; i++)
window.mcHandler.elements[i].style.color = color;
}
}
window.mcHandler.elements.push(elem);
if(window.mcHandler.timer == undefined) {
window.mcHandler.timer = setInterval(window.mcHandler.run, 500);
}
}
function passwordShow(value) {
if(value==4) {
$('span_password').style.display = '';
$('tb_selectgroup').style.display = 'none';
} else if(value==2) {
$('span_password').style.display = 'none';
$('tb_selectgroup').style.display = '';
} else {
$('span_password').style.display = 'none';
$('tb_selectgroup').style.display = 'none';
}
}
function getgroup(gid) {
if(gid) {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=privacy&inajax=1&op=getgroup&gid='+gid, function(s){
s = s + ' ';
$('target_names').innerHTML += s;
});
}
}
function pmsendappend() {
$('pm_append').style.display = '';
$('pm_append').id = '';
div = document.createElement('div');
div.id = 'pm_append';
div.style.display = 'none';
$('pm_ul').appendChild(div);
$('replymessage').value = '';
showCreditPrompt();
}
function succeedhandle_pmsend(locationhref, message, param) {
ajaxget('home.php?mod=spacecp&ac=pm&op=viewpmid&pmid=' + param['pmid'], 'pm_append', 'ajaxwaitid', '', null, 'pmsendappend()');
}
function getchatpmappendmember() {
var users = document.getElementsByName('users[]');
var appendmember = '';
if(users.length) {
var comma = '';
for(var i = 0; i < users.length; i++) {
appendmember += comma + users[i].value;
if(!comma) {
comma = ',';
}
}
}
if($('username').value) {
appendmember = appendmember ? (appendmember + ',' + $('username').value) : $('username').value;
}
var href = $('a_appendmember').href + '&memberusername=' + appendmember;
showWindow('a_appendmember', href, 'get', 0);
}
function markreadpm(markreadids) {
var markreadidarr = markreadids.split(',');
if(markreadidarr.length > 0) {
for(var i = 0; i < markreadidarr.length; i++) {
$(markreadidarr[i]).className = 'bbda cl';
}
}
}
function setpmstatus(form) {
var ids_gpmid = new Array();
var ids_plid = new Array();
var type = '';
var requesturl = '';
var markreadids = new Array();
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.id && e.id.match('a_delete') && e.checked) {
var idarr = new Array();
idarr = e.id.split('_');
if(idarr[1] == 'deleteg') {
ids_gpmid.push(idarr[2]);
markreadids.push('gpmlist_' + idarr[2]);
} else if(idarr[1] == 'delete') {
ids_plid.push(idarr[2]);
markreadids.push('pmlist_' + idarr[2]);
}
}
}
if(ids_gpmid.length > 0) {
requesturl += '&gpmids=' + ids_gpmid.join(',');
}
if(ids_plid.length > 0) {
requesturl += '&plids=' + ids_plid.join(',');
}
if(requesturl) {
ajaxget('home.php?mod=spacecp&ac=pm&op=setpmstatus' + requesturl, '', 'ajaxwaitid', '', 'none', 'markreadpm(\''+ markreadids.join(',') +'\')');
}
}
function changedeletedpm(pmid) {
$('pmlist_' + pmid).style.display = 'none';
var membernum = parseInt($('membernum').innerHTML);
$('membernum').innerHTML = membernum - 1;
}
function changeOrderRange(id) {
if(!$(id)) return false;
var url = window.location.href;
var a = $(id).getElementsByTagName('a');
for(var i = 0; i < a.length; i++) {
a[i].onclick = function () {
if(url.indexOf("&orderby=") == -1) {
url += "&orderby=" + this.id;
} else {
url = url.replace(/orderby=.*/, "orderby=" + this.id);
}
window.location = url;
return false;
}
}
}
function addBlockLink(id, tag) {
if(!$(id)) return false;
var a = $(id).getElementsByTagName(tag);
var taglist = {'A':1, 'INPUT':1, 'IMG':1};
for(var i = 0, len = a.length; i < len; i++) {
a[i].onmouseover = function () {
if(this.className.indexOf(' hover') == -1) {
this.className = this.className + ' hover';
}
};
a[i].onmouseout = function () {
this.className = this.className.replace(' hover', '');
};
a[i].onclick = function (e) {
e = e ? e : window.event;
var target = e.target || e.srcElement;
if(!taglist[target.tagName]) {
window.location.href = $(this.id + '_a').href;
}
};
}
}
function checkSynSignature() {
if($('to_signhtml').value == '1') {
$('syn_signature').className = 'syn_signature';
$('to_signhtml').value = '0';
} else {
$('syn_signature').className = 'syn_signature_check';
$('to_signhtml').value = '1';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_diy.js 22076 2011-04-21 06:22:09Z zhangguosheng $
*/
var drag = new Drag();
drag.extend({
'getBlocksTimer' : '',
'blocks' : [],
'blockDefaultClass' : [{'key':'选择样式','value':''},{'key':'无边框且无边距','value':'cl_block_bm'},{'key':'样式1','value':'xbs_1'},{'key':'样式2','value':'xbs xbs_2'},{'key':'样式3','value':'xbs xbs_3'},{'key':'样式4','value':'xbs xbs_4'},{'key':'样式5','value':'xbs xbs_5'},{'key':'样式6','value':'xbs xbs_6'},{'key':'样式7','value':'xbs xbs_7'}],
'frameDefaultClass' : [{'key':'选择样式','value':''},{'key':'无边框且无边距','value':'cl_frame_bm'},{'key':'无边框框架','value':'xfs xfs_nbd'},{'key':'样式1','value':'xfs xfs_1'},{'key':'样式2','value':'xfs xfs_2'},{'key':'样式3','value':'xfs xfs_3'},{'key':'样式4','value':'xfs xfs_4'},{'key':'样式5','value':'xfs xfs_5'}],
setDefalutMenu : function () {
this.addMenu('default','标题','drag.openTitleEdit(event)');
this.addMenu('default','样式','drag.openStyleEdit(event)');
this.addMenu('default', '删除', 'drag.removeBlock(event)');
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
this.addMenu('frame', '导出', 'drag.frameExport(event)');
this.addMenu('tab', '导出', 'drag.frameExport(event)');
},
setSampleMenu : function () {
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
},
openBlockEdit : function (e,op) {
e = Util.event(e);
op = (op=='data') ? 'data' : 'block';
var bid = e.aim.id.replace('cmd_portal_block_','');
this.removeMenu();
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op='+op+'&bid='+bid+'&tpl='+document.diyform.template.value, 'get', -1);
},
getDiyClassName : function (id,index) {
var obj = this.getObjByName(id);
var ele = $(id);
var eleClassName = ele.className.replace(/ {2,}/g,' ');
var className = '',srcClassName = '';
if (obj instanceof Block) {
className = eleClassName.split(this.blockClass+' ');
srcClassName = this.blockClass;
} else if(obj instanceof Tab) {
className = eleClassName.split(this.tabClass+' ');
srcClassName = this.tabClass;
} else if(obj instanceof Frame) {
className = eleClassName.split(this.frameClass+' ');
srcClassName = this.frameClass;
}
if (index != null && index<className.length) {
className = className[index].replace(/^ | $/g,'');
} else {
className.push(srcClassName);
}
return className;
},
getOption : function (arr,value) {
var html = '';
for (var i in arr) {
if (typeof arr[i] == 'function') continue;
var selected = arr[i]['value'] == value ? ' selected="selected"' : '';
html += '<option value="'+arr[i]['value']+'"'+selected+'>'+arr[i]['key']+'</option>';
}
return html;
},
getRule : function (selector,attr) {
selector = spaceDiy.checkSelector(selector);
var value = (!selector || !attr) ? '' : spaceDiy.styleSheet.getRule(selector, attr);
return value;
},
openStyleEdit : function (e) {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
var obj = this.getObjByName(id);
var objType = obj instanceof Block ? 1 : 0;
var bgcolor = '',bgimage = '',bgrepeat = '',html = '',diyClassName = '',fontcolor = '',fontsize = '',linkcolor = '',linkfontsize = '';
var bdtstyle = '',bdtwidth = '',bdtcolor = '',bdrstyle = '',bdrwidth = '',bdrcolor = '',bdbstyle = '',bdbwidth = '',bdbcolor = '',bdlstyle = '',bdlwidth = '',bdlcolor = '';
var margint = '',marginr = '',marginb = '',marginl = '',cmargint = '',cmarginr = '',cmarginb = '',cmarginl ='';
var selector = '#'+id;
bgcolor = this.getRule(selector, 'backgroundColor');
bgimage = this.getRule(selector, 'backgroundImage');
bgrepeat = this.getRule(selector, 'backgroundRepeat');
bgimage = bgimage && bgimage != 'none' ? Util.trimUrl(bgimage) : '';
fontcolor = this.getRule(selector+' .'+this.contentClass, 'color');
fontsize = this.getRule(selector+' .'+this.contentClass, 'fontSize').replace('px','');
var linkSelector = spaceDiy.checkSelector(selector+ ' .'+this.contentClass+' a');
linkcolor = this.getRule(linkSelector, 'color');
linkfontsize = this.getRule(linkSelector, 'fontSize').replace('px','');
fontcolor = Util.formatColor(fontcolor);
linkcolor = Util.formatColor(linkcolor);
bdtstyle = this.getRule(selector, 'borderTopStyle');
bdrstyle = this.getRule(selector, 'borderRightStyle');
bdbstyle = this.getRule(selector, 'borderBottomStyle');
bdlstyle = this.getRule(selector, 'borderLeftStyle');
bdtwidth = this.getRule(selector, 'borderTopWidth');
bdrwidth = this.getRule(selector, 'borderRightWidth');
bdbwidth = this.getRule(selector, 'borderBottomWidth');
bdlwidth = this.getRule(selector, 'borderLeftWidth');
bdtcolor = this.getRule(selector, 'borderTopColor');
bdrcolor = this.getRule(selector, 'borderRightColor');
bdbcolor = this.getRule(selector, 'borderBottomColor');
bdlcolor = this.getRule(selector, 'borderLeftColor');
bgcolor = Util.formatColor(bgcolor);
bdtcolor = Util.formatColor(bdtcolor);
bdrcolor = Util.formatColor(bdrcolor);
bdbcolor = Util.formatColor(bdbcolor);
bdlcolor = Util.formatColor(bdlcolor);
margint = this.getRule(selector, 'marginTop').replace('px','');
marginr = this.getRule(selector, 'marginRight').replace('px','');
marginb = this.getRule(selector, 'marginBottom').replace('px','');
marginl = this.getRule(selector, 'marginLeft').replace('px','');
if (objType == 1) {
selector = selector + ' .'+this.contentClass;
cmargint = this.getRule(selector, 'marginTop').replace('px','');
cmarginr = this.getRule(selector, 'marginRight').replace('px','');
cmarginb = this.getRule(selector, 'marginBottom').replace('px','');
cmarginl = this.getRule(selector, 'marginLeft').replace('px','');
}
diyClassName = this.getDiyClassName(id,0);
var widtharr = [];
for (var k=0;k<11;k++) {
var key = k+'px';
widtharr.push({'key':key,'value':key});
}
var bigarr = [];
for (var k=0;k<31;k++) {
key = k+'px';
bigarr.push({'key':key,'value':key});
}
var repeatarr = [{'key':'平铺','value':'repeat'},{'key':'不平铺','value':'no-repeat'},{'key':'横向平铺','value':'repeat-x'},{'key':'纵向平铺','value':'repeat-y'}];
var stylearr = [{'key':'无样式','value':'none'},{'key':'实线','value':'solid'},{'key':'点线','value':'dotted'},{'key':'虚线','value':'dashed'}];
var table = '<table class="tfm">';
table += '<tr><th>字体</th><td><input type="text" id="fontsize" class="px p_fre vm" value="'+fontsize+'" size="2" />px <input type="text" id="fontcolor" class="px p_fre vm" value="'+fontcolor+'" size="2" />';
table += getColorPalette(id+'_fontPalette', 'fontcolor' ,fontcolor)+'</td></tr>';
table += '<tr><th>链接</th><td><input type="text" id="linkfontsize" class="px p_fre vm" value="'+linkfontsize+'" size="2" />px <input type="text" id="linkcolor" class="px p_fre vm" value="'+linkcolor+'" size="2" />';
table += getColorPalette(id+'_linkPalette', 'linkcolor' ,linkcolor)+'</td></tr>';
var ulclass = 'borderul', opchecked = '';
if (bdtwidth != '' || bdtcolor != '' ) {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>边框</th><td><ul id="borderul" class="'+ulclass+'">';
table += '<li><label>上</label><select class="ps vm" id="bdtwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdtwidth)+'</select>';
table += ' <select class="ps vm" id="bdtstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdtstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdtcolor" class="px p_fre vm" value="'+bdtcolor+'" size="7" />';
table += getColorPalette(id+'_bdtPalette', 'bdtcolor' ,bdtcolor)+'</li>';
table += '<li class="bordera mtn"><label>右</label><select class="ps vm" id="bdrwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdrwidth)+'</select>';
table += ' <select class="ps vm" id="bdrstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdrstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdrcolor" class="px p_fre vm" value="'+bdrcolor+'" size="7" />';
table += getColorPalette(id+'_bdrPalette', 'bdrcolor' ,bdrcolor)+'</li>';
table += '<li class="bordera mtn"><label>下</label><select class="ps vm" id="bdbwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdbwidth)+'</select>';
table += ' <select class="ps vm" id="bdbstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdbstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdbcolor" class="px p_fre vm" value="'+bdbcolor+'" size="7" />';
table += getColorPalette(id+'_bdbPalette', 'bdbcolor' ,bdbcolor)+'</li>';
table += '<li class="bordera mtn"><label>左</label><select class="ps vm" id="bdlwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdlwidth)+'</select>';
table += ' <select class="ps vm" id="bdlstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdlstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdlcolor" class="px p_fre vm" value="'+bdlcolor+'" size="7" />';
table += getColorPalette(id+'_bdlPalette', 'bdlcolor' ,bdlcolor)+'</li>';
table += '</ul><p class="ptm"><label><input id="borderop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'borderul\').className = $(\'borderul\').className == \'borderul\' ? \'borderula\' : \'borderul\'">分别设置</label></p></td></tr>';
bigarr = [];
for (k=-20;k<31;k++) {
key = k+'px';
bigarr.push({'key':key,'value':key});
}
ulclass = 'borderul', opchecked = '';
if (margint != '') {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>外边距</th><td><div id="margindiv" class="'+ulclass+'"><span><label>上</label> <input type="text" id="margint" class="px p_fre vm" value="'+margint+'" size="1"/>px </span>';
table += '<span class="bordera"><label>右</label> <input type="text" id="marginr" class="px p_fre vm" value="'+marginr+'" size="1" />px </span>';
table += '<span class="bordera"><label>下</label> <input type="text" id="marginb" class="px p_fre vm" value="'+marginb+'" size="1" />px </span>';
table += '<span class="bordera"><label>左</label> <input type="text" id="marginl" class="px p_fre vm" value="'+marginl+'" size="1" />px</span>';
table += '</div><p class="ptm"><label><input id="marginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'margindiv\').className = $(\'margindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'">分别设置</label></p></td></tr>';
if (objType == 1) {
ulclass = 'borderul', opchecked = '';
if (cmargint != '') {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>内边距</th><td><div id="cmargindiv" class="'+ulclass+'"><span><label>上</label> <input class="px p_fre" id="cmargint" value="'+cmargint+'" size="1" />px </span>';
table += '<span class="bordera"><label>右</label> <input class="px p_fre" id="cmarginr" value="'+cmarginr+'" size="1" />px </span>';
table += '<span class="bordera"><label>下</label> <input class="px p_fre" id="cmarginb" value="'+cmarginb+'" size="1" />px </span>';
table += '<span class="bordera"><label>左</label> <input class="px p_fre" id="cmarginl" value="'+cmarginl+'" size="1" />px </span>';
table += '</div><p class="ptm"><label><input id="cmarginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'cmargindiv\').className = $(\'cmargindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'"> 分别设置</label></p></td></tr>';
}
table += '<tr><th>背景颜色</th><td><input type="text" id="bgcolor" class="px p_fre vm" value="'+bgcolor+'" size="4" />';
table += getColorPalette(id+'_bgcPalette', 'bgcolor' ,bgcolor)+'</td></tr>';
table += '<tr><th>背景图片</th><td><input type="text" id="bgimage" class="px p_fre vm" value="'+bgimage+'" size="25" /> <select class="ps vm" id="bgrepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>';
var classarr = objType == 1 ? this.blockDefaultClass : this.frameDefaultClass;
table += '<tr><th>指定class</th><td><input type="text" id="diyClassName" class="px p_fre" value="'+diyClassName+'" size="8" /> <select class="ps vm" id="bgrepeat" onchange="$(\'diyClassName\').value=this.value;" >'+this.getOption(classarr, diyClassName)+'</select></td></tr>';
table += '</table>';
var wname = objType ? '模块' : '框架';
html = '<div class="c diywin" style="width:450px;position:relative;">'+table+'</div>';
var h = '<h3 class="flb"><em>编辑'+wname+'样式</em><span><a href="javascript:;" class="flbc" onclick="drag.closeStyleEdit(\''+id+'\');return false;" title="关闭">\n\
关闭</a></span></h3>';
var f = '<p class="o pns"><button onclick="drag.saveStyle(\''+id+'\');drag.closeStyleEdit(\''+id+'\');" class="pn pnc" value="true">\n\
<strong>确定</strong></button><button onclick="drag.closeStyleEdit(\''+id+'\')" class="pn" value="true"><strong>取消</strong></button></p>';
this.removeMenu(e);
showWindow('eleStyle',h + html + f, 'html', 0);
},
closeStyleEdit : function (id) {
this.deleteFrame([id+'_bgcPalette',id+'_bdtPalette',id+'_bdrPalette',id+'_bdbPalette',id+'_bdlPalette',id+'_fontPalette',id+'_linkPalette']);
hideWindow('eleStyle');
},
saveStyle : function (id) {
var className = this.getDiyClassName(id);
var diyClassName = $('diyClassName').value;
$(id).className = diyClassName+' '+className[2]+' '+className[1];
var obj = this.getObjByName(id);
var objType = obj instanceof Block ? 1 : 0;
if (objType == 1) this.saveBlockClassName(id,diyClassName);
var selector = '#'+id;
var random = Math.random();
spaceDiy.setStyle(selector, 'background-color', $('bgcolor').value, random);
var bgimage = $('bgimage').value && $('bgimage') != 'none' ? Util.url($('bgimage').value) : '';
var bgrepeat = bgimage ? $('bgrepeat').value : '';
if ($('bgcolor').value != '' && bgimage == '') bgimage = 'none';
spaceDiy.setStyle(selector, 'background-image', bgimage, random);
spaceDiy.setStyle(selector, 'background-repeat', bgrepeat, random);
spaceDiy.setStyle(selector+' .'+this.contentClass, 'color', $('fontcolor').value, random);
spaceDiy.setStyle(selector+' .'+this.contentClass, 'font-size', this.formatValue('fontsize'), random);
spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'color', $('linkcolor').value, random);
var linkfontsize = parseInt($('linkfontsize').value);
linkfontsize = isNaN(linkfontsize) ? '' : linkfontsize+'px';
spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'font-size', this.formatValue('linkfontsize'), random);
if ($('borderop').checked) {
var bdtwidth = $('bdtwidth').value,bdrwidth = $('bdrwidth').value,bdbwidth = $('bdbwidth').value,bdlwidth = $('bdlwidth').value;
var bdtstyle = $('bdtstyle').value,bdrstyle = $('bdrstyle').value,bdbstyle = $('bdbstyle').value,bdlstyle = $('bdlstyle').value;
var bdtcolor = $('bdtcolor').value,bdrcolor = $('bdrcolor').value,bdbcolor = $('bdbcolor').value,bdlcolor = $('bdlcolor').value;
} else {
bdlwidth = bdbwidth = bdrwidth = bdtwidth = $('bdtwidth').value;
bdlstyle = bdbstyle = bdrstyle = bdtstyle = $('bdtstyle').value;
bdlcolor = bdbcolor = bdrcolor = bdtcolor = $('bdtcolor').value;
}
spaceDiy.setStyle(selector, 'border', '', random);
spaceDiy.setStyle(selector, 'border-top-width', bdtwidth, random);
spaceDiy.setStyle(selector, 'border-right-width', bdrwidth, random);
spaceDiy.setStyle(selector, 'border-bottom-width', bdbwidth, random);
spaceDiy.setStyle(selector, 'border-left-width', bdlwidth, random);
spaceDiy.setStyle(selector, 'border-top-style', bdtstyle, random);
spaceDiy.setStyle(selector, 'border-right-style', bdrstyle, random);
spaceDiy.setStyle(selector, 'border-bottom-style', bdbstyle, random);
spaceDiy.setStyle(selector, 'border-left-style', bdlstyle, random);
spaceDiy.setStyle(selector, 'border-top-color', bdtcolor, random);
spaceDiy.setStyle(selector, 'border-right-color', bdrcolor, random);
spaceDiy.setStyle(selector, 'border-bottom-color', bdbcolor, random);
spaceDiy.setStyle(selector, 'border-left-color', bdlcolor, random);
if ($('marginop').checked) {
var margint = this.formatValue('margint'),marginr = this.formatValue('marginr'), marginb = this.formatValue('marginb'), marginl = this.formatValue('marginl');
} else {
marginl = marginb = marginr = margint = this.formatValue('margint');
}
spaceDiy.setStyle(selector, 'margin-top',margint, random);
spaceDiy.setStyle(selector, 'margin-right', marginr, random);
spaceDiy.setStyle(selector, 'margin-bottom', marginb, random);
spaceDiy.setStyle(selector, 'margin-left', marginl, random);
if (objType == 1) {
if ($('cmarginop').checked) {
var cmargint = this.formatValue('cmargint'),cmarginr = this.formatValue('cmarginr'), cmarginb = this.formatValue('cmarginb'), cmarginl = this.formatValue('cmarginl');
} else {
cmarginl = cmarginb = cmarginr = cmargint = this.formatValue('cmargint');
}
selector = selector + ' .'+this.contentClass;
spaceDiy.setStyle(selector, 'margin-top', cmargint, random);
spaceDiy.setStyle(selector, 'margin-right', cmarginr, random);
spaceDiy.setStyle(selector, 'margin-bottom', cmarginb, random);
spaceDiy.setStyle(selector, 'margin-left', cmarginl, random);
}
this.setClose();
},
formatValue : function(id) {
var value = '';
if ($(id)) {
value = parseInt($(id).value);
value = isNaN(value) ? '' : value+'px';
}
return value;
},
saveBlockClassName : function(id,className){
if (!$('saveblockclassname')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="saveblockclassname" method="post" action=""><input type="hidden" name="classname" value="" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="saveclassnamesubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('saveblockclassname').action = 'portal.php?mod=portalcp&ac=block&op=saveblockclassname&bid='+id.replace('portal_block_','');
document.forms.saveblockclassname.classname.value = className;
ajaxpost('saveblockclassname','ajaxwaitid');
},
closeTitleEdit : function (fid) {
this.deleteFrame(fid+'bgPalette_0');
for (var i = 0 ; i<=10; i++) {
this.deleteFrame(fid+'Palette_'+i);
}
hideWindow('frameTitle');
},
openTitleEdit : function (e) {
if (typeof e == 'object') {
e = Util.event(e);
var fid = e.aim.id.replace('cmd_','');
} else {
fid = e;
}
var obj = this.getObjByName(fid);
var titlename = obj instanceof Block ? '模块' : '框架';
var repeatarr = [{'key':'平铺','value':'repeat'},{'key':'不平铺','value':'no-repeat'},{'key':'横向平铺','value':'repeat-x'},{'key':'纵向平铺','value':'repeat-y'}];
var len = obj.titles.length;
var bgimage = obj.titles.style && obj.titles.style['background-image'] ? obj.titles.style['background-image'] : '';
bgimage = bgimage != 'none' ? Util.trimUrl(bgimage) : '';
var bgcolor = obj.titles.style && obj.titles.style['background-color'] ? obj.titles.style['background-color'] : '';
bgcolor = Util.formatColor(bgcolor);
var bgrepeat = obj.titles.style && obj.titles.style['background-repeat'] ? obj.titles.style['background-repeat'] : '';
var common = '<table class="tfm">';
common += '<tr><th>背景图片:</th><td><input type="text" id="titleBgImage" class="px p_fre" value="'+bgimage+'" /> <select class="ps vm" id="titleBgRepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>';
common += '<tr><th>背景颜色:</th><td><input type="text" id="titleBgColor" class="px p_fre" value="'+bgcolor+'" size="7" />';
common += getColorPalette(fid+'bgPalette_0', 'titleBgColor' ,bgcolor)+'</td></tr>';
if (obj instanceof Tab) {
var switchArr = [{'key':'点击','value':'click'},{'key':'滑过','value':'mouseover'}];
var switchType = obj.titles['switchType'] ? obj.titles['switchType'][0] : 'click';
common += '<tr><th>切换类型:</th><td><select class="ps" id="switchType" >'+this.getOption(switchArr,switchType)+'</select></td></tr>';
}
common += '</table><hr class="l">';
var li = '';
li += '<div id="titleInput_0"><table class="tfm"><tr><th>'+titlename+'标题:</th><td><input type="text" id="titleText_0" class="px p_fre" value="`title`" /></td></tr>';
li += '<tr><th>链接:</th><td><input type="text" id="titleLink_0" class="px p_fre" value="`link`" /></td></tr>';
li += '<tr><th>图片:</th><td><input type="text" id="titleSrc_0" class="px p_fre" value="`src`" /></td></tr>';
li += '<tr><th>位置:</th><td><select id="titleFloat_0" class="ps vm"><option value="" `left`>居左</option><option value="right" `right`>居右</option></select>';
li += ' 偏移量: <input type="text" id="titleMargin_0" class="px p_fre vm" value="`margin`" size="2" />px</td></tr>';
li += '<tr><th>字体:</th><td><select class="ps vm" id="titleSize_0" ><option value="">大小</option>`size`</select>';
li += ' 颜色: <input type="text" id="titleColor_0" class="px p_fre vm" value="`color`" size="4" />';
li += getColorPalette(fid+'Palette_0', 'titleColor_0' ,'`color`');
li += '</td></tr><tr><td colspan="2"><hr class="l"></td></tr></table></div>';
var html = '';
if (obj.titles['first']) {
html = this.getTitleHtml(obj, 'first', li);
}
for (var i = 0; i < len; i++ ) {
html += this.getTitleHtml(obj, i, li);
}
if (!html) {
var bigarr = [];
for (var k=7;k<27;k++) {
var key = k+'px';
bigarr.push({'key':key,'value':key});
}
var ssize = this.getOption(bigarr,ssize);
html = li.replace('`size`', ssize).replace(/`\w+`/g, '');
}
var c = len + 1;
html = '<div class="c diywin" style="width:450px;height:400px; overflow:auto;"><table cellspacing="0" cellpadding="0" class="tfm pns"><tr><th></th><td><button type="button" id="addTitleInput" class="pn" onclick="drag.addTitleInput('+c+');"><em>添加新标题</em></button></td></tr></table><div id="titleEdit">'+html+common+'</div></div>';
var h = '<h3 class="flb"><em>编辑'+titlename+'标题</em><span><a href="javascript:;" class="flbc" onclick="drag.closeTitleEdit(\''+fid+'\');return false;" title="关闭">\n\
关闭</a></span></h3>';
var f = '<p class="o pns"><button onclick="drag.saveTitleEdit(\''+fid+'\');drag.closeTitleEdit(\''+fid+'\');" class="pn pnc" value="true">\n\
<strong>确定</strong></button><button onclick="drag.closeTitleEdit(\''+fid+'\')" class="pn" value="true"><strong>取消</strong></button></p>';
this.removeMenu(e);
showWindow('frameTitle',h + html + f, 'html', 0);
},
getTitleHtml : function (obj, i, li) {
var shtml = '',stitle = '',slink = '',sfloat = '',ssize = '',scolor = '',margin = '',src = '';
var c = i == 'first' ? '0' : i+1;
stitle = obj.titles[i]['text'] ? obj.titles[i]['text'] : '';
slink = obj.titles[i]['href'] ? obj.titles[i]['href'] : '';
sfloat = obj.titles[i]['float'] ? obj.titles[i]['float'] : '';
margin = obj.titles[i]['margin'] ? obj.titles[i]['margin'] : '';
ssize = obj.titles[i]['font-size'] ? obj.titles[i]['font-size']+'px' : '';
scolor = obj.titles[i]['color'] ? obj.titles[i]['color'] : '';
src = obj.titles[i]['src'] ? obj.titles[i]['src'] : '';
var bigarr = [];
for (var k=7;k<27;k++) {
var key = k+'px';
bigarr.push({'key':key,'value':key});
}
ssize = this.getOption(bigarr,ssize);
shtml = li.replace(/_0/g, '_' + c).replace('`title`', stitle).replace('`link`', slink).replace('`size`', ssize).replace('`src`',src);
var left = sfloat == '' ? 'selected' : '';
var right = sfloat == 'right' ? 'selected' : '';
scolor = Util.formatColor(scolor);
shtml = shtml.replace(/`color`/g, scolor).replace('`left`', left).replace('`right`', right).replace('`margin`', margin);
return shtml;
},
addTitleInput : function (c) {
if (c > 10) return false;
var pre = $('titleInput_'+(c-1));
var dom = document.createElement('div');
dom.className = 'tfm';
var exp = new RegExp('_'+(c-1), 'g');
dom.id = 'titleInput_'+c;
dom.innerHTML = pre.innerHTML.replace(exp, '_'+c);
Util.insertAfter(dom, pre);
$('addTitleInput').onclick = function () {drag.addTitleInput(c+1)};
},
saveTitleEdit : function (fid) {
var obj = this.getObjByName(fid);
var ele = $(fid);
var children = ele.childNodes;
var title = first = '';
var hastitle = 0;
var c = 0;
for (var i in children) {
if (typeof children[i] == 'object' && Util.hasClass(children[i], this.titleClass)) {
title = children[i];
break;
}
}
if (title) {
var arrDel = [];
for (var i in title.childNodes) {
if (typeof title.childNodes[i] == 'object' && Util.hasClass(title.childNodes[i], this.titleTextClass)) {
first = title.childNodes[i];
this._createTitleHtml(first, c);
if (first.innerHTML != '') hastitle = 1;
} else if (typeof title.childNodes[i] == 'object' && !Util.hasClass(title.childNodes[i], this.moveableObject)) {
arrDel.push(title.childNodes[i]);
}
}
for (var i = 0; i < arrDel.length; i++) {
title.removeChild(arrDel[i]);
}
} else {
var className = obj instanceof Tab ? this.tabClass : obj instanceof Frame ? 'frame' : obj instanceof Block ? 'block' : '';
title = document.createElement('div');
title.className = className + 'title' + ' '+ this.titleClass;
ele.insertBefore(title,ele.firstChild);
}
if (!first) {
var first = document.createElement('span');
first.className = this.titleTextClass;
this._createTitleHtml(first, c);
if (first.innerHTML != '') {
title.insertBefore(first, title.firstChild);
hastitle = 1;
}
}
while ($('titleText_'+(++c))) {
var dom = document.createElement('span');
dom.className = 'subtitle';
this._createTitleHtml(dom, c);
if (dom.innerHTML != '') {
if (dom.innerHTML) Util.insertAfter(dom, first);
first = dom;
hastitle = 1;
}
}
var titleBgImage = $('titleBgImage').value;
titleBgImage = titleBgImage && titleBgImage != 'none' ? Util.url(titleBgImage) : '';
if ($('titleBgColor').value != '' && titleBgImage == '') titleBgImage = 'none';
title.style['backgroundImage'] = titleBgImage;
if (titleBgImage) {
title.style['backgroundRepeat'] = $('titleBgRepeat').value;
}
title.style['backgroundColor'] = $('titleBgColor').value;
if ($('switchType')) {
title.switchType = [];
title.switchType[0] = $('switchType').value ? $('switchType').value : 'click';
title.setAttribute('switchtype',title.switchType[0]);
}
obj.titles = [];
if (hastitle == 1) {
this._initTitle(obj,title);
} else {
if (!(obj instanceof Tab)) title.parentNode.removeChild(title);
title = '';
this.initPosition();
}
if (obj instanceof Block) this.saveBlockTitle(fid,title);
this.setClose();
},
_createTitleHtml : function (ele,tid) {
var html = '',img = '';
tid = '_' + tid ;
var ttext = $('titleText'+tid).value;
var tlink = $('titleLink'+tid).value;
var tfloat = $('titleFloat'+tid).value;
var tmargin_ = tfloat != '' ? tfloat : 'left';
var tmargin = $('titleMargin'+tid).value;
var tsize = $('titleSize'+tid).value;
var tcolor = $('titleColor'+tid).value;
var src = $('titleSrc'+tid).value;
var divStyle = 'float:'+tfloat+';margin-'+tmargin_+':'+tmargin+'px;font-size:'+tsize;
var aStyle = 'color:'+tcolor+';';
if (src) {
img = '<img class="vm" src="'+src+'" alt="'+ttext+'" />';
}
if (ttext || img) {
if (tlink) {
Util.setStyle(ele, divStyle);
html = '<a href='+tlink+' target="_blank" style="'+aStyle+'">'+img+ttext+'</a>';
} else {
Util.setStyle(ele, divStyle+';'+aStyle);
html = img+ttext;
}
}
ele.innerHTML = html;
return true;
},
saveBlockTitle : function (id,title) {
if (!$('saveblocktitle')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="saveblocktitle" method="post" action=""><input type="hidden" name="title" value="" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="savetitlesubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('saveblocktitle').action = 'portal.php?mod=portalcp&ac=block&op=saveblocktitle&bid='+id.replace('portal_block_','');
var html = !title ? '' : title.outerHTML;
document.forms.saveblocktitle.title.value = html;
ajaxpost('saveblocktitle','ajaxwaitid');
},
removeBlock : function (e, flag) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var obj = this.getObjByName(id);
if (!flag) {
if (!confirm('您确实要删除吗,删除以后将不可恢复')) return false;
}
if (obj instanceof Block) {
this.delBlock(id);
} else if (obj instanceof Frame) {
this.delFrame(obj);
}
$(id).parentNode.removeChild($(id));
var content = $(id+'_content');
if(content) {
content.parentNode.removeChild(content);
}
this.setClose();
this.initPosition();
this.initChkBlock();
},
delBlock : function (bid) {
spaceDiy.removeCssSelector('#'+bid);
this.stopSlide(bid);
},
delFrame : function (frame) {
spaceDiy.removeCssSelector('#'+frame.name);
for (var i in frame['columns']) {
if (frame['columns'][i] instanceof Column) {
var children = frame['columns'][i]['children'];
for (var j in children) {
if (children[j] instanceof Frame) {
this.delFrame(children[j]);
} else if (children[j] instanceof Block) {
this.delBlock(children[j]['name']);
}
}
}
}
this.setClose();
},
initChkBlock : function (data) {
if (typeof name == 'undefined' || data == null ) data = this.data;
if ( data instanceof Frame) {
this.initChkBlock(data['columns']);
} else if (data instanceof Block) {
var el = $('chk'+data.name);
if (el != null) el.checked = true;
} else if (typeof data == 'object') {
for (var i in data) {
this.initChkBlock(data[i]);
}
}
},
getBlockData : function (blockname) {
var bid = this.dragObj.id;
var eleid = bid;
if (bid.indexOf('portal_block_') != -1) {
eleid = 0;
}else {
bid = 0;
}
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=block&classname='+blockname+'&bid='+bid+'&eleid='+eleid+'&tpl='+document.diyform.template.value,'get',-1);
drag.initPosition();
this.fn = '';
return true;
},
stopSlide : function (id) {
if (typeof slideshow == 'undefined' || typeof slideshow.entities == 'undefined') return false;
var slidebox = $C('slidebox',$(id));
if(slidebox && slidebox.length > 0) {
if(slidebox[0].id) {
var timer = slideshow.entities[slidebox[0].id].timer;
if(timer) clearTimeout(timer);
slideshow.entities[slidebox[0].id] = '';
}
}
},
blockForceUpdate : function (e,all) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var bid = id.replace('portal_block_', '');
var bcontent = $(id+'_content');
if (!bcontent) {
bcontent = document.createElement('div');
bcontent.id = id+'_content';
bcontent.className = this.contentClass;
}
this.stopSlide(id);
var height = Util.getFinallyStyle(bcontent, 'height');
bcontent.style.lineHeight = height == 'auto' ? '' : (height == '0px' ? '20px' : height);
bcontent.innerHTML = '<center>正在加载内容...</center>';
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=getblock&forceupdate=1&inajax=1&bid='+bid+'&tpl='+document.diyform.template.value, function(s) {
var obj = document.createElement('div');
obj.innerHTML = s;
bcontent.parentNode.removeChild(bcontent);
$(id).innerHTML = obj.childNodes[0].innerHTML;
evalscript(s);
if(s.indexOf('runslideshow()') != -1) {runslideshow();}
drag.initPosition();
if (all) {drag.getBlocks();}
});
},
frameExport : function (e) {
var flag = true;
if (drag.isChange) {
flag = confirm('您已经做过修改,请保存后再做导出,否则导出的数据将不包括您这次所做的修改。');
}
if (flag) {
if ( typeof e == 'object') {
e = Util.event(e);
var frame = e.aim.id.replace('cmd_','');
} else {
frame = e == undefined ? '' : e;
}
if (!$('frameexport')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="frameexport" method="post" action="" target="_blank"><input type="hidden" name="frame" value="" />\n\
<input type="hidden" name="tpl" value="'+document.diyform.template.value+'" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="exportsubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('frameexport').action = 'portal.php?mod=portalcp&ac=diy&op=export';
document.forms.frameexport.frame.value = frame;
document.forms.frameexport.submit();
}
doane();
},
openFrameImport : function (type) {
type = type || 0;
showWindow('showimport','portal.php?mod=portalcp&ac=diy&op=import&tpl='+document.diyform.template.value+'&type='+type, 'get');
},
endBlockForceUpdateBatch : function () {
if($('allupdate')) {
$('allupdate').innerHTML = '已操作完成。';
$('fwin_dialog_submit').style.display = '';
$('fwin_dialog_cancel').style.display = 'none';
}
this.initPosition();
},
getBlocks : function () {
if (this.blocks.length == 0) {
this.endBlockForceUpdateBatch();
}
if (this.blocks.length > 0) {
var cur = this.blocksLen - this.blocks.length;
if($('allupdate')) {
$('allupdate').innerHTML = '共<span style="color:blue">'+this.blocksLen+'</span>个模块,正在更新第<span style="color:red">'+cur+'</span>个,已完成<span style="color:red">'+(parseInt(cur / this.blocksLen * 100)) + '%</span>';
var bid = 'portal_block_'+this.blocks.pop();
this.blockForceUpdate(bid,true);
}
}
},
blockForceUpdateBatch : function (blocks) {
if (blocks) {
this.blocks = blocks;
} else {
this.initPosition();
this.blocks = this.allBlocks;
}
this.blocksLen = this.blocks.length;
showDialog('<div id="allupdate" style="width:350px;line-height:28px;">开始更新...</div>','confirm','更新模块数据', '', true, 'drag.endBlockForceUpdateBatch()');
var wait = function() {
if($('fwin_dialog_submit')) {
$('fwin_dialog_submit').style.display = 'none';
setTimeout(function(){drag.getBlocks()},500);
} else {
setTimeout(wait,100);
}
};
wait();
doane();
},
clearAll : function () {
if (confirm('您确实要清空页面上所在DIY数据吗,清空以后将不可恢复')) {
for (var i in this.data) {
for (var j in this.data[i]) {
if (typeof(this.data[i][j]) == 'object' && this.data[i][j].name.indexOf('_temp')<0) {
this.delFrame(this.data[i][j]);
$(this.data[i][j].name).parentNode.removeChild($(this.data[i][j].name));
}
}
}
this.initPosition();
this.setClose();
}
doane();
},
createObj : function (e,objType,contentType) {
if (objType == 'block' && !this.checkHasFrame()) {alert("提示:未找到框架,请先添加框架。");spaceDiy.getdiy('frame');return false;}
e = Util.event(e);
if(e.which != 1 ) {return false;}
var html = '',offWidth = 0;
if (objType == 'frame') {
html = this.getFrameHtml(contentType);
offWidth = 600;
} else if (objType == 'block') {
html = this.getBlockHtml(contentType);
offWidth = 200;
this.fn = function (e) {drag.getBlockData(contentType);};
} else if (objType == 'tab') {
html = this.getTabHtml(contentType);
offWidth = 300;
}
var ele = document.createElement('div');
ele.innerHTML = html;
ele = ele.childNodes[0];
document.body.appendChild(ele);
this.dragObj = this.overObj = ele;
if (!this.getTmpBoxElement()) return false;
var scroll = Util.getScroll();
this.dragObj.style.position = 'absolute';
this.dragObj.style.left = e.clientX + scroll.l - 60 + "px";
this.dragObj.style.top = e.clientY + scroll.t - 10 + "px";
this.dragObj.style.width = offWidth + 'px';
this.dragObj.style.cursor = 'move';
this.dragObj.lastMouseX = e.clientX;
this.dragObj.lastMouseY = e.clientY;
Util.insertBefore(this.tmpBoxElement,this.overObj);
Util.addClass(this.dragObj,this.moving);
this.dragObj.style.zIndex = 500 ;
this.scroll = Util.getScroll();
this.newFlag = true;
var _method = this;
document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);};
document.onmouseup = function (e){Drag.prototype.dragEnd.call(_method, e);};
},
getFrameHtml : function (type) {
var id = 'frame'+Util.getRandom(6);
var className = [this.frameClass,this.moveableObject].join(' ');
className = className + ' cl frame-' + type;
var str = '<div id="'+id+'" class="'+className+'">';
str += '<div id="'+id+'_title" class="'+this.titleClass+' '+this.frameTitleClass+'"><span class="'+this.titleTextClass+'">'+type+'框架</span></div>';
var cols = type.split('-');
var clsl='',clsc='',clsr='';
clsl = ' frame-'+type+'-l';
clsc = ' frame-'+type+'-c';
clsr = ' frame-'+type+'-r';
var len = cols.length;
if (len == 1) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsc+'"></div>';
} else if (len == 2) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+ '"></div>';
str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsr+ '"></div>';
} else if (len == 3) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+'"></div>';
str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsc+'"></div>';
str += '<div id="'+id+'_right" class="'+this.moveableColumn+clsr+'"></div>';
}
str += '</div>';
return str;
},
getTabHtml : function () {
var id = 'tab'+Util.getRandom(6);
var className = [this.tabClass,this.moveableObject].join(' ');
className = className + ' cl';
var titleClassName = [this.tabTitleClass, this.titleClass, this.moveableColumn, 'cl'].join(' ');
var str = '<div id="'+id+'" class="'+className+'">';
str += '<div id="'+id+'_title" class="'+titleClassName+'"><span class="'+this.titleTextClass+'">tab标签</span></div>';
str += '<div id="'+id+'_content" class="'+this.tabContentClass+'"></div>';
str += '</div>';
return str;
},
getBlockHtml : function () {
var id = 'block'+Util.getRandom(6);
var str = '<div id="'+id+'" class="block move-span"></div>';
str += '</div>';
return str;
},
setClose : function () {
if(this.sampleMode) {
return true;
} else {
if (!this.isChange) {
window.onbeforeunload = function() {
return '您的数据已经修改,退出将无法保存您的修改。';
};
}
this.isChange = true;
spaceDiy.enablePreviewButton();
}
},
clearClose : function () {
this.isChange = false;
this.isClearClose = true;
window.onbeforeunload = function () {};
},
goonDIY : function () {
if ($('prefile').value == '1') {
showDialog('<div style="line-height:28px;">按继续按钮将打开暂存数据并DIY,<br />按删除按钮将删除暂存数据。</div>','confirm','是否继续暂存数据的DIY?', function(){location.replace(location.href+'&preview=yes');}, true, 'spaceDiy.cancelDIY()', '', '继续', '删除');
} else if (location.search.indexOf('preview=yes') > -1) {
spaceDiy.enablePreviewButton();
} else {
spaceDiy.disablePreviewButton();
}
setInterval(function(){spaceDiy.save('savecache', 1);},180000);
}
});
var spaceDiy = new DIY();
spaceDiy.extend({
save : function (optype,rejs) {
optype = typeof optype == 'undefined' ? '' : optype;
if (optype == 'savecache' && !drag.isChange) {return false;}
var tplpre = document.diyform.template.value.split(':');
if (!optype) {
if (['portal/portal_topic_content', 'portal/list', 'portal/view'].indexOf(tplpre[0]) == -1) {
if (document.diyform.template.value.indexOf(':') > -1 && !document.selectsave) {
var schecked = '',dchecked = '';
if (document.diyform.savemod.value == '1') {
dchecked = ' checked';
} else {
schecked = ' checked';
}
showDialog('<form name="selectsave" action="" method="get"><label><input type="radio" value="0" name="savemod"'+schecked+' />应用于此类全部页面</label>\n\
<label><input type="radio" value="1" name="savemod"'+dchecked+' />只应用于本页面</label></form>','notice', '', spaceDiy.save);
return false;
}
if (document.selectsave) {
if (document.selectsave.savemod[0].checked) {
document.diyform.savemod.value = document.selectsave.savemod[0].value;
} else {
document.diyform.savemod.value = document.selectsave.savemod[1].value;
}
}
} else {
document.diyform.savemod.value = 1;
}
} else if (optype == 'savecache') {
if (!drag.isChange) return false;
this.checkPreview_form();
document.diyform.rejs.value = rejs ? 0 : 1;
} else if (optype =='preview') {
if (drag.isChange) {
optype = 'savecache';
} else {
this.checkPreview_form();
$('preview_form').submit();
return false;
}
}
document.diyform.action = document.diyform.action.replace(/[&|\?]inajax=1/, '');
document.diyform.optype.value = optype;
document.diyform.spacecss.value = spaceDiy.getSpacecssStr();
document.diyform.style.value = spaceDiy.style;
document.diyform.layoutdata.value = drag.getPositionStr();
document.diyform.gobackurl.value = spaceDiy.cancelDiyUrl();
drag.clearClose();
if (optype == 'savecache') {
document.diyform.handlekey.value = 'diyform';
ajaxpost('diyform','ajaxwaitid','ajaxwaitid','onerror');
} else {
saveUserdata('diy_advance_mode', '');
document.diyform.submit();
}
},
checkPreview_form : function () {
if (!$('preview_form')) {
var dom = document.createElement('div');
var search = '';
var sarr = location.search.replace('?','').split('&');
for (var i = 0;i<sarr.length;i++){
var kv = sarr[i].split('=');
if (kv.length>1 && kv[0] != 'diy') {
search += '<input type="hidden" value="'+kv[1]+'" name="'+kv[0]+'" />';
}
}
search += '<input type="hidden" value="yes" name="preview" />';
dom.innerHTML = '<form action="'+location.href+'" target="_bloak" method="get" id="preview_form">'+search+'</form>';
var form = dom.getElementsByTagName('form');
$('append_parent').appendChild(form[0]);
}
},
cancelDiyUrl : function () {
return location.href.replace(/[\?|\&]diy\=yes/g,'').replace(/[\?|\&]preview=yes/,'');
},
cancel : function () {
saveUserdata('diy_advance_mode', '');
if (drag.isClearClose) {
showDialog('<div style="line-height:28px;">是否保留暂存数据?<br />按确定按钮将保留暂存数据,按取消按钮将删除暂存数据。</div>','confirm','保留暂存数据', function(){location.href = spaceDiy.cancelDiyUrl();}, true, function(){window.onunload=function(){spaceDiy.cancelDIY()};location.href = spaceDiy.cancelDiyUrl();});
} else {
location.href = this.cancelDiyUrl();
}
},
recover : function() {
if (confirm('您确定要恢复到上一版本保存的结果吗?')) {
drag.clearClose();
document.diyform.recover.value = '1';
document.diyform.gobackurl.value = location.href.replace(/(\?diy=yes)|(\&diy=yes)/,'').replace(/[\?|\&]preview=yes/,'');
document.diyform.submit();
}
doane();
},
enablePreviewButton : function () {
if ($('preview')){
$('preview').className = '';
if(drag.isChange) {
$('diy_preview').onclick = function () {spaceDiy.save('savecache');return false;};
} else {
$('diy_preview').onclick = function () {spaceDiy.save('preview');return false;};
}
Util.show($('savecachemsg'))
}
},
disablePreviewButton : function () {
if ($('preview')) {
$('preview').className = 'unusable';
$('diy_preview').onclick = function () {return false;};
}
},
cancelDIY : function () {
this.disablePreviewButton();
document.diyform.optype.value = 'canceldiy';
var x = new Ajax();
x.post($('diyform').action+'&inajax=1','optype=canceldiy&diysubmit=1&template='+document.diyform.template.value+'&savemod='+document.diyform.savemod.value+'&formhash='+document.diyform.formhash.value,function(s){});
},
switchBlockclass : function(blockclass) {
var navs = $('contentblockclass_nav').getElementsByTagName('a');
var contents = $('contentblockclass').getElementsByTagName('ul');
for(var i=0; i<navs.length; i++) {
if(navs[i].id=='bcnav_'+blockclass) {
navs[i].className = 'a';
} else {
navs[i].className = '';
}
}
for(var i=0; i<contents.length; i++) {
if(contents[i].id=='contentblockclass_'+blockclass) {
contents[i].style.display = '';
} else {
contents[i].style.display = 'none';
}
}
},
getdiy : function (type) {
if (type) {
var nav = $('controlnav').children;
for (var i in nav) {
if (nav[i].className == 'current') {
nav[i].className = '';
var contentid = 'content'+nav[i].id.replace('nav', '');
if ($(contentid)) $(contentid).style.display = 'none';
}
}
$('nav'+type).className = 'current';
if (type == 'start' || type == 'frame') {
$('content'+type).style.display = 'block';
return true;
}
if(type == 'blockclass' && $('content'+type).innerHTML !='') {
$('content'+type).style.display = 'block';
return true;
}
var para = '&op='+type;
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
para += '&' + arguments[i] + '=' + arguments[++i];
}
}
var ajaxtarget = type == 'diy' ? 'diyimages' : '';
var x = new Ajax();
x.showId = ajaxtarget;
x.get('portal.php?mod=portalcp&ac=diy'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s, x) {
if (s) {
if (typeof cpb_frame == 'object' && !BROWSER.ie) {delete cpb_frame;}
if (!$('content'+type)) {
var dom = document.createElement('div');
dom.id = 'content'+type;
$('controlcontent').appendChild(dom);
}
$('content'+type).innerHTML = s;
$('content'+type).style.display = 'block';
if (type == 'diy') {
spaceDiy.setCurrentDiy(spaceDiy.currentDiy);
if (spaceDiy.styleSheet.rules.length > 0) {
Util.show('recover_button');
}
}
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
ajaxupdateevents($(x.showId));
}
}
if(!evaled) evalscript(s);
}
});
}
}
});
spaceDiy.init(1);
function succeedhandle_diyform (url, message, values) {
if (values['rejs'] == '1') {
document.diyform.rejs.value = '';
parent.$('preview_form').submit();
}
spaceDiy.enablePreviewButton();
return false;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common_extra.js 22925 2011-06-01 10:23:08Z liulanbo $
*/
function _relatedlinks(rlinkmsgid) {
if(!$(rlinkmsgid) || $(rlinkmsgid).innerHTML.match(/<script[^\>]*?>/i)) {
return;
}
var alink = new Array(), ignore = new Array();
var i = 0;
var msg = $(rlinkmsgid).innerHTML;
msg = msg.replace(/(<ignore_js_op\>[\s|\S]*?<\/ignore_js_op\>)/ig, function($1) {
ignore[i] = $1;
i++;
return '#ignore_js_op '+(i - 1)+'#';
});
i = 0;
msg = msg.replace(/(<a.*?<\/a\>)/ig, function($1) {
alink[i] = $1;
i++;
return '#alink '+(i - 1)+'#';
});
var relatedid = new Array();
msg = msg.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
for(var j = 0; j > -1; j++) {
if(relatedlink[j] && !relatedid[j]) {
var ra = '<a href="'+relatedlink[j]['surl']+'" target="_blank" class="relatedlink">'+relatedlink[j]['sname']+'</a>';
var $rtmp = $3;
$3 = $3.replace(relatedlink[j]['sname'], ra);
if($3 != $rtmp) {
relatedid[j] = 1;
}
} else {
break;
}
}
return $2 + $3;
});
for(var k in alink) {
msg = msg.replace('#alink '+k+'#', alink[k]);
}
for(var l in ignore) {
msg = msg.replace('#ignore_js_op '+l+'#', ignore[l]);
}
$(rlinkmsgid).innerHTML = msg;
}
function _updatesecqaa(idhash) {
if($('secqaa_' + idhash)) {
$('secqaaverify_' + idhash).value = '';
if(secST['qaa_' + idhash]) {
clearTimeout(secST['qaa_' + idhash]);
}
$('checksecqaaverify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/none.gif" width="16" height="16" class="vm" />';
ajaxget('misc.php?mod=secqaa&action=update&idhash=' + idhash, 'secqaa_' + idhash, null, '', '', function() {
secST['qaa_' + idhash] = setTimeout(function() {$('secqaa_' + idhash).innerHTML = '<span class="xi2 cur1" onclick="updatesecqaa(\''+idhash+'\')">刷新验证问答</span>';}, 180000);
});
}
}
function _updateseccode(idhash, play) {
if(isUndefined(play)) {
if($('seccode_' + idhash)) {
$('seccodeverify_' + idhash).value = '';
if(secST['code_' + idhash]) {
clearTimeout(secST['code_' + idhash]);
}
$('checkseccodeverify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/none.gif" width="16" height="16" class="vm" />';
ajaxget('misc.php?mod=seccode&action=update&idhash=' + idhash, 'seccode_' + idhash, null, '', '', function() {
secST['code_' + idhash] = setTimeout(function() {$('seccode_' + idhash).innerHTML = '<span class="xi2 cur1" onclick="updateseccode(\''+idhash+'\')">刷新验证码</span>';}, 180000);
});
}
} else {
eval('window.document.seccodeplayer_' + idhash + '.SetVariable("isPlay", "1")');
}
}
function _checksec(type, idhash, showmsg, recall) {
var showmsg = !showmsg ? 0 : showmsg;
var secverify = $('sec' + type + 'verify_' + idhash).value;
if(!secverify) {
return;
}
var x = new Ajax('XML', 'checksec' + type + 'verify_' + idhash);
x.loading = '';
$('checksec' + type + 'verify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" />';
x.get('misc.php?mod=sec' + type + '&action=check&inajax=1&&idhash=' + idhash + '&secverify=' + (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(secverify) : secverify), function(s){
var obj = $('checksec' + type + 'verify_' + idhash);
obj.style.display = '';
if(s.substr(0, 7) == 'succeed') {
obj.innerHTML = '<img src="'+ IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
if(showmsg) {
recall(1);
}
} else {
obj.innerHTML = '<img src="'+ IMGDIR + '/check_error.gif" width="16" height="16" class="vm" />';
if(showmsg) {
if(type == 'code') {
showError('验证码错误,请重新填写');
} else if(type == 'qaa') {
showError('验证问答错误,请重新填写');
}
recall(0);
}
}
});
}
function _setDoodle(fid, oid, url, tid, from) {
if(tid == null) {
hideWindow(fid);
} else {
$(tid).style.display = '';
$(fid).style.display = 'none';
}
var doodleText = '[img]'+url+'[/img]';
if($(oid) != null) {
if(from == "editor") {
insertImage(url);
} else if(from == "fastpost") {
seditor_insertunit('fastpost', doodleText);
} else if(from == "forumeditor") {
if(wysiwyg) {
insertText('<img src="' + url + '" border="0" alt="" />', false);
} else {
insertText(doodleText, strlen(doodleText), 0);
}
} else {
insertContent(oid, doodleText);
}
}
}
function _showdistrict(container, elems, totallevel, changelevel) {
var getdid = function(elem) {
var op = elem.options[elem.selectedIndex];
return op['did'] || op.getAttribute('did') || '0';
};
var pid = changelevel >= 1 && elems[0] && $(elems[0]) ? getdid($(elems[0])) : 0;
var cid = changelevel >= 2 && elems[1] && $(elems[1]) ? getdid($(elems[1])) : 0;
var did = changelevel >= 3 && elems[2] && $(elems[2]) ? getdid($(elems[2])) : 0;
var coid = changelevel >= 4 && elems[3] && $(elems[3]) ? getdid($(elems[3])) : 0;
var url = "home.php?mod=misc&ac=ajax&op=district&container="+container
+"&province="+elems[0]+"&city="+elems[1]+"&district="+elems[2]+"&community="+elems[3]
+"&pid="+pid + "&cid="+cid+"&did="+did+"&coid="+coid+'&level='+totallevel+'&handlekey='+container+'&inajax=1'+(isUndefined(changelevel) ? '&showdefault=1' : '');
ajaxget(url, container, '');
}
function _copycode(obj) {
if(!obj) return false;
if(window.getSelection) {
var sel = window.getSelection();
if (sel.setBaseAndExtent) {
sel.setBaseAndExtent(obj, 0, obj, 1);
} else {
var rng = document.createRange();
rng.selectNodeContents(obj);
sel.addRange(rng);
}
} else {
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.select();
}
setCopy(BROWSER.ie ? obj.innerText.replace(/\r\n\r\n/g, '\r\n') : obj.textContent, '代码已复制到剪贴板');
}
function _setCopy(text, msg){
if(BROWSER.ie) {
var r = clipboardData.setData('Text', text);
if(r) {
if(msg) {
showPrompt(null, null, '<span>' + msg + '</span>', 1500);
}
} else {
showDialog('<div class="c"><div style="width: 200px; text-align: center;">复制失败,请选择“允许访问”</div></div>', 'alert');
}
} else {
var msg = '<div class="c"><div style="width: 200px; text-align: center; text-decoration:underline;">点此复制到剪贴板</div>' +
AC_FL_RunContent('id', 'clipboardswf', 'name', 'clipboardswf', 'devicefont', 'false', 'width', '200', 'height', '40', 'src', STATICURL + 'image/common/clipboard.swf', 'menu', 'false', 'allowScriptAccess', 'sameDomain', 'swLiveConnect', 'true', 'wmode', 'transparent', 'style' , 'margin-top:-20px') + '</div>';
showDialog(msg, 'info');
text = text.replace(/[\xA0]/g, ' ');
CLIPBOARDSWFDATA = text;
}
}
function _showselect(obj, inpid, t, rettype) {
var showselect_row = function (inpid, s, v, notime, rettype) {
if(v >= 0) {
if(!rettype) {
var notime = !notime ? 0 : 1;
var t = today.getTime();
t += 86400000 * v;
var d = new Date();
d.setTime(t);
var month = d.getMonth() + 1;
month = month < 10 ? '0' + month : month;
var day = d.getDate();
day = day < 10 ? '0' + day : day;
var hour = d.getHours();
hour = hour < 10 ? '0' + hour : hour;
var minute = d.getMinutes();
minute = minute < 10 ? '0' + minute : minute;
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + d.getFullYear() + '-' + month + '-' + day + (!notime ? ' ' + hour + ':' + minute: '') + '\'">' + s + '</a>';
} else {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + v + '\'">' + s + '</a>';
}
} else if(v == -1) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').focus()">' + s + '</a>';
} else if(v == -2) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').onclick()">' + s + '</a>';
}
};
if(!obj.id) {
var t = !t ? 0 : t;
var rettype = !rettype ? 0 : rettype;
obj.id = 'calendarexp_' + Math.random();
div = document.createElement('div');
div.id = obj.id + '_menu';
div.style.display = 'none';
div.className = 'p_pop';
$('append_parent').appendChild(div);
s = '';
if(!t) {
s += showselect_row(inpid, '一天', 1, 0, rettype);
s += showselect_row(inpid, '一周', 7, 0, rettype);
s += showselect_row(inpid, '一个月', 30, 0, rettype);
s += showselect_row(inpid, '三个月', 90, 0, rettype);
s += showselect_row(inpid, '自定义', -2);
} else {
if($(t)) {
var lis = $(t).getElementsByTagName('LI');
for(i = 0;i < lis.length;i++) {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = this.innerHTML;$(\''+obj.id+'_menu\').style.display=\'none\'">' + lis[i].innerHTML + '</a>';
}
s += showselect_row(inpid, '自定义', -1);
} else {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'0\'">永久</a>';
s += showselect_row(inpid, '7 天', 7, 1, rettype);
s += showselect_row(inpid, '14 天', 14, 1, rettype);
s += showselect_row(inpid, '一个月', 30, 1, rettype);
s += showselect_row(inpid, '三个月', 90, 1, rettype);
s += showselect_row(inpid, '半年', 182, 1, rettype);
s += showselect_row(inpid, '一年', 365, 1, rettype);
s += showselect_row(inpid, '自定义', -1);
}
}
$(div.id).innerHTML = s;
}
showMenu({'ctrlid':obj.id,'evt':'click'});
if(BROWSER.ie && BROWSER.ie < 7) {
doane(event);
}
}
function _zoom(obj, zimg, nocover, pn) {
zimg = !zimg ? obj.src : zimg;
if(!zoomstatus) {
window.open(zimg, '', '');
return;
}
if(!obj.id) obj.id = 'img_' + Math.random();
var menuid = 'imgzoom';
var zoomid = menuid + '_zoom';
var imgtitle = !nocover && obj.title ? '<div class="ptn pbn">' + obj.title + '</div>' : '';
var cover = !nocover ? 1 : 0;
var pn = !pn ? 0 : 1;
var maxh = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) - 70;
var loadCheck = function (obj) {
if(obj.complete) {
var imgw = loading.width;
var imgh = loading.height;
var r = imgw / imgh;
var w = document.body.clientWidth * 0.95;
w = imgw > w ? w : imgw;
var h = w / r;
if(h > maxh) {
h = maxh;
w = h * r;
}
showimage(zimg, w, h, imgw, imgh);
} else {
setTimeout(function () { loadCheck(loading); }, 100);
}
};
var showloading = function (zimg, pn) {
if(!pn) {
if(!$(menuid + '_waiting')) {
waiting = document.createElement('img');
waiting.id = menuid + '_waiting';
waiting.src = IMGDIR + '/imageloading.gif';
waiting.style.opacity = '0.8';
waiting.style.filter = 'alpha(opacity=80)';
waiting.style.position = 'absolute';
waiting.style.zIndex = 100000;
$('append_parent').appendChild(waiting);
}
}
$(menuid + '_waiting').style.display = '';
$(menuid + '_waiting').style.left = (document.body.clientWidth - 42) / 2 + 'px';
$(menuid + '_waiting').style.top = ((document.documentElement.clientHeight - 42) / 2 + Math.max(document.documentElement.scrollTop, document.body.scrollTop)) + 'px';
loading = new Image();
setTimeout(function () { loadCheck(loading); }, 100);
if(!pn) {
$(menuid + '_zoomlayer').style.display = 'none';
}
loading.src = zimg;
};
var adjustpn = function(h) {
h = h < 90 ? 90 : h;
if($('zimg_prev')) {
$('zimg_prev').style.height= parseInt(h) + 'px';
}
if($('zimg_next')) {
$('zimg_next').style.height= parseInt(h) + 'px';
}
};
var showimage = function (zimg, w, h, imgw, imgh) {
$(menuid + '_waiting').style.display = 'none';
$(menuid + '_zoomlayer').style.display = '';
$(menuid + '_img').style.width = 'auto';
$(menuid + '_img').style.height = 'auto';
$(menuid).style.width = (w < 300 ? 300 : w + 20) + 'px';
mheight = h + 50;
$(menuid).style.height = mheight + 'px';
$(menuid + '_zoomlayer').style.height = (mheight < 120 ? 120 : mheight) + 'px';
$(menuid + '_img').innerHTML = '<img id="' + zoomid + '" src="' + zimg + '" width="' + w + '" height="' + h + '" w="' + imgw + '" h="' + imgh + '" />' + imgtitle;
if($(menuid + '_imglink')) {
$(menuid + '_imglink').href = zimg;
}
setMenuPosition('', menuid, '00');
adjustpn(h);
};
var adjust = function(e, a) {
if(!$(zoomid)) {
return;
}
var imgw = $(zoomid).getAttribute('w');
var imgh = $(zoomid).getAttribute('h');
var imgwstep = imgw / 10;
var imghstep = imgh / 10;
if(!a) {
if(!e) e = window.event;
if(e.altKey || e.shiftKey || e.ctrlKey) return;
if(e.wheelDelta <= 0 || e.detail > 0) {
if($(zoomid).width - imgwstep <= 200 || $(zoomid).height - imghstep <= 200) {
doane(e);return;
}
$(zoomid).width -= imgwstep;
$(zoomid).height -= imghstep;
} else {
if($(zoomid).width + imgwstep >= imgw) {
doane(e);return;
}
$(zoomid).width += imgwstep;
$(zoomid).height += imghstep;
}
} else {
$(zoomid).width = imgw;
$(zoomid).height = imgh;
}
$(menuid).style.width = (parseInt($(zoomid).width < 300 ? 300 : parseInt($(zoomid).width)) + 20) + 'px';
mheight = (parseInt($(zoomid).height) + 50);
$(menuid).style.height = mheight + 'px';
$(menuid + '_zoomlayer').style.height = (mheight < 120 ? 120 : mheight) + 'px';
adjustpn($(zoomid).height);
setMenuPosition('', menuid, '00');
doane(e);
};
if(!$(menuid) && !pn) {
menu = document.createElement('div');
menu.id = menuid;
if(cover) {
menu.innerHTML = '<div class="zoominner" id="' + menuid + '_zoomlayer" style="display:none"><p><span class="y"><a id="' + menuid + '_imglink" class="imglink" target="_blank" title="在新窗口打开">在新窗口打开</a><a id="' + menuid + '_adjust" href="javascipt:;" class="imgadjust" title="实际大小">实际大小</a>' +
'<a href="javascript:;" onclick="hideMenu()" class="imgclose" title="关闭">关闭</a></span>鼠标滚轮缩放图片</p>' +
'<div class="zimg_p" id="' + menuid + '_picpage"></div><div class="hm" id="' + menuid + '_img"></div></div>';
} else {
menu.innerHTML = '<div class="popupmenu_popup" id="' + menuid + '_zoomlayer" style="width:auto"><span class="right y"><a href="javascript:;" onclick="hideMenu()" class="flbc" style="width:20px;margin:0 0 2px 0">关闭</a></span>鼠标滚轮缩放图片<div class="zimg_p" id="' + menuid + '_picpage"></div><div class="hm" id="' + menuid + '_img"></div></div>';
}
if(BROWSER.ie || BROWSER.chrome){
menu.onmousewheel = adjust;
} else {
menu.addEventListener('DOMMouseScroll', adjust, false);
}
$('append_parent').appendChild(menu);
if($(menuid + '_adjust')) {
$(menuid + '_adjust').onclick = function(e) {adjust(e, 1)};
}
}
showloading(zimg, pn);
picpage = '';
$(menuid + '_picpage').innerHTML = '';
if(typeof zoomgroup == 'object' && zoomgroup[obj.id] && typeof aimgcount == 'object' && aimgcount[zoomgroup[obj.id]]) {
authorimgs = aimgcount[zoomgroup[obj.id]];
var aid = obj.id.substr(5), authorlength = authorimgs.length, authorcurrent = '';
if(authorlength > 1) {
for(i = 0; i < authorlength;i++) {
if(aid == authorimgs[i]) {
authorcurrent = i;
}
}
if(authorcurrent !== '') {
paid = authorcurrent > 0 ? authorimgs[authorcurrent - 1] : authorimgs[authorlength - 1];
picpage += ' <div id="zimg_prev" onmouseover="dragMenuDisabled=true;this.style.backgroundPosition=\'0 50px\'" onmouseout="dragMenuDisabled=false;this.style.backgroundPosition=\'0 -100px\';" onclick="zoom($(\'aimg_' + paid + '\'), $(\'aimg_' + paid + '\').getAttribute(\'zoomfile\'), 0, 1)" class="zimg_prev"><strong>上一张</strong></div> ';
paid = authorcurrent < authorlength - 1 ? authorimgs[authorcurrent + 1] : authorimgs[0];
picpage += ' <div id="zimg_next" onmouseover="dragMenuDisabled=true;this.style.backgroundPosition=\'100% 50px\'" onmouseout="dragMenuDisabled=false;this.style.backgroundPosition=\'100% -100px\';" onclick="zoom($(\'aimg_' + paid + '\'), $(\'aimg_' + paid + '\').getAttribute(\'zoomfile\'), 0, 1)" class="zimg_next"><strong>下一张</strong></div> ';
}
if(picpage) {
$(menuid + '_picpage').innerHTML = picpage;
}
}
}
showMenu({'ctrlid':obj.id,'menuid':menuid,'duration':3,'pos':'00','cover':cover,'drag':menuid,'maxh':''});
}
function _switchTab(prefix, current, total, activeclass) {
activeclass = !activeclass ? 'a' : activeclass;
for(var i = 1; i <= total;i++) {
var classname = ' '+$(prefix + '_' + i).className+' ';
$(prefix + '_' + i).className = classname.replace(' '+activeclass+' ','').substr(1);
$(prefix + '_c_' + i).style.display = 'none';
}
$(prefix + '_' + current).className = $(prefix + '_' + current).className + ' '+activeclass;
$(prefix + '_c_' + current).style.display = '';
}
function _initTab(frameId, type) {
if (typeof document['diyform'] == 'object' || $(frameId).className.indexOf('tab') < 0) return false;
type = type || 'click';
var tabs = $(frameId+'_title').childNodes;
var arrTab = [];
for(var i in tabs) {
if (tabs[i]['nodeType'] == 1 && tabs[i]['className'].indexOf('move-span') > -1) {
arrTab.push(tabs[i]);
}
}
var counter = 0;
var tab = document.createElement('ul');
tab.className = 'tb cl';
var len = arrTab.length;
for(var i = 0;i < len; i++) {
var tabId = arrTab[i].id;
if (hasClass(arrTab[i],'frame') || hasClass(arrTab[i],'tab')) {
var arrColumn = [];
for (var j in arrTab[i].childNodes) {
if (typeof arrTab[i].childNodes[j] == 'object' && !hasClass(arrTab[i].childNodes[j],'title')) arrColumn.push(arrTab[i].childNodes[j]);
}
var frameContent = document.createElement('div');
frameContent.id = tabId+'_content';
frameContent.className = hasClass(arrTab[i],'frame') ? 'content cl '+arrTab[i].className.substr(arrTab[i].className.lastIndexOf(' ')+1) : 'content cl';
var colLen = arrColumn.length;
for (var k = 0; k < colLen; k++) {
frameContent.appendChild(arrColumn[k]);
}
} else {
var frameContent = $(tabId+'_content');
frameContent = frameContent || document.createElement('div');
}
frameContent.style.display = counter ? 'none' : '';
$(frameId+'_content').appendChild(frameContent);
var li = document.createElement('li');
li.id = tabId;
li.className = counter ? '' : 'a';
var reg = new RegExp('style=\"(.*?)\"', 'gi');
var matchs = '', style = '', imgs = '';
while((matchs = reg.exec(arrTab[i].innerHTML))) {
if(matchs[1].substr(matchs[1].length,1) != ';') {
matchs[1] += ';';
}
style += matchs[1];
}
style = style ? ' style="'+style+'"' : '';
reg = new RegExp('(<img.*?>)', 'gi');
while((matchs = reg.exec(arrTab[i].innerHTML))) {
imgs += matchs[1];
}
li.innerHTML = arrTab[i]['innerText'] ? arrTab[i]['innerText'] : arrTab[i]['textContent'];
var a = arrTab[i].getElementsByTagName('a');
var href = a && a[0] ? a[0].href : 'javascript:;';
var onclick = type == 'click' ? ' onclick="return false;"' : '';
li.innerHTML = '<a href="' + href + '"' + onclick + ' onfocus="this.blur();" ' + style + '>' + imgs + li.innerHTML + '</a>';
_attachEvent(li, type, switchTabUl);
tab.appendChild(li);
$(frameId+'_title').removeChild(arrTab[i]);
counter++;
}
$(frameId+'_title').appendChild(tab);
}
function switchTabUl (e) {
e = e || window.event;
var aim = e.target || e.srcElement;
var tabId = aim.id;
var parent = aim.parentNode;
while(parent['nodeName'] != 'UL' && parent['nodeName'] != 'BODY') {
tabId = parent.id;
parent = parent.parentNode;
}
if(parent['nodeName'] == 'BODY') return false;
var tabs = parent.childNodes;
var len2 = tabs.length;
for(var j = 0; j < len2; j++) {
tabs[j].className = (tabs[j].id == tabId) ? 'a' : '';
var content = $(tabs[j].id+'_content');
if (content) content.style.display = tabs[j].id == tabId ? '' : 'none';
}
}
function slideshow(el) {
var obj = this;
if(!el.id) el.id = Math.random();
if(typeof slideshow.entities == 'undefined') {
slideshow.entities = {};
}
this.id = el.id;
if(slideshow.entities[this.id]) return false;
slideshow.entities[this.id] = this;
this.slideshows = [];
this.slidebar = [];
this.slideother = [];
this.slidebarup = '';
this.slidebardown = '';
this.slidenum = 0;
this.slidestep = 0;
this.container = el;
this.imgs = [];
this.imgLoad = [];
this.imgLoaded = 0;
this.imgWidth = 0;
this.imgHeight = 0;
this.getMEvent = function(ele, value) {
value = !value ? 'mouseover' : value;
var mevent = !ele ? '' : ele.getAttribute('mevent');
mevent = (mevent == 'click' || mevent == 'mouseover') ? mevent : value;
return mevent;
};
this.slideshows = $C('slideshow', el);
this.slideshows = this.slideshows.length>0 ? this.slideshows[0].childNodes : null;
this.slidebar = $C('slidebar', el);
this.slidebar = this.slidebar.length>0 ? this.slidebar[0] : null;
this.barmevent = this.getMEvent(this.slidebar);
this.slideother = $C('slideother', el);
this.slidebarup = $C('slidebarup', el);
this.slidebarup = this.slidebarup.length>0 ? this.slidebarup[0] : null;
this.barupmevent = this.getMEvent(this.slidebarup, 'click');
this.slidebardown = $C('slidebardown', el);
this.slidebardown = this.slidebardown.length>0 ? this.slidebardown[0] : null;
this.bardownmevent = this.getMEvent(this.slidebardown, 'click');
this.slidenum = parseInt(this.container.getAttribute('slidenum'));
this.slidestep = parseInt(this.container.getAttribute('slidestep'));
this.timestep = parseInt(this.container.getAttribute('timestep'));
this.timestep = !this.timestep ? 2500 : this.timestep;
this.index = this.length = 0;
this.slideshows = !this.slideshows ? filterTextNode(el.childNodes) : filterTextNode(this.slideshows);
this.length = this.slideshows.length;
for(i=0; i<this.length; i++) {
this.slideshows[i].style.display = "none";
_attachEvent(this.slideshows[i], 'mouseover', function(){obj.stop();});
_attachEvent(this.slideshows[i], 'mouseout', function(){obj.goon();});
}
for(i=0, L=this.slideother.length; i<L; i++) {
for(var j=0;j<this.slideother[i].childNodes.length;j++) {
if(this.slideother[i].childNodes[j].nodeType == 1) {
this.slideother[i].childNodes[j].style.display = "none";
}
}
}
if(!this.slidebar) {
if(!this.slidenum && !this.slidestep) {
this.container.parentNode.style.position = 'relative';
this.slidebar = document.createElement('div');
this.slidebar.className = 'slidebar';
this.slidebar.style.position = 'absolute';
this.slidebar.style.top = '5px';
this.slidebar.style.left = '4px';
this.slidebar.style.display = 'none';
var html = '<ul>';
for(var i=0; i<this.length; i++) {
html += '<li on'+this.barmevent+'="slideshow.entities[' + this.id + '].xactive(' + i + '); return false;">' + (i + 1).toString() + '</li>';
}
html += '</ul>';
this.slidebar.innerHTML = html;
this.container.parentNode.appendChild(this.slidebar);
this.controls = this.slidebar.getElementsByTagName('li');
}
} else {
this.controls = filterTextNode(this.slidebar.childNodes);
for(i=0; i<this.controls.length; i++) {
if(this.slidebarup == this.controls[i] || this.slidebardown == this.controls[i]) continue;
_attachEvent(this.controls[i], this.barmevent, function(){slidexactive()});
_attachEvent(this.controls[i], 'mouseout', function(){obj.goon();});
}
}
if(this.slidebarup) {
_attachEvent(this.slidebarup, this.barupmevent, function(){slidexactive('up')});
}
if(this.slidebardown) {
_attachEvent(this.slidebardown, this.bardownmevent, function(){slidexactive('down')});
}
this.activeByStep = function(index) {
var showindex = 0,i = 0;
if(index == 'down') {
showindex = this.index + 1;
if(showindex >= this.length) {
this.runRoll();
} else {
for (i = 0; i < this.slidestep; i++) {
if(showindex >= this.length) showindex = 0;
this.index = this.index - this.slidenum + 1;
if(this.index < 0) this.index = this.length - Math.abs(this.index);
this.active(showindex);
showindex++;
}
}
} else if (index == 'up') {
var tempindex = this.index;
showindex = this.index - this.slidenum;
if(showindex < 0) return false;
for (i = 0; i < this.slidestep; i++) {
if(showindex < 0) showindex = this.length - Math.abs(showindex);
this.active(showindex);
this.index = tempindex = tempindex - 1;
if(this.index <0) this.index = this.length - 1;
showindex--;
}
}
return false;
};
this.active = function(index) {
this.slideshows[this.index].style.display = "none";
this.slideshows[index].style.display = "block";
if(this.controls && this.controls.length > 0) {
this.controls[this.index].className = '';
this.controls[index].className = 'on';
}
for(var i=0,L=this.slideother.length; i<L; i++) {
this.slideother[i].childNodes[this.index].style.display = "none";
this.slideother[i].childNodes[index].style.display = "block";
}
this.index = index;
};
this.xactive = function(index) {
if(!this.slidenum && !this.slidestep) {
this.stop();
if(index == 'down') index = this.index == this.length-1 ? 0 : this.index+1;
if(index == 'up') index = this.index == 0 ? this.length-1 : this.index-1;
this.active(index);
} else {
this.activeByStep(index);
}
};
this.goon = function() {
this.stop();
var curobj = this;
this.timer = setTimeout(function () {
curobj.run();
}, this.timestep);
};
this.stop = function() {
clearTimeout(this.timer);
};
this.run = function() {
var index = this.index + 1 < this.length ? this.index + 1 : 0;
this.active(index);
var ss = this;
this.timer = setTimeout(function(){
ss.run();
}, this.timestep);
};
this.runRoll = function() {
for(var i = 0; i < this.slidenum; i++) {
if(this.slideshows[i] && typeof this.slideshows[i].style != 'undefined') this.slideshows[i].style.display = "block";
for(var j=0,L=this.slideother.length; j<L; j++) {
this.slideother[j].childNodes[i].style.display = "block";
}
}
this.index = this.slidenum - 1;
};
var imgs = this.slideshows.length ? this.slideshows[0].parentNode.getElementsByTagName('img') : [];
for(i=0, L=imgs.length; i<L; i++) {
this.imgs.push(imgs[i]);
this.imgLoad.push(new Image());
this.imgLoad[i].onerror = function (){obj.imgLoaded ++;};
this.imgLoad[i].src = this.imgs[i].src;
}
this.getSize = function () {
if(this.imgs.length == 0) return false;
var img = this.imgs[0];
this.imgWidth = img.width ? parseInt(img.width) : 0;
this.imgHeight = img.height ? parseInt(img.height) : 0;
var ele = img.parentNode;
while ((!this.imgWidth || !this.imgHeight) && !hasClass(ele,'slideshow') && ele != document.body) {
this.imgWidth = ele.style.width ? parseInt(ele.style.width) : 0;
this.imgHeight = ele.style.height ? parseInt(ele.style.height) : 0;
ele = ele.parentNode;
}
return true;
};
this.getSize();
this.checkLoad = function () {
var obj = this;
this.container.style.display = 'block';
for(i = 0;i < this.imgs.length;i++) {
if(this.imgLoad[i].complete && !this.imgLoad[i].status) {
this.imgLoaded++;
this.imgLoad[i].status = 1;
}
}
var percentEle = $(this.id+'_percent');
if(this.imgLoaded < this.imgs.length) {
if (!percentEle) {
var dom = document.createElement('div');
dom.id = this.id+"_percent";
dom.style.width = this.imgWidth ? this.imgWidth+'px' : '150px';
dom.style.height = this.imgHeight ? this.imgHeight+'px' : '150px';
dom.style.lineHeight = this.imgHeight ? this.imgHeight+'px' : '150px';
dom.style.backgroundColor = '#ccc';
dom.style.textAlign = 'center';
dom.style.top = '0';
dom.style.left = '0';
dom.style.marginLeft = 'auto';
dom.style.marginRight = 'auto';
this.slideshows[0].parentNode.appendChild(dom);
percentEle = dom;
}
el.parentNode.style.position = 'relative';
percentEle.innerHTML = (parseInt(this.imgLoaded / this.imgs.length * 100)) + '%';
setTimeout(function () {obj.checkLoad();}, 100);
} else {
if (percentEle) percentEle.parentNode.removeChild(percentEle);
if(this.slidebar) this.slidebar.style.display = '';
this.index = this.length - 1 < 0 ? 0 : this.length - 1;
if(this.slideshows.length > 0) {
if(!this.slidenum || !this.slidestep) {
this.run();
} else {
this.runRoll();
}
}
}
};
this.checkLoad();
}
function slidexactive(step) {
var e = getEvent();
var aim = e.target || e.srcElement;
var parent = aim.parentNode;
var xactivei = null, slideboxid = null,currentslideele = null;
currentslideele = hasClass(aim, 'slidebarup') || hasClass(aim, 'slidebardown') || hasClass(parent, 'slidebar') ? aim : null;
while(parent && parent != document.body) {
if(!currentslideele && hasClass(parent.parentNode, 'slidebar')) {
currentslideele = parent;
}
if(!currentslideele && (hasClass(parent.parentNode, 'slidebarup') || hasClass(parent.parentNode, 'slidebardown'))) {
currentslideele = parent.parentNode;
}
if(hasClass(parent, 'slidebox')) {
slideboxid = parent.id;
break;
}
parent = parent.parentNode;
}
var slidebar = $C('slidebar', parent);
var children = slidebar.length == 0 ? [] : filterTextNode(slidebar[0].childNodes);
if(currentslideele && (hasClass(currentslideele, 'slidebarup') || hasClass(currentslideele, 'slidebardown'))) {
xactivei = step;
} else {
for(var j=0,i=0,L=children.length;i<L;i++){
if(currentslideele && children[i] == currentslideele) {
xactivei = j;
break;
}
if(!hasClass(children[i], 'slidebarup') && !hasClass(children[i], 'slidebardown')) j++;
}
}
if(slideboxid != null && xactivei != null) slideshow.entities[slideboxid].xactive(xactivei);
}
function filterTextNode(list) {
var newlist = [];
for(var i=0; i<list.length; i++) {
if (list[i].nodeType == 1) {
newlist.push(list[i]);
}
}
return newlist;
}
function _runslideshow() {
var slideshows = $C('slidebox');
for(var i=0,L=slideshows.length; i<L; i++) {
new slideshow(slideshows[i]);
}
}
function _showTip(ctrlobj) {
if(!ctrlobj.id) {
ctrlobj.id = 'tip_' + Math.random();
}
menuid = ctrlobj.id + '_menu';
if(!$(menuid)) {
var div = document.createElement('div');
div.id = ctrlobj.id + '_menu';
div.className = 'tip tip_js';
div.style.display = 'none';
div.innerHTML = '<div class="tip_horn"></div><div class="tip_c">' + ctrlobj.getAttribute('tip') + '</div>';
$('append_parent').appendChild(div);
}
$(ctrlobj.id).onmouseout = function () { hideMenu('', 'prompt'); };
showMenu({'mtype':'prompt','ctrlid':ctrlobj.id,'pos':'210!','duration':2,'zindex':JSMENU['zIndex']['prompt']});
}
function _showPrompt(ctrlid, evt, msg, timeout) {
var menuid = ctrlid ? ctrlid + '_pmenu' : 'ntcwin';
var duration = timeout ? 0 : 3;
if($(menuid)) {
$(menuid).parentNode.removeChild($(menuid));
}
var div = document.createElement('div');
div.id = menuid;
div.className = ctrlid ? 'tip tip_js' : 'ntcwin';
div.style.display = 'none';
$('append_parent').appendChild(div);
if(ctrlid) {
msg = '<div id="' + ctrlid + '_prompt"><div class="tip_horn"></div><div class="tip_c">' + msg + '</div>';
} else {
msg = '<table cellspacing="0" cellpadding="0" class="popupcredit"><tr><td class="pc_l"> </td><td class="pc_c"><div class="pc_inner">' + msg +
'</td><td class="pc_r"> </td></tr></table>';
}
div.innerHTML = msg;
if(ctrlid) {
if(!timeout) {
evt = 'click';
}
if($(ctrlid)) {
if($(ctrlid).evt !== false) {
var prompting = function() {
showMenu({'mtype':'prompt','ctrlid':ctrlid,'evt':evt,'menuid':menuid,'pos':'210'});
};
if(evt == 'click') {
$(ctrlid).onclick = prompting;
} else {
$(ctrlid).onmouseover = prompting;
}
}
showMenu({'mtype':'prompt','ctrlid':ctrlid,'evt':evt,'menuid':menuid,'pos':'210','duration':duration,'timeout':timeout,'zindex':JSMENU['zIndex']['prompt']});
$(ctrlid).unselectable = false;
}
} else {
showMenu({'mtype':'prompt','pos':'00','menuid':menuid,'duration':duration,'timeout':timeout,'zindex':JSMENU['zIndex']['prompt']});
$(menuid).style.top = (parseInt($(menuid).style.top) - 100) + 'px';
}
}
function _showCreditPrompt() {
var notice = getcookie('creditnotice').split('D');
var basev = getcookie('creditbase').split('D');
var creditrule = decodeURI(getcookie('creditrule', 1)).replace(String.fromCharCode(9), ' ');
if(!discuz_uid || notice.length < 2 || notice[9] != discuz_uid) {
setcookie('creditnotice', '');
setcookie('creditrule', '');
return;
}
var creditnames = creditnotice.split(',');
var creditinfo = [];
var e;
for(var i = 0; i < creditnames.length; i++) {
e = creditnames[i].split('|');
creditinfo[e[0]] = [e[1], e[2]];
}
creditShow(creditinfo, notice, basev, 0, 1, creditrule);
}
function creditShow(creditinfo, notice, basev, bk, first, creditrule) {
var s = '', check = 0;
for(i = 1; i <= 8; i++) {
v = parseInt(Math.abs(parseInt(notice[i])) / 5) + 1;
if(notice[i] !== '0' && creditinfo[i]) {
s += '<span>' + creditinfo[i][0] + (notice[i] != 0 ? (notice[i] > 0 ? '<em>+' : '<em class="desc">') + notice[i] + '</em>' : '') + creditinfo[i][1] + '</span>';
}
if(notice[i] > 0) {
notice[i] = parseInt(notice[i]) - v;
basev[i] = parseInt(basev[i]) + v;
} else if(notice[i] < 0) {
notice[i] = parseInt(notice[i]) + v;
basev[i] = parseInt(basev[i]) - v;
}
if($('hcredit_' + i)) {
$('hcredit_' + i).innerHTML = basev[i];
}
}
for(i = 1; i <= 8; i++) {
if(notice[i] != 0) {
check = 1;
}
}
if(!s || first) {
setcookie('creditnotice', '');
setcookie('creditbase', '');
setcookie('creditrule', '');
if(!s) {
return;
}
}
if(!$('creditpromptdiv')) {
showPrompt(null, null, '<div id="creditpromptdiv">' + (creditrule ? '<i>' + creditrule + '</i> ' : '') + s + '</div>', 0);
} else {
$('creditpromptdiv').innerHTML = s;
}
setTimeout(function () {hideMenu(1, 'prompt');$('append_parent').removeChild($('ntcwin'));}, 1500);
}
function _showColorBox(ctrlid, layer, k, bgcolor) {
var tag1 = !bgcolor ? 'color' : 'backcolor', tag2 = !bgcolor ? 'forecolor' : 'backcolor';
if(!$(ctrlid + '_menu')) {
var menu = document.createElement('div');
menu.id = ctrlid + '_menu';
menu.className = 'p_pop colorbox';
menu.unselectable = true;
menu.style.display = 'none';
var coloroptions = ['Black', 'Sienna', 'DarkOliveGreen', 'DarkGreen', 'DarkSlateBlue', 'Navy', 'Indigo', 'DarkSlateGray', 'DarkRed', 'DarkOrange', 'Olive', 'Green', 'Teal', 'Blue', 'SlateGray', 'DimGray', 'Red', 'SandyBrown', 'YellowGreen', 'SeaGreen', 'MediumTurquoise', 'RoyalBlue', 'Purple', 'Gray', 'Magenta', 'Orange', 'Yellow', 'Lime', 'Cyan', 'DeepSkyBlue', 'DarkOrchid', 'Silver', 'Pink', 'Wheat', 'LemonChiffon', 'PaleGreen', 'PaleTurquoise', 'LightBlue', 'Plum', 'White'];
var colortexts = ['黑色', '赭色', '暗橄榄绿色', '暗绿色', '暗灰蓝色', '海军色', '靛青色', '墨绿色', '暗红色', '暗桔黄色', '橄榄色', '绿色', '水鸭色', '蓝色', '灰石色', '暗灰色', '红色', '沙褐色', '黄绿色', '海绿色', '间绿宝石', '皇家蓝', '紫色', '灰色', '红紫色', '橙色', '黄色', '酸橙色', '青色', '深天蓝色', '暗紫色', '银色', '粉色', '浅黄色', '柠檬绸色', '苍绿色', '苍宝石绿', '亮蓝色', '洋李色', '白色'];
var str = '';
for(var i = 0; i < 40; i++) {
str += '<input type="button" style="background-color: ' + coloroptions[i] + '"' + (typeof setEditorTip == 'function' ? ' onmouseover="setEditorTip(\'' + colortexts[i] + '\')" onmouseout="setEditorTip(\'\')"' : '') + ' onclick="'
+ (typeof wysiwyg == 'undefined' ? 'seditor_insertunit(\'' + k + '\', \'[' + tag1 + '=' + coloroptions[i] + ']\', \'[/' + tag1 + ']\')' : (ctrlid == editorid + '_tbl_param_4' ? '$(\'' + ctrlid + '\').value=\'' + coloroptions[i] + '\';hideMenu(2)' : 'discuzcode(\'' + tag2 + '\', \'' + coloroptions[i] + '\')'))
+ '" title="' + colortexts[i] + '" />' + (i < 39 && (i + 1) % 8 == 0 ? '<br />' : '');
}
menu.innerHTML = str;
$('append_parent').appendChild(menu);
}
showMenu({'ctrlid':ctrlid,'evt':'click','layer':layer});
}
function _toggle_collapse(objname, noimg, complex, lang) {
var obj = $(objname);
if(obj) {
obj.style.display = obj.style.display == '' ? 'none' : '';
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, objname, !obj.style.display);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
}
if(!noimg) {
var img = $(objname + '_img');
if(img.tagName != 'IMG') {
if(img.className.indexOf('_yes') == -1) {
img.className = img.className.replace(/_no/, '_yes');
if(lang) {
img.innerHTML = lang[0];
}
} else {
img.className = img.className.replace(/_yes/, '_no');
if(lang) {
img.innerHTML = lang[1];
}
}
} else {
img.src = img.src.indexOf('_yes.gif') == -1 ? img.src.replace(/_no\.gif/, '_yes\.gif') : img.src.replace(/_yes\.gif/, '_no\.gif');
}
img.blur();
}
if(complex) {
var objc = $(objname + '_c');
if(objc) {
objc.className = objc.className == 'umh' ? 'umh umn' : 'umh';
}
}
}
function _extstyle(css) {
if(!$('css_extstyle')) {
loadcss('extstyle');
}
$('css_extstyle').href = css ? css + '/style.css' : STATICURL + 'image/common/extstyle_none.css';
currentextstyle = css;
setcookie('extstyle', css, 86400 * 30);
if($('css_widthauto') && !$('css_widthauto').disabled) {
CSSLOADED['widthauto'] = 0;
loadcss('widthauto');
}
}
function _widthauto(obj) {
if($('css_widthauto')) {
CSSLOADED['widthauto'] = 1;
}
if(!CSSLOADED['widthauto'] || $('css_widthauto').disabled) {
if(!CSSLOADED['widthauto']) {
loadcss('widthauto');
} else {
$('css_widthauto').disabled = false;
}
HTMLNODE.className += ' widthauto';
setcookie('widthauto', 1, 86400 * 30);
obj.innerHTML = '切换到窄版';
} else {
$('css_widthauto').disabled = true;
HTMLNODE.className = HTMLNODE.className.replace(' widthauto', '');
setcookie('widthauto', -1, 86400 * 30);
obj.innerHTML = '切换到宽版';
}
hideMenu();
}
function _showCreditmenu() {
if(!$('extcreditmenu_menu')) {
menu = document.createElement('div');
menu.id = 'extcreditmenu_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
menu.innerHTML = '<div class="p_opt"><img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" /> 请稍候...</div>';
$('append_parent').appendChild(menu);
ajaxget($('extcreditmenu').href, 'extcreditmenu_menu', 'ajaxwaitid');
}
showMenu({'ctrlid':'extcreditmenu','ctrlclass':'a','duration':1});
}
function _imageRotate(imgid, direct) {
var image = $(imgid);
if(!image.getAttribute('deg')) {
var deg = 0;
image.setAttribute('ow', image.width);
image.setAttribute('oh', image.height);
if(BROWSER.ie) {
image.setAttribute('om', parseInt(image.currentStyle.marginBottom));
}
} else {
var deg = parseInt(image.getAttribute('deg'));
}
var ow = image.getAttribute('ow');
var oh = image.getAttribute('oh');
deg = direct == 1 ? deg - 90 : deg + 90;
if(deg > 270) {
deg = 0;
} else if(deg < 0) {
deg = 270;
}
image.setAttribute('deg', deg);
if(BROWSER.ie) {
if(!isNaN(image.getAttribute('om'))) {
image.style.marginBottom = (image.getAttribute('om') + (BROWSER.ie < 8 ? 0 : (deg == 90 || deg == 270 ? Math.abs(ow - oh) : 0))) + 'px';
}
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (deg / 90) + ')';
} else {
switch(deg) {
case 90:var cow = oh, coh = ow, cx = 0, cy = -oh;break;
case 180:var cow = ow, coh = oh, cx = -ow, cy = -oh;break;
case 270:var cow = oh, coh = ow, cx = -ow, cy = 0;break;
}
var canvas = $(image.getAttribute('canvasid'));
if(!canvas) {
var i = document.createElement("canvas");
i.id = 'canva_' + Math.random();
image.setAttribute('canvasid', i.id);
image.parentNode.insertBefore(i, image);
canvas = $(i.id);
}
if(deg) {
var canvasContext = canvas.getContext('2d');
canvas.setAttribute('width', cow);
canvas.setAttribute('height', coh);
canvasContext.rotate(deg * Math.PI / 180);
canvasContext.drawImage(image, cx, cy, ow, oh);
image.style.display = 'none';
canvas.style.display = '';
} else {
image.style.display = '';
canvas.style.display = 'none';
}
}
}
function _createPalette(colorid, id, func) {
var iframe = "<iframe name=\"c"+colorid+"_frame\" src=\"\" frameborder=\"0\" width=\"210\" height=\"148\" scrolling=\"no\"></iframe>";
if (!$("c"+colorid+"_menu")) {
var dom = document.createElement('span');
dom.id = "c"+colorid+"_menu";
dom.style.display = 'none';
dom.innerHTML = iframe;
$('append_parent').appendChild(dom);
}
var base = document.getElementsByTagName('base');
var baseurl = base && base > 0 ? base[0].getAttribute('href') : '';
func = !func ? '' : '|' + func;
window.frames["c"+colorid+"_frame"].location.href = baseurl+STATICURL+"image/admincp/getcolor.htm?c"+colorid+"|"+id+func;
showMenu({'ctrlid':'c'+colorid});
var iframeid = "c"+colorid+"_menu";
_attachEvent(window, 'scroll', function(){hideMenu(iframeid);});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_moderate.js 21562 2011-03-31 08:40:33Z monkey $
*/
function modaction(action, pid, extra, mod) {
if(!action) {
return;
}
var mod = mod ? mod : 'forum.php?mod=topicadmin';
var extra = !extra ? '' : '&' + extra;
if(!pid && in_array(action, ['delpost', 'banpost'])) {
var checked = 0;
var pid = '';
for(var i = 0; i < $('modactions').elements.length; i++) {
if($('modactions').elements[i].name.match('topiclist')) {
checked = 1;
break;
}
}
} else {
var checked = 1;
}
if(!checked) {
alert('请选择需要操作的帖子');
} else {
$('modactions').action = mod + '&action='+ action +'&fid=' + fid + '&tid=' + tid + '&handlekey=mods&infloat=yes&nopost=yes' + (!pid ? '' : '&topiclist[]=' + pid) + extra + '&r' + Math.random();
showWindow('mods', 'modactions', 'post');
if(BROWSER.ie) {
doane(event);
}
hideMenu();
}
}
function modthreads(optgroup, operation) {
var operation = !operation ? '' : operation;
$('modactions').action = 'forum.php?mod=topicadmin&action=moderate&fid=' + fid + '&moderate[]=' + tid + '&handlekey=mods&infloat=yes&nopost=yes' + (optgroup != 3 && optgroup != 2 ? '&from=' + tid : '');
$('modactions').optgroup.value = optgroup;
$('modactions').operation.value = operation;
hideWindow('mods');
showWindow('mods', 'modactions', 'post', 0);
if(BROWSER.ie) {
doane(event);
}
}
function pidchecked(obj) {
if(obj.checked) {
try {
var inp = document.createElement('<input name="topiclist[]" />');
} catch(e) {
try {
var inp = document.createElement('input');
inp.name = 'topiclist[]';
} catch(e) {
return;
}
}
inp.id = 'topiclist_' + obj.value;
inp.value = obj.value;
inp.type = 'hidden';
$('modactions').appendChild(inp);
} else {
$('modactions').removeChild($('topiclist_' + obj.value));
}
}
var modclickcount = 0;
function modclick(obj, pid) {
if(obj.checked) {
modclickcount++;
} else {
modclickcount--;
}
$('mdct').innerHTML = modclickcount;
if(modclickcount > 0) {
var offset = fetchOffset(obj);
$('mdly').style.top = offset['top'] - 65 + 'px';
$('mdly').style.left = offset['left'] - 215 + 'px';
$('mdly').style.display = '';
} else {
$('mdly').style.display = 'none';
}
}
function resetmodcount() {
modclickcount = 0;
$('mdly').style.display = 'none';
}
function tmodclick(obj) {
if(obj.checked) {
modclickcount++;
} else {
modclickcount--;
}
$('mdct').innerHTML = modclickcount;
if(modclickcount > 0) {
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent).id != 'threadlist') {
top_offset += obj.offsetTop;
}
$('mdly').style.top = top_offset - 7 + 'px';
$('mdly').style.display = '';
} else {
$('mdly').style.display = 'none';
}
}
function tmodthreads(optgroup, operation) {
var checked = 0;
var operation = !operation ? '' : operation;
for(var i = 0; i < $('moderate').elements.length; i++) {
if($('moderate').elements[i].name.match('moderate') && $('moderate').elements[i].checked) {
checked = 1;
break;
}
}
if(!checked) {
alert('请选择需要操作的帖子');
} else {
$('moderate').optgroup.value = optgroup;
$('moderate').operation.value = operation;
showWindow('mods', 'moderate', 'post');
}
}
loadcss('forum_moderator'); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: seditor.js 21135 2011-03-16 06:24:11Z svn_project_zhangjie $
*/
function seditor_showimgmenu(seditorkey) {
var imgurl = $(seditorkey + '_image_param_1').value;
var width = parseInt($(seditorkey + '_image_param_2').value);
var height = parseInt($(seditorkey + '_image_param_3').value);
var extparams = '';
if(width || height) {
extparams = '=' + width + ',' + height
}
seditor_insertunit(seditorkey, '[img' + extparams + ']' + imgurl, '[/img]', null, 1);
$(seditorkey + '_image_param_1').value = '';
hideMenu();
}
function seditor_menu(seditorkey, tag) {
var sel = false;
if(!isUndefined($(seditorkey + 'message').selectionStart)) {
sel = $(seditorkey + 'message').selectionEnd - $(seditorkey + 'message').selectionStart;
} else if(document.selection && document.selection.createRange) {
$(seditorkey + 'message').focus();
var sel = document.selection.createRange();
$(seditorkey + 'message').sel = sel;
sel = sel.text ? true : false;
}
if(sel) {
seditor_insertunit(seditorkey, '[' + tag + ']', '[/' + tag + ']');
return;
}
var ctrlid = seditorkey + tag;
var menuid = ctrlid + '_menu';
if(!$(menuid)) {
switch(tag) {
case 'url':
str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" sautocomplete="off" style="width: 98%" value="" class="px" />' +
'<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />';
submitstr = "$('" + ctrlid + "_param_2').value !== '' ? seditor_insertunit('" + seditorkey + "', '[url='+$('" + ctrlid + "_param_1').value+']'+$('" + ctrlid + "_param_2').value, '[/url]', null, 1) : seditor_insertunit('" + seditorkey + "', '[url]'+$('" + ctrlid + "_param_1').value, '[/url]', null, 1);hideMenu();";
break;
case 'code':
case 'quote':
var tagl = {'quote' : '请输入要插入的引用', 'code' : '请输入要插入的代码'};
str = tagl[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>';
submitstr = "seditor_insertunit('" + seditorkey + "', '[" + tag + "]'+$('" + ctrlid + "_param_1').value, '[/" + tag + "]', null, 1);hideMenu();";
break;
case 'img':
str = '请输入图片地址:<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="px" onchange="loadimgsize(this.value, \'' + seditorkey + '\',\'' + tag + '\')" />' +
'<p class="mtm">宽(可选): <input type="text" id="' + ctrlid + '_param_2" style="width: 15%" value="" class="px" /> ' +
'高(可选): <input type="text" id="' + ctrlid + '_param_3" style="width: 15%" value="" class="px" /></p>';
submitstr = "seditor_insertunit('" + seditorkey + "', '[img' + ($('" + ctrlid + "_param_2').value !== '' && $('" + ctrlid + "_param_3').value !== '' ? '='+$('" + ctrlid + "_param_2').value+','+$('" + ctrlid + "_param_3').value : '')+']'+$('" + ctrlid + "_param_1').value, '[/img]', null, 1);hideMenu();";
break;
}
var menu = document.createElement('div');
menu.id = menuid;
menu.style.display = 'none';
menu.className = 'p_pof upf';
menu.style.width = '270px';
$('append_parent').appendChild(menu);
menu.innerHTML = '<span class="y"><a onclick="hideMenu()" class="flbc" href="javascript:;">关闭</a></span><div class="p_opt cl"><form onsubmit="' + submitstr + ';return false;" autocomplete="off"><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button><button type="button" onClick="hideMenu()" class="pn"><em>取消</em></button></div></form></div>';
}
showMenu({'ctrlid':ctrlid,'evt':'click','duration':3,'cache':0,'drag':1});
}
function seditor_insertunit(key, text, textend, moveend, selappend) {
if($(key + 'message')) {
$(key + 'message').focus();
}
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
selappend = isUndefined(selappend) ? 1 : selappend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($(key + 'message').selectionStart)) {
if(selappend) {
var opn = $(key + 'message').selectionStart + 0;
if(textend != '') {
text = text + $(key + 'message').value.substring($(key + 'message').selectionStart, $(key + 'message').selectionEnd) + textend;
}
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
if(!moveend) {
$(key + 'message').selectionStart = opn + strlen(text) - endlen;
$(key + 'message').selectionEnd = opn + strlen(text) - endlen;
}
} else {
text = text + textend;
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(!sel.text.length && $(key + 'message').sel) {
sel = $(key + 'message').sel;
$(key + 'message').sel = null;
}
if(selappend) {
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
sel.text = text + textend;
}
} else {
$(key + 'message').value += text;
}
hideMenu(2);
if(BROWSER.ie) {
doane();
}
}
function seditor_ctlent(event, script) {
if(event.ctrlKey && event.keyCode == 13 || event.altKey && event.keyCode == 83) {
eval(script);
}
}
function loadimgsize(imgurl, editor, p) {
var editor = !editor ? editorid : editor;
var s = new Object();
var p = !p ? '_image' : p;
s.img = new Image();
s.img.src = imgurl;
s.loadCheck = function () {
if(s.img.complete) {
$(editor + p + '_param_2').value = s.img.width ? s.img.width : '';
$(editor + p + '_param_3').value = s.img.height ? s.img.height : '';
} else {
setTimeout(function () {s.loadCheck();}, 100);
}
};
s.loadCheck();
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: logging.js 21541 2011-03-31 02:44:01Z monkey $
*/
function lsSubmit(op) {
var op = !op ? 0 : op;
if(op) {
$('lsform').cookietime.value = 2592000;
}
if($('ls_username').value == '' || $('ls_password').value == '') {
showWindow('login', 'member.php?mod=logging&action=login' + (op ? '&cookietime=1' : ''));
} else {
ajaxpost('lsform', 'return_ls', 'return_ls');
}
return false;
}
function errorhandle_ls(str, param) {
if(!param['type']) {
showError(str);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: editor.js 22848 2011-05-26 01:36:50Z monkey $
*/
var editorcurrentheight = 400, editorminheight = 400, savedataInterval = 30, editbox = null, editwin = null, editdoc = null, editcss = null, savedatat = null, savedatac = 0, autosave = 1, framemObj = null, cursor = -1, stack = [], initialized = false, postSubmited = false, editorcontroltop = false, editorcontrolwidth = false, editorcontrolheight = false, editorisfull = 0, fulloldheight = 0, savesimplodemode = null;
function newEditor(mode, initialtext) {
wysiwyg = parseInt(mode);
if(!(BROWSER.ie || BROWSER.firefox || (BROWSER.opera >= 9))) {
allowswitcheditor = wysiwyg = 0;
}
if(!BROWSER.ie) {
$(editorid + '_paste').parentNode.style.display = 'none';
}
if(!allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
if(wysiwyg) {
if($(editorid + '_iframe')) {
editbox = $(editorid + '_iframe');
} else {
var iframe = document.createElement('iframe');
iframe.frameBorder = '0';
iframe.tabIndex = 2;
iframe.hideFocus = true;
iframe.style.display = 'none';
editbox = textobj.parentNode.appendChild(iframe);
editbox.id = editorid + '_iframe';
}
editwin = editbox.contentWindow;
editdoc = editwin.document;
writeEditorContents(isUndefined(initialtext) ? textobj.value : initialtext);
} else {
editbox = editwin = editdoc = textobj;
if(!isUndefined(initialtext)) {
writeEditorContents(initialtext);
}
addSnapshot(textobj.value);
}
setEditorEvents();
initEditor();
}
function setEditorTip(s) {
$(editorid + '_tip').innerHTML = ' ' + s;
}
function initEditor() {
if(BROWSER.other) {
$(editorid + '_controls').style.display = 'none';
return;
}
var buttons = $(editorid + '_controls').getElementsByTagName('a');
for(var i = 0; i < buttons.length; i++) {
if(buttons[i].id.indexOf(editorid + '_') != -1) {
buttons[i].href = 'javascript:;';
if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'fullswitcher') {
buttons[i].innerHTML = !editorisfull ? '全屏' : '返回';
buttons[i].onmouseover = function(e) {setEditorTip(editorisfull ? '恢复编辑器大小' : '全屏方式编辑');};
buttons[i].onclick = function(e) {editorfull();doane();}
} else if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'simple') {
buttons[i].innerHTML = !simplodemode ? '常用' : '高级';
buttons[i].onclick = function(e) {editorsimple();doane();}
} else {
_attachEvent(buttons[i], 'mouseover', function(e) {setEditorTip(BROWSER.ie ? window.event.srcElement.title : e.target.title);});
if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'url') {
buttons[i].onclick = function(e) {discuzcode('unlink');discuzcode('url');doane();};
} else {
if(!buttons[i].getAttribute('init')) {
buttons[i].onclick = function(e) {discuzcode(this.id.substr(this.id.indexOf('_') + 1));doane();};
}
}
}
buttons[i].onmouseout = function(e) {setEditorTip('');};
}
}
setUnselectable($(editorid + '_controls'));
textobj.onkeydown = function(e) {ctlent(e ? e : event)};
if(editorcontroltop === false && (BROWSER.ie && BROWSER.ie > 6 || !BROWSER.ie)) {
seteditorcontrolpos();
var obj = wysiwyg ? editwin.document.body.parentNode : $(editorid + '_textarea');
editorcontrolwidth = $(editorid + '_controls').clientWidth - 8;
ctrlmObj = document.createElement('div');
ctrlmObj.style.display = 'none';
ctrlmObj.style.height = $(editorid + '_controls').clientHeight + 'px';
ctrlmObj.id = editorid + '_controls_mask';
$(editorid + '_controls').parentNode.insertBefore(ctrlmObj, $(editorid + '_controls'));
_attachEvent(window, 'scroll', function () { editorcontrolpos(); }, document);
}
if($(editorid + '_fullswitcher') && BROWSER.ie && BROWSER.ie < 7) {
$(editorid + '_fullswitcher').onclick = function () {
showDialog('你的浏览器不支持此功能,请升级浏览器版本', 'notice', '友情提示');
};
$(editorid + '_fullswitcher').className = 'xg1';
}
if($(editorid + '_svdsecond') && savedatat === null) {
savedatac = savedataInterval;
autosave = !getcookie('editorautosave_' + editorid) || getcookie('editorautosave_' + editorid) == 1 ? 1 : 0;
savedataTime();
savedatat = setInterval("savedataTime()", 10000);
}
}
function savedataTime() {
if(!autosave) {
$(editorid + '_svdsecond').innerHTML = '<a title="点击开启自动保存" href="javascript:;" onclick="setAutosave()">开启自动保存</a> ';
return;
}
if(!savedatac) {
savedatac = savedataInterval;
saveData();
d = new Date();
var h = d.getHours();
var m = d.getMinutes();
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
setEditorTip('数据已于 ' + h + ':' + m + ' 保存');
}
$(editorid + '_svdsecond').innerHTML = '<a title="点击关闭自动保存" href="javascript:;" onclick="setAutosave()">' + savedatac + ' 秒后保存</a> ';
savedatac -= 10;
}
function setAutosave() {
autosave = !autosave;
setEditorTip(autosave ? '数据自动保存已开启' : '数据自动保存已关闭');
setcookie('editorautosave_' + editorid, autosave ? 1 : -1, 2592000);
savedataTime();
}
function unloadAutoSave() {
if(autosave) {
saveData();
}
}
function seteditorcontrolpos() {
var objpos = fetchOffset($(editorid + '_controls'));
editorcontroltop = objpos['top'];
}
function editorcontrolpos() {
if(editorisfull) {
return;
}
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
if(scrollTop > editorcontroltop && editorcurrentheight > editorminheight) {
$(editorid + '_controls').style.position = 'fixed';
$(editorid + '_controls').style.top = '0px';
$(editorid + '_controls').style.width = editorcontrolwidth + 'px';
$(editorid + '_controls_mask').style.display = '';
} else {
$(editorid + '_controls').style.position = $(editorid + '_controls').style.top = $(editorid + '_controls').style.width = '';
$(editorid + '_controls_mask').style.display = 'none';
}
}
function editorsize(op, v) {
var obj = wysiwyg ? editwin.document.body.parentNode : $(editorid + '_textarea');
var editorheight = obj.clientHeight;
if(!v) {
if(op == '+') {
editorheight += 200;
} else{
editorheight -= 200;
}
} else {
editorheight = v;
}
editorcurrentheight = editorheight > editorminheight ? editorheight : editorminheight;
if($(editorid + '_iframe')) {
$(editorid + '_iframe').style.height = $(editorid + '_iframe').contentWindow.document.body.style.height = editorcurrentheight + 'px';
}
if(framemObj) {
framemObj.style.height = editorcurrentheight + 'px';
}
$(editorid + '_textarea').style.height = editorcurrentheight + 'px';
}
var editorsizepos = [];
function editorresize(e, op) {
op = !op ? 1 : op;
e = e ? e : window.event;
if(op == 1) {
if(wysiwyg) {
var objpos = fetchOffset($(editorid + '_iframe'));
framemObj = document.createElement('div');
framemObj.style.width = $(editorid + '_iframe').clientWidth + 'px';
framemObj.style.height = $(editorid + '_iframe').clientHeight + 'px';
framemObj.style.position = 'absolute';
framemObj.style.left = objpos['left'] + 'px';
framemObj.style.top = objpos['top'] + 'px';
$('append_parent').appendChild(framemObj);
} else {
framemObj = null;
}
editorsizepos = [e.clientY, editorcurrentheight, framemObj];
document.onmousemove = function(e) {try{editorresize(e, 2);}catch(err){}};
document.onmouseup = function(e) {try{editorresize(e, 3);}catch(err){}};
doane(e);
}else if(op == 2 && editorsizepos !== []) {
var dragnow = e.clientY;
editorsize('', editorsizepos[1] + dragnow - editorsizepos[0]);
doane(e);
}else if(op == 3) {
if(wysiwyg) {
$('append_parent').removeChild(editorsizepos[2]);
}
editorsizepos = [];
document.onmousemove = null;
document.onmouseup = null;
}
}
function editorfull(op) {
var op = !op ? 0 : op, control = $(editorid + '_controls'), area = $(editorid + '_textarea').parentNode, bbar = $(editorid + '_bbar'), iswysiwyg = wysiwyg;
if(op) {
var editorheight = document.documentElement.clientHeight - control.offsetHeight - bbar.offsetHeight - parseInt(getCurrentStyle(area, 'paddingTop', 'padding-top')) - parseInt(getCurrentStyle(area, 'paddingBottom', 'padding-bottom'));
area.style.position = 'fixed';
area.style.top = control.offsetHeight + 'px';
area.style.height = editorheight + 'px';
editorsize('', editorheight);
bbar.style.position = 'fixed';
bbar.style.top = (document.documentElement.clientHeight - bbar.offsetHeight) + 'px';
return;
}
if(iswysiwyg) {
switchEditor(0);
}
if(!editorisfull) {
savesimplodemode = 0;
if(simplodemode) {
savesimplodemode = 1;
editorsimple();
}
$(editorid + '_simple').style.visibility = 'hidden';
fulloldheight = editorcurrentheight;
document.body.style.overflow = 'hidden';
document.body.scroll = 'no';
control.style.position = 'fixed';
control.style.top = '0px';
control.style.left = '0px';
control.style.width = '100%';
control.style.minWidth = '800px';
area.style.backgroundColor = $(editorid + '_textarea') ? getCurrentStyle($(editorid + '_textarea'), 'backgroundColor', 'background-color') : '#fff';
$(editorid + '_switcher').style.paddingRight = '10px';
var editorheight = document.documentElement.clientHeight - control.offsetHeight - bbar.offsetHeight - parseInt(getCurrentStyle(area, 'paddingTop', 'padding-top')) - parseInt(getCurrentStyle(area, 'paddingBottom', 'padding-bottom'));
area.style.position = 'fixed';
area.style.top = control.offsetHeight + 'px';
area.style.left = '0px';
area.style.width = '100%';
area.style.height = editorheight + 'px';
editorsize('', editorheight);
bbar.style.position = 'fixed';
bbar.style.top = (document.documentElement.clientHeight - bbar.offsetHeight) + 'px';
bbar.style.left = '0px';
bbar.style.width = '100%';
control.style.zIndex = area.style.zIndex = bbar.style.zIndex = '200';
if($(editorid + '_resize')) {
$(editorid + '_resize').style.display = 'none';
}
window.onresize = function() { editorfull(1); };
editorisfull = 1;
} else {
if(savesimplodemode) {
editorsimple();
}
$(editorid + '_simple').style.visibility = 'visible';
window.onresize = null;
document.body.style.overflow = 'auto';
document.body.scroll = 'yes';
control.style.position = control.style.top = control.style.left = control.style.width = control.style.minWidth = control.style.zIndex =
area.style.position = area.style.top = area.style.left = area.style.width = area.style.height = area.style.zIndex =
bbar.style.position = bbar.style.top = bbar.style.left = bbar.style.width = bbar.style.zIndex = '';
editorheight = fulloldheight;
$(editorid + '_switcher').style.paddingRight = '0px';
editorsize('', editorheight);
if($(editorid + '_resize')) {
$(editorid + '_resize').style.display = '';
}
editorisfull = 0;
editorcontrolpos();
}
if(iswysiwyg) {
switchEditor(1);
}
$(editorid + '_fullswitcher').innerHTML = editorisfull ? '返回' : '全屏';
}
function editorsimple() {
if($(editorid + '_body').className == 'edt') {
v = 'none';
$(editorid + '_simple').innerHTML = '高级';
$(editorid + '_body').className = 'edt simpleedt';
$(editorid + '_adv_s0').className = 'b2r';
$(editorid + '_adv_s1').className = 'b2r';
$(editorid + '_adv_s2').className = 'b2r';
if(allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
simplodemode = 1;
} else {
v = '';
$(editorid + '_simple').innerHTML = '常用';
$(editorid + '_body').className = 'edt';
$(editorid + '_adv_s0').className = 'b1r';
$(editorid + '_adv_s1').className = 'b1r';
$(editorid + '_adv_s2').className = 'b2r nbr';
if(allowswitcheditor) {
$(editorid + '_switcher').style.display = '';
}
simplodemode = 0;
}
setcookie('editormode_' + editorid, simplodemode ? 1 : -1, 2592000);
for(i = 1;i <= 9;i++) {
if($(editorid + '_adv_' + i)) {
$(editorid + '_adv_' + i).style.display = v;
}
}
}
function pasteWord(str) {
var mstest = /<\w[^>]* class="?[MsoNormal|xl]"?/gi;
if(mstest.test(str)){
str = str.replace(/<!--\[if[\s\S]+?<!\[endif\]-->/gi, "");
str = str.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3");
str = str.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, function ($1, $2, $3, $4) {
var style = '';
re = new RegExp('(^|[;\\s])color:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'color:' + match[2] + ';';
}
re = new RegExp('(^|[;\\s])text-indent:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'text-indent:' + parseInt(parseInt(match[2]) / 10) + 'em;';
}
re = new RegExp('(^|[;\\s])font-size:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'font-size:' + match[2] + ';';
}
if(style) {
style = ' style="' + style + '"';
}
return '<' + $2 + style + $4;
});
htstrml = str.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3");
str = str.replace(/<\\?\?xml[^>]*>/gi, "");
str = str.replace(/<\/?\w+:[^>]*>/gi, "");
str = str.replace(/ /, " ");
var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)", 'ig');
str = str.replace(re, "<div$2</div>");
if(!wysiwyg) {
str = html2bbcode(str);
}
insertText(str, str.length, 0);
}
}
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && editorsubmit) {
if(in_array(editorsubmit.name, ['topicsubmit', 'replysubmit', 'editsubmit']) && !validate(editorform)) {
doane(event);
return;
}
postSubmited = true;
editorsubmit.disabled = true;
editorform.submit();
return;
}
if(event.keyCode == 9) {
doane(event);
}
if(event.keyCode == 8 && wysiwyg) {
var sel = getSel();
if(sel) {
insertText('', sel.length - 1, 0);
doane(event);
}
}
}
function checkFocus() {
var obj = wysiwyg ? (!BROWSER.chrome ? editwin.document.body : editwin) : textobj;
if(!obj.hasfocus) {
if(!BROWSER.safari || BROWSER.chrome) {
obj.focus();
}
try {
if(BROWSER.safari && !obj.safarifocus) {
var sel = editwin.getSelection();
var node = editdoc.body.lastChild;
var range = editdoc.createRange();
range.selectNodeContents(node);
sel.removeAllRanges();
sel.addRange(range);
obj.safarifocus = true;
}
} catch(e) {}
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
showDialog('当前长度: ' + mb_strlen(message) + ' 字节,' + (postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节。' : ''), 'notice', '字数检查');
}
function setUnselectable(obj) {
if(BROWSER.ie && BROWSER.ie > 4 && typeof obj.tagName != 'undefined') {
if(obj.hasChildNodes()) {
for(var i = 0; i < obj.childNodes.length; i++) {
setUnselectable(obj.childNodes[i]);
}
}
if(obj.tagName != 'INPUT') {
obj.unselectable = 'on';
}
}
}
function writeEditorContents(text) {
if(wysiwyg) {
if(text == '' && (BROWSER.firefox || BROWSER.opera)) {
text = '<p></p>';
}
if(initialized && !(BROWSER.firefox && BROWSER.firefox >= '3' || BROWSER.opera)) {
editdoc.body.innerHTML = text;
} else {
text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
'<html><head id="editorheader"><meta http-equiv="Content-Type" content="text/html; charset=' + charset + '" />' +
(BROWSER.ie && BROWSER.ie > 7 ? '<meta http-equiv="X-UA-Compatible" content="IE=7" />' : '' ) +
'<link rel="stylesheet" type="text/css" href="data/cache/style_' + STYLEID + '_wysiwyg.css?' + VERHASH + '" />' +
(BROWSER.ie ? '<script>window.onerror = function() { return true; }</script>' : '') +
'</head><body>' + text + '</body></html>';
editdoc.designMode = allowhtml ? 'on' : 'off';
editdoc = editwin.document;
editdoc.open('text/html', 'replace');
editdoc.write(text);
editdoc.close();
if(!BROWSER.ie) {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.text = 'window.onerror = function() { return true; }';
editdoc.getElementById('editorheader').appendChild(scriptNode);
}
editdoc.body.contentEditable = true;
editdoc.body.spellcheck = false;
initialized = true;
if(BROWSER.safari) {
editdoc.onclick = safariSel;
}
}
} else {
textobj.value = text;
}
setEditorStyle();
}
function safariSel(e) {
e = e.target;
if(e.tagName.match(/(img|embed)/i)) {
var sel = editwin.getSelection(),rng= editdoc.createRange(true);
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function getEditorContents() {
return wysiwyg ? editdoc.body.innerHTML : editdoc.value;
}
function setEditorStyle() {
if(wysiwyg) {
textobj.style.display = 'none';
editbox.style.display = '';
editbox.className = textobj.className;
if(BROWSER.ie) {
editdoc.body.style.border = '0px';
editdoc.body.addBehavior('#default#userData');
try{$('subject').focus();} catch(e) {editwin.focus();}
}
if($(editorid + '_iframe')) {
$(editorid + '_iframe').style.height = $(editorid + '_iframe').contentWindow.document.body.style.height = editorcurrentheight + 'px';
}
} else {
var iframe = textobj.parentNode.getElementsByTagName('iframe')[0];
if(iframe) {
textobj.style.display = '';
iframe.style.display = 'none';
}
if(BROWSER.ie) {
try{
$('subject').focus();
} catch(e) {}
}
}
}
function setEditorEvents() {
if(wysiwyg) {
if(BROWSER.firefox || BROWSER.opera) {
editdoc.addEventListener('mouseup', function(e) {setContext();}, true);
editdoc.addEventListener('keyup', function(e) {setContext();}, true);
editwin.addEventListener('keydown', function(e) {ctlent(e);}, true);
} else if(editdoc.attachEvent) {
editdoc.body.attachEvent('onmouseup', setContext);
editdoc.body.attachEvent('onkeyup', setContext);
editdoc.body.attachEvent('onkeydown', ctlent);
}
}
editwin.onfocus = function(e) {this.hasfocus = true;};
editwin.onblur = function(e) {this.hasfocus = false;};
editwin.onclick = function(e) {this.safarifocus = true;}
}
function wrapTags(tagname, useoption, selection) {
if(isUndefined(selection)) {
var selection = getSel();
if(selection === false) {
selection = '';
} else {
selection += '';
}
}
if(useoption !== false) {
var opentag = '[' + tagname + '=' + useoption + ']';
} else {
var opentag = '[' + tagname + ']';
}
var closetag = '[/' + tagname + ']';
var text = opentag + selection + closetag;
insertText(text, strlen(opentag), strlen(closetag), in_array(tagname, ['code', 'quote', 'free', 'hide']) ? true : false);
}
function applyFormat(cmd, dialog, argument) {
if(wysiwyg) {
editdoc.execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
return;
}
switch(cmd) {
case 'paste':
if(BROWSER.ie) {
var str = clipboardData.getData("TEXT");
insertText(str, str.length, 0);
}
break;
case 'bold':
case 'italic':
case 'underline':
case 'strikethrough':
wrapTags(cmd.substr(0, 1), false);
break;
case 'inserthorizontalrule':
insertText('[hr]', 4, 0);
break;
case 'justifyleft':
case 'justifycenter':
case 'justifyright':
wrapTags('align', cmd.substr(7));
break;
case 'fontname':
wrapTags('font', argument);
break;
case 'fontsize':
wrapTags('size', argument);
break;
case 'forecolor':
wrapTags('color', argument);
break;
case 'hilitecolor':
case 'backcolor':
wrapTags('backcolor', argument);
break;
}
}
function getCaret() {
if(wysiwyg) {
var obj = editdoc.body;
var s = document.selection.createRange();
s.setEndPoint('StartToStart', obj.createTextRange());
var matches1 = s.htmlText.match(/<\/p>/ig);
var matches2 = s.htmlText.match(/<br[^\>]*>/ig);
var fix = (matches1 ? matches1.length - 1 : 0) + (matches2 ? matches2.length : 0);
var pos = s.text.replace(/\r?\n/g, ' ').length;
if(matches3 = s.htmlText.match(/<img[^\>]*>/ig)) pos += matches3.length;
if(matches4 = s.htmlText.match(/<\/tr|table>/ig)) pos += matches4.length;
return [pos, fix];
} else {
checkFocus();
var sel = document.selection.createRange();
editbox.sel = sel;
}
}
function setCaret(pos) {
var obj = wysiwyg ? editdoc.body : editbox;
var r = obj.createTextRange();
r.moveStart('character', pos);
r.collapse(true);
r.select();
}
function isEmail(email) {
return email.length > 6 && /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test(email);
}
function insertAttachTag(aid) {
var txt = '[attach]' + aid + '[/attach]';
if(wysiwyg) {
insertText(txt, false);
} else {
insertText(txt, strlen(txt), 0);
}
}
function insertAttachimgTag(aid) {
if(wysiwyg) {
insertText('<img src="' + $('image_' + aid).src + '" border="0" aid="attachimg_' + aid + '" alt="" />', false);
} else {
var txt = '[attachimg]' + aid + '[/attachimg]';
insertText(txt, strlen(txt), 0);
}
}
function insertSmiley(smilieid) {
checkFocus();
var src = $('smilie_' + smilieid).src;
var code = $('smilie_' + smilieid).alt;
if(wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
insertText('<img src="' + src + '" border="0" smilieid="' + smilieid + '" alt="" />', false);
} else {
code += ' ';
insertText(code, strlen(code), 0);
}
hideMenu();
}
function discuzcode(cmd, arg) {
if(cmd != 'redo') {
addSnapshot(getEditorContents());
}
checkFocus();
if(in_array(cmd, ['sml', 'url', 'quote', 'code', 'free', 'hide', 'aud', 'vid', 'fls', 'attach', 'image', 'pasteword']) || cmd == 'tbl' || in_array(cmd, ['fontname', 'fontsize', 'forecolor', 'backcolor']) && !arg) {
showEditorMenu(cmd);
return;
} else if(cmd.substr(0, 3) == 'cst') {
showEditorMenu(cmd.substr(5), cmd.substr(3, 1));
return;
} else if(wysiwyg && cmd == 'inserthorizontalrule') {
insertText('<hr class="l">', 14);
} else if(cmd == 'autotypeset') {
autoTypeset();
return;
} else if(!wysiwyg && cmd == 'removeformat') {
var simplestrip = new Array('b', 'i', 'u');
var complexstrip = new Array('font', 'color', 'backcolor', 'size');
var str = getSel();
if(str === false) {
return;
}
for(var tag in simplestrip) {
str = stripSimple(simplestrip[tag], str);
}
for(var tag in complexstrip) {
str = stripComplex(complexstrip[tag], str);
}
insertText(str);
} else if(cmd == 'undo') {
addSnapshot(getEditorContents());
moveCursor(-1);
if((str = getSnapshot()) !== false) {
if(wysiwyg) {
editdoc.body.innerHTML = str;
} else {
editdoc.value = str;
}
}
} else if(cmd == 'redo') {
moveCursor(1);
if((str = getSnapshot()) !== false) {
if(wysiwyg) {
editdoc.body.innerHTML = str;
} else {
editdoc.value = str;
}
}
} else if(!wysiwyg && in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
var listtype = cmd == 'insertorderedlist' ? '1' : '';
var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
var closetag = '[/list]';
if(txt = getSel()) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
while(listvalue = prompt('输入一个列表项目.\r\n留空或者点击取消完成此列表.', '')) {
if(BROWSER.opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertText(listvalue, strlen(listvalue) + 1, 0);
} else {
listvalue = '[*]' + listvalue + '\n';
insertText(listvalue, strlen(listvalue), 0);
}
}
}
} else if(!wysiwyg && cmd == 'unlink') {
var sel = getSel();
sel = stripSimple('url', sel);
sel = stripComplex('url', sel);
insertText(sel);
} else if(cmd == 'floatleft' || cmd == 'floatright') {
var arg = cmd == 'floatleft' ? 'left' : 'right';
if(wysiwyg) {
if(txt = getSel()) {
argm = arg == 'left' ? 'right' : 'left';
insertText('<br style="clear: both"><table class="float" style="float: ' + arg + '; margin-' + argm + ': 5px;"><tbody><tr><td>' + txt + '</td></tr></tbody></table>', true);
}
} else {
var opentag = '[float=' + arg + ']';
var closetag = '[/float]';
if(txt = getSel()) {
txt = opentag + txt + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
}
}
} else if(cmd == 'rst') {
loadData();
setEditorTip('数据已恢复');
} else if(cmd == 'svd') {
saveData();
setEditorTip('数据已保存');
} else if(cmd == 'chck') {
checklength(editorform);
} else if(cmd == 'tpr') {
if(confirm('您确认要清除所有内容吗?')) {
clearContent();
}
} else if(cmd == 'downremoteimg') {
showDialog('<div id="remotedowninfo"><p class="mbn">正在下载远程附件,请稍等……</p><p><img src="' + STATICURL + 'image/common/uploading.gif" alt="" /></p></div>', 'notice', '', null, 1);
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!editorform.parseurloff.checked ? parseurl(editorform.message.value) : editorform.message.value);
var oldValidate = editorform.onsubmit;
var oldAction = editorform.action;
editorform.onsubmit = '';
editorform.action = 'forum.php?mod=ajax&action=downremoteimg&wysiwyg='+(wysiwyg ? 1 : 0);
editorform.target = "ajaxpostframe";
editorform.message.value = message;
editorform.submit();
editorform.onsubmit = oldValidate;
editorform.action = oldAction;
editorform.target = "";
} else {
var formatcmd = cmd == 'backcolor' && !BROWSER.ie ? 'hilitecolor' : cmd;
try {
var ret = applyFormat(formatcmd, false, (isUndefined(arg) ? true : arg));
} catch(e) {
var ret = false;
}
}
if(cmd != 'undo') {
addSnapshot(getEditorContents());
}
if(wysiwyg) {
setContext(cmd);
}
if(in_array(cmd, ['bold', 'italic', 'underline', 'strikethrough', 'inserthorizontalrule', 'fontname', 'fontsize', 'forecolor', 'backcolor', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'floatleft', 'floatright', 'removeformat', 'unlink', 'undo', 'redo'])) {
hideMenu();
}
doane();
return ret;
}
function setContext(cmd) {
var cmd = !cmd ? '' : cmd;
var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
for(var i in contextcontrols) {
var controlid = contextcontrols[i];
var obj = $(editorid + '_' + controlid);
if(obj != null) {
if(cmd == 'clear') {
obj.className = '';
continue;
}
try {
var state = editdoc.queryCommandState(contextcontrols[i]);
} catch(e) {
var state = false;
}
if(isUndefined(obj.state)) {
obj.state = false;
}
if(obj.state != state) {
obj.state = state;
buttonContext(obj, state ? 'mouseover' : 'mouseout');
}
}
}
var fs = editdoc.queryCommandValue('fontname');
if(fs == '' && !BROWSER.ie && window.getComputedStyle) {
fs = editdoc.body.style.fontFamily;
} else if(fs == null) {
fs = '';
}
fs = fs && cmd != 'clear' ? fs : '字体';
if(fs != $(editorid + '_font').fontstate) {
thingy = fs.indexOf(',') > 0 ? fs.substr(0, fs.indexOf(',')) : fs;
$(editorid + '_font').innerHTML = thingy;
$(editorid + '_font').fontstate = fs;
}
try {
var ss = editdoc.queryCommandValue('fontsize');
if(ss == null || ss == '' || cmd == 'clear') {
ss = formatFontsize(editdoc.body.style.fontSize);
} else {
var ssu = ss.substr(-2);
if(ssu == 'px' || ssu == 'pt') {
ss = formatFontsize(ss);
}
}
} catch(e) {}
if(ss != $(editorid + '_size').sizestate) {
if($(editorid + '_size').sizestate == null) {
$(editorid + '_size').sizestate = '';
}
$(editorid + '_size').innerHTML = ss;
$(editorid + '_size').sizestate = ss;
}
}
function buttonContext(obj, state) {
if(state == 'mouseover') {
obj.style.cursor = 'pointer';
var mode = obj.state ? 'down' : 'hover';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = 'hover';
}
} else {
var mode = obj.state ? 'selected' : 'normal';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = mode == 'selected' ? 'hover' : '';
}
}
}
function formatFontsize(csssize) {
switch(csssize) {
case '7.5pt':
case '10px': return 1;
case '13px':
case '10pt': return 2;
case '16px':
case '12pt': return 3;
case '18px':
case '14pt': return 4;
case '24px':
case '18pt': return 5;
case '32px':
case '24pt': return 6;
case '48px':
case '36pt': return 7;
default: return '大小';
}
}
function showEditorMenu(tag, params) {
var sel, selection;
var str = '', strdialog = 0, stitle = '';
var ctrlid = editorid + (params ? '_cst' + params + '_' : '_') + tag;
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
var menu = $(ctrlid + '_menu');
var pos = [0, 0];
var menuwidth = 270;
var menupos = '43!';
var menutype = 'menu';
if(BROWSER.ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
pos = getCaret();
}
selection = sel ? (wysiwyg ? sel.htmlText : sel.text) : getSel();
if(menu) {
if($(ctrlid).getAttribute('menupos') !== null) {
menupos = $(ctrlid).getAttribute('menupos');
}
if($(ctrlid).getAttribute('menuwidth') !== null) {
menu.style.width = $(ctrlid).getAttribute('menuwidth') + 'px';
}
if(menupos == '00') {
menu.className = 'fwinmask';
if($(editorid + '_' + tag + '_menu').style.visibility == 'hidden') {
$(editorid + '_' + tag + '_menu').style.visibility = 'visible';
} else {
showMenu({'ctrlid':ctrlid,'mtype':'win','evt':'click','pos':menupos,'timeout':250,'duration':3,'drag':ctrlid + '_ctrl'});
}
} else {
showMenu({'ctrlid':ctrlid,'evt':'click','pos':menupos,'timeout':250,'duration':in_array(tag, ['fontname', 'fontsize', 'sml']) ? 2 : 3,'drag':1});
}
} else {
switch(tag) {
case 'url':
str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="px" />'+
(selection ? '' : '<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />');
break;
case 'forecolor':
showColorBox(ctrlid, 1);
return;
case 'backcolor':
showColorBox(ctrlid, 1, '', 1);
return;
case 'code':
if(wysiwyg) {
opentag = '<div class="blockcode"><blockquote>';
closetag = '</blockquote></div><br />';
}
case 'quote':
if(wysiwyg && tag == 'quote') {
opentag = '<div class="quote"><blockquote>';
closetag = '</blockquote></div><br />';
}
case 'hide':
case 'free':
if(selection) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var lang = {'quote' : '请输入要插入的引用', 'code' : '请输入要插入的代码', 'hide' : '请输入要隐藏的信息内容', 'free' : '如果您设置了帖子售价,请输入购买前免费可见的信息内容'};
str += lang[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>' +
(tag == 'hide' ? '<br /><label><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_1" class="pc" checked="checked" />只有当浏览者回复本帖时才显示</label><br /><label><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_2" class="pc" />只有当浏览者积分高于</label> <input type="text" size="3" id="' + ctrlid + '_param_2" class="px pxs" /> 时才显示' : '');
break;
case 'tbl':
str = '<p class="pbn">表格行数: <input type="text" id="' + ctrlid + '_param_1" size="2" value="2" class="px" /> 表格列数: <input type="text" id="' + ctrlid + '_param_2" size="2" value="2" class="px" /></p><p class="pbn">表格宽度: <input type="text" id="' + ctrlid + '_param_3" size="2" value="" class="px" /> 背景颜色: <input type="text" id="' + ctrlid + '_param_4" size="2" class="px" onclick="showColorBox(this.id, 2)" /></p><p class="xg2 pbn" style="cursor:pointer" onclick="showDialog($(\'tbltips_msg\').innerHTML, \'notice\', \'小提示\', null, 0)"><img id="tbltips" title="小提示" class="vm" src="' + IMGDIR + '/info_small.gif"> 快速书写表格提示</p>';
str += '<div id="tbltips_msg" style="display: none">“[tr=颜色]” 定义行背景<br />“[td=宽度]” 定义列宽<br />“[td=列跨度,行跨度,宽度]” 定义行列跨度<br /><br />快速书写表格范例:<div class=\'xs0\' style=\'margin:0 5px\'>[table]<br />Name:|Discuz!<br />Version:|X1<br />[/table]</div>用“|”分隔每一列,表格中如有“|”用“\\|”代替,换行用“\\n”代替。</div>';
break;
case 'aud':
str = '<p class="pbn">请输入音乐文件地址:</p><p class="pbn"><input type="text" id="' + ctrlid + '_param_1" class="px" value="" style="width: 220px;" /></p><p class="xg2 pbn">支持 wma mp3 ra rm 等音乐格式<br />示例: http://server/audio.wma</p>';
break;
case 'vid':
str = '<p class="pbn">请输入视频地址:</p><p class="pbn"><input type="text" value="" id="' + ctrlid + '_param_1" style="width: 220px;" class="px" /></p><p class="pbn">宽: <input id="' + ctrlid + '_param_2" size="5" value="500" class="px" /> 高: <input id="' + ctrlid + '_param_3" size="5" value="375" class="px" /></p><p class="xg2 pbn">支持优酷、土豆、56、酷6等视频站的视频网址<br />支持 wmv avi rmvb mov swf flv 等视频格式<br />示例: http://server/movie.wmv</p>';
break;
case 'fls':
str = '<p class="pbn">请输入 Flash 文件地址:</p><p class="pbn"><input type="text" id="' + ctrlid + '_param_1" class="px" value="" style="width: 220px;" /></p><p class="pbn">宽: <input id="' + ctrlid + '_param_2" size="5" value="" class="px" /> 高: <input id="' + ctrlid + '_param_3" size="5" value="" class="px" /></p><p class="xg2 pbn">支持 swf flv 等 Flash 网址<br />示例: http://server/flash.swf</p>';
break;
case 'pasteword':
stitle = '从 Word 粘贴内容';
str = '<p class="px" style="height:300px"><iframe id="' + ctrlid + '_param_1" frameborder="0" style="width:100%;height:100%" onload="this.contentWindow.document.body.style.width=\'550px\';this.contentWindow.document.body.contentEditable=true;this.contentWindow.document.body.focus();this.onload=null"></iframe></p><p class="xg2 pbn">请通过快捷键(Ctrl+V)把 Word 文件中的内容粘贴到上方</p>';
menuwidth = 600;
menupos = '00';
menutype = 'win';
break;
default:
var haveSel = selection == null || selection == false || in_array(trim(selection), ['', 'null', 'undefined', 'false']) ? 0 : 1;
if(params == 1 && haveSel) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var promptlang = custombbcodes[tag]['prompt'].split("\t");
for(var i = 1; i <= params; i++) {
if(i != params || !haveSel) {
str += (promptlang[i - 1] ? promptlang[i - 1] : '请输入第 ' + i + ' 个参数:') + '<br /><input type="text" id="' + ctrlid + '_param_' + i + '" style="width: 98%" value="" class="px" />' + (i < params ? '<br />' : '');
}
}
break;
}
var menu = document.createElement('div');
menu.id = ctrlid + '_menu';
menu.style.display = 'none';
menu.className = 'p_pof upf';
menu.style.width = menuwidth + 'px';
if(menupos == '00') {
menu.className = 'fwinmask';
s = '<table width="100%" cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"></td><td class="t_r"></td></tr><tr><td class="m_l"> </td><td class="m_c">'
+ '<h3 class="flb"><em>' + stitle + '</em><span><a onclick="hideMenu(\'\', \'win\');return false;" class="flbc" href="javascript:;">关闭</a></span></h3><div class="c">' + str + '</div>'
+ '<p class="o pns"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button></p>'
+ '</td><td class="m_r"></td></tr><tr><td class="b_l"></td><td class="b_c"></td><td class="b_r"></td></tr></table>';
} else {
s = '<div class="p_opt cl"><span class="y" style="margin:-10px -10px 0 0"><a onclick="hideMenu();return false;" class="flbc" href="javascript:;">关闭</a></span><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button></div></div>';
}
menu.innerHTML = s;
$(editorid + '_editortoolbar').appendChild(menu);
showMenu({'ctrlid':ctrlid,'mtype':menutype,'evt':'click','duration':3,'cache':0,'drag':1,'pos':menupos});
}
try {
if($(ctrlid + '_param_1')) {
$(ctrlid + '_param_1').focus();
}
} catch(e) {}
var objs = menu.getElementsByTagName('*');
for(var i = 0; i < objs.length; i++) {
_attachEvent(objs[i], 'keydown', function(e) {
e = e ? e : event;
obj = BROWSER.ie ? event.srcElement : e.target;
if((obj.type == 'text' && e.keyCode == 13) || (obj.type == 'textarea' && e.ctrlKey && e.keyCode == 13)) {
if($(ctrlid + '_submit') && tag != 'image') $(ctrlid + '_submit').click();
doane(e);
} else if(e.keyCode == 27) {
hideMenu();
doane(e);
}
});
}
if($(ctrlid + '_submit')) $(ctrlid + '_submit').onclick = function() {
checkFocus();
if(BROWSER.ie && wysiwyg) {
setCaret(pos[0]);
}
switch(tag) {
case 'url':
var href = $(ctrlid + '_param_1').value;
href = (isEmail(href) ? 'mailto:' : '') + href;
if(href != '') {
var v = selection ? selection : ($(ctrlid + '_param_2').value ? $(ctrlid + '_param_2').value : href);
str = wysiwyg ? ('<a href="' + href + '">' + v + '</a>') : '[url=' + href + ']' + v + '[/url]';
if(wysiwyg) insertText(str, str.length - v.length, 0, (selection ? true : false), sel);
else insertText(str, str.length - v.length - 6, 6, (selection ? true : false), sel);
}
break;
case 'code':
if(wysiwyg) {
opentag = '<div class="blockcode"><blockquote>';
closetag = '</blockquote></div><br />';
if(!BROWSER.ie) {
selection = selection ? selection : '\n';
}
}
case 'quote':
if(wysiwyg && tag == 'quote') {
opentag = '<div class="quote"><blockquote>';
closetag = '</blockquote></div><br />';
if(!BROWSER.ie) {
selection = selection ? selection : '\n';
}
}
case 'hide':
case 'free':
if(tag == 'hide' && $(ctrlid + '_radio_2').checked) {
var mincredits = parseInt($(ctrlid + '_param_2').value);
opentag = mincredits > 0 ? '[hide=' + mincredits + ']' : '[hide]';
}
str = $(ctrlid + '_param_1') && $(ctrlid + '_param_1').value ? $(ctrlid + '_param_1').value : (selection ? selection : '');
if(wysiwyg) {
str = preg_replace(['<', '>'], ['<', '>'], str);
str = str.replace(/\r?\n/g, '<br />');
}
str = opentag + str + closetag;
insertText(str, strlen(opentag), strlen(closetag), false, sel);
break;
case 'tbl':
var rows = $(ctrlid + '_param_1').value;
var columns = $(ctrlid + '_param_2').value;
var width = $(ctrlid + '_param_3').value;
var bgcolor = $(ctrlid + '_param_4').value;
rows = /^[-\+]?\d+$/.test(rows) && rows > 0 && rows <= 30 ? rows : 2;
columns = /^[-\+]?\d+$/.test(columns) && columns > 0 && columns <= 30 ? columns : 2;
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
bgcolor = /[\(\)%,#\w]+/.test(bgcolor) ? bgcolor : '';
if(wysiwyg) {
str = '<table cellspacing="0" cellpadding="0" width="' + (width ? width : '50%') + '" class="t_table"' + (bgcolor ? ' bgcolor="' + bgcolor + '"' : '') + '>';
for (var row = 0; row < rows; row++) {
str += '<tr>\n';
for (col = 0; col < columns; col++) {
str += '<td> </td>\n';
}
str += '</tr>\n';
}
str += '</table>\n';
} else {
str = '[table=' + (width ? width : '50%') + (bgcolor ? ',' + bgcolor : '') + ']\n';
for (var row = 0; row < rows; row++) {
str += '[tr]';
for (col = 0; col < columns; col++) {
str += '[td] [/td]';
}
str += '[/tr]\n';
}
str += '[/table]\n';
}
insertText(str, str.length, 0, false, sel);
break;
case 'aud':
insertText('[audio]' + $(ctrlid + '_param_1').value + '[/audio]', 7, 8, false, sel);
break;
case 'fls':
if($(ctrlid + '_param_2').value && $(ctrlid + '_param_3').value) {
insertText('[flash=' + parseInt($(ctrlid + '_param_2').value) + ',' + parseInt($(ctrlid + '_param_3').value) + ']' + $(ctrlid + '_param_1').value + '[/flash]', 7, 8, false, sel);
} else {
insertText('[flash]' + $(ctrlid + '_param_1').value + '[/flash]', 7, 8, false, sel);
}
break;
case 'vid':
var mediaUrl = $(ctrlid + '_param_1').value;
var auto = '';
var ext = mediaUrl.lastIndexOf('.') == -1 ? '' : mediaUrl.substr(mediaUrl.lastIndexOf('.') + 1, mb_strlen(mediaUrl)).toLowerCase();
ext = in_array(ext, ['mp3', 'wma', 'ra', 'rm', 'ram', 'mid', 'asx', 'wmv', 'avi', 'mpg', 'mpeg', 'rmvb', 'asf', 'mov', 'flv', 'swf']) ? ext : 'x';
if(ext == 'x') {
if(/^mms:\/\//.test(mediaUrl)) {
ext = 'mms';
} else if(/^(rtsp|pnm):\/\//.test(mediaUrl)) {
ext = 'rtsp';
}
}
var str = '[media=' + ext + ',' + $(ctrlid + '_param_2').value + ',' + $(ctrlid + '_param_3').value + ']' + mediaUrl + '[/media]';
insertText(str, str.length, 0, false, sel);
break;
case 'image':
var width = parseInt($(ctrlid + '_param_2').value);
var height = parseInt($(ctrlid + '_param_3').value);
var src = $(ctrlid + '_param_1').value;
var style = '';
if(wysiwyg) {
style += width ? ' width=' + width : '';
style += height ? ' height=' + height : '';
var str = '<img src=' + src + style + ' border=0 />';
insertText(str, str.length, 0, false, sel);
} else {
style += width || height ? '=' + width + ',' + height : '';
insertText('[img' + style + ']' + src + '[/img]', 0, 0, false, sel);
}
$(ctrlid + '_param_1').value = '';
break;
case 'pasteword':
pasteWord($(ctrlid + '_param_1').contentWindow.document.body.innerHTML);
hideMenu('', 'win');
break;
default:
var first = $(ctrlid + '_param_1').value;
if($(ctrlid + '_param_2')) var second = $(ctrlid + '_param_2').value;
if($(ctrlid + '_param_3')) var third = $(ctrlid + '_param_3').value;
if((params == 1 && first) || (params == 2 && first && (haveSel || second)) || (params == 3 && first && second && (haveSel || third))) {
if(params == 1) {
str = first;
} else if(params == 2) {
str = haveSel ? selection : second;
opentag = '[' + tag + '=' + first + ']';
} else {
str = haveSel ? selection : third;
opentag = '[' + tag + '=' + first + ',' + second + ']';
}
insertText((opentag + str + closetag), strlen(opentag), strlen(closetag), true, sel);
}
break;
}
hideMenu();
};
}
function autoTypeset() {
var sel;
if(BROWSER.ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
}
var selection = sel ? (wysiwyg ? sel.htmlText.replace(/<\/?p>/ig, '<br />') : sel.text) : getSel();
selection = wysiwyg ? selection.replace(/<br[^\>]*>/ig, "\n") : selection.replace(/\r?\n/g, "\n");
selection = trim(selection);
selection = wysiwyg ? selection.replace(/\n+/g, '</p><p style="line-height: 30px; text-indent: 2em;">') : selection.replace(/\n/g, '[/p][p=30, 2, left]');
opentag = wysiwyg ? '<p style="line-height: 30px; text-indent: 2em;">' : '[p=30, 2, left]';
var s = opentag + selection + (wysiwyg ? '</p>' : '[/p]');
insertText(s, strlen(opentag), 4, false, sel);
hideMenu();
}
function getSel() {
if(wysiwyg) {
try {
selection = editwin.getSelection();
checkFocus();
range = selection ? selection.getRangeAt(0) : editdoc.createRange();
return readNodes(range.cloneContents(), false);
} catch(e) {
try {
var range = editdoc.selection.createRange();
if(range.htmlText && range.text) {
return range.htmlText;
} else {
var htmltext = '';
for(var i = 0; i < range.length; i++) {
htmltext += range.item(i).outerHTML;
}
return htmltext;
}
} catch(e) {
return '';
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
}
function insertText(text, movestart, moveend, select, sel) {
checkFocus();
if(wysiwyg) {
try {
editdoc.execCommand('insertHTML', false, text);
} catch(e) {
if(!isUndefined(editdoc.selection) && editdoc.selection.type != 'Text' && editdoc.selection.type != 'None') {
movestart = false;
editdoc.selection.clear();
}
if(isUndefined(sel)) {
sel = editdoc.selection.createRange();
}
sel.pasteHTML(text);
if(text.indexOf('\n') == -1) {
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) + movestart);
sel.moveEnd('character', -moveend);
} else if(movestart != false) {
sel.moveStart('character', -strlen(text));
}
if(!isUndefined(select) && select) {
sel.select();
}
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
var opn = editdoc.selectionStart + 0;
editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);
if(!isUndefined(movestart)) {
editdoc.selectionStart = opn + movestart;
editdoc.selectionEnd = opn + strlen(text) - moveend;
} else if(movestart !== false) {
editdoc.selectionStart = opn;
editdoc.selectionEnd = opn + strlen(text);
}
} else if(document.selection && document.selection.createRange) {
if(isUndefined(sel)) {
sel = document.selection.createRange();
}
if(editbox.sel) {
sel = editbox.sel;
editbox.sel = null;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) +movestart);
sel.moveEnd('character', -moveend);
} else if(movestart !== false) {
sel.moveStart('character', -strlen(text));
}
sel.select();
} else {
editdoc.value += text;
}
}
checkFocus();
}
function stripSimple(tag, str, iterations) {
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
}
return str;
}
function readNodes(root, toptag) {
var html = "";
var moz_check = /_moz/i;
switch(root.nodeType) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
var closed;
if(toptag) {
closed = !root.hasChildNodes();
html = '<' + root.tagName.toLowerCase();
var attr = root.attributes;
for(var i = 0; i < attr.length; ++i) {
var a = attr.item(i);
if(!a.specified || a.name.match(moz_check) || a.value.match(moz_check)) {
continue;
}
html += " " + a.name.toLowerCase() + '="' + a.value + '"';
}
html += closed ? " />" : ">";
}
for(var i = root.firstChild; i; i = i.nextSibling) {
html += readNodes(i, true);
}
if(toptag && !closed) {
html += "</" + root.tagName.toLowerCase() + ">";
}
break;
case Node.TEXT_NODE:
html = htmlspecialchars(root.data);
break;
}
return html;
}
function stripComplex(tag, str, iterations) {
var opentag = '[' + tag + '=';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var openend = stripos(str, ']', startindex);
if(openend !== false && openend > startindex && openend < stopindex) {
var text = str.substr(openend + 1, stopindex - openend - 1);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
} else {
break;
}
}
return str;
}
function stripos(haystack, needle, offset) {
if(isUndefined(offset)) {
offset = 0;
}
var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);
return (index == -1 ? false : index);
}
function switchEditor(mode) {
if(mode == wysiwyg || !allowswitcheditor) {
return;
}
if(!mode) {
var controlbar = $(editorid + '_controls');
var controls = [];
var buttons = controlbar.getElementsByTagName('a');
var buttonslength = buttons.length;
for(var i = 0; i < buttonslength; i++) {
if(buttons[i].id) {
controls[controls.length] = buttons[i].id;
}
}
var controlslength = controls.length;
for(var i = 0; i < controlslength; i++) {
var control = $(controls[i]);
if(control.id.indexOf(editorid + '_') != -1) {
control.state = false;
control.mode = 'normal';
} else if(control.id.indexOf(editorid + '_popup_') != -1) {
control.state = false;
}
}
setContext('clear');
}
cursor = -1;
stack = [];
var parsedtext = getEditorContents();
parsedtext = mode ? bbcode2html(parsedtext) : html2bbcode(parsedtext);
wysiwyg = mode;
$(editorid + '_mode').value = mode;
newEditor(mode, parsedtext);
setEditorStyle();
editwin.focus();
setCaretAtEnd();
}
function setCaretAtEnd() {
if(wysiwyg) {
editdoc.body.innerHTML += '';
} else {
editdoc.value += '';
}
}
function moveCursor(increment) {
var test = cursor + increment;
if(test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
cursor += increment;
}
}
function addSnapshot(str) {
if(stack[cursor] == str) {
return;
} else {
cursor++;
stack[cursor] = str;
if(!isUndefined(stack[cursor + 1])) {
stack[cursor + 1] = null;
}
}
}
function getSnapshot() {
if(!isUndefined(stack[cursor]) && stack[cursor] != null) {
return stack[cursor];
} else {
return false;
}
}
function loadimgsize(imgurl, editor, p) {
var editor = !editor ? editorid : editor;
var s = new Object();
var p = !p ? '_image' : p;
s.img = new Image();
s.img.src = imgurl;
s.loadCheck = function () {
if(s.img.complete) {
$(editor + p + '_param_2').value = s.img.width ? s.img.width : '';
$(editor + p + '_param_3').value = s.img.height ? s.img.height : '';
} else {
setTimeout(function () {s.loadCheck();}, 100);
}
};
s.loadCheck();
}
if(typeof jsloaded == 'function') {
jsloaded('editor');
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: space_diy.js 21831 2011-04-13 08:53:11Z maruitao $
*/
var drag = new Drag();
drag.extend({
setDefalutMenu : function () {
this.addMenu('default', '删除', 'drag.removeBlock(event)');
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
},
removeBlock : function (e) {
if ( typeof e !== 'string') {
e = Util.event(e);
id = e.aim.id.replace('cmd_','');
} else {
id = e;
}
if (!confirm('您确实要删除吗,删除以后将不可恢复')) return false;
$(id).parentNode.removeChild($(id));
var el = $('chk'+id);
if (el != null) el.className = '';
this.initPosition();
this.initChkBlock();
},
initChkBlock : function (data) {
if (typeof name == 'undefined' || data == null ) data = this.data;
if ( data instanceof Frame) {
this.initChkBlock(data['columns']);
} else if (data instanceof Block) {
var el = $('chk'+data.name);
if (el != null) el.className = 'activity';
} else if (typeof data == 'object') {
for (var i in data) {
this.initChkBlock(data[i]);
}
}
},
toggleBlock : function (blockname) {
var el = $('chk'+blockname);
if (el != null) {
if (el.className == '') {
this.getBlockData(blockname);
el.className = 'activity';
} else {
this.removeBlock(blockname);
this.initPosition();
}
this.setClose();
}
},
getBlockData : function (blockname) {
var el = $(blockname);
if (el != null) {
Util.show(blockname);
} else {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=index&op=getblock&blockname='+blockname+'&inajax=1',function(s) {
if (s) {
el = document.createElement("div");
el.className = drag.blockClass + ' ' + drag.moveableObject;
el.id = blockname;
s = s.replace(/\<script.*\<\/script\>/ig,'<font color="red"> [javascript脚本保存后显示] </font>');
el.innerHTML = s;
var id = drag.data['diypage'][0]['columns']['frame1_left']['children'][0]['name'];
$('frame1_left').insertBefore(el,$(id));
drag.initPosition();
}
});
}
},
openBlockEdit : function (e) {
e = Util.event(e);
var blockname = e.aim.id.replace('cmd_','');
this.removeMenu();
showWindow('showblock', 'home.php?mod=spacecp&ac=index&op=edit&blockname='+blockname,'get',0);
}
});
var spaceDiy = new DIY();
spaceDiy.extend({
save:function () {
drag.clearClose();
document.diyform.spacecss.value = this.getSpacecssStr();
document.diyform.style.value = this.style;
document.diyform.layoutdata.value = drag.getPositionStr();
document.diyform.currentlayout.value = this.currentLayout;
document.diyform.submit();
},
getdiy : function (type) {
var type_ = type == 'image' ? 'diy' : type;
if (type_) {
var nav = $('controlnav').children;
for (var i in nav) {
if (nav[i].className == 'current') {
nav[i].className = '';
}
}
$('nav'+type_).className = 'current';
var para = '&op='+type;
if (arguments.length > 1) {
for (i = 1; i < arguments.length; i++) {
para += '&' + arguments[i] + '=' + arguments[++i];
}
}
var ajaxtarget = type == 'image' ? 'diyimages' : '';
var x = new Ajax();
x.showId = ajaxtarget;
x.get('home.php?mod=spacecp&ac=index'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s) {
if (s) {
drag.deleteFrame(['pb', 'bpb', 'tpb', 'lpb']);
if (type == 'image') {
$('diyimages').innerHTML = s;
} else {
$('controlcontent').innerHTML = s;
x.showId = 'controlcontent';
}
if (type_ == 'block') {
drag.initPosition();
drag.initChkBlock();
} else if (type_ == 'layout') {
$('layout'+spaceDiy.currentLayout).className = 'activity';
} else if (type_ == 'diy' && type != 'image') {
spaceDiy.setCurrentDiy(spaceDiy.currentDiy);
if (spaceDiy.styleSheet.rules.length > 0) {
Util.show('recover_button');
}
}
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
ajaxupdateevents($(x.showId));
}
}
if(!evaled) evalscript(s);
}
});
}
},
menuChange : function (tabs, menu) {
var tabobj = $(tabs);
var aobj = tabobj.getElementsByTagName("li");
for(i=0; i<aobj.length; i++) {
aobj[i].className = '';
$(aobj[i].id+'_content').style.display = 'none';
}
$(menu).className = 'a';
$(menu+'_content').style.display="block";
doane(null);
},
delIframe : function (){
drag.deleteFrame(['m_ctc', 'm_bc', 'm_fc']);
},
showEditSpaceInfo : function () {
$('spaceinfoshow').style.display='none';
if (!$('spaceinfoedit')) {
var dom = document.createElement('h2');
dom.id = 'spaceinfoedit';
Util.insertBefore(dom, $('spaceinfoshow'));
}
ajaxget('home.php?mod=spacecp&ac=index&op=getspaceinfo','spaceinfoedit');
},
spaceInfoCancel : function () {
if ($('spaceinfoedit')) $('spaceinfoedit').style.display = 'none';
if ($('spaceinfoshow')) $('spaceinfoshow').style.display = 'inline';
},
spaceInfoSave : function () {
ajaxpost('savespaceinfo','spaceinfoshow');
},
init : function () {
drag.init();
this.style = document.diyform.style.value;
this.currentLayout = typeof document.diyform.currentlayout == 'undefined' ? '' : document.diyform.currentlayout.value;
this.initStyleSheet();
if (this.styleSheet.rules) this.initDiyStyle();
this.initSpaceInfo();
},
initSpaceInfo : function () {
this.spaceInfoCancel();
if ($('spaceinfoshow')) {
if (!$('infoedit')) {
var dom = document.createElement('em');
dom.id = 'infoedit';
dom.innerHTML = '编辑';
$('spacename').appendChild(dom);
}
$('spaceinfoshow').onmousedown = function () {spaceDiy.showEditSpaceInfo();};
}
if ($('nv')) {
if(!$('nv').getElementsByTagName('li').length) {
$('nv').getElementsByTagName('ul')[0].className = 'mininv';
}
$('nv').onmouseover = function () {spaceDiy.showEditNvInfo();};
$('nv').onmouseout = function () {spaceDiy.hideEditNvInfo();};
}
},
showEditNvInfo : function () {
var nv = $('editnvinfo');
if(!nv) {
var dom = document.createElement('div');
dom.innerHTML = '<span id="editnvinfo" class="edit" style="background-color:#336699;" onclick="spaceDiy.opNvEditInfo();">设置</span>';
$('nv').appendChild(dom.childNodes[0]);
} else {
nv.style.display = '';
}
},
hideEditNvInfo : function () {
var nv = $('editnvinfo');
if(nv) {
nv.style.display = 'none';
}
},
opNvEditInfo : function () {
showWindow('showpersonalnv', 'home.php?mod=spacecp&ac=index&op=editnv','get',0);
},
getPersonalNv : function (show) {
var x = new Ajax();
show = !show ? '' : '&show=1';
x.get('home.php?mod=spacecp&ac=index&op=getpersonalnv&inajax=1'+show, function(s) {
if($('nv')) {
$('hd').removeChild($('nv'));
}
var dom = document.createElement('div');
dom.innerHTML = !s ? ' ' : s;
$('hd').appendChild(dom.childNodes[0]);
spaceDiy.initSpaceInfo();
});
}
});
spaceDiy.init(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: google.js 17172 2010-09-25 08:17:48Z zhangguosheng $
*/
document.writeln('<script type="text/javascript">');
document.writeln('function validate_google(theform) {');
document.writeln(' if(theform.site.value == 1) {');
document.writeln(' theform.q.value = \'site:' + google_host + ' \' + theform.q.value;');
document.writeln(' }');
document.writeln('}');
document.writeln('function submitFormWithChannel(channelname) {');
document.writeln(' document.gform.channel.value=channelname;');
document.writeln(' document.gform.submit();');
document.writeln(' return;');
document.writeln('}');
document.writeln('</script>');
document.writeln('<form name="gform" id="gform" method="get" autocomplete="off" action="http://www.google.com/search?" target="_blank" onSubmit="validate_google(this);">');
document.writeln('<input type="hidden" name="client" value="' + (!google_client ? 'aff-discuz' : google_client) + '" />');
document.writeln('<input type="hidden" name="ie" value="' + google_charset + '" />');
document.writeln('<input type="hidden" name="oe" value="UTF-8" />');
document.writeln('<input type="hidden" name="hl" value="' + google_hl + '" />');
document.writeln('<input type="hidden" name="lr" value="' + google_lr + '" />');
document.writeln('<input type="hidden" name="channel" value="search" />');
document.write('<div onclick="javascript:submitFormWithChannel(\'logo\')" style="cursor:pointer;float: left;width:70px;height:23px;background: url(' + STATICURL + 'image/common/Google_small.png) !important;background: none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + STATICURL+ 'image/common/Google_small.png\', sizingMethod=\'scale\')"><img src="' + STATICURL + 'image/common/none.gif" border="0" alt="Google" /></div>');
document.writeln(' <input type="text" class="txt" size="20" name="q" id="q" maxlength="255" value=""></input>');
document.writeln('<select name="site">');
document.writeln('<option value="0"' + google_default_0 + '>网页搜索</option>');
document.writeln('<option value="1"' + google_default_1 + '>站内搜索</option>');
document.writeln('</select>');
document.writeln(' <button type="submit" name="sa" value="true">搜索</button>');
document.writeln('</form>'); | JavaScript |
function uploadEdit(obj) {
mainForm = obj.form;
forms = $('attachbody').getElementsByTagName("FORM");
albumid = $('uploadalbum').value;
edit_save();
upload();
}
function edit_save() {
var p = window.frames['uchome-ifrHtmlEditor'];
var obj = p.window.frames['HtmlEditor'];
var status = p.document.getElementById('uchome-editstatus').value;
if(status == 'code') {
$('uchome-ttHtmlEditor').value = p.document.getElementById('sourceEditor').value;
} else if(status == 'text') {
if(BROWSER.ie) {
obj.document.body.innerText = p.document.getElementById('dvtext').value;
$('uchome-ttHtmlEditor').value = obj.document.body.innerHTML;
} else {
obj.document.body.textContent = p.document.getElementById('dvtext').value;
var sOutText = obj.document.body.innerHTML;
$('uchome-ttHtmlEditor').value = sOutText.replace(/\r\n|\n/g,"<br>");
}
} else {
$('uchome-ttHtmlEditor').value = obj.document.body.innerHTML;
}
backupContent($('uchome-ttHtmlEditor').value);
}
function relatekw() {
edit_save();
var subject = cnCode($('subject').value);
var message = cnCode($('uchome-ttHtmlEditor').value);
if(message) {
message = message.substr(0, 500);
}
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=relatekw&inajax=1&subjectenc=' + subject + '&messageenc=' + message, function(s){
$('tag').value = s;
});
}
function downRemoteFile() {
edit_save();
var formObj = $("articleform");
var oldAction = formObj.action;
formObj.action = "portal.php?mod=portalcp&ac=upload&op=downremotefile";
formObj.onSubmit = "";
formObj.target = "uploadframe";
formObj.submit();
formObj.action = oldAction;
formObj.target = "";
}
function backupContent(sHTML) {
if(sHTML.length > 11) {
var obj = $('uchome-ttHtmlEditor').form;
if(!obj) return;
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject' || el.name == 'title') {
subject = trim(elvalue);
} else if(el.name == 'message' || el.name == 'content') {
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message) {
return;
}
saveUserdata('home', data);
}
}
function edit_insert(html) {
var p = window.frames['uchome-ifrHtmlEditor'];
var obj = p.window.frames['HtmlEditor'];
var status = p.document.getElementById('uchome-editstatus').value;
if(status != 'html') {
alert('本操作只在多媒体编辑模式下才有效');
return;
}
obj.focus();
if(BROWSER.ie){
var f = obj.document.selection.createRange();
f.pasteHTML(html);
f.collapse(false);
f.select();
} else {
obj.document.execCommand('insertHTML', false, html);
}
}
function insertImage(image, url) {
url = typeof url == 'undefined' || url === null ? image : url;
var html = '<p><a href="' + url + '" target="_blank"><img src="'+image+'"></a></p>';
edit_insert(html);
}
function insertFile(file, url) {
url = typeof url == 'undefined' || url === null ? image : url;
var html = '<p><a href="' + url + '" target="_blank" class="attach">' + file + '</a></p>';
edit_insert(html);
} | JavaScript |
var gSetColorType = "";
var gIsIE = document.all;
var gIEVer = fGetIEVer();
var gLoaded = false;
var ev = null;
var gIsHtml = true;
var pos = 0;
var sLength = 0;
function fGetEv(e){
ev = e;
}
function fGetIEVer(){
var iVerNo = 0;
var sVer = navigator.userAgent;
if(sVer.indexOf("MSIE")>-1){
var sVerNo = sVer.split(";")[1];
sVerNo = sVerNo.replace("MSIE","");
iVerNo = parseFloat(sVerNo);
}
return iVerNo;
}
function fSetEditable(){
var f = window.frames["HtmlEditor"];
f.document.designMode="on";
if(!gIsIE)
f.document.execCommand("useCSS",false, true);
}
function renewContent() {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
if(window.confirm('您确定要恢复上次保存?')) {
var data = loadUserdata('home');
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
parent.showDialog('没有可以恢复的数据!');
return;
}
var data = data.split(/\x09\x09/);
if(parent.$('subject')) {
var formObj = parent.$('subject').form;
} else if(parent.$('title')) {
var formObj = parent.$('title').form;
} else {
return;
}
for(var i = 0; i < formObj.elements.length; i++) {
var el = formObj.elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message' || ele[0] == 'content') {
var f = window.frames["HtmlEditor"];
f.document.body.innerHTML = elvalue;
} else {
el.value = elvalue;
}
}
break
}
}
}
}
}
}
function fSetFrmClick(){
var f = window.frames["HtmlEditor"];
f.document.onclick = function(){
fHideMenu();
}
if(gIsIE) {
f.document.attachEvent("onkeydown", listenKeyDown);
} else {
f.addEventListener('keydown', function(e) {listenKeyDown(e);}, true);
}
}
function listenKeyDown(event) {
parent.gIsEdited = true;
parent.ctrlEnter(event, 'issuance');
}
window.onload = function(){
try{
gLoaded = true;
fSetEditable();
fSetFrmClick();
}catch(e){
}
}
window.onbeforeunload = parent.edit_save;
function fSetColor(){
var dvForeColor =$("dvForeColor");
if(dvForeColor.getElementsByTagName("TABLE").length == 1){
dvForeColor.innerHTML = drawCube() + dvForeColor.innerHTML;
}
}
document.onmousemove = function(e){
if(gIsIE) var el = event.srcElement;
else var el = e.target;
var tdView = $("tdView");
var tdColorCode = $("tdColorCode");
if(el.tagName == "IMG"){
try{
if(fInObj(el, "dvForeColor")){
tdView.bgColor = el.parentNode.bgColor;
tdColorCode.innerHTML = el.parentNode.bgColor
}
}catch(e){}
}
}
function fInObj(el, id){
if(el){
if(el.id == id){
return true;
}else{
if(el.parentNode){
return fInObj(el.parentNode, id);
}else{
return false;
}
}
}
}
function fDisplayObj(id){
var o = $(id);
if(o) o.style.display = "";
}
document.onclick = function(e){
if(gIsIE) var el = event.srcElement;
else var el = e.target;
var dvForeColor =$("dvForeColor");
var dvPortrait =$("dvPortrait");
if(el.tagName == "IMG"){
try{
if(fInObj(el, "dvForeColor")){
format(gSetColorType, el.parentNode.bgColor);
dvForeColor.style.display = "none";
return;
}
}catch(e){}
try{
if(fInObj(el, "dvPortrait")){
format("InsertImage", el.src);
dvPortrait.style.display = "none";
return;
}
}catch(e){}
}
try{
if(fInObj(el, "createUrl") || fInObj(el, "createImg") || fInObj(el, "createSwf") || fInObj(el, "createPage")){
return;
}
}catch(e){}
fHideMenu();
var hideId = "";
if(arrMatch[el.id]){
hideId = arrMatch[el.id];
fDisplayObj(hideId);
}
}
var arrMatch = {
imgFontface:"fontface",
imgFontsize:"fontsize",
imgFontColor:"dvForeColor",
imgBackColor:"dvForeColor",
imgFace:"dvPortrait",
imgAlign:"divAlign",
imgList:"divList",
imgInOut:"divInOut",
faceBox:"editFaceBox",
icoUrl:"createUrl",
icoImg:"createImg",
icoSwf:"createSwf",
icoPage:"createPage"
}
function format(type, para){
var f = window.frames["HtmlEditor"];
var sAlert = "";
if(!gIsIE){
switch(type){
case "Cut":
sAlert = "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成";
break;
case "Copy":
sAlert = "您的浏览器安全设置不允许编辑器自动执行拷贝操作,请使用键盘快捷键(Ctrl+C)来完成";
break;
case "Paste":
sAlert = "您的浏览器安全设置不允许编辑器自动执行粘贴操作,请使用键盘快捷键(Ctrl+V)来完成";
break;
}
}
if(sAlert != ""){
alert(sAlert);
return;
}
f.focus();
if(!para){
if(gIsIE){
f.document.execCommand(type);
}else{
f.document.execCommand(type,false,false);
}
}else{
if(type == 'insertHTML') {
try{
f.document.execCommand('insertHTML', false, para);
}catch(exp){
var obj = f.document.selection.createRange();
obj.pasteHTML(para);
obj.collapse(false);
obj.select();
}
} else {
try{
f.document.execCommand(type,false,para);
}catch(exp){}
}
}
f.focus();
}
function setMode(bStatus){
var sourceEditor = $("sourceEditor");
var HtmlEditor = $("HtmlEditor");
var divEditor = $("divEditor");
var f = window.frames["HtmlEditor"];
var body = f.document.getElementsByTagName("BODY")[0];
if(bStatus){
sourceEditor.style.display = "block";
divEditor.style.display = "none";
sourceEditor.value = body.innerHTML;
$('uchome-editstatus').value = 'code';
}else{
sourceEditor.style.display = "none";
divEditor.style.display = "";
body.innerHTML = sourceEditor.value;
$('uchome-editstatus').value = 'html';
}
}
function foreColor(e) {
fDisplayColorBoard(e);
gSetColorType = "foreColor";
}
function faceBox(e) {
if(gIsIE){
var e = window.event;
}
var dvFaceBox = $("editFaceBox");
var iX = e.clientX;
var iY = e.clientY;
dvFaceBox.style.display = "";
dvFaceBox.style.left = (iX-140) + "px";
dvFaceBox.style.top = 33 + "px";
dvFaceBox.innerHTML = "";
var faceul = document.createElement("ul");
for(i=1; i<31; i++) {
var faceli = document.createElement("li");
faceli.innerHTML = '<img src="' + parent.STATICURL + 'image/smiley/comcom/'+i+'.gif" onclick="insertImg(this.src);" class="cur1" />';
faceul.appendChild(faceli);
}
dvFaceBox.appendChild(faceul);
return true;
}
function insertImg(src) {
format("insertHTML", '<img src="' + src + '"/>');
}
function doodleBox(event, id) {
if(parent.$('uchome-ttHtmlEditor') != null) {
parent.showWindow(id, 'home.php?mod=magic&mid=doodle&showid=blog_doodle&target=uchome-ttHtmlEditor&from=editor');
} else {
alert("找不到涂鸦板初始化数据");
}
}
function backColor(e){
var sColor = fDisplayColorBoard(e);
if(gIsIE)
gSetColorType = "backcolor";
else
gSetColorType = "backcolor";
}
function fDisplayColorBoard(e){
if(gIsIE){
var e = window.event;
}
if(gIEVer<=5.01 && gIsIE){
var arr = showModalDialog("ColorSelect.htm", "", "font-family:Verdana; font-size:12; status:no; dialogWidth:21em; dialogHeight:21em");
if (arr != null) return arr;
return;
}
var dvForeColor =$("dvForeColor");
var iX = e.clientX;
var iY = e.clientY;
dvForeColor.style.display = "";
dvForeColor.style.left = (iX-30) + "px";
dvForeColor.style.top = 33 + "px";
return true;
}
function createLink(e, show) {
if(typeof show == 'undefined') {
var urlObj = $('insertUrl');
var sURL = urlObj.value;
if ((sURL!=null) && (sURL!="http://")){
setCaret();
format("CreateLink", sURL);
}
fHide($('createUrl'));
urlObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvUrlBox = $("createUrl");
var iX = e.clientX;
var iY = e.clientY;
dvUrlBox.style.display = "";
dvUrlBox.style.left = (iX-300) + "px";
dvUrlBox.style.top = 33 + "px";
}
}
function getCaret() {
if(gIsIE){
window.frames["HtmlEditor"].focus();
var ran = window.frames["HtmlEditor"].document.selection.createRange();
sLength = ran.text.replace(/\r?\n/g, ' ').length;
if(!sLength) {
ran = window.frames["HtmlEditor"].document.body.createTextRange();
}
var rang = document.selection.createRange();
rang.setEndPoint("StartToStart", ran);
pos = rang.text.replace(/\r?\n/g, ' ').length;
}
}
function setCaret() {
if(gIsIE){
window.frames["HtmlEditor"].focus();
var r = window.frames["HtmlEditor"].document.body.createTextRange();
var textLen = r.text.replace(/\r?\n/g, ' ').length;
r.moveStart('character', pos);
if(sLength) {
var eLen = sLength - (textLen - pos);
r.moveEnd('character', eLen);
} else {
r.collapse(true);
}
r.select();
}
}
function clearLink() {
format("Unlink", false);
}
function createImg(e, show) {
if(typeof show == 'undefined') {
var imgObj = $('imgUrl');
var sPhoto = imgObj.value;
if ((sPhoto!=null) && (sPhoto!="http://")){
setCaret();
format("InsertImage", sPhoto);
}
fHide($('createImg'));
imgObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvImgBox = $("createImg");
var iX = e.clientX;
var iY = e.clientY;
dvImgBox.style.display = "";
dvImgBox.style.left = (iX-300) + "px";
dvImgBox.style.top = 33 + "px";
}
}
function createFlash(e, show) {
if(typeof show == 'undefined') {
var flashtag = '';
var vObj = $('videoUrl');
var sFlash = vObj.value;
if ((sFlash!=null) && (sFlash!="http://")){
setCaret();
var sFlashType = $('vtype').value;
if(sFlashType==1) {
flashtag = '[flash=media]';
} else if(sFlashType==2) {
flashtag = '[flash=real]';
} else if(sFlashType==3) {
flashtag = '[flash=mp3]';
} else {
flashtag = '[flash]';
}
format("insertHTML", flashtag + sFlash + '[/flash]');
}
fHide($('createSwf'));
vObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvSwfBox = $("createSwf");
var iX = e.clientX;
var iY = e.clientY;
dvSwfBox.style.display = "";
dvSwfBox.style.left = (iX-350) + "px";
dvSwfBox.style.top = 33 + "px";
}
}
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
function fSetBorderMouseOver(obj) {
obj.style.borderRight="1px solid #aaa";
obj.style.borderBottom="1px solid #aaa";
obj.style.borderTop="1px solid #fff";
obj.style.borderLeft="1px solid #fff";
}
function fSetBorderMouseOut(obj) {
obj.style.border="none";
}
function fSetBorderMouseDown(obj) {
obj.style.borderRight="1px #F3F8FC solid";
obj.style.borderBottom="1px #F3F8FC solid";
obj.style.borderTop="1px #cccccc solid";
obj.style.borderLeft="1px #cccccc solid";
}
function fDisplayElement(element,displayValue) {
if(gIEVer<=5.01 && gIsIE){
alert('只支持IE 5.01以上版本');
return;
}
fHideMenu();
if ( typeof element == "string" )
element = $(element);
if (element == null) return;
element.style.display = displayValue;
if(gIsIE){
var e = event;
var target = e.srcElement;
}else{
var e = ev;
var target = e.target;
}
var iX = f_GetX(target);
element.style.display = "";
element.style.left = (iX) + "px";
element.style.top = 33 + "px";
return true;
}
function fSetModeTip(obj){
var x = f_GetX(obj);
var y = f_GetY(obj);
var dvModeTip = $("dvModeTip");
if(!dvModeTip){
var dv = document.createElement("DIV");
dv.style.position = "absolute";
dv.style.top = 33 + "px";
dv.style.left = (x-40) + "px";
dv.style.zIndex = "999";
dv.style.fontSize = "12px";
dv.id = "dvModeTip";
dv.style.padding = "2px";
dv.style.border = "1px #000000 solid";
dv.style.backgroundColor = "#FFFFCC";
dv.innerHTML = "编辑源码";
document.body.appendChild(dv);
}else{
dvModeTip.style.display = "";
}
}
function fHideTip(){
$("dvModeTip").style.display = "none";
}
function f_GetX(e)
{
var l=e.offsetLeft;
while(e=e.offsetParent){
l+=e.offsetLeft;
}
return l;
}
function f_GetY(e)
{
var t=e.offsetTop;
while(e=e.offsetParent){
t+=e.offsetTop;
}
return t;
}
function fHideMenu(){
try{
var arr = ["fontface", "fontsize", "dvForeColor", "dvPortrait", "divAlign", "divList" ,"divInOut", "editFaceBox", "createUrl", "createImg", "createSwf", "createPage"];
for(var i=0;i<arr.length;i++){
var obj = $(arr[i]);
if(obj){
obj.style.display = "none";
}
}
try{
parent.LetterPaper.control(window, "hide");
}catch(exp){}
}catch(exp){}
}
function $(id){
return document.getElementById(id);
}
function fHide(obj){
obj.style.display="none";
}
function pageBreak(e, show) {
if(!show) {
var obj = $('pageTitle');
var title = obj ? obj.value : '';
if(obj) {
obj.value = '';
}
var insertText = title ? '[title='+title+']': '';
setCaret();
format("insertHTML", '###NextPage'+insertText+'###');
fHide($('createPage'));
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvSwfBox = $("createPage");
var iX = e.clientX;
var iY = e.clientY;
dvSwfBox.style.display = "";
dvSwfBox.style.left = (iX-300) + "px";
dvSwfBox.style.top = 33 + "px";
}
}
function changeEditType(flag, ev){
gIsHtml = flag;
try{
var mod = parent.MM["compose"];
mod.html = flag;
}catch(exp){}
try{
var dvhtml = $("dvhtml");
var dvtext = $("dvtext");
var HtmlEditor = window.frames["HtmlEditor"];
var ifmHtmlEditor = $("HtmlEditor");
var sourceEditor = $("sourceEditor");
var switchMode = $("switchMode");
var sourceEditor = $("sourceEditor");
var dvHtmlLnk = $("dvHtmlLnk");
if(flag){
dvhtml.style.display = "";
dvtext.style.display = "none";
dvHtmlLnk.style.display = "none";
if(switchMode.checked){
sourceEditor.value = dvtext.value;
$('uchome-editstatus').value = 'code';
}else{
if(document.all){
HtmlEditor.document.body.innerText = dvtext.value;
} else {
HtmlEditor.document.body.innerHTML = dvtext.value.unescapeHTML();
}
$('uchome-editstatus').value = 'html';
}
}else{
function sub1(){
dvhtml.style.display = "none";
dvtext.style.display = "";
dvHtmlLnk.style.display = "";
if(switchMode.checked){
dvtext.value = sourceEditor.value.unescapeHTML();
}else{
if(document.all){
dvtext.value = HtmlEditor.document.body.innerText;
}else{
dvtext.value = HtmlEditor.document.body.innerHTML.unescapeHTML();
}
}
}
ev = ev || event;
if(ev){
if(window.confirm("转换为纯文本时将会遗失某些格式。\n您确定要继续吗?")){
$('uchome-editstatus').value = 'text';
sub1();
}else{
return;
}
}
}
}catch(exp){
}
}
String.prototype.stripTags = function(){
return this.replace(/<\/?[^>]+>/gi, '');
};
String.prototype.unescapeHTML = function(){
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0].nodeValue;
};
var s = "";
var hex = new Array(6)
hex[0] = "FF"
hex[1] = "CC"
hex[2] = "99"
hex[3] = "66"
hex[4] = "33"
hex[5] = "00"
function drawCell(red, green, blue) {
var color = '#' + red + green + blue;
if(color == "#000066") color = "#000000";
s += '<TD BGCOLOR="' + color + '" style="height:12px;width:12px;" >';
s += '<IMG '+ ((document.all)?"":"src='editor_none.gif'") +' HEIGHT=12 WIDTH=12>';
s += '</TD>';
}
function drawRow(red, blue) {
s += '<TR>';
for (var i = 0; i < 6; ++i) {
drawCell(red, hex[i], blue)
}
s += '</TR>';
}
function drawTable(blue) {
s += '<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0>';
for (var i = 0; i < 6; ++i) {
drawRow(hex[i], blue)
}
s += '</TABLE>';
}
function drawCube() {
s += '<TABLE CELLPADDING=0 CELLSPACING=0 style="border:1px #888888 solid"><TR>';
for (var i = 0; i < 2; ++i) {
s += '<TD BGCOLOR="#FFFFFF">';
drawTable(hex[i])
s += '</TD>';
}
s += '</TR><TR>';
for (var i = 2; i < 4; ++i) {
s += '<TD BGCOLOR="#FFFFFF">';
drawTable(hex[i])
s += '</TD>';
}
s += '</TR></TABLE>';
return s;
}
function EV(){}
EV.getTarget = fGetTarget;
EV.getEvent = fGetEvent;
EV.stopEvent = fStopEvent;
EV.stopPropagation = fStopPropagation;
EV.preventDefault = fPreventDefault;
function fGetTarget(ev, resolveTextNode){
if(!ev) ev = this.getEvent();
var t = ev.target || ev.srcElement;
if (resolveTextNode && t && "#text" == t.nodeName) {
return t.parentNode;
} else {
return t;
}
}
function fGetEvent (e) {
var ev = e || window.event;
if (!ev) {
var c = this.getEvent.caller;
while (c) {
ev = c.arguments[0];
if (ev && Event == ev.constructor) {
break;
}
c = c.caller;
}
}
return ev;
}
function fStopEvent(ev) {
if(!ev) ev = this.getEvent();
this.stopPropagation(ev);
this.preventDefault(ev);
}
function fStopPropagation(ev) {
if(!ev) ev = this.getEvent();
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
}
function fPreventDefault(ev) {
if(!ev) ev = this.getEvent();
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
}
function getExt(path) {
return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function checkURL(obj, mod) {
if(mod) {
if(obj.value == 'http://') {
obj.value = '';
}
} else {
if(obj.value == '') {
obj.value = 'http://';
}
}
} | JavaScript |
function submitForm() {
if (dialogHtml == '') {
dialogHtml = $('siteInfo').innerHTML;
$('siteInfo').innerHTML = '';
}
showWindow(null, dialogHtml, 'html');
$('fwin_null').style.top = '80px';
$('cloud_api_ip').value = cloudApiIp;
return false;
}
function dealHandle(msg) {
getMsg = true;
if (msg['status'] == 'error') {
$('loadinginner').innerHTML = '<font color="red">' + msg['content'] + '</font>';
return;
}
$('loading').style.display = 'none';
$('mainArea').style.display = '';
if(cloudStatus == 'upgrade') {
$('title').innerHTML = msg['cloudIntroduction']['upgrade_title'];
$('msg').innerHTML = msg['cloudIntroduction']['upgrade_content'];
} else {
$('title').innerHTML = msg['cloudIntroduction']['open_title'];
$('msg').innerHTML = msg['cloudIntroduction']['open_content'];
}
if (msg['navSteps']) {
$('nav_steps').innerHTML = msg['navSteps'];
}
if (msg['protocalUrl']) {
$('protocal_url').href = msg['protocalUrl'];
}
if (msg['cloudApiIp']) {
cloudApiIp = msg['cloudApiIp'];
}
if (msg['manyouUpdateTips']) {
$('manyou_update_tips').innerHTML = msg['manyouUpdateTips'];
}
}
function expiration() {
if(!getMsg) {
$('loadinginner').innerHTML = '<font color="red">' + expirationText + '</font>';
clearTimeout(expirationTimeout);
}
} | JavaScript |
var j = jQuery.noConflict();
if (typeof disallowfloat == 'undefined' || disallowfloat === null) {
var disallowfloat = '';
}
var currentNormalEditDisplay = 0;
j(document).ready(function() {
ajaxGetSearchResultThreads();
j('#previewForm').submit(function() {
return previewFormSubmit();
});
});
function previewFormSubmit() {
saveAllThread();
if (!selectedTopicId || selectedNormalIds.length < 1) {
alert('请至少推送一条头条主题和一条列表主题');
return false;
}
var i = 1;
for (var k = 1; k <= 5; k++) {
var input_displayorder = j('#normal_thread_' + k).find('.preview_displayorder');
if (input_displayorder.size()) {
input_displayorder.val(i);
i++;
}
}
return true;
}
function initSelect() {
var initTopicObj = j('#search_result .qqqun_op .qqqun_op_topon');
initTopicObj.addClass('qqqun_op_top');
initTopicObj.removeClass('qqqun_op_topon');
var initNormalObj = j('#search_result .qqqun_op .qqqun_op_liston');
initNormalObj.addClass('qqqun_op_list');
initNormalObj.removeClass('qqqun_op_liston');
selectedTopicId = parseInt(selectedTopicId);
if (selectedTopicId) {
j('#thread_addtop_' + selectedTopicId).addClass('qqqun_op_topon');
j('#thread_addtop_' + selectedTopicId).removeClass('qqqun_op_top');
}
j.each(selectedNormalIds, function(k, v) {
v = parseInt(v);
if (v) {
j('#thread_addlist_' + v).addClass('qqqun_op_liston');
j('#thread_addlist_' + v).removeClass('qqqun_op_list');
}
});
}
function ajaxChangeSearch() {
j('#srchtid').val('');
ajaxGetSearchResultThreads();
}
function ajaxGetSearchResultThreads() {
j('#search_result').html('<tr><td colspan="3">加载中...</td></tr>');
ajaxpost('search_form', 'search_result', null, null, null, function() {initSelect(); return false});
return false;
}
function ajaxGetPageResultThreads(page, mpurl) {
j('#search_result').html('<tr><td colspan="3">加载中...</td></tr>');
if (typeof page == 'undefined' || page === null) {
page = 1;
}
if (typeof mpurl == 'undefined' || !mpurl) {
return false;
}
ajaxget(mpurl + '&page=' + page, 'search_result', null, null, null, function() {initSelect();} );
}
function addMiniportalTop(tid) {
tid = parseInt(tid);
if (j.inArray(tid, selectedNormalIds) > -1) {
removeNormalThreadByTid(tid);
}
addMiniportalTopId(tid);
initSelect();
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread&tid=' + tid, 'topicDiv', null, null, null, function() { clickTopicEditor(); });
}
function addMiniportalTopId(tid) {
selectedTopicId = tid;
}
function showPreviewEditor(topic, hideall) {
if (hideall) {
j('.qqqun_list .qqqun_editor').hide();
j('.qqqun_list .qqqun_xl li').removeClass('current');
j('.qqqun_list').removeClass('qqqun_list_editor');
j('.qqqun_top .qqqun_editor').hide();
j('.qqqun_top').removeClass('qqqun_top_editor');
} else {
if (topic) {
j('.qqqun_list .qqqun_editor').hide();
j('.qqqun_list .qqqun_xl li').removeClass('current');
j('.qqqun_list').removeClass('qqqun_list_editor');
j('.qqqun_top .qqqun_editor').show();
j('.qqqun_top').addClass('qqqun_top_editor');
} else {
j('.qqqun_list .qqqun_editor').show();
j('.qqqun_list').addClass('qqqun_list_editor');
j('.qqqun_list .qqqun_xl li').removeClass('current');
j('.qqqun_top .qqqun_editor').hide();
j('.qqqun_top').removeClass('qqqun_top_editor');
}
}
}
function clickTopicEditor(topicFocus) {
if (typeof topicFocus == 'undefined') {
var topicFocus = 'title';
}
showPreviewEditor(true, false);
if (topicFocus == 'title') {
j('#topic-editor-input-title').addClass('pt_focus');
j('#topic-editor-input-title').focus();
} else if (topicFocus == 'content') {
j('#topic-editor-textarea-content').addClass('pt_focus');
j('#topic-editor-textarea-content').focus();
}
currentNormalEditDisplay = 0;
}
function blurTopic(obj) {
var thisobj = j(obj);
thisobj.removeClass('pt_focus');
}
function clickNormalEditor(obj) {
var thisobj = j(obj);
showPreviewEditor(false, false);
thisobj.addClass('pt_focus');
thisobj.focus();
currentNormalEditDisplay = parseInt(thisobj.parent().attr('displayorder'));
}
function blurNormalTextarea(obj) {
var thisobj = j(obj);
liObj = thisobj.parent();
var displayorder = parseInt(liObj.attr('displayorder'));
if (displayorder == currentNormalEditDisplay) {
liObj.addClass('current');
}
j('.qqqun_list .qqqun_xl textarea').removeClass('pt_focus');
}
function addMiniportalList(tid) {
tid = parseInt(tid);
if (j.inArray(tid, selectedNormalIds) > -1) {
return false;
}
if (selectedNormalIds.length >= 5) {
alert('推送帖子已达到5条,请在右侧取消一些再重试。');
return false;
}
if (tid == selectedTopicId) {
selectedTopicId = 0;
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread&tid=0', 'topicDiv');
}
addMiniportalListId(tid);
initSelect();
var insertPos = 'normal_thread_' + selectedNormalIds.length;
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getNormalThread&tid=' + tid, insertPos, null, null, null, function() { clickNormalEditor(j('#' + insertPos).find('textarea')); });
}
function addMiniportalListId(tid) {
selectedNormalIds.push(tid);
}
function editNormalThread() {
var threadLi = j('#normal_thread_' + currentNormalEditDisplay);
clickNormalEditor(threadLi.find('textarea'));
}
function saveAllThread() {
showPreviewEditor(false, true);
currentNormalEditDisplay = 0;
}
function moveNormalThread(up) {
var displayorder = currentNormalEditDisplay;
var threadLi = j('#normal_thread_' + displayorder);
if (!threadLi.attr('id') || !displayorder) {
return false;
}
var newDisplayorder = 0;
if (up) {
newDisplayorder = displayorder - 1;
} else {
newDisplayorder = displayorder + 1;
}
if (newDisplayorder < 1 || newDisplayorder > 5) {
return false;
}
var newLiId = 'normal_thread_' + newDisplayorder;
var newThreadLi = j('#' + newLiId);
if (!newThreadLi.find('textarea').size()) {
return false;
}
var tmpHtml = newThreadLi.html();
newThreadLi.html(threadLi.html());
threadLi.html(tmpHtml);
newThreadLi.addClass('current');
threadLi.removeClass('current');
currentNormalEditDisplay = newDisplayorder;
}
function removeTopicThread(tid) {
tid = parseInt(tid);
selectedTopicId = 0;
initSelect();
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread', 'topicDiv', null, null, null, function() { showPreviewEditor(false, true)});
}
function removeNormalThread() {
var displayorder = currentNormalEditDisplay;
var removeTid = parseInt(j('#normal_thread_' + displayorder).find('.normal_thread_tid').val());
return removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, true);
}
function removeNormalThreadByTid(tid) {
tid = parseInt(tid);
var threadInput = j('.qqqun_list .qqqun_xl .normal_thread_tid[value="' + tid + '"]');
if (threadInput.size()) {
var displayorder = threadInput.parent().attr('displayorder');
var removeTid = tid;
return removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, false);
}
}
function removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, inNormalEditor) {
displayorder = parseInt(displayorder);
removeTid = parseInt(removeTid);
var threadLi = j('#normal_thread_' + displayorder);
if (!threadLi.attr('id') || !displayorder) {
return false;
}
threadLi.removeClass('current');
var index = j.inArray(removeTid, selectedNormalIds);
if (index != -1) {
selectedNormalIds.splice(index, 1);
}
initSelect();
if (typeof inNormalEditor == 'udefined') {
var inNormalEditor = false;
}
threadLi.slideUp(100, function() { removeNormalThreadRecall(displayorder, inNormalEditor)});
}
function removeNormalThreadRecall(displayorder, inNormalEditor) {
for (var i = displayorder; i <= 5; i++) {
var currentDisplayorder = i;
var nextDisplayorder = i + 1;
var currentLiId = 'normal_thread_' + currentDisplayorder;
var currentThreadLi = j('#' + currentLiId);
var nextLiId = 'normal_thread_' + nextDisplayorder;
var nextThreadLi = j('#' + nextLiId);
if (nextThreadLi.find('textarea').size()) {
currentThreadLi.html(nextThreadLi.html());
currentThreadLi.show();
} else {
currentThreadLi.html('');
currentThreadLi.hide();
break;
}
}
var threadLi = j('#normal_thread_' + displayorder);
var prevDisplayorder = displayorder - 1;
if (threadLi.find('textarea').size()) {
if (inNormalEditor) {
threadLi.addClass('current');
}
currentNormalEditDisplay = displayorder;
} else if (prevDisplayorder) {
var prevThreadLi = j('#normal_thread_' + prevDisplayorder);
if (inNormalEditor) {
prevThreadLi.addClass('current');
}
currentNormalEditDisplay = prevDisplayorder;
} else {
var firstThreadLi = j('#normal_thread_1');
if (inNormalEditor) {
saveAllThread();
}
firstThreadLi.html('<div class="tips">点击左侧 <img src="static/image/admincp/cloud/qun_op_list.png" align="absmiddle" /> 将信息推送到列表</div>');
firstThreadLi.show();
}
}
function ajaxUploadQQGroupImage() {
j('#uploadImageResult').parent().show();
j('#uploadImageResult').text('图片上传中,请稍后...');
ajaxpost('uploadImage', 'uploadImageResult', null, null, null, 'uploadRecall()');
}
function uploadRecall() {
if(j('#uploadImageResult').find('#upload_msg_success').size()) {
j('#uploadImageResult').parent().show();
var debug_rand = Math.random();
var imagePath = j('#uploadImageResult #upload_msg_imgpath').text();
var imageUrl = j('#uploadImageResult #upload_msg_imgurl').text();
j('#topic_image_value').val(imagePath);
j('#topic_editor_thumb').attr('src', imageUrl + '?' + debug_rand);
j('#topic_preview_thumb').attr('src', imageUrl + '?' + debug_rand);
setTimeout(function() {hideWindow('uploadImgWin');}, 2000);
}
} | JavaScript |
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function $(id) {
return document.getElementById(id);
}
Array.prototype.push = function(value) {
this[this.length] = value;
return this.length;
}
function getcookie(name) {
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
seconds = seconds ? seconds : 8400000;
var expires = new Date();
expires.setTime(expires.getTime() + seconds);
document.cookie = escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
function _cancelBubble(e, returnValue) {
if(!e) return ;
if(is_ie) {
if(!returnValue) e.returnValue = false;
e.cancelBubble = true;
} else {
e.stopPropagation();
if(!returnValue) e.preventDefault();
}
}
function checkall(name) {
var e = is_ie ? event : checkall.caller.arguments[0];
obj = is_ie ? e.srcElement : e.target;
var arr = document.getElementsByName(name);
var k = arr.length;
for(var i=0; i<k; i++) {
arr[i].checked = obj.checked;
}
}
function getposition(obj) {
var r = new Array();
r['x'] = obj.offsetLeft;
r['y'] = obj.offsetTop;
while(obj = obj.offsetParent) {
r['x'] += obj.offsetLeft;
r['y'] += obj.offsetTop;
}
return r;
}
function addMouseEvent(obj){
var checkbox,atr,ath,i;
atr=obj.getElementsByTagName("tr");
for(i=0;i<atr.length;i++){
atr[i].onclick=function(){
ath=this.getElementsByTagName("th");
checkbox=this.getElementsByTagName("input")[0];
if(!ath.length && checkbox.getAttribute("type")=="checkbox"){
if(this.className!="currenttr"){
this.className="currenttr";
checkbox.checked=true;
}else{
this.className="";
checkbox.checked=false;
}
}
}
}
}
// editor.js
if(is_ie) document.documentElement.addBehavior("#default#userdata");
function setdata(key, value){
if(is_ie){
document.documentElement.load(key);
document.documentElement.setAttribute("value", value);
document.documentElement.save(key);
return document.documentElement.getAttribute("value");
} else {
sessionStorage.setItem(key,value);
}
}
function getdata(key){
if(is_ie){
document.documentElement.load(key);
return document.documentElement.getAttribute("value");
} else {
return sessionStorage.getItem(key) && sessionStorage.getItem(key).toString().length == 0 ? '' : (sessionStorage.getItem(key) == null ? '' : sessionStorage.getItem(key));
}
}
function form_option_selected(obj, value) {
for(var i=0; i<obj.options.length; i++) {
if(obj.options[i].value == value) {
obj.options[i].selected = true;
}
}
}
function switchcredit(obj, value) {
var creditsettings = credit[value];
var s = '<select name="credit' + obj + '">';
for(var i in creditsettings) {
s += '<option value="' + creditsettings[i][0] + '">' + creditsettings[i][1] + '</option>';
}
s += '</select>';
$(obj).innerHTML = s;
}
function setselect(selectobj, value) {
var len = selectobj.options.length;
for(i = 0;i < len;i++) {
if(selectobj.options[i].value == value) {
selectobj.options[i].selected = true;
}
}
}
function show(id, display) {
if(!$(id)) return false;
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
} | JavaScript |
//Common
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function $(id) {
return document.getElementById(id);
}
function fetchOffset(obj) {
var left_offset = obj.offsetLeft;
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
return { 'left' : left_offset, 'top' : top_offset };
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
function strlen(str) {
return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
//Menu
var menus = new menu_handler();
function menu_handler() {
this.menu = Array();
}
function menuitems() {
this.ctrlobj = null,
this.menuobj = null;
this.parentids = Array();
this.allowhide = 1;
this.hidelock = 0;
this.clickstatus = 0;
}
function menuobjpos(id, offset) {
if(!menus.menu[id]) {
return;
}
if(!offset) {
offset = 0;
}
var showobj = menus.menu[id].ctrlobj;
var menuobj = menus.menu[id].menuobj;
showobj.pos = fetchOffset(showobj);
showobj.X = showobj.pos['left'];
showobj.Y = showobj.pos['top'];
showobj.w = showobj.offsetWidth;
showobj.h = showobj.offsetHeight;
menuobj.w = menuobj.offsetWidth;
menuobj.h = menuobj.offsetHeight;
if(offset < 3) {
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + 'px';
menuobj.style.top = offset == 1 ? showobj.Y + 'px' : (offset == 2 || ((showobj.Y + showobj.h + menuobj.h > document.documentElement.scrollTop + document.documentElement.clientHeight) && (showobj.Y - menuobj.h >= 0)) ? (showobj.Y - menuobj.h) + 'px' : showobj.Y + showobj.h + 'px');
} else if(offset == 3) {
menuobj.style.left = (document.body.clientWidth - menuobj.clientWidth) / 2 + document.body.scrollLeft + 'px';
menuobj.style.top = (document.body.clientHeight - menuobj.clientHeight) / 2 + document.body.scrollTop + 'px';
} else if(offset == 4) {
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + showobj.w + 'px';
menuobj.style.top = showobj.Y + 'px';
}
if(menuobj.style.clip && !is_opera) {
menuobj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
function showmenu(event, id, click, position) {
if(isUndefined(click)) click = false;
if(!menus.menu[id]) {
menus.menu[id] = new menuitems();
menus.menu[id].ctrlobj = $(id);
if(!menus.menu[id].ctrlobj.getAttribute('parentmenu')) {
menus.menu[id].parentids = Array();
} else {
menus.menu[id].parentids = menus.menu[id].ctrlobj.getAttribute('parentmenu').split(',');
}
menus.menu[id].menuobj = $(id + '_menu');
menus.menu[id].menuobj.style.position = 'absolute';
if(event.type == 'mouseover') {
_attachEvent(menus.menu[id].ctrlobj, 'mouseout', function() { setTimeout(function() {hidemenu(id)}, 100); });
_attachEvent(menus.menu[id].menuobj, 'mouseover', function() { lockmenu(id, 0); });
_attachEvent(menus.menu[id].menuobj, 'mouseout', function() { lockmenu(id, 1);setTimeout(function() {hidemenu(id)}, 100); });
} else if(click || event.type == 'click') {
menus.menu[id].clickstatus = 1;
lockmenu(id, 0);
}
} else if(menus.menu[id].clickstatus == 1) {
lockmenu(id, 1);
hidemenu(id);
menus.menu[id].clickstatus = 0;
return;
}
menuobjpos(id, position);
menus.menu[id].menuobj.style.display = '';
}
function hidemenu(id) {
if(!menus.menu[id] || !menus.menu[id].allowhide || menus.menu[id].hidelock) {
return;
}
menus.menu[id].menuobj.style.display = 'none';
}
function lockmenu(id, value) {
if(!menus.menu[id]) {
return;
}
for(i = 0;i < menus.menu[id].parentids.length;i++) {
menus.menu[menus.menu[id].parentids[i]].hidelock = value == 0 ? 1 : 0;
}
menus.menu[id].allowhide = value;
}
//Editor
var lang = new Array();
function insertunit(text, textend, moveend) {
$('pm_textarea').focus();
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($('pm_textarea').selectionStart)) {
var opn = $('pm_textarea').selectionStart + 0;
if(textend != '') {
text = text + $('pm_textarea').value.substring($('pm_textarea').selectionStart, $('pm_textarea').selectionEnd) + textend;
}
$('pm_textarea').value = $('pm_textarea').value.substr(0, $('pm_textarea').selectionStart) + text + $('pm_textarea').value.substr($('pm_textarea').selectionEnd);
if(!moveend) {
$('pm_textarea').selectionStart = opn + strlen(text) - endlen;
$('pm_textarea').selectionEnd = opn + strlen(text) - endlen;
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
$('pm_textarea').value += text;
}
}
function getSel() {
if(!isUndefined($('pm_textarea').selectionStart)) {
return $('pm_textarea').value.substr($('pm_textarea').selectionStart, $('pm_textarea').selectionEnd - $('pm_textarea').selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
function insertlist(type) {
txt = getSel();
type = isUndefined(type) ? '' : '=' + type;
if(txt) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = '[list' + type + ']\n' + txt.replace(regex, '$1[*]') + '\n' + '[/list]';
insertunit(txt);
} else {
insertunit('[list' + type + ']\n', '[/list]');
while(listvalue = prompt(lang['pm_prompt_list'], '')) {
if(is_opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertunit(listvalue);
} else {
listvalue = '[*]' + listvalue + '\n';
insertunit(listvalue);
}
}
}
}
function inserttag(tag, type) {
txt = getSel();
type = isUndefined(type) ? 0 : type;
if(!type) {
if(!txt) {
txt = prompt(lang['pm_prompt_' + tag], '')
}
if(txt) {
insertunit('[' + tag + ']' + txt + '[/' + tag + ']');
}
} else {
txt1 = prompt(lang['pm_prompt_' + tag], '');
if(!txt) {
txt = txt1;
}
if(txt1) {
insertunit('[' + tag + '=' + txt1 + ']' + txt + '[/' + tag + ']');
}
}
} | JavaScript |
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute;z-index:100;" onclick="_cancelBubble(event)">';
s += '<iframe id="calendariframe" frameborder="0" style="height:200px; z-index: 110; position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<div style="padding:5px; width: 210px; border: 1px solid #B5CFD9; background:#F2F9FD; position: absolute; z-index: 120">';
s += '<table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;" class="table1">';
s += '<thead>';
s += '<tr align="center" id="calendar_week">';
s += '<th><a href="###" onclick="refreshcalendar(yy, mm-1)" title="上一月">《</a></th>';
s += '<th colspan="5" style="text-align: center"><a href="###" onclick="showdiv(\'year\');_cancelBubble(event)" title="点击选择年份" id="year"></a> - <a id="month" title="点击选择月份" href="###" onclick="showdiv(\'month\');_cancelBubble(event)"></a></th>';
s += '<th><A href="###" onclick="refreshcalendar(yy, mm+1)" title="下一月">》</A></th>';
s += '</tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
s += '</thead>';
s += '<tbody>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute"><td colspan="7" align="center"><input type="text" size="2" value="" id="hour" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'> 点 <input type="text" size="2" value="" id="minute" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'> 分</td></tr>';
s += '</tbody>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="_cancelBubble(event)" style="display: none; z-index: 130;" class="calendarmenu"><div class="col" style="float: left; margin-right: 5px;">';
for(var k = 1930; k <= 2019; k++) {
s += k != 1930 && k % 10 == 0 ? '</div><div style="float: left; margin-right: 5px;">' : '';
s += '<a href="###" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="bold"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="_cancelBubble(event)" style="display: none; padding: 3px; z-index: 140" class="calendarmenu">';
for(var k = 1; k <= 12; k++) {
s += '<a href="###" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'; "><span' + (today.getMonth()+1 == k ? ' class="bold"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
var div = document.createElement('div');
div.innerHTML = s;
$('append').appendChild(div);
_attachEvent(document, 'click', function() {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
});
$('calendar').onclick = function(e) {
e = is_ie ? event : e;
_cancelBubble(e);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
}
function showcalendar(addtime1, startdate1, enddate1) {
e = is_ie ? event : showcalendar.caller.arguments[0];
controlid1 = is_ie ? e.srcElement : e.target;
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
var p = getposition(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['x']+'px';
$('calendar').style.top = (p['y'] + 20)+'px';
_cancelBubble(e);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = '';
$('calendar_year_' + today.getFullYear()).className = 'bold';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = '';
$('calendar_month_' + (today.getMonth() + 1)).className = 'bold';
}
$('calendar_year_' + currday.getFullYear()).className = 'error bold';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'error bold';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.innerHTML = '<a href="###" onclick="settime(' + d + ');return false">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'grey';
} else {
dd.className = '';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'bold';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'error bold';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = getposition($(id));
$('calendar_' + id).style.left = p['x']+'px';
$('calendar_' + id).style.top = (p['y'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
window.onload = function() {
loadcalendar();
} | JavaScript |
var Ajaxs = new Array();
function Ajax(waitId) {
var aj = new Object();
aj.waitId = waitId ? $(waitId) : null;
aj.targetUrl = '';
aj.sendString = '';
aj.resultHandle = null;
aj.loading = '<img src="image/common/loading.gif" style="margin: 3px; vertical-align: middle" />Loading... ';
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) request.overrideMimeType('text/xml');
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) return request;
} catch(e) {/*alert(e.message);*/}
}
}
return request;
}
aj.request = aj.createXMLHttpRequest();
if(aj.waitId) {
aj.waitId.orgdisplay = aj.waitId.style.display;
aj.waitId.style.display = '';
aj.waitId.innerHTML = aj.loading;
}
aj.processHandle = function() {
if(aj.request.readyState == 4 && aj.request.status == 200) {
for(k in Ajaxs) {
if(Ajaxs[k] == aj.targetUrl) Ajaxs[k] = null;
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
aj.waitId.style.display = aj.waitId.orgdisplay;
}
aj.resultHandle(aj.request.responseXML.lastChild.firstChild.nodeValue);
}
}
aj.get = function(targetUrl, resultHandle) {
if(in_array(targetUrl, Ajaxs)) {
return false;
} else {
Ajaxs.push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
if(window.XMLHttpRequest) {
aj.request.open('GET', aj.targetUrl);
aj.request.send(null);
} else {
aj.request.open("GET", targetUrl, true);
aj.request.send();
}
}
/* aj.post = function(targetUrl, sendString, resultHandle) {
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.request.open('POST', targetUrl);
aj.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.request.send(aj.sendString);
}*/
return aj;
}
function show(id, display) {
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
}
/*
ajaxget('www.baidu.com', 'showid', 'waitid', 'display(\'showid\', 1)');
*/
function ajaxget(url, showId, waitId, display, recall) {
e = is_ie ? event : ajaxget.caller.arguments[0];
ajaxget2(e, url, showId, waitId, display, recall);
_cancelBubble(e);
}
function ajaxget2(e, url, showId, waitId, display, recall) {
target = e ? (is_ie ? e.srcElement : e.target) : null;
display = display ? display : '';
var x = new Ajax(waitId);
x.showId = showId;
x.display = display;
var sep = url.indexOf('?') != -1 ? '&' : '?';
x.target = target;
x.recall = recall;
x.get(url+sep+'inajax=1', function(s) {
if(x.display == 'auto' && x.target) {
x.target.onclick = newfunc('show', x.showId, 'auto');
}
show(x.showId, x.display);
$(x.showId).innerHTML = s;
evalscript(s);
if(x.recall)eval(x.recall);
});
_cancelBubble(e);
}
/*
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}*/
var evalscripts = new Array();
function evalscript(s) {
if(!s || s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?src=\"([^\x00]+?)\"[^\>]*( reload=\"1\")?><\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) appendscript(arr[1], '', arr[2]);
p = /<script[^\>]*?( reload=\"1\")?>([^\x00]+?)<\/script>/ig;
while(arr = p.exec(s)) appendscript('', arr[2], arr[1]);
return s;
}
function appendscript(src, text, reload) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
if(src) {
scriptNode.src = src;
} else if(text){
scriptNode.text = text;
}
$('append').appendChild(scriptNode);
}
// 得到一个定长的 hash 值, 依赖于 stringxor()
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function in_array(needle, haystack) {
for(var i in haystack) {if(haystack[i] == needle) return true;}
return false;
}
function newfunc(func){
var args = new Array();
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(e){
window[func].apply(window, args);
_cancelBubble(is_ie ? event : e);
}
}
function ajaxmenu(url, position) {
e = is_ie ? event : ajaxmenu.caller.arguments[0];
controlid = is_ie ? e.srcElement : e.target;
var menuid = hash(url);// 使每个 url 对应一个弹出层,避免重复请求
createmenu(menuid);
showmenu2(e, menuid, position, controlid);
if(!$(menuid).innerHTML) {
ajaxget2(e, url, menuid, menuid, '', "setposition('" + menuid + "', '" + position + "', '" + controlid + "')");
} else {
//alert(menuid.innerHTML);
}
_cancelBubble(e);
}
var ajaxpostHandle = null;
function ajaxpost(formid, showid, recall) {
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
if(ajaxframe == null) {
if (is_ie) {
ajaxframe = document.createElement("<iframe name='" + ajaxframeid + "' id='" + ajaxframeid + "'></iframe>");
} else {
ajaxframe = document.createElement("iframe");
ajaxframe.name = ajaxframeid;
ajaxframe.id = ajaxframeid;
}
ajaxframe.style.display = 'none';
$('append').appendChild(ajaxframe);
}
$(formid).target = ajaxframeid;
ajaxpostHandle = [formid, showid, ajaxframeid, recall];
_attachEvent(ajaxframe, 'load', ajaxpost_load);
$(formid).submit();
return false;
}
function ajaxpost_load() {
var s = (is_ie && $(ajaxpostHandle[2])) ? $(ajaxpostHandle[2]).contentWindow.document.XMLDocument.text : $(ajaxpostHandle[2]).contentWindow.document.documentElement.firstChild.nodeValue;
evalscript(s);
if(s) {
// setMenuPosition($(ajaxpostHandle[0]).ctrlid, 0);
$(ajaxpostHandle[1]).innerHTML = s;
if(ajaxpostHandle[3]) {
eval(ajaxpostHandle[3]);
}
// setTimeout("hideMenu()", 3000);
}
// $(ajaxpostHandle[2]).target = ajaxpostHandle[3];
// ajaxpostHandle = null;
}
| JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: soso_smilies.js 84 2011-02-28 14:15:44Z yexinhao $
*/
var sosojs = document.createElement('script');
sosojs.type = 'text/javascript';
sosojs.charset = "utf-8";
sosojs.src = 'http://bq.soso.com/js/sosoexp_platform.js';
var sosolo = document.getElementsByTagName('script')[0];
sosolo.parentNode.insertBefore(sosojs, sosolo);
function bbcode2html_sososmilies(sososmilieid, getsrc) {
var imgsrc = '';
sososmilieid = String(sososmilieid);
var imgid = 'soso_' + sososmilieid;
if(sososmilieid.indexOf('_') == 0) {
var realsmilieid = sososmilieid.substr(0, sososmilieid.length-2);
var serverid = sososmilieid.substr(sososmilieid.length-1);
imgsrc = "http://piccache"+serverid+".soso.com/face/"+realsmilieid;
} else {
imgsrc = "http://cache.soso.com/img/img/"+sososmilieid+".gif";
}
if(!isUndefined(getsrc)) {
return imgsrc;
}
return '<img src="'+imgsrc+'" smilieid="'+imgid+'" border="0" alt="" />';
}
function html2bbcode_sososmilies(htmlsmilies) {
if(htmlsmilies) {
htmlsmilies = htmlsmilies.replace(/<img[^>]+smilieid=(["']?)soso_(\w+)(\1)[^>]*>/ig, function($1, $2, $3) { return sososmileycode($3);});
}
return htmlsmilies;
}
function sososmileycode(sososmilieid) {
if(sososmilieid) {
return "{:soso_"+sososmilieid+":}";
}
}
function sososmiliesurl2id(sosourl) {
var sososmilieid = '';
if(sosourl && sosourl.length > 30) {
var idindex = sosourl.lastIndexOf('/');
if(sosourl.indexOf('http://piccache') == 0) {
var serverid = sosourl.substr(15,1);
var realsmilieid = sosourl.substr(idindex+1);
sososmilieid = realsmilieid+'_'+serverid;
} else if(sosourl.indexOf('http://cache.soso.com') == 0) {
sososmilieid = sosourl.substring(idindex+1, sosourl.length-4);
}
return sososmilieid;
}
}
function insertsosoSmiley(sosourl) {
var sososmilieid = sososmiliesurl2id(sosourl);
if(sososmilieid) {
var code = sososmileycode(sososmilieid);
var src = bbcode2html_sososmilies(sososmilieid, true);
checkFocus();
if(wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
insertText(bbcode2html_sososmilies(sososmilieid), false);
} else {
code += ' ';
insertText(code, strlen(code), 0);
}
hideMenu();
}
}
function insertfastpostSmiley(sosourl, textareaid) {
var sososmilieid = sososmiliesurl2id(sosourl);
if(sososmilieid) {
var code = sososmileycode(sososmilieid);
seditor_insertunit(textareaid, code);
}
}
var TimeCounter = 0;
function SOSO_EXP_CHECK(textareaid) {
TimeCounter++;
if(typeof editorid!='undefined' && textareaid == 'newthread') {
var eExpBtn = $(editorid + '_sml'),
eEditBox = $(editorid + '_textarea');
eExpBtn.setAttribute('init', 1);
fFillEditBox = function(editbox, url) {
insertsosoSmiley(url);
};
} else if(in_array(textareaid, ['post', 'fastpost', 'pm', 'send', 'reply', 'sightml'])) {
var eExpBtn = $(textareaid+"sml"),
eEditBox = $(textareaid+"message"),
fFillEditBox = function(editbox, url) {
insertfastpostSmiley(url, textareaid);
};
} else {
return false;
}
if(typeof SOSO_EXP != "undefined" && typeof SOSO_EXP.Register == "function" && eExpBtn && eEditBox) {
var pos = 'bottom';
if(in_array(textareaid, ['fastpost', 'pm', 'reply'])) {
pos = 'top';
}
eExpBtn.onclick = function() { return null; };
SOSO_EXP.Register(60001, 'discuz', eExpBtn, pos, eEditBox, fFillEditBox);
if(typeof editdoc != "undefined" && editdoc && editdoc.body) {
editdoc.body.onclick = extrafunc_soso_showmenu;
document.body.onclick = extrafunc_soso_showmenu;
}
return true;
} else if(TimeCounter<15) {
setTimeout(function () { SOSO_EXP_CHECK(textareaid) ; }, 2000);
return false;
} else if(typeof SOSO_EXP == "undefined" || typeof SOSO_EXP.Register != "function") {
return false;
} else {
return false;
}
}
if(typeof EXTRAFUNC['bbcode2html'] != "undefined") {
EXTRAFUNC['bbcode2html']['soso'] = 'extrafunc_soso_bbcode2html';
EXTRAFUNC['html2bbcode']['soso'] = 'extrafunc_soso_html2bbcode';
if(typeof editdoc != "undefined") {
EXTRAFUNC['showmenu']['soso'] = 'extrafunc_soso_showmenu';
}
}
function extrafunc_soso_showmenu() {
SOSO_EXP.Platform.hideBox();
}
function extrafunc_soso_bbcode2html() {
if(!fetchCheckbox('smileyoff') && allowsmilies) {
EXTRASTR = EXTRASTR.replace(/\{\:soso_(\w+)\:\}/ig, function($1, $2) { return bbcode2html_sososmilies($2);});
}
return EXTRASTR;
}
function extrafunc_soso_html2bbcode() {
if((allowhtml && fetchCheckbox('htmlon')) || (!fetchCheckbox('bbcodeoff') && allowbbcode)) {
EXTRASTR = html2bbcode_sososmilies(EXTRASTR);
}
return EXTRASTR;
} | JavaScript |
var url = window.location.href;
var siteUrl = url.substr(0, url.indexOf('api/manyou/cloud_channel.htm'));
var params = getUrlParams(url);
var action = params['action'];
var identifier = params['identifier'];
setTopFrame();
changPageStatus(identifier);
function changPageStatus(identifier) {
var navText = '';
var cloudText = '';
var menuItem;
try {
var discuzIframe = window.top.window;
menuItem = discuzIframe.document.getElementById('menu_cloud').getElementsByTagName('li');
cloudText = 'Discuz!' + discuzIframe.document.getElementById('header_cloud').innerHTML;
} catch(e) {
return false;
}
for (i=0; i < menuItem.length; i ++) {
if (menuItem[i].innerHTML.indexOf('operation=' + identifier) != -1) {
menuItem[i].getElementsByTagName('a')[0].className = 'tabon';
navText = menuItem[i].innerHTML;
navText = navText.replace(/<em.*<\/em>/i, '');
p = /<a.+?href="(.+?)".+?>(.+?)<\/a>/i;
arr = p.exec(navText);
if (arr) {
link = arr[1];
text = arr[2];
if(discuzIframe.document.getElementById('admincpnav')) {
title = discuzIframe.document.title;
if (title.indexOf(' - ') > 0) {
title = title.substr(0, title.indexOf(' - '));
}
discuzIframe.document.title = title + ' - ' + cloudText + ' - ' + text;
discuzIframe.document.getElementById('admincpnav').innerHTML= cloudText + ' » ' + text + ' <a target="main" title="添加到常用操作" href="' + link + '">[+]</a>';
}
}
} else {
menuItem[i].getElementsByTagName('a')[0].className = '';
}
}
}
function setTopFrame() {
try {
var topUrl = top.location.href;
} catch(e) { }
if (typeof(topUrl) == 'undefined' || topUrl.indexOf(siteUrl) == -1) {
top.location = siteUrl + 'admin.php?frames=yes&action=cloud&operation=' + identifier;
}
}
function getUrlParams(url) {
var pos = url.indexOf('?');
if (pos < 0) {
return false;
}
var query = url.substr(pos + 1);
var arr = query.split('&');
var item = '';
var _params = [];
for (k in arr) {
item = arr[k].split('=');
_params[item[0]] = item[1];
}
return _params;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal.js 21566 2011-03-31 09:00:16Z zhangguosheng $
*/
function block_get_setting(classname, script, bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=setting&bid='+bid+'&classname='+classname+'&script='+script+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_setting'), s);
});
}
function switch_blocktab(type) {
if(type == 'setting') {
$('blockformsetting').style.display = '';
$('blockformdata').style.display = 'none';
$('li_setting').className = 'a';
$('li_data').className = '';
} else {
$('blockformsetting').style.display = 'none';
$('blockformdata').style.display = '';
$('li_setting').className = '';
$('li_data').className = 'a';
}
}
function showpicedit(pre) {
pre = pre ? pre : 'pic';
if($(pre+'way_remote').checked) {
$(pre+'_remote').style.display = "block";
$(pre+'_upload').style.display = "none";
} else {
$(pre+'_remote').style.display = "none";
$(pre+'_upload').style.display = "block";
}
}
function block_show_thumbsetting(classname, styleid, bid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=thumbsetting&classname='+classname+'&styleid='+styleid+'&bid='+bid+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_thumbsetting'), s);
});
}
function block_showstyle(stylename) {
var el_span = $('span_'+stylename);
var el_value = $('value_' + stylename);
if (el_value.value == '1'){
el_value.value = '0';
el_span.className = "";
} else {
el_value.value = '1';
el_span.className = "a";
}
}
function block_pushitem(bid, itemid) {
var id = $('push_id').value;
var idtype = $('push_idtype').value;
if(id && idtype) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=push&&bid='+bid+'&itemid='+itemid+'&idtype='+idtype+'&id='+id+'&inajax=1', function(s){
ajaxinnerhtml($('tbody_pushcontent'), s);
});
}
}
function block_delete_item(bid, itemid, itemtype, itemfrom, from) {
var msg = itemtype==1 ? '您确定要删除该数据吗?' : '您确定要屏蔽该数据吗?';
if(confirm(msg)) {
var url = 'portal.php?mod=portalcp&ac=block&op=remove&bid='+bid+'&itemid='+itemid;
if(itemfrom=='ajax') {
var x = new Ajax();
x.get(url+'&inajax=1', function(){
if(succeedhandle_showblock) succeedhandle_showblock('', '', {'bid':bid});
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=data&bid='+bid+'&from='+from+'&tab=data&t='+(+ new Date()), 'get', 0);
});
} else {
location.href = url;
}
}
doane();
}
function portal_comment_requote(cid) {
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=comment&op=requote&cid='+cid+'&inajax=1', function(s){
$('message').focus();
ajaxinnerhtml($('message'), s);
});
}
function insertImage(text) {
text = "\n[img]" + text + "[/img]\n";
insertContent('message', text);
}
function insertContent(target, text) {
var obj = $(target);
selection = document.selection;
checkFocus(target);
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = text;
sel.moveStart('character', -strlen(text));
} else {
obj.value += text;
}
}
function searchblock(from) {
var value = $('searchkey').value;
var targettplname = $('targettplname').value;
value = BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(value) : (value ? value.replace(/#/g,'%23') : '');
var url = 'portal.php?mod=portalcp&ac=portalblock&searchkey='+value+'&from='+from;
url += targettplname != '' ? '&targettplname='+targettplname+'&type=page' : '&type=block';
reloadselection(url);
}
function reloadselection(url) {
ajaxget(url+'&t='+(+ new Date()), 'block_selection');
}
function getColorPalette(colorid, id, background) {
return "<input id=\"c"+colorid+"\" onclick=\"createPalette('"+colorid+"', '"+id+"');\" type=\"button\" class=\"pn colorwd\" value=\"\" style=\"background-color: "+background+"\">";
}
function listblock_bypage(id, idtype) {
var tpl = $('rtargettplname') ? $('rtargettplname').value : '';
var searchkey = $('rsearchkey') ? $('rsearchkey').value.replace('#', '%23') : '';
ajaxget('portal.php?mod=portalcp&ac=portalblock&op=recommend&getdata=yes&searchkey='+searchkey+'&targettplname='+tpl+'&id='+id+'&idtype='+idtype, 'itemeditarea');
}
function recommenditem_check() {
var sel = $('recommend_bid');
if(sel && sel.value) {
document.forms['recommendform'].action = document.forms['recommendform'].action+'&bid='+sel.value;
return true;
} else {
alert("请选择一个模块!");
return false;
}
}
function recommenditem_byblock(bid, id, idtype) {
var editarea = $('itemeditarea');
if(editarea) {
var olditemeditarea = $('olditemeditarea');
ajaxinnerhtml(olditemeditarea, editarea.innerHTML);
if(!$('recommendback')) {
var back = document.createElement('div');
back.innerHTML = '<em id="recommendback" onclick="recommenditem_back()" class="cur1"> «返回</em>';
var return_mods = $('return_mods') || $('return_');
if(return_mods) {
return_mods.parentNode.appendChild(back.childNodes[0]);
}
}
if(bid) {
if($('recommend_bid')) {
$('recommend_bid').value = bid;
}
ajaxget('portal.php?mod=portalcp&ac=block&op=recommend&bid='+bid+'&id='+id+'&idtype='+idtype+'&handlekey=recommenditem', 'itemeditarea');
} else {
ajaxinnerhtml(editarea, '<tr><td> </td><td> </td></tr>');
}
}
}
function recommenditem_back(){
var editarea = $('itemeditarea');
var oldeditarea = $('olditemeditarea');
var recommendback = $('recommendback');
if(oldeditarea){
ajaxinnerhtml(editarea, oldeditarea.innerHTML);
ajaxupdateevents(editarea);
}
if(recommendback) {
recommendback.parentNode.removeChild(recommendback);
}
if($('recommend_bid')) {
$('recommend_bid').value = '';
}
}
function blockBindTips() {
var elems = ($('blockformsetting') || document).getElementsByTagName('img');
var k = 0;
var stamp = (+new Date());
var tips = '';
for(var i = 0; i < elems.length; i++) {
tips = elems[i]['tips'] || elems[i].getAttribute('tips') || '';
if(tips && ! elems[i].isBindTips) {
elems[i].isBindTips = '1';
elems[i].id = elems[i].id ? elems[i].id : ('elem_' + stamp + k.toString());
k++;
showPrompt(elems[i].id, 'mouseover', tips, 1, true);
}
}
}
function blockSetCacheTime(timer) {
$('txt_cachetime').value=timer;
doane();
}
function toggleSettingShow() {
if(!$('tbody_setting').style.display) {
$('tbody_setting').style.display = 'none';
$('a_setting_show').innerHTML = '展开设置项';
} else {
$('tbody_setting').style.display = '';
$('a_setting_show').innerHTML = '收起设置项';
}
doane();
}
function switchSetting() {
var checked = $('isblank').checked;
if(checked) {
$('tbody_setting').style.display = 'none';
$('a_setting_show').innerHTML = '展开设置项';
} else {
$('tbody_setting').style.display = '';
$('a_setting_show').innerHTML = '收起设置项';
}
}
function checkblockname(form) {
if(!(trim(form.name.value) > '')) {
showDialog('模块标识不能为空', 'error', null, function(){form.name.focus();});
return false;
}
if(form.summary && form.summary.value) {
var tag = blockCheckTag(form.summary.value, true);
if(tag) {
showBlockSummary();
form.summary.focus();
showDialog('自定义内容错误,HTML代码:'+tag+' 标签不匹配', 'error', null, function(){form.summary.select();});
return false;
}
}
return true;
}
function blockCheckTag(summary, returnValue) {
var obj = null, fn = null;
if(typeof summary == 'object') {
obj = summary;
summary = summary.value;
fn = function(){obj.focus();obj.select();};
}
if(trim(summary) > '') {
var tags = ['div', 'table', 'tbody', 'tr', 'td', 'th'];
for(var i = 0; i < tags.length; i++) {
var tag = tags[i];
var reg = new RegExp('<'+tag+'', 'gi');
var preTag = [];
var one = [];
while (one = reg.exec(summary)) {
preTag.push(one[0]);
}
reg = new RegExp('</'+tag+'>', 'gi');
var endTag = [];
var one = [];
while (one = reg.exec(summary)) {
endTag.push(one[0]);
}
if(!preTag && !endTag) continue;
if((!preTag && endTag) || (preTag && !endTag) || preTag.length != endTag.length) {
if(returnValue) {
return tag;
} else {
showDialog('HTML代码:'+tag+' 标签不匹配', 'error', null, fn, true, fn);
return false;
}
}
}
}
return false;
}
function showBlockSummary() {
$('block_sumamry_content').style.display='';
$('a_summary_show').style.display='none';
$('a_summary_hide').style.display='';
return false;
}
function hideBlockSummary() {
$('block_sumamry_content').style.display='none';
$('a_summary_hide').style.display='none';
$('a_summary_show').style.display='';
return false;
}
function blockconver(ele,bid) {
if(ele && bid) {
if(confirm('你确定要转换模块的类型从 '+ele.options[0].innerHTML+' 到 '+ele.options[ele.selectedIndex].innerHTML)) {
ajaxget('portal.php?mod=portalcp&ac=block&op=convert&bid='+bid+'&toblockclass='+ele.value,'blockshow');
} else {
ele.selectedIndex = 0;
}
}
}
function blockFavorite(bid){
if(bid) {
ajaxget('portal.php?mod=portalcp&ac=block&op=favorite&bid='+bid,'bfav_'+bid);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: tree.js 15149 2010-08-19 08:02:46Z monkey $
*/
var icon = new Object();
icon.root = IMGDIR + '/tree_root.gif';
icon.folder = IMGDIR + '/tree_folder.gif';
icon.folderOpen = IMGDIR + '/tree_folderopen.gif';
icon.file = IMGDIR + '/tree_file.gif';
icon.empty = IMGDIR + '/tree_empty.gif';
icon.line = IMGDIR + '/tree_line.gif';
icon.lineMiddle = IMGDIR + '/tree_linemiddle.gif';
icon.lineBottom = IMGDIR + '/tree_linebottom.gif';
icon.plus = IMGDIR + '/tree_plus.gif';
icon.plusMiddle = IMGDIR + '/tree_plusmiddle.gif';
icon.plusBottom = IMGDIR + '/tree_plusbottom.gif';
icon.minus = IMGDIR + '/tree_minus.gif';
icon.minusMiddle = IMGDIR + '/tree_minusmiddle.gif';
icon.minusBottom = IMGDIR + '/tree_minusbottom.gif';
function treeNode(id, pid, name, url, target, open) {
var obj = new Object();
obj.id = id;
obj.pid = pid;
obj.name = name;
obj.url = url;
obj.target = target;
obj.open = open;
obj._isOpen = open;
obj._lastChildId = 0;
obj._pid = 0;
return obj;
}
function dzTree(treeName) {
this.nodes = new Array();
this.openIds = getcookie('leftmenu_openids');
this.pushNodes = new Array();
this.addNode = function(id, pid, name, url, target, open) {
var theNode = new treeNode(id, pid, name, url, target, open);
this.pushNodes.push(id);
if(!this.nodes[pid]) {
this.nodes[pid] = new Array();
}
this.nodes[pid]._lastChildId = id;
for(k in this.nodes) {
if(this.openIds && this.openIds.indexOf('_' + theNode.id) != -1) {
theNode._isOpen = true;
}
if(this.nodes[k].pid == id) {
theNode._lastChildId = this.nodes[k].id;
}
}
this.nodes[id] = theNode;
};
this.show = function() {
var s = '<div class="tree">';
s += this.createTree(this.nodes[0]);
s += '</div>';
document.write(s);
};
this.createTree = function(node, padding) {
padding = padding ? padding : '';
if(node.id == 0){
var icon1 = '';
} else {
var icon1 = '<img src="' + this.getIcon1(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon1_' + node.id + '" style="cursor: pointer;">';
}
var icon2 = '<img src="' + this.getIcon2(node) + '" onclick="' + treeName + '.switchDisplay(\'' + node.id + '\')" id="icon2_' + node.id + '" style="cursor: pointer;">';
var s = '<div class="node" id="node_' + node.id + '">' + padding + icon1 + icon2 + this.getName(node) + '</div>';
s += '<div class="nodes" id="nodes_' + node.id + '" style="display:' + (node._isOpen ? '' : 'none') + '">';
for(k in this.pushNodes) {
var id = this.pushNodes[k];
var theNode = this.nodes[id];
if(theNode.pid == node.id) {
if(node.id == 0){
var thePadding = '';
} else {
var thePadding = padding + (node.id == this.nodes[node.pid]._lastChildId ? '<img src="' + icon.empty + '">' : '<img src="' + icon.line + '">');
}
if(!theNode._lastChildId) {
var icon1 = '<img src="' + this.getIcon1(theNode) + '"' + ' id="icon1_' + theNode.id + '">';
var icon2 = '<img src="' + this.getIcon2(theNode) + '" id="icon2_' + theNode.id + '">';
s += '<div class="node" id="node_' + theNode.id + '">' + thePadding + icon1 + icon2 + this.getName(theNode) + '</div>';
} else {
s += this.createTree(theNode, thePadding);
}
}
}
s += '</div>';
return s;
};
this.getIcon1 = function(theNode) {
var parentNode = this.nodes[theNode.pid];
var src = '';
if(theNode._lastChildId) {
if(theNode._isOpen) {
if(theNode.id == 0) {
return icon.minus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.minusBottom;
} else {
src = icon.minusMiddle;
}
} else {
if(theNode.id == 0) {
return icon.plus;
}
if(theNode.id == parentNode._lastChildId) {
src = icon.plusBottom;
} else {
src = icon.plusMiddle;
}
}
} else {
if(theNode.id == parentNode._lastChildId) {
src = icon.lineBottom;
} else {
src = icon.lineMiddle;
}
}
return src;
};
this.getIcon2 = function(theNode) {
var src = '';
if(theNode.id == 0 ) {
return icon.root;
}
if(theNode._lastChildId) {
if(theNode._isOpen) {
src = icon.folderOpen;
} else {
src = icon.folder;
}
} else {
src = icon.file;
}
return src;
};
this.getName = function(theNode) {
if(theNode.url) {
return '<a href="'+theNode.url+'" target="' + theNode.target + '"> '+theNode.name+'</a>';
} else {
return theNode.name;
}
};
this.switchDisplay = function(nodeId) {
eval('var theTree = ' + treeName);
var theNode = theTree.nodes[nodeId];
if($('nodes_' + nodeId).style.display == 'none') {
theTree.openIds = updatestring(theTree.openIds, nodeId);
setcookie('leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = true;
$('nodes_' + nodeId).style.display = '';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
} else {
theTree.openIds = updatestring(theTree.openIds, nodeId, true);
setcookie('leftmenu_openids', theTree.openIds, 8640000000);
theNode._isOpen = false;
$('nodes_' + nodeId).style.display = 'none';
$('icon1_' + nodeId).src = theTree.getIcon1(theNode);
$('icon2_' + nodeId).src = theTree.getIcon2(theNode);
}
};
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: bbcode.js 22924 2011-06-01 07:41:29Z monkey $
*/
var re, DISCUZCODE = [];
DISCUZCODE['num'] = '-1';
DISCUZCODE['html'] = [];
EXTRAFUNC['bbcode2html'] = [];
EXTRAFUNC['html2bbcode'] = [];
function addslashes(str) {
return preg_replace(['\\\\', '\\\'', '\\\/', '\\\(', '\\\)', '\\\[', '\\\]', '\\\{', '\\\}', '\\\^', '\\\$', '\\\?', '\\\.', '\\\*', '\\\+', '\\\|'], ['\\\\', '\\\'', '\\/', '\\(', '\\)', '\\[', '\\]', '\\{', '\\}', '\\^', '\\$', '\\?', '\\.', '\\*', '\\+', '\\|'], str);
}
function atag(aoptions, text) {
if(trim(text) == '') {
return '';
}
var pend = parsestyle(aoptions, '', '');
href = getoptionvalue('href', aoptions);
if(href.substr(0, 11) == 'javascript:') {
return trim(recursion('a', text, 'atag'));
}
return pend['prepend'] + '[url=' + href + ']' + trim(recursion('a', text, 'atag')) + '[/url]' + pend['append'];
}
function bbcode2html(str) {
if(str == '') {
return '';
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = str.replace(/\[code\]([\s\S]+?)\[\/code\]/ig, function($1, $2) {return parsecode($2);});
}
if(fetchCheckbox('allowimgurl')) {
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
}
if(!allowhtml || !fetchCheckbox('htmlon')) {
str = str.replace(/</g, '<');
str = str.replace(/>/g, '>');
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'html', false);
}
}
for(i in EXTRAFUNC['bbcode2html']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['bbcode2html'][i] + '()');
} catch(e) {}
}
if(!fetchCheckbox('smileyoff') && allowsmilies) {
if(typeof smilies_type == 'object') {
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
re = new RegExp(preg_quote(smilies_array[typeid][page][i][1]), "g");
str = str.replace(re, '<img src="' + STATICURL + 'image/smiley/' + smilies_type['_' + typeid][1] + '/' + smilies_array[typeid][page][i][2] + '" border="0" smilieid="' + smilies_array[typeid][page][i][0] + '" alt="' + smilies_array[typeid][page][i][1] + '" />');
}
}
}
}
}
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = clearcode(str);
str = str.replace(/\[url\]\s*((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.)([^\[\"']+?)\s*\[\/url\]/ig, function($1, $2, $3, $4) {return cuturl($2 + $4);});
str = str.replace(/\[url=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\r\n\[\"']+?)\]([\s\S]+?)\[\/url\]/ig, '<a href="$1$3" target="_blank">$4</a>');
str = str.replace(/\[email\](.*?)\[\/email\]/ig, '<a href="mailto:$1">$1</a>');
str = str.replace(/\[email=(.[^\[]*)\](.*?)\[\/email\]/ig, '<a href="mailto:$1" target="_blank">$2</a>');
str = str.replace(/\[color=([^\[\<]+?)\]/ig, '<font color="$1">');
str = str.replace(/\[backcolor=([^\[\<]+?)\]/ig, '<font style="background-color:$1">');
str = str.replace(/\[size=(\d+?)\]/ig, '<font size="$1">');
str = str.replace(/\[size=(\d+(\.\d+)?(px|pt)+?)\]/ig, '<font style="font-size: $1">');
str = str.replace(/\[font=([^\[\<]+?)\]/ig, '<font face="$1">');
str = str.replace(/\[align=([^\[\<]+?)\]/ig, '<p align="$1">');
str = str.replace(/\[p=(\d{1,2}|null), (\d{1,2}|null), (left|center|right)\]/ig, '<p style="line-height: $1px; text-indent: $2em; text-align: $3;">');
str = str.replace(/\[float=left\]/ig, '<br style="clear: both"><span style="float: left; margin-right: 5px;">');
str = str.replace(/\[float=right\]/ig, '<br style="clear: both"><span style="float: right; margin-left: 5px;">');
str = str.replace(/\[quote]([\s\S]*?)\[\/quote\]\s?\s?/ig, '<div class="quote"><blockquote>$1</blockquote></div>\n');
re = /\[table(?:=(\d{1,4}%?)(?:,([\(\)%,#\w ]+))?)?\]\s*([\s\S]+?)\s*\[\/table\]/ig;
for (i = 0; i < 4; i++) {
str = str.replace(re, function($1, $2, $3, $4) {return parsetable($2, $3, $4);});
}
str = preg_replace([
'\\\[\\\/color\\\]', '\\\[\\\/backcolor\\\]', '\\\[\\\/size\\\]', '\\\[\\\/font\\\]', '\\\[\\\/align\\\]', '\\\[\\\/p\\\]', '\\\[b\\\]', '\\\[\\\/b\\\]',
'\\\[i\\\]', '\\\[\\\/i\\\]', '\\\[u\\\]', '\\\[\\\/u\\\]', '\\\[s\\\]', '\\\[\\\/s\\\]', '\\\[hr\\\]', '\\\[list\\\]', '\\\[list=1\\\]', '\\\[list=a\\\]',
'\\\[list=A\\\]', '\\s?\\\[\\\*\\\]', '\\\[\\\/list\\\]', '\\\[indent\\\]', '\\\[\\\/indent\\\]', '\\\[\\\/float\\\]'
], [
'</font>', '</font>', '</font>', '</font>', '</p>', '</p>', '<b>', '</b>', '<i>',
'</i>', '<u>', '</u>', '<strike>', '</strike>', '<hr class="l" />', '<ul>', '<ul type=1 class="litype_1">', '<ul type=a class="litype_2">',
'<ul type=A class="litype_3">', '<li>', '</ul>', '<blockquote>', '</blockquote>', '</span>'
], str, 'g');
}
if(!fetchCheckbox('bbcodeoff')) {
if(allowimgcode) {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<img src="$1" border="0" alt="" style="max-width:400px" />');
str = str.replace(/\[attachimg\](\d+)\[\/attachimg\]/ig, function ($1, $2) {
if(!$('image_' + $2)) {
return '';
}
width = $('image_' + $2).getAttribute('cwidth');
if(!width) {
re = /cwidth=(["']?)(\d+)(\1)/i;
var matches = re.exec($('image_' + $2).outerHTML);
if(matches != null) {
width = matches[2];
}
}
return '<img src="' + $('image_' + $2).src + '" border="0" aid="attachimg_' + $2 + '" width="' + width + '" alt="" style="max-width:400px" />';
});
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, function ($1, $2, $3, $4) {return '<img' + ($2 > 0 ? ' width="' + $2 + '"' : '') + ($3 > 0 ? ' height="' + $3 + '"' : '') + ' src="' + $4 + '" border="0" alt="" style="max-width:400px" />'});
} else {
str = str.replace(/\[img\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
str = str.replace(/\[img=(\d{1,4})[x|\,](\d{1,4})\]\s*([^\[\<\r\n]+?)\s*\[\/img\]/ig, '<a href="$1" target="_blank">$1</a>');
}
}
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
if(!allowhtml || !fetchCheckbox('htmlon')) {
str = str.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
return $2 + preg_replace(['\t', ' ', ' ', '(\r\n|\n|\r)'], [' ', ' ', ' ', '<br />'], $3);
});
}
return str;
}
function clearcode(str) {
str= str.replace(/\[url\]\[\/url\]/ig, '', str);
str= str.replace(/\[url=((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|thunder|qqdl|synacast){1}:\/\/|www\.|mailto:)?([^\s\[\"']+?)\]\[\/url\]/ig, '', str);
str= str.replace(/\[email\]\[\/email\]/ig, '', str);
str= str.replace(/\[email=(.[^\[]*)\]\[\/email\]/ig, '', str);
str= str.replace(/\[color=([^\[\<]+?)\]\[\/color\]/ig, '', str);
str= str.replace(/\[size=(\d+?)\]\[\/size\]/ig, '', str);
str= str.replace(/\[size=(\d+(\.\d+)?(px|pt)+?)\]\[\/size\]/ig, '', str);
str= str.replace(/\[font=([^\[\<]+?)\]\[\/font\]/ig, '', str);
str= str.replace(/\[align=([^\[\<]+?)\]\[\/align\]/ig, '', str);
str= str.replace(/\[p=(\d{1,2}), (\d{1,2}), (left|center|right)\]\[\/p\]/ig, '', str);
str= str.replace(/\[float=([^\[\<]+?)\]\[\/float\]/ig, '', str);
str= str.replace(/\[quote\]\[\/quote\]/ig, '', str);
str= str.replace(/\[code\]\[\/code\]/ig, '', str);
str= str.replace(/\[table\]\[\/table\]/ig, '', str);
str= str.replace(/\[free\]\[\/free\]/ig, '', str);
str= str.replace(/\[b\]\[\/b]/ig, '', str);
str= str.replace(/\[u\]\[\/u]/ig, '', str);
str= str.replace(/\[i\]\[\/i]/ig, '', str);
str= str.replace(/\[s\]\[\/s]/ig, '', str);
return str;
}
function cuturl(url) {
var length = 65;
var urllink = '<a href="' + (url.toLowerCase().substr(0, 4) == 'www.' ? 'http://' + url : url) + '" target="_blank">';
if(url.length > length) {
url = url.substr(0, parseInt(length * 0.5)) + ' ... ' + url.substr(url.length - parseInt(length * 0.3));
}
urllink += url + '</a>';
return urllink;
}
function dstag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
var pend = parsestyle(options, '', '');
var prepend = pend['prepend'];
var append = pend['append'];
if(in_array(tagname, ['div', 'p'])) {
align = getoptionvalue('align', options);
if(in_array(align, ['left', 'center', 'right'])) {
prepend = '[align=' + align + ']' + prepend;
append += '[/align]';
} else {
append += '\n';
}
}
return prepend + recursion(tagname, text, 'dstag') + append;
}
function ptag(options, text, tagname) {
if(trim(text) == '') {
return '\n';
}
if(trim(options) == '') {
return text + '\n';
}
var lineHeight = null;
var textIndent = null;
var align, re, matches;
re = /line-height\s?:\s?(\d{1,3})px/i;
matches = re.exec(options);
if(matches != null) {
lineHeight = matches[1];
}
re = /text-indent\s?:\s?(\d{1,3})em/i;
matches = re.exec(options);
if(matches != null) {
textIndent = matches[1];
}
re = /text-align\s?:\s?(left|center|right)/i;
matches = re.exec(options);
if(matches != null) {
align = matches[1];
} else {
align = getoptionvalue('align', options);
}
align = in_array(align, ['left', 'center', 'right']) ? align : 'left';
style = getoptionvalue('style', options);
style = preg_replace(['line-height\\\s?:\\\s?(\\\d{1,3})px', 'text-indent\\\s?:\\\s?(\\\d{1,3})em', 'text-align\\\s?:\\\s?(left|center|right)'], '', style);
if(lineHeight === null && textIndent === null) {
return '[align=' + align + ']' + (style ? '<span style="' + style + '">' : '') + text + (style ? '</span>' : '') + '[/align]';
} else {
return '[p=' + lineHeight + ', ' + textIndent + ', ' + align + ']' + (style ? '<span style="' + style + '">' : '') + text + (style ? '</span>' : '') + '[/p]';
}
}
function fetchCheckbox(cbn) {
return $(cbn) && $(cbn).checked == true ? 1 : 0;
}
function fetchoptionvalue(option, text) {
if((position = strpos(text, option)) !== false) {
delimiter = position + option.length;
if(text.charAt(delimiter) == '"') {
delimchar = '"';
} else if(text.charAt(delimiter) == '\'') {
delimchar = '\'';
} else {
delimchar = ' ';
}
delimloc = strpos(text, delimchar, delimiter + 1);
if(delimloc === false) {
delimloc = text.length;
} else if(delimchar == '"' || delimchar == '\'') {
delimiter++;
}
return trim(text.substr(delimiter, delimloc - delimiter));
} else {
return '';
}
}
function fonttag(fontoptions, text) {
var prepend = '';
var append = '';
var tags = new Array();
tags = {'font' : 'face=', 'size' : 'size=', 'color' : 'color='};
for(bbcode in tags) {
optionvalue = fetchoptionvalue(tags[bbcode], fontoptions);
if(optionvalue) {
prepend += '[' + bbcode + '=' + optionvalue + ']';
append = '[/' + bbcode + ']' + append;
}
}
var pend = parsestyle(fontoptions, prepend, append);
return pend['prepend'] + recursion('font', text, 'fonttag') + pend['append'];
}
function getoptionvalue(option, text) {
re = new RegExp(option + "(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)", "ig");
var matches = re.exec(text);
if(matches != null) {
return trim(matches[3]);
}
return '';
}
function html2bbcode(str) {
if((allowhtml && fetchCheckbox('htmlon')) || trim(str) == '') {
for(i in EXTRAFUNC['html2bbcode']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['html2bbcode'][i] + '()');
} catch(e) {}
}
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
str = str.replace(/<img([^>]*aid=[^>]*)>/ig, function($1, $2) {return imgtag($2);});
return str;
}
str = str.replace(/<div\sclass=["']?blockcode["']?>[\s\S]*?<blockquote>([\s\S]+?)<\/blockquote>[\s\S]*?<\/div>/ig, function($1, $2) {return codetag($2);});
str = preg_replace(['<style.*?>[\\\s\\\S]*?<\/style>', '<script.*?>[\\\s\\\S]*?<\/script>', '<noscript.*?>[\\\s\\\S]*?<\/noscript>', '<select.*?>[\s\S]*?<\/select>', '<object.*?>[\s\S]*?<\/object>', '<!--[\\\s\\\S]*?-->', ' on[a-zA-Z]{3,16}\\\s?=\\\s?"[\\\s\\\S]*?"'], '', str);
str= str.replace(/(\r\n|\n|\r)/ig, '');
str= str.replace(/&((#(32|127|160|173))|shy|nbsp);/ig, ' ');
if(fetchCheckbox('allowimgurl')) {
str = str.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
}
if(!fetchCheckbox('parseurloff')) {
str = parseurl(str, 'bbcode', false);
}
for(i in EXTRAFUNC['html2bbcode']) {
EXTRASTR = str;
try {
eval('str = ' + EXTRAFUNC['html2bbcode'][i] + '()');
} catch(e) {}
}
str = str.replace(/<br\s+?style=(["']?)clear: both;?(\1)[^\>]*>/ig, '');
str = str.replace(/<br[^\>]*>/ig, "\n");
if(!fetchCheckbox('bbcodeoff') && allowbbcode) {
str = preg_replace([
'<table[^>]*float:\\\s*(left|right)[^>]*><tbody><tr><td>\\\s*([\\\s\\\S]+?)\\\s*<\/td><\/tr></tbody><\/table>',
'<table([^>]*(width|background|background-color|backcolor)[^>]*)>',
'<table[^>]*>',
'<tr[^>]*(?:background|background-color|backcolor)[:=]\\\s*(["\']?)([\(\)\\\s%,#\\\w]+)(\\1)[^>]*>',
'<tr[^>]*>',
'(<t[dh]([^>]*(left|center|right)[^>]*)>)\\\s*([\\\s\\\S]+?)\\\s*(<\/t[dh]>)',
'<t[dh]([^>]*(width|colspan|rowspan)[^>]*)>',
'<t[dh][^>]*>',
'<\/t[dh]>',
'<\/tr>',
'<\/table>',
'<h\\\d[^>]*>',
'<\/h\\\d>'
], [
function($1, $2, $3) {return '[float=' + $2 + ']' + $3 + '[/float]';},
function($1, $2) {return tabletag($2);},
'[table]\n',
function($1, $2, $3) {return '[tr=' + $3 + ']';},
'[tr]',
function($1, $2, $3, $4, $5, $6) {return $2 + '[align=' + $4 + ']' + $5 + '[/align]' + $6},
function($1, $2) {return tdtag($2);},
'[td]',
'[/td]',
'[/tr]\n',
'[/table]',
'[b]',
'[/b]'
], str);
str = str.replace(/<h([0-9]+)[^>]*>(.*)<\/h\\1>/ig, "[size=$1]$2[/size]\n\n");
str = str.replace(/<hr[^>]*>/ig, "[hr]");
str = str.replace(/<img[^>]+smilieid=(["']?)(\d+)(\1)[^>]*>/ig, function($1, $2, $3) {return smileycode($3);});
str = str.replace(/<img([^>]*src[^>]*)>/ig, function($1, $2) {return imgtag($2);});
str = str.replace(/<a\s+?name=(["']?)(.+?)(\1)[\s\S]*?>([\s\S]*?)<\/a>/ig, '$4');
str = str.replace(/<div[^>]*quote[^>]*><blockquote>([\s\S]*?)<\/blockquote><\/div>([\s\S]*?)(<br[^>]*>)?/ig, "[quote]$1[/quote]");
str = str.replace(/<div[^>]*blockcode[^>]*><blockquote>([\s\S]*?)<\/blockquote><\/div>([\s\S]*?)(<br[^>]*>)?/ig, "[code]$1[/code]");
str = recursion('b', str, 'simpletag', 'b');
str = recursion('strong', str, 'simpletag', 'b');
str = recursion('i', str, 'simpletag', 'i');
str = recursion('em', str, 'simpletag', 'i');
str = recursion('u', str, 'simpletag', 'u');
str = recursion('strike', str, 'simpletag', 's');
str = recursion('a', str, 'atag');
str = recursion('font', str, 'fonttag');
str = recursion('blockquote', str, 'simpletag', 'indent');
str = recursion('ol', str, 'listtag');
str = recursion('ul', str, 'listtag');
str = recursion('div', str, 'dstag');
str = recursion('p', str, 'ptag');
str = recursion('span', str, 'fonttag');
}
str = str.replace(/<[\/\!]*?[^<>]*?>/ig, '');
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
str = clearcode(str);
return preg_replace([' ', '<', '>', '&'], [' ', '<', '>', '&'], str);
}
function tablesimple(s, table, str) {
if(strpos(str, '[tr=') || strpos(str, '[td=')) {
return s;
} else {
return '[table=' + table + ']\n' + preg_replace(['\\\[tr\\\]', '\\\[\\\/td\\\]\\\s?\\\[td\\\]', '\\\[\\\/tr\\\]\s?', '\\\[td\\\]', '\\\[\\\/td\\\]', '\\\[\\\/td\\\]\\\[\\\/tr\\\]'], ['', '|', '', '', '', '', ''], str) + '[/table]';
}
}
function imgtag(attributes) {
var width = '';
var height = '';
re = /src=(["']?)([\s\S]*?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
var src = matches[2];
} else {
return '';
}
re = /(max-)?width\s?:\s?(\d{1,4})(px)?/i;
var matches = re.exec(attributes);
if(matches != null && !matches[1]) {
width = matches[2];
}
re = /height\s?:\s?(\d{1,4})(px)?/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[1];
}
if(!width) {
re = /width=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
}
if(!height) {
re = /height=(["']?)(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
height = matches[2];
}
}
re = /aid=(["']?)attachimg_(\d+)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
return '[attachimg]' + matches[2] + '[/attachimg]';
}
width = width > 0 ? width : 0;
height = height > 0 ? height : 0;
return width > 0 || height > 0 ?
'[img=' + width + ',' + height + ']' + src + '[/img]' :
'[img]' + src + '[/img]';
}
function listtag(listoptions, text, tagname) {
text = text.replace(/<li>(([\s\S](?!<\/li))*?)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/ig, '<li>$1</li>') + (BROWSER.opera ? '</li>' : '');
text = recursion('li', text, 'litag');
var opentag = '[list]';
var listtype = fetchoptionvalue('type=', listoptions);
listtype = listtype != '' ? listtype : (tagname == 'ol' ? '1' : '');
if(in_array(listtype, ['1', 'a', 'A'])) {
opentag = '[list=' + listtype + ']';
}
return text ? opentag + '\n' + recursion(tagname, text, 'listtag') + '[/list]' : '';
}
function litag(listoptions, text) {
return '[*]' + text.replace(/(\s+)$/g, '') + '\n';
}
function parsecode(text) {
DISCUZCODE['num']++;
DISCUZCODE['html'][DISCUZCODE['num']] = '<div class="blockcode"><blockquote>' + htmlspecialchars(text) + '</blockquote></div>';
return "[\tDISCUZ_CODE_" + DISCUZCODE['num'] + "\t]";
}
function parsestyle(tagoptions, prepend, append) {
var searchlist = [
['align', true, 'text-align:\\s*(left|center|right);?', 1],
['float', true, 'float:\\s*(left|right);?', 1],
['color', true, '(^|[;\\s])color:\\s*([^;]+);?', 2],
['backcolor', true, '(^|[;\\s])background-color:\\s*([^;]+);?', 2],
['font', true, 'font-family:\\s*([^;]+);?', 1],
['size', true, 'font-size:\\s*(\\d+(\\.\\d+)?(px|pt|in|cm|mm|pc|em|ex|%|));?', 1],
['size', true, 'font-size:\\s*(x\\-small|small|medium|large|x\\-large|xx\\-large|\\-webkit\\-xxx\\-large);?', 1, 'size'],
['b', false, 'font-weight:\\s*(bold);?'],
['i', false, 'font-style:\\s*(italic);?'],
['u', false, 'text-decoration:\\s*(underline);?'],
['s', false, 'text-decoration:\\s*(line-through);?']
];
var sizealias = {'x-small':1,'small':2,'medium':3,'large':4,'x-large':5,'xx-large':6,'-webkit-xxx-large':7};
var style = getoptionvalue('style', tagoptions);
re = /^(?:\s|)color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/i;
style = style.replace(re, function($1, $2, $3, $4, $5) {return("color:#" + parseInt($2).toString(16) + parseInt($3).toString(16) + parseInt($4).toString(16) + $5);});
var len = searchlist.length;
for(var i = 0; i < len; i++) {
searchlist[i][4] = !searchlist[i][4] ? '' : searchlist[i][4];
re = new RegExp(searchlist[i][2], "ig");
match = re.exec(style);
if(match != null) {
opnvalue = match[searchlist[i][3]];
if(searchlist[i][4] == 'size') {
opnvalue = sizealias[opnvalue];
}
prepend += '[' + searchlist[i][0] + (searchlist[i][1] == true ? '=' + opnvalue + ']' : ']');
append = '[/' + searchlist[i][0] + ']' + append;
}
}
return {'prepend' : prepend, 'append' : append};
}
function parsetable(width, bgcolor, str) {
if(isUndefined(width)) {
var width = '';
} else {
try {
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
} catch(e) { width = ''; }
}
if(isUndefined(str)) {
return;
}
if(strpos(str, '[/tr]') === false && strpos(str, '[/td]') === false) {
var rows = str.split('\n');
var s = '';
for(i = 0;i < rows.length;i++) {
s += '<tr><td>' + preg_replace(['\r', '\\\\\\\|', '\\\|', '\\\\n'], ['', '|', '</td><td>', '\n'], rows[i]) + '</td></tr>';
}
str = s;
simple = ' simpletable';
} else {
simple = '';
str = str.replace(/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,4}%?))?\]/ig, function($1, $2, $3) {
return '<tr' + ($2 ? ' style="background-color: ' + $2 + '"' : '') + '><td' + ($3 ? ' width="' + $3 + '"' : '') + '>';
});
str = str.replace(/\[tr(?:=([\(\)\s%,#\w]+))?\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4, $5) {
return '<tr' + ($2 ? ' style="background-color: ' + $2 + '"' : '') + '><td' + ($3 ? ' colspan="' + $3 + '"' : '') + ($4 ? ' rowspan="' + $4 + '"' : '') + ($5 ? ' width="' + $5 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,4}%?))?\]/ig, function($1, $2) {
return '</td><td' + ($2 ? ' width="' + $2 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[td(?:=(\d{1,2}),(\d{1,2})(?:,(\d{1,4}%?))?)?\]/ig, function($1, $2, $3, $4) {
return '</td><td' + ($2 ? ' colspan="' + $2 + '"' : '') + ($3 ? ' rowspan="' + $3 + '"' : '') + ($4 ? ' width="' + $4 + '"' : '') + '>';
});
str = str.replace(/\[\/td\]\s*\[\/tr\]\s*/ig, '</td></tr>');
str = str.replace(/<td> <\/td>/ig, '<td> </td>');
}
return '<table ' + (width == '' ? '' : 'width="' + width + '" ') + 'class="t_table"' + (isUndefined(bgcolor) ? '' : ' style="background-color: ' + bgcolor + '"') + simple +'>' + str + '</table>';
}
function preg_quote(str) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!<>\|\:])/g, "\\$1");
}
function recursion(tagname, text, dofunction, extraargs) {
if(extraargs == null) {
extraargs = '';
}
tagname = tagname.toLowerCase();
var open_tag = '<' + tagname;
var open_tag_len = open_tag.length;
var close_tag = '</' + tagname + '>';
var close_tag_len = close_tag.length;
var beginsearchpos = 0;
do {
var textlower = text.toLowerCase();
var tagbegin = textlower.indexOf(open_tag, beginsearchpos);
if(tagbegin == -1) {
break;
}
var strlen = text.length;
var inquote = '';
var found = false;
var tagnameend = false;
var optionend = 0;
var t_char = '';
for(optionend = tagbegin; optionend <= strlen; optionend++) {
t_char = text.charAt(optionend);
if((t_char == '"' || t_char == "'") && inquote == '') {
inquote = t_char;
} else if((t_char == '"' || t_char == "'") && inquote == t_char) {
inquote = '';
} else if(t_char == '>' && !inquote) {
found = true;
break;
} else if((t_char == '=' || t_char == ' ') && !tagnameend) {
tagnameend = optionend;
}
}
if(!found) {
break;
}
if(!tagnameend) {
tagnameend = optionend;
}
var offset = optionend - (tagbegin + open_tag_len);
var tagoptions = text.substr(tagbegin + open_tag_len, offset);
var acttagname = textlower.substr(tagbegin * 1 + 1, tagnameend - tagbegin - 1);
if(acttagname != tagname) {
beginsearchpos = optionend;
continue;
}
var tagend = textlower.indexOf(close_tag, optionend);
if(tagend == -1) {
break;
}
var nestedopenpos = textlower.indexOf(open_tag, optionend);
while(nestedopenpos != -1 && tagend != -1) {
if(nestedopenpos > tagend) {
break;
}
tagend = textlower.indexOf(close_tag, tagend + close_tag_len);
nestedopenpos = textlower.indexOf(open_tag, nestedopenpos + open_tag_len);
}
if(tagend == -1) {
beginsearchpos = optionend;
continue;
}
var localbegin = optionend + 1;
var localtext = eval(dofunction)(tagoptions, text.substr(localbegin, tagend - localbegin), tagname, extraargs);
text = text.substring(0, tagbegin) + localtext + text.substring(tagend + close_tag_len);
beginsearchpos = tagbegin + localtext.length;
} while(tagbegin != -1);
return text;
}
function simpletag(options, text, tagname, parseto) {
if(trim(text) == '') {
return '';
}
text = recursion(tagname, text, 'simpletag', parseto);
return '[' + parseto + ']' + text + '[/' + parseto + ']';
}
function smileycode(smileyid) {
if(typeof smilies_type != 'object') return;
for(var typeid in smilies_array) {
for(var page in smilies_array[typeid]) {
for(var i in smilies_array[typeid][page]) {
if(smilies_array[typeid][page][i][0] == smileyid) {
return smilies_array[typeid][page][i][1];
break;
}
}
}
}
}
function strpos(haystack, needle, _offset) {
if(isUndefined(_offset)) {
_offset = 0;
}
var _index = haystack.toLowerCase().indexOf(needle.toLowerCase(), _offset);
return _index == -1 ? false : _index;
}
function tabletag(attributes) {
var width = '';
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2].substr(matches[2].length - 1, matches[2].length) == '%' ?
(matches[2].substr(0, matches[2].length - 1) <= 98 ? matches[2] : '98%') :
(matches[2] <= 560 ? matches[2] : '98%');
} else {
re = /width\s?:\s?(\d{1,4})([px|%])/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2] == '%' ? (matches[1] <= 98 ? matches[1] + '%' : '98%') : (matches[1] <= 560 ? matches[1] : '98%');
}
}
var bgcolor = '';
re = /(?:background|background-color|bgcolor)[:=]\s*(["']?)((rgb\(\d{1,3}%?,\s*\d{1,3}%?,\s*\d{1,3}%?\))|(#[0-9a-fA-F]{3,6})|([a-zA-Z]{1,20}))(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
bgcolor = matches[2];
width = width ? width : '98%';
}
return bgcolor ? '[table=' + width + ',' + bgcolor + ']\n' : (width ? '[table=' + width + ']\n' : '[table]\n');
}
function tdtag(attributes) {
var colspan = 1;
var rowspan = 1;
var width = '';
re = /colspan=(["']?)(\d{1,2})(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
colspan = matches[2];
}
re = /rowspan=(["']?)(\d{1,2})(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
rowspan = matches[2];
}
re = /width=(["']?)(\d{1,4}%?)(\1)/i;
var matches = re.exec(attributes);
if(matches != null) {
width = matches[2];
}
return in_array(width, ['', '0', '100%']) ?
(colspan == 1 && rowspan == 1 ? '[td]' : '[td=' + colspan + ',' + rowspan + ']') :
(colspan == 1 && rowspan == 1 ? '[td=' + width + ']' : '[td=' + colspan + ',' + rowspan + ',' + width + ']');
}
if(typeof jsloaded == 'function') {
jsloaded('bbcode');
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_post.js 22843 2011-05-25 09:39:50Z monkey $
*/
var postSubmited = false;
var AID = {0:1,1:1};
var UPLOADSTATUS = -1;
var UPLOADFAILED = UPLOADCOMPLETE = AUTOPOST = 0;
var CURRENTATTACH = '0';
var FAILEDATTACHS = '';
var UPLOADWINRECALL = null;
var imgexts = typeof imgexts == 'undefined' ? 'jpg, jpeg, gif, png, bmp' : imgexts;
var ATTACHORIMAGE = '0';
var STATUSMSG = {
'-1' : '内部服务器错误',
'0' : '上传成功',
'1' : '不支持此类扩展名',
'2' : '服务器限制无法上传那么大的附件',
'3' : '用户组限制无法上传那么大的附件',
'4' : '不支持此类扩展名',
'5' : '文件类型限制无法上传那么大的附件',
'6' : '今日你已无法上传更多的附件',
'7' : '请选择图片文件(' + imgexts + ')',
'8' : '附件文件无法保存',
'9' : '没有合法的文件被上传',
'10' : '非法操作',
'11' : '今日你已无法上传那么大的附件'
};
EXTRAFUNC['validator'] = [];
function checkFocus() {
var obj = wysiwyg ? editwin : textobj;
if(!obj.hasfocus) {
obj.focus();
}
}
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && $('postsubmit')) {
if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit', 'editsubmit']) && !validate($('postform'))) {
doane(event);
return;
}
postSubmited = true;
$('postsubmit').disabled = true;
$('postform').submit();
}
if(event.keyCode == 9) {
doane(event);
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
showDialog('当前长度: ' + mb_strlen(message) + ' 字节,' + (postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节。' : ''), 'notice', '字数检查');
}
if(!tradepost) {
var tradepost = 0;
}
function validate(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
if(($('postsubmit').name != 'replysubmit' && !($('postsubmit').name == 'editsubmit' && !isfirstpost) && theform.subject.value == "") || !sortid && !special && trim(message) == "") {
showError('抱歉,您尚未输入标题或内容');
return false;
} else if(mb_strlen(theform.subject.value) > 80) {
showError('您的标题超过 80 个字符的限制');
return false;
}
if(ispicstyleforum == 1 && ATTACHORIMAGE == 0 && isfirstpost) {
showError('帖图版块至少应上传一张图片作为封面');
return false;
}
if(in_array($('postsubmit').name, ['topicsubmit', 'editsubmit'])) {
if(theform.typeid && (theform.typeid.options && theform.typeid.options[theform.typeid.selectedIndex].value == 0) && typerequired) {
showError('请选择主题对应的分类');
return false;
}
if(theform.sortid && (theform.sortid.options && theform.sortid.options[theform.sortid.selectedIndex].value == 0) && sortrequired) {
showError('请选择主题对应的分类信息');
return false;
}
}
for(i in EXTRAFUNC['validator']) {
try {
eval('var v = ' + EXTRAFUNC['validator'][i] + '()');
if(!v) {
return false;
}
} catch(e) {}
}
if(!disablepostctrl && !sortid && !special && ((postminchars != 0 && mb_strlen(message) < postminchars) || (postmaxchars != 0 && mb_strlen(message) > postmaxchars))) {
showError('您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(message) + ' 字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节');
return false;
}
if(UPLOADSTATUS == 0) {
if(!confirm('您有等待上传的附件,确认不上传这些附件吗?')) {
return false;
}
} else if(UPLOADSTATUS == 1) {
showDialog('您有正在上传的附件,请稍候,上传完成后帖子将会自动发表...', 'notice');
AUTOPOST = 1;
return false;
}
if($(editorid + '_attachlist')) {
$('postbox').appendChild($(editorid + '_attachlist'));
$(editorid + '_attachlist').style.display = 'none';
}
if($(editorid + '_imgattachlist')) {
$('postbox').appendChild($(editorid + '_imgattachlist'));
$(editorid + '_imgattachlist').style.display = 'none';
}
hideMenu();
theform.message.value = message;
if($('postsubmit').name == 'editsubmit') {
return true;
} else if(in_array($('postsubmit').name, ['topicsubmit', 'replysubmit'])) {
if(seccodecheck || secqaacheck) {
var chk = 1, chkv = '';
if(secqaacheck) {
chkv = $('checksecqaaverify_' + theform.sechash.value).innerHTML;
if(chkv.indexOf('loading') != -1) {
setTimeout(function () { validate(theform); }, 100);
chk = 0;
} else if(chkv.indexOf('check_right') == -1) {
showError('验证问答错误,请重新填写');
chk = 0;
}
}
if(seccodecheck) {
chkv = $('checkseccodeverify_' + theform.sechash.value).innerHTML;
if(chkv.indexOf('loading') !== -1) {
setTimeout(function () { validate(theform); }, 100);
chk = 0;
} else if(chkv.indexOf('check_right') === -1) {
showError('验证码错误,请重新填写');
chk = 0;
}
}
if(chk) {
postsubmit(theform);
}
} else {
postsubmit(theform);
}
return false;
}
}
function postsubmit(theform) {
theform.replysubmit ? theform.replysubmit.disabled = true : (theform.editsubmit ? theform.editsubmit.disabled = true : theform.topicsubmit.disabled = true);
theform.submit();
}
function relatekw(subject, message) {
if(isUndefined(subject) || subject == -1) {
subject = $('subject').value;
subject = subject.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
subject = subject.replace(/\s{2,}/ig, ' ');
}
if(isUndefined(message) || message == -1) {
message = getEditorContents();
message = message.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
message = message.replace(/\s{2,}/ig, ' ');
}
subject = (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(subject) : subject);
message = (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(message) : message);
message = message.replace(/&/ig, '', message).substr(0, 500);
ajaxget('forum.php?mod=relatekw&subjectenc=' + subject + '&messageenc=' + message, 'tagselect');
}
function switchicon(iconid, obj) {
$('iconid').value = iconid;
$('icon_img').src = obj.src;
hideMenu();
}
function clearContent() {
if(wysiwyg) {
editdoc.body.innerHTML = BROWSER.firefox ? '<br />' : '';
} else {
textobj.value = '';
}
}
function uploadNextAttach() {
var str = $('attachframe').contentWindow.document.body.innerHTML;
if(str == '') return;
var arr = str.split('|');
var att = CURRENTATTACH.split('|');
var sizelimit = '';
if(arr[4] == 'ban') {
sizelimit = '(附件类型被禁止)';
} else if(arr[4] == 'perday') {
sizelimit = '(不能超过 ' + arr[5] + ' 字节)';
} else if(arr[4] > 0) {
sizelimit = '(不能超过 ' + arr[4] + ' 字节)';
}
uploadAttach(parseInt(att[0]), arr[0] == 'DISCUZUPLOAD' ? parseInt(arr[1]) : -1, att[1], sizelimit);
}
function uploadAttach(curId, statusid, prefix, sizelimit) {
prefix = isUndefined(prefix) ? '' : prefix;
var nextId = 0;
for(var i = 0; i < AID[prefix ? 1 : 0] - 1; i++) {
if($(prefix + 'attachform_' + i)) {
nextId = i;
if(curId == 0) {
break;
} else {
if(i > curId) {
break;
}
}
}
}
if(nextId == 0) {
return;
}
CURRENTATTACH = nextId + '|' + prefix;
if(curId > 0) {
if(statusid == 0) {
UPLOADCOMPLETE++;
} else {
FAILEDATTACHS += '<br />' + mb_cutstr($(prefix + 'attachnew_' + curId).value.substr($(prefix + 'attachnew_' + curId).value.replace(/\\/g, '/').lastIndexOf('/') + 1), 25) + ': ' + STATUSMSG[statusid] + sizelimit;
UPLOADFAILED++;
}
$(prefix + 'cpdel_' + curId).innerHTML = '<img src="' + IMGDIR + '/check_' + (statusid == 0 ? 'right' : 'error') + '.gif" alt="' + STATUSMSG[statusid] + '" />';
if(nextId == curId || in_array(statusid, [6, 8])) {
if(prefix == 'img') {
updateImageList();
} else {
updateAttachList();
}
if(UPLOADFAILED > 0) {
showDialog('附件上传完成!成功 ' + UPLOADCOMPLETE + ' 个,失败 ' + UPLOADFAILED + ' 个:' + FAILEDATTACHS);
FAILEDATTACHS = '';
}
UPLOADSTATUS = 2;
for(var i = 0; i < AID[prefix ? 1 : 0] - 1; i++) {
if($(prefix + 'attachform_' + i)) {
reAddAttach(prefix, i)
}
}
$(prefix + 'uploadbtn').style.display = '';
$(prefix + 'uploading').style.display = 'none';
if(AUTOPOST) {
hideMenu();
validate($('postform'));
} else if(UPLOADFAILED == 0 && (prefix == 'img' || prefix == '')) {
showDialog('附件上传完成!', 'right', null, null, 0, null, null, null, null, 3);
}
UPLOADFAILED = UPLOADCOMPLETE = 0;
CURRENTATTACH = '0';
FAILEDATTACHS = '';
return;
}
} else {
$(prefix + 'uploadbtn').style.display = 'none';
$(prefix + 'uploading').style.display = '';
}
$(prefix + 'cpdel_' + nextId).innerHTML = '<img src="' + IMGDIR + '/loading.gif" alt="上传中..." />';
UPLOADSTATUS = 1;
$(prefix + 'attachform_' + nextId).submit();
}
function addAttach(prefix) {
var id = AID[prefix ? 1 : 0];
var tags, newnode, i;
prefix = isUndefined(prefix) ? '' : prefix;
newnode = $(prefix + 'attachbtnhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'Filedata') {
tags[i].id = prefix + 'attachnew_' + id;
tags[i].onchange = function() {insertAttach(prefix, id)};
tags[i].unselectable = 'on';
} else if(tags[i].name == 'attachid') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('form');
tags[0].name = tags[0].id = prefix + 'attachform_' + id;
$(prefix + 'attachbtn').appendChild(newnode);
newnode = $(prefix + 'attachbodyhidden').firstChild.cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == prefix + 'localid[]') {
tags[i].value = id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == prefix + 'localfile[]') {
tags[i].id = prefix + 'localfile_' + id;
} else if(tags[i].id == prefix + 'cpdel[]') {
tags[i].id = prefix + 'cpdel_' + id;
} else if(tags[i].id == prefix + 'localno[]') {
tags[i].id = prefix + 'localno_' + id;
} else if(tags[i].id == prefix + 'deschidden[]') {
tags[i].id = prefix + 'deschidden_' + id;
}
}
AID[prefix ? 1 : 0]++;
newnode.style.display = 'none';
$(prefix + 'attachbody').appendChild(newnode);
}
function insertAttach(prefix, id) {
var localimgpreview = '';
var path = $(prefix + 'attachnew_' + id).value;
var extpos = path.lastIndexOf('.');
var ext = extpos == -1 ? '' : path.substr(extpos + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $(prefix + 'attachnew_' + id).value.substr($(prefix + 'attachnew_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
var filename = mb_cutstr(localfile, 30);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
reAddAttach(prefix, id);
showError('对不起,不支持上传此类扩展名的附件。');
return;
}
if(prefix == 'img' && imgexts.indexOf(ext) == -1) {
reAddAttach(prefix, id);
showError('请选择图片文件(' + imgexts + ')');
return;
}
$(prefix + 'cpdel_' + id).innerHTML = '<a href="javascript:;" class="d" onclick="reAddAttach(\'' + prefix + '\', ' + id + ')">删除</a>';
$(prefix + 'localfile_' + id).innerHTML = '<span>' + filename + '</span>';
$(prefix + 'attachnew_' + id).style.display = 'none';
$(prefix + 'deschidden_' + id).style.display = '';
$(prefix + 'deschidden_' + id).title = localfile;
$(prefix + 'localno_' + id).parentNode.parentNode.style.display = '';
addAttach(prefix);
UPLOADSTATUS = 0;
}
function reAddAttach(prefix, id) {
$(prefix + 'attachbody').removeChild($(prefix + 'localno_' + id).parentNode.parentNode);
$(prefix + 'attachbtn').removeChild($(prefix + 'attachnew_' + id).parentNode.parentNode);
$(prefix + 'attachbody').innerHTML == '' && addAttach(prefix);
$('localimgpreview_' + id) ? document.body.removeChild($('localimgpreview_' + id)) : null;
}
function delAttach(id, type) {
var ids = {};
if(typeof id == 'number') {
ids[id] = id;
} else {
ids = id;
}
for(id in ids) {
if($('attach_' + id)) {
$('attach_' + id).style.display = 'none';
ATTACHNUM['attach' + (type ? 'un' : '') + 'used']--;
updateattachnum('attach');
}
}
appendAttachDel(ids);
}
function delImgAttach(id, type) {
var ids = {};
if(typeof id == 'number') {
ids[id] = id;
} else {
ids = id;
}
for(id in ids) {
if($('image_td_' + id)) {
$('image_td_' + id).className = 'imgdeleted';
$('image_' + id).onclick = null;
$('image_desc_' + id).disabled = true;
ATTACHNUM['image' + (type ? 'un' : '') + 'used']--;
updateattachnum('image');
}
}
appendAttachDel(ids);
}
function appendAttachDel(ids) {
if(!ids) {
return;
}
var aids = '';
for(id in ids) {
aids += '&aids[]=' + id;
}
var x = new Ajax();
x.get('forum.php?mod=ajax&action=deleteattach&inajax=yes&tid=' + (typeof tid == 'undefined' ? 0 : tid) + '&pid=' + (typeof pid == 'undefined' ? 0 : pid) + aids, function() {});
if($('delattachop')) {
$('delattachop').value = 1;
}
}
function updateAttach(aid) {
objupdate = $('attachupdate'+aid);
obj = $('attach' + aid);
if(!objupdate.innerHTML) {
obj.style.display = 'none';
objupdate.innerHTML = '<input type="file" name="attachupdate[paid' + aid + ']"><a href="javascript:;" onclick="updateAttach(' + aid + ')">取消</a>';
} else {
obj.style.display = '';
objupdate.innerHTML = '';
}
}
function updateattachnum(type) {
ATTACHNUM[type + 'used'] = ATTACHNUM[type + 'used'] >= 0 ? ATTACHNUM[type + 'used'] : 0;
ATTACHNUM[type + 'unused'] = ATTACHNUM[type + 'unused'] >= 0 ? ATTACHNUM[type + 'unused'] : 0;
var num = ATTACHNUM[type + 'used'] + ATTACHNUM[type + 'unused'];
if(num) {
if($(editorid + '_' + type)) {
$(editorid + '_' + type).title = '包含 ' + num + (type == 'image' ? ' 个图片附件' : ' 个附件');
}
if($(editorid + '_' + type + 'n')) {
$(editorid + '_' + type + 'n').style.display = '';
}
ATTACHORIMAGE = 1;
} else {
if($(editorid + '_' + type)) {
$(editorid + '_' + type).title = type == 'image' ? '图片' : '附件';
}
if($(editorid + '_' + type + 'n')) {
$(editorid + '_' + type + 'n').style.display = 'none';
}
}
}
function swfHandler(action, type) {
if(action == 2) {
if(type == 'image') {
updateImageList();
} else {
updateAttachList();
}
}
}
function updateAttachList(action, aids) {
ajaxget('forum.php?mod=ajax&action=attachlist' + (!action ? '&posttime=' + $('posttime').value : (!aids ? '' : '&aids=' + aids)) + (!fid ? '' : '&fid=' + fid), 'attachlist');
switchAttachbutton('attachlist');$('attach_tblheader').style.display = $('attach_notice').style.display = '';
}
function updateImageList(action, aids) {
ajaxget('forum.php?mod=ajax&action=imagelist' + (!action ? '&pid=' + pid + '&posttime=' + $('posttime').value : (!aids ? '' : '&aids=' + aids)) + (!fid ? '' : '&fid=' + fid), 'imgattachlist');
switchImagebutton('imgattachlist');$('imgattach_notice').style.display = '';
}
function updateDownImageList(msg) {
if(msg == '') {
showError('抱歉,暂无远程附件');
} else {
ajaxget('forum.php?mod=ajax&action=imagelist&pid=' + pid + '&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'imgattachlist', null, null, null, function(){if(wysiwyg) {editdoc.body.innerHTML = msg;switchEditor(0);switchEditor(1)} else {textobj.value = msg;}});
switchImagebutton('imgattachlist');$('imgattach_notice').style.display = '';
showDialog('远程附件下载完成!', 'right', null, null, 0, null, null, null, null, 3);
}
}
function switchButton(btn, type) {
var btnpre = editorid + '_btn_';
if(!$(btnpre + btn) || !$(editorid + '_' + btn)) {
return;
}
var tabs = $(editorid + '_' + type + '_ctrl').getElementsByTagName('LI');
$(btnpre + btn).style.display = '';
$(editorid + '_' + btn).style.display = '';
$(btnpre + btn).className = 'current';
var btni = '';
for(i = 0;i < tabs.length;i++) {
if(tabs[i].id.indexOf(btnpre) !== -1) {
btni = tabs[i].id.substr(btnpre.length);
}
if(btni != btn) {
if(!$(editorid + '_' + btni) || !$(editorid + '_btn_' + btni)) {
continue;
}
$(editorid + '_' + btni).style.display = 'none';
$(editorid + '_btn_' + btni).className = '';
}
}
}
function uploadWindowstart() {
$('uploadwindowing').style.visibility = 'visible';
}
function uploadWindowload() {
$('uploadwindowing').style.visibility = 'hidden';
var str = $('uploadattachframe').contentWindow.document.body.innerHTML;
if(str == '') return;
var arr = str.split('|');
if(arr[0] == 'DISCUZUPLOAD' && arr[2] == 0) {
UPLOADWINRECALL(arr[3], arr[5], arr[6]);
hideWindow('upload', 0);
} else {
var sizelimit = '';
if(arr[7] == 'ban') {
sizelimit = '(附件类型被禁止)';
} else if(arr[7] == 'perday') {
sizelimit = '(不能超过 ' + arr[8] + ' 字节)';
} else if(arr[7] > 0) {
sizelimit = '(不能超过 ' + arr[7] + ' 字节)';
}
showError(STATUSMSG[arr[2]] + sizelimit);
}
if($('attachlimitnotice')) {
ajaxget('forum.php?mod=ajax&action=updateattachlimit&fid=' + fid, 'attachlimitnotice');
}
}
function uploadWindow(recall, type) {
var type = isUndefined(type) ? 'image' : type;
UPLOADWINRECALL = recall;
showWindow('upload', 'forum.php?mod=misc&action=upload&fid=' + fid + '&type=' + type, 'get', 0, {'zindex':601});
}
function updatetradeattach(aid, url, attachurl) {
$('tradeaid').value = aid;
$('tradeattach_image').innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function updateactivityattach(aid, url, attachurl) {
$('activityaid').value = aid;
$('activityattach_image').innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function updatesortattach(aid, url, attachurl, identifier) {
$('sortaid_' + identifier).value = aid;
$('sortattachurl_' + identifier).value = attachurl + '/' + url;
$('sortattach_image_' + identifier).innerHTML = '<img src="' + attachurl + '/' + url + '" class="spimg" />';
ATTACHORIMAGE = 1;
}
function switchpollm(swt) {
t = $('pollchecked').checked && swt ? 2 : 1;
var v = '';
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption')) {
if(t == 2 && e.tagName == 'INPUT') {
v += e.value + '\n';
} else if(t == 1 && e.tagName == 'TEXTAREA') {
v += e.value;
}
}
}
}
if(t == 1) {
var a = v.split('\n');
var pcount = 0;
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption')) {
pcount++;
if(e.tagName == 'INPUT') e.value = '';
}
}
}
for(var i = 0; i < a.length - pcount + 2; i++) {
addpolloption();
}
var ii = 0;
for(var i = 0; i < $('postform').elements.length; i++) {
var e = $('postform').elements[i];
if(!isUndefined(e.name)) {
if(e.name.match('^polloption') && e.tagName == 'INPUT' && a[ii]) {
e.value = a[ii++];
}
}
}
} else if(t == 2) {
$('postform').polloptions.value = trim(v);
}
$('postform').tpolloption.value = t;
if(swt) {
display('pollm_c_1');
display('pollm_c_2');
}
}
function addpolloption() {
if(curoptions < maxoptions) {
$('polloption_new').outerHTML = '<p>' + $('polloption_hidden').innerHTML + '</p>' + $('polloption_new').outerHTML;
curoptions++;
} else {
$('polloption_new').outerHTML = '<span>已达到最大投票数'+maxoptions+'</span>';
}
}
function delpolloption(obj) {
obj.parentNode.parentNode.removeChild(obj.parentNode);
curoptions--;
}
function insertsave(pid) {
var x = new Ajax();
x.get('forum.php?mod=misc&action=loadsave&inajax=yes&pid=' + pid + '&type=' + wysiwyg, function(str, x) {
insertText(str, str.length, 0);
});
}
function userdataoption(op) {
if(!op) {
saveUserdata('forum', '');
display('rstnotice');
} else {
loadData();
checkFocus();
}
doane();
}
function attachoption(type, op) {
if(!op) {
if(type == 'attach') {
delAttach(ATTACHUNUSEDAID, 1);
ATTACHNUM['attachunused'] = 0;
display('attachnotice_attach');
} else {
delImgAttach(IMGUNUSEDAID, 1);
ATTACHNUM['imageunused'] = 0;
display('attachnotice_img');
}
} else if(op == 1) {
var obj = $('unusedwin') ? $('unusedwin') : $('unusedlist_' + type);
list = obj.getElementsByTagName('INPUT'), aids = '';
for(i = 0;i < list.length;i++) {
if(list[i].name.match('unused') && list[i].checked) {
aids += '|' + list[i].value;
}
}
if(aids) {
if(type == 'attach') {
updateAttachList(1, aids);
} else {
updateImageList(1, aids);
}
}
display('attachnotice_' + type);
} else if(op == 2) {
showDialog('<div id="unusedwin" class="c altw" style="overflow:auto;height:100px;">' + $('unusedlist_' + type).innerHTML + '</div>' +
'<p class="o pns"><span class="z xg1"><label for="unusedwinchkall"><input id="unusedwinchkall" type="checkbox" onclick="attachoption(\'' + type + '\', 3)" checked="checked" />全选</label></span>' +
'<button onclick="attachoption(\'' + type + '\', 1);hideMenu(\'fwin_dialog\', \'dialog\')" class="pn pnc"><strong>确定</strong></button></p>', 'info', '未使用的' + (type == 'attach' ? '附件' : '图片'));
} else if(op == 3) {
list = $('unusedwin').getElementsByTagName('INPUT');
for(i = 0;i < list.length;i++) {
if(list[i].name.match('unused')) {
list[i].checked = $('unusedwinchkall').checked;
}
}
return;
}
doane();
}
function insertAttachTag(aid) {
var txt = '[attach]' + aid + '[/attach]';
seditor_insertunit('fastpost', txt);
}
function insertAttachimgTag(aid) {
var txt = '[attachimg]' + aid + '[/attachimg]';
seditor_insertunit('fastpost', txt);
}
function insertText(str) {
seditor_insertunit('fastpost', str);
}
function insertAllAttachTag() {
var attachListObj = $('e_attachlist').getElementsByTagName("tbody");
for(var i in attachListObj) {
if(typeof attachListObj[i] == "object") {
var attach = attachListObj[i];
var ids = attach.id.split('_');
if(ids[0] == 'attach') {
if($('attachname'+ids[1])) {
if(parseInt($('attachname'+ids[1]).getAttribute('isimage'))) {
insertAttachimgTag(ids[1]);
} else {
insertAttachTag(ids[1]);
}
var txt = wysiwyg ? '\r\n<br/><br/>\r\n' : '\r\n\r\n';
insertText(txt, strlen(txt), 0);
}
}
}
}
doane();
}
function selectAllSaveImg(state) {
var inputListObj = $('imgattachlist').getElementsByTagName("input");
for(i in inputListObj) {
if(typeof inputListObj[i] == "object" && inputListObj[i].id) {
var inputObj = inputListObj[i];
var ids = inputObj.id.split('_');
if(ids[0] == 'albumaidchk' && $('image_td_' + ids[1]).className != 'imgdeleted' && inputObj.checked != state) {
inputObj.click();
}
}
}
}
function showExtra(id) {
if ($(id+'_c').style.display == 'block') {
$(id+'_b').className = 'pn z';
$(id+'_c').style.display = 'none';
} else {
var extraButton = $('post_extra_tb').getElementsByTagName('label');
var extraForm = $('post_extra_c').getElementsByTagName('div');
for (i=0;i<extraButton.length;i++) {
extraButton[i].className = '';
}
for (i=0;i<extraForm.length;i++) {
if(hasClass(extraForm[i],'exfm')) {
extraForm[i].style.display = 'none';
}
}
for (i=0;i<extraForm.length;i++) {
if(hasClass(extraForm[i],'exfm')) {
extraForm[i].style.display = 'none';
}
}
$(id+'_b').className = 'a';
$(id+'_c').style.display = 'block';
}
}
function extraCheck(op) {
if(!op && $('extra_replycredit_chk')) {
$('extra_replycredit_chk').className = $('replycredit_extcredits').value > 0 && $('replycredit_times').value > 0 ? 'a' : '';
} else if(op == 1 && $('readperm')) {
$('extra_readperm_chk').className = $('readperm').value !== '' ? 'a' : '';
} else if(op == 2 && $('price')) {
$('extra_price_chk').className = $('price').value > 0 ? 'a' : '';
} else if(op == 3 && $('rushreply')) {
$('extra_rushreplyset_chk').className = $('rushreply').checked ? 'a' : '';
} else if(op == 4 && $('tags')) {
$('extra_tag_chk').className = $('tags').value !== '' ? 'a' : '';
}
}
function getreplycredit() {
var replycredit_extcredits = $('replycredit_extcredits');
var replycredit_times = $('replycredit_times');
var credit_once = parseInt(replycredit_extcredits.value) > 0 ? parseInt(replycredit_extcredits.value) : 0;
var times = parseInt(replycredit_times.value) > 0 ? parseInt(replycredit_times.value) : 0;
if(parseInt(credit_once * times) - have_replycredit > 0) {
var real_reply_credit = Math.ceil(parseInt(credit_once * times) - have_replycredit + ((parseInt(credit_once * times) - have_replycredit) * creditstax));
} else {
var real_reply_credit = Math.ceil(parseInt(credit_once * times) - have_replycredit);
}
var reply_credits_sum = Math.ceil(parseInt(credit_once * times));
if(real_reply_credit > userextcredit) {
$('replycredit').innerHTML = '<b class="xi1">回帖奖励积分总额过大('+real_reply_credit+')</b>';
} else {
if(have_replycredit > 0 && real_reply_credit < 0) {
$('replycredit').innerHTML = "<font class='xi1'>返还"+Math.abs(real_reply_credit)+"</font>";
} else {
$('replycredit').innerHTML = replycredit_result_lang + (real_reply_credit > 0 ? real_reply_credit : 0 );
}
$('replycredit_sum').innerHTML = reply_credits_sum > 0 ? reply_credits_sum : 0 ;
}
}
function extraCheckall() {
for(i = 0;i < 5;i++) {
extraCheck(i);
}
}
function deleteThread() {
if(confirm('确定要删除该帖子吗?') != 0){
$('delete').value = '1';
$('postform').submit();
}
}
function hideAttachMenu(id) {
if($(editorid + '_' + id + '_menu')) {
$(editorid + '_' + id + '_menu').style.visibility = 'hidden';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: admincp.js 22381 2011-05-05 03:05:16Z monkey $
*/
function redirect(url) {
window.location.replace(url);
}
function scrollTopBody() {
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkAll(type, form, value, checkall, changestyle) {
var checkall = checkall ? checkall : 'chkall';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(type == 'option' && e.type == 'radio' && e.value == value && e.disabled != true) {
e.checked = true;
} else if(type == 'value' && e.type == 'checkbox' && e.getAttribute('chkvalue') == value) {
e.checked = form.elements[checkall].checked;
if(changestyle) {
multiupdate(e);
}
} else if(type == 'prefix' && e.name && e.name != checkall && (!value || (value && e.name.match(value)))) {
e.checked = form.elements[checkall].checked;
if(changestyle) {
if(e.parentNode && e.parentNode.tagName.toLowerCase() == 'li') {
e.parentNode.className = e.checked ? 'checked' : '';
}
if(e.parentNode.parentNode && e.parentNode.parentNode.tagName.toLowerCase() == 'div') {
e.parentNode.parentNode.className = e.checked ? 'item checked' : 'item';
}
}
}
}
}
function altStyle(obj, disabled) {
function altStyleClear(obj) {
var input, lis, i;
lis = obj.parentNode.getElementsByTagName('li');
for(i=0; i < lis.length; i++){
lis[i].className = '';
}
}
var disabled = !disabled ? 0 : disabled;
if(disabled) {
return;
}
var input, lis, i, cc, o;
cc = 0;
lis = obj.getElementsByTagName('li');
for(i=0; i < lis.length; i++){
lis[i].onclick = function(e) {
o = BROWSER.ie ? event.srcElement.tagName : e.target.tagName;
altKey = BROWSER.ie ? window.event.altKey : e.altKey;
if(cc) {
return;
}
cc = 1;
input = this.getElementsByTagName('input')[0];
if(input.getAttribute('type') == 'checkbox' || input.getAttribute('type') == 'radio') {
if(input.getAttribute('type') == 'radio') {
altStyleClear(this);
}
if(BROWSER.ie || o != 'INPUT' && input.onclick) {
input.click();
}
if(this.className != 'checked') {
this.className = 'checked';
input.checked = true;
} else {
this.className = '';
input.checked = false;
}
if(altKey && input.name.match(/^multinew\[\d+\]/)) {
miid = input.id.split('|');
mi = 0;
while($(miid[0] + '|' + mi)) {
$(miid[0] + '|' + mi).checked = input.checked;
if(input.getAttribute('type') == 'radio') {
altStyleClear($(miid[0] + '|' + mi).parentNode);
}
$(miid[0] + '|' + mi).parentNode.className = input.checked ? 'checked' : '';
mi++;
}
}
}
};
lis[i].onmouseup = function(e) {
cc = 0;
}
}
}
var addrowdirect = 0;
function addrow(obj, type) {
var table = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
if(!addrowdirect) {
var row = table.insertRow(obj.parentNode.parentNode.parentNode.rowIndex);
} else {
var row = table.insertRow(obj.parentNode.parentNode.parentNode.rowIndex + 1);
}
var typedata = rowtypedata[type];
for(var i = 0; i <= typedata.length - 1; i++) {
var cell = row.insertCell(i);
cell.colSpan = typedata[i][0];
var tmp = typedata[i][1];
if(typedata[i][2]) {
cell.className = typedata[i][2];
}
tmp = tmp.replace(/\{(\d+)\}/g, function($1, $2) {return addrow.arguments[parseInt($2) + 1];});
cell.innerHTML = tmp;
}
addrowdirect = 0;
}
function deleterow(obj) {
var table = obj.parentNode.parentNode.parentNode.parentNode.parentNode;
var tr = obj.parentNode.parentNode.parentNode;
table.deleteRow(tr.rowIndex);
}
function dropmenu(obj){
showMenu({'ctrlid':obj.id, 'menuid':obj.id + 'child', 'evt':'mouseover'});
$(obj.id + 'child').style.top = (parseInt($(obj.id + 'child').style.top) - Math.max(document.body.scrollTop, document.documentElement.scrollTop)) + 'px';
if(BROWSER.ie > 6 || !BROWSER.ie) {
$(obj.id + 'child').style.left = (parseInt($(obj.id + 'child').style.left) - Math.max(document.body.scrollLeft, document.documentElement.scrollLeft)) + 'px';
}
}
var heightag = BROWSER.chrome ? 4 : 0;
function textareasize(obj, op) {
if(!op) {
if(obj.scrollHeight > 70) {
obj.style.height = (obj.scrollHeight < 300 ? obj.scrollHeight - heightag: 300) + 'px';
if(obj.style.position == 'absolute') {
obj.parentNode.style.height = (parseInt(obj.style.height) + 20) + 'px';
}
}
} else {
if(obj.style.position == 'absolute') {
obj.style.position = '';
obj.style.width = '';
obj.parentNode.style.height = '';
} else {
obj.parentNode.style.height = obj.parentNode.offsetHeight + 'px';
obj.style.width = BROWSER.ie > 6 || !BROWSER.ie ? '90%' : '600px';
obj.style.position = 'absolute';
}
}
}
function showanchor(obj) {
var navs = $('submenu').getElementsByTagName('li');
for(var i = 0; i < navs.length; i++) {
if(navs[i].id.substr(0, 4) == 'nav_' && navs[i].id != obj.id) {
if($(navs[i].id.substr(4))) {
navs[i].className = '';
$(navs[i].id.substr(4)).style.display = 'none';
if($(navs[i].id.substr(4) + '_tips')) $(navs[i].id.substr(4) + '_tips').style.display = 'none';
}
}
}
obj.className = 'current';
currentAnchor = obj.id.substr(4);
$(currentAnchor).style.display = '';
if($(currentAnchor + '_tips')) $(currentAnchor + '_tips').style.display = '';
if($(currentAnchor + 'form')) {
$(currentAnchor + 'form').anchor.value = currentAnchor;
} else if($('cpform')) {
$('cpform').anchor.value = currentAnchor;
}
}
function updatecolorpreview(obj) {
$(obj).style.background = $(obj + '_v').value;
}
function entersubmit(e, name) {
var e = e ? e : event;
if(e.keyCode != 13) {
return;
}
var tag = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tag != 'TEXTAREA') {
doane(e);
if($('submit_' + name).offsetWidth) {
$('formscrolltop').value = document.documentElement.scrollTop;
$('submit_' + name).click();
}
}
}
function parsetag(tag) {
var parse = function (tds) {
for(var i = 0; i < tds.length; i++) {
if(tds[i].getAttribute('s') == '1') {
var str = tds[i].innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
if(tag && $3.indexOf(tag) != -1) {
re = new RegExp(tag, "g");
$3 = $3.replace(re, '<h_>');
}
return $2 + $3;
});
tds[i].innerHTML = str.replace(/<h_>/ig, function($1, $2) {
return '<font class="highlight">' + tag + '</font>';
});
}
}
}
parse(document.body.getElementsByTagName('td'));
parse(document.body.getElementsByTagName('span'));
}
function sdisplay(id, obj) {
obj.innerHTML = $(id).style.display == 'none' ? '<img src="static/image/admincp/desc.gif" style="vertical-align:middle" />' : '<img src="static/image/admincp/add.gif" style="vertical-align:middle" />'
display(id);
}
if(ISFRAME) {
try {
_attachEvent(document.documentElement, 'keydown', parent.resetEscAndF5);
} catch(e) {}
}
var multiids = new Array();
function multiupdate(obj) {
v = obj.value;
if(obj.checked) {
multiids[v] = v;
} else {
multiids[v] = null;
}
}
function getmultiids() {
var ids = '', comma = '';
for(i in multiids) {
if(multiids[i] != null) {
ids += comma + multiids[i];
comma = ',';
}
}
return ids;
}
function toggle_group(oid, obj, conf) {
obj = obj ? obj : $('a_'+oid);
if(!conf) {
var conf = {'show':'[-]','hide':'[+]'};
}
var obody = $(oid);
if(obody.style.display == 'none') {
obody.style.display = '';
obj.innerHTML = conf.show;
} else {
obody.style.display = 'none';
obj.innerHTML = conf.hide;
}
}
function show_all() {
var tbodys = $("cpform").getElementsByTagName('tbody');
for(var i = 0; i < tbodys.length; i++) {
var re = /^group_(\d+)$/;
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = '';
$('a_group_' + matches[1]).innerHTML = '[-]';
}
}
}
function hide_all() {
var tbodys = $("cpform").getElementsByTagName('tbody');
for(var i = 0; i < tbodys.length; i++) {
var re = /^group_(\d+)$/;
var matches = re.exec(tbodys[i].id);
if(matches != null) {
tbodys[i].style.display = 'none';
$('a_group_' + matches[1]).innerHTML = '[+]';
}
}
}
function srchforum() {
var fname = $('srchforumipt').value;
if(!fname) return false;
var inputs = $("cpform").getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].name.match(/^name\[\d+\]$/)) {
if(inputs[i].value.substr(0, fname.length).toLowerCase() == fname.toLowerCase()) {
inputs[i].parentNode.parentNode.parentNode.parentNode.style.display = '';
inputs[i].parentNode.parentNode.parentNode.style.background = '#eee';
window.scrollTo(0, fetchOffset(inputs[i]).top - 100);
return false;
}
}
}
return false;
}
function setfaq(obj, id) {
if(!$(id)) {
return;
}
$(id).style.display = '';
if(!obj.onmouseout) {
obj.onmouseout = function () {
$(id).style.display = 'none';
}
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common.js 22634 2011-05-16 05:52:08Z monkey $
*/
var BROWSER = {};
var USERAGENT = navigator.userAgent.toLowerCase();
browserVersion({'ie':'msie','firefox':'','chrome':'','opera':'','safari':'','mozilla':'','webkit':'','maxthon':'','qq':'qqbrowser'});
if(BROWSER.safari) {
BROWSER.firefox = true;
}
BROWSER.opera = BROWSER.opera ? opera.version() : 0;
HTMLNODE = document.getElementsByTagName('head')[0].parentNode;
if(BROWSER.ie) {
BROWSER.iemode = parseInt(typeof document.documentMode != 'undefined' ? document.documentMode : BROWSER.ie);
HTMLNODE.className = 'ie_all ie' + BROWSER.iemode;
}
var CSSLOADED = [];
var JSLOADED = [];
var JSMENU = [];
JSMENU['active'] = [];
JSMENU['timer'] = [];
JSMENU['drag'] = [];
JSMENU['layer'] = 0;
JSMENU['zIndex'] = {'win':200,'menu':300,'dialog':400,'prompt':500};
JSMENU['float'] = '';
var AJAX = [];
AJAX['url'] = [];
AJAX['stack'] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var CURRENTSTYPE = null;
var discuz_uid = isUndefined(discuz_uid) ? 0 : discuz_uid;
var creditnotice = isUndefined(creditnotice) ? '' : creditnotice;
var cookiedomain = isUndefined(cookiedomain) ? '' : cookiedomain;
var cookiepath = isUndefined(cookiepath) ? '' : cookiepath;
var EXTRAFUNC = [], EXTRASTR = '';
EXTRAFUNC['showmenu'] = [];
var DISCUZCODE = [];
DISCUZCODE['num'] = '-1';
DISCUZCODE['html'] = [];
var USERABOUT_BOX = true;
var USERCARDST = null;
var CLIPBOARDSWFDATA = '';
var NOTICETITLE = [];
if(BROWSER.firefox && window.HTMLElement) {
HTMLElement.prototype.__defineSetter__('outerHTML', function(sHTML) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r.createContextualFragment(sHTML);
this.parentNode.replaceChild(df,this);
return sHTML;
});
HTMLElement.prototype.__defineGetter__('outerHTML', function() {
var attr;
var attrs = this.attributes;
var str = '<' + this.tagName.toLowerCase();
for(var i = 0;i < attrs.length;i++){
attr = attrs[i];
if(attr.specified)
str += ' ' + attr.name + '="' + attr.value + '"';
}
if(!this.canHaveChildren) {
return str + '>';
}
return str + '>' + this.innerHTML + '</' + this.tagName.toLowerCase() + '>';
});
HTMLElement.prototype.__defineGetter__('canHaveChildren', function() {
switch(this.tagName.toLowerCase()) {
case 'area':case 'base':case 'basefont':case 'col':case 'frame':case 'hr':case 'img':case 'br':case 'input':case 'isindex':case 'link':case 'meta':case 'param':
return false;
}
return true;
});
}
function $(id) {
return !id ? null : document.getElementById(id);
}
function $C(classname, ele, tag) {
var returns = [];
ele = ele || document;
tag = tag || '*';
if(ele.getElementsByClassName) {
var eles = ele.getElementsByClassName(classname);
if(tag != '*') {
for (var i = 0, L = eles.length; i < L; i++) {
if (eles[i].tagName.toLowerCase() == tag.toLowerCase()) {
returns.push(eles[i]);
}
}
} else {
returns = eles;
}
}else {
eles = ele.getElementsByTagName(tag);
var pattern = new RegExp("(^|\\s)"+classname+"(\\s|$)");
for (i = 0, L = eles.length; i < L; i++) {
if (pattern.test(eles[i].className)) {
returns.push(eles[i]);
}
}
}
return returns;
}
function _attachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(eventobj.attachEvent) {
obj.attachEvent('on' + evt, func);
}
}
function _detachEvent(obj, evt, func, eventobj) {
eventobj = !eventobj ? obj : eventobj;
if(obj.removeEventListener) {
obj.removeEventListener(evt, func, false);
} else if(eventobj.detachEvent) {
obj.detachEvent('on' + evt, func);
}
}
function browserVersion(types) {
var other = 1;
for(i in types) {
var v = types[i] ? types[i] : i;
if(USERAGENT.indexOf(v) != -1) {
var re = new RegExp(v + '(\\/|\\s)([\\d\\.]+)', 'ig');
var matches = re.exec(USERAGENT);
var ver = matches != null ? matches[2] : 0;
other = ver !== 0 && v != 'mozilla' ? 0 : other;
}else {
var ver = 0;
}
eval('BROWSER.' + i + '= ver');
}
BROWSER.other = other;
}
function getEvent() {
if(document.all) return window.event;
func = getEvent.caller;
while(func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof(arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
return arg0;
}
}
func=func.caller;
}
return null;
}
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function in_array(needle, haystack) {
if(typeof needle == 'string' || typeof needle == 'number') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function trim(str) {
return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}
function strlen(str) {
return (BROWSER.ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
function mb_strlen(str) {
var len = 0;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
}
return len;
}
function mb_cutstr(str, maxlen, dot) {
var len = 0;
var ret = '';
var dot = !dot ? '...' : '';
maxlen = maxlen - dot.length;
for(var i = 0; i < str.length; i++) {
len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (charset == 'utf-8' ? 3 : 2) : 1;
if(len > maxlen) {
ret += dot;
break;
}
ret += str.substr(i, 1);
}
return ret;
}
function preg_replace(search, replace, str, regswitch) {
var regswitch = !regswitch ? 'ig' : regswitch;
var len = search.length;
for(var i = 0; i < len; i++) {
re = new RegExp(search[i], regswitch);
str = str.replace(re, typeof replace == 'string' ? replace : (replace[i] ? replace[i] : replace[0]));
}
return str;
}
function htmlspecialchars(str) {
return preg_replace(['&', '<', '>', '"'], ['&', '<', '>', '"'], str);
}
function display(id) {
var obj = $(id);
if(obj.style.visibility) {
obj.style.visibility = obj.style.visibility == 'visible' ? 'hidden' : 'visible';
} else {
obj.style.display = obj.style.display == '' ? 'none' : '';
}
}
function checkall(form, prefix, checkall) {
var checkall = checkall ? checkall : 'chkall';
count = 0;
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name && e.name != checkall && (!prefix || (prefix && e.name.match(prefix)))) {
e.checked = form.elements[checkall].checked;
if(e.checked) {
count++;
}
}
}
return count;
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
var expires = new Date();
if(cookieValue == '' || seconds < 0) {
cookieValue = '';
seconds = -2592000;
}
expires.setTime(expires.getTime() + seconds * 1000);
domain = !domain ? cookiedomain : domain;
path = !path ? cookiepath : path;
document.cookie = escape(cookiepre + cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function getcookie(name, nounescape) {
name = cookiepre + name;
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
if(cookie_start == -1) {
return '';
} else {
var v = document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length));
return !nounescape ? unescape(v) : v;
}
}
function Ajax(recvType, waitId) {
for(var stackId = 0; stackId < AJAX['stack'].length && AJAX['stack'][stackId] != 0; stackId++);
AJAX['stack'][stackId] = 1;
var aj = new Object();
aj.loading = '请稍候...';
aj.recvType = recvType ? recvType : 'XML';
aj.waitId = waitId ? $(waitId) : null;
aj.resultHandle = null;
aj.sendString = '';
aj.targetUrl = '';
aj.stackId = 0;
aj.stackId = stackId;
aj.setLoading = function(loading) {
if(typeof loading !== 'undefined' && loading !== null) aj.loading = loading;
};
aj.setRecvType = function(recvtype) {
aj.recvType = recvtype;
};
aj.setWaitId = function(waitid) {
aj.waitId = typeof waitid == 'object' ? waitid : $(waitid);
};
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) {
request.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) {
return request;
}
} catch(e) {}
}
}
return request;
};
aj.XMLHttpRequest = aj.createXMLHttpRequest();
aj.showLoading = function() {
if(aj.waitId && (aj.XMLHttpRequest.readyState != 4 || aj.XMLHttpRequest.status != 200)) {
aj.waitId.style.display = '';
aj.waitId.innerHTML = '<span><img src="' + IMGDIR + '/loading.gif" class="vm"> ' + aj.loading + '</span>';
}
};
aj.processHandle = function() {
if(aj.XMLHttpRequest.readyState == 4 && aj.XMLHttpRequest.status == 200) {
for(k in AJAX['url']) {
if(AJAX['url'][k] == aj.targetUrl) {
AJAX['url'][k] = null;
}
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
}
if(aj.recvType == 'HTML') {
aj.resultHandle(aj.XMLHttpRequest.responseText, aj);
} else if(aj.recvType == 'XML') {
if(!aj.XMLHttpRequest.responseXML || !aj.XMLHttpRequest.responseXML.lastChild || aj.XMLHttpRequest.responseXML.lastChild.localName == 'parsererror') {
aj.resultHandle('<a href="' + aj.targetUrl + '" target="_blank" style="color:red">内部错误,无法显示此内容</a>' , aj);
} else {
aj.resultHandle(aj.XMLHttpRequest.responseXML.lastChild.firstChild.nodeValue, aj);
}
}
AJAX['stack'][aj.stackId] = 0;
}
};
aj.get = function(targetUrl, resultHandle) {
targetUrl = hostconvert(targetUrl);
setTimeout(function(){aj.showLoading()}, 250);
if(in_array(targetUrl, AJAX['url'])) {
return false;
} else {
AJAX['url'].push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
var attackevasive = isUndefined(attackevasive) ? 0 : attackevasive;
var delay = attackevasive & 1 ? (aj.stackId + 1) * 1001 : 100;
if(window.XMLHttpRequest) {
setTimeout(function(){
aj.XMLHttpRequest.open('GET', aj.targetUrl);
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send(null);}, delay);
} else {
setTimeout(function(){
aj.XMLHttpRequest.open("GET", targetUrl, true);
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send();}, delay);
}
};
aj.post = function(targetUrl, sendString, resultHandle) {
targetUrl = hostconvert(targetUrl);
setTimeout(function(){aj.showLoading()}, 250);
if(in_array(targetUrl, AJAX['url'])) {
return false;
} else {
AJAX['url'].push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.XMLHttpRequest.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.XMLHttpRequest.open('POST', targetUrl);
aj.XMLHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.XMLHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
aj.XMLHttpRequest.send(aj.sendString);
};
return aj;
}
function getHost(url) {
var host = "null";
if(typeof url == "undefined"|| null == url) {
url = window.location.href;
}
var regex = /^\w+\:\/\/([^\/]*).*/;
var match = url.match(regex);
if(typeof match != "undefined" && null != match) {
host = match[1];
}
return host;
}
function hostconvert(url) {
if(!url.match(/^https?:\/\//)) url = SITEURL + url;
var url_host = getHost(url);
var cur_host = getHost().toLowerCase();
if(url_host && cur_host != url_host) {
url = url.replace(url_host, cur_host);
}
return url;
}
function newfunction(func) {
var args = [];
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(event) {
doane(event);
window[func].apply(window, args);
return false;
}
}
function evalscript(s) {
if(s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
var arr = [];
while(arr = p.exec(s)) {
var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
var arr1 = [];
arr1 = p1.exec(arr[0]);
if(arr1) {
appendscript(arr1[1], '', arr1[2], arr1[3]);
} else {
p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
arr1 = p1.exec(arr[0]);
appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
}
}
return s;
}
var safescripts = {}, evalscripts = [];
function safescript(id, call, seconds, times, timeoutcall, endcall, index) {
seconds = seconds || 1000;
times = times || 0;
var checked = true;
try {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
} catch(e) {
checked = false;
}
if(!checked) {
if(!safescripts[id] || !index) {
safescripts[id] = safescripts[id] || [];
safescripts[id].push({
'times':0,
'si':setInterval(function () {
safescript(id, call, seconds, times, timeoutcall, endcall, safescripts[id].length);
}, seconds)
});
} else {
index = (index || 1) - 1;
safescripts[id][index]['times']++;
if(safescripts[id][index]['times'] >= times) {
clearInterval(safescripts[id][index]['si']);
if(typeof timeoutcall == 'function') {
timeoutcall();
} else {
eval(timeoutcall);
}
}
}
} else {
try {
index = (index || 1) - 1;
if(safescripts[id][index]['si']) {
clearInterval(safescripts[id][index]['si']);
}
if(typeof endcall == 'function') {
endcall();
} else {
eval(endcall);
}
} catch(e) {}
}
}
function $F(func, args, script) {
var run = function () {
var argc = args.length, s = '';
for(i = 0;i < argc;i++) {
s += ',args[' + i + ']';
}
eval('var check = typeof ' + func + ' == \'function\'');
if(check) {
eval(func + '(' + s.substr(1) + ')');
} else {
setTimeout(function () { checkrun(); }, 50);
}
};
var checkrun = function () {
if(JSLOADED[src]) {
run();
} else {
setTimeout(function () { checkrun(); }, 50);
}
};
script = script || 'common_extra';
src = JSPATH + script + '.js?' + VERHASH;
if(!JSLOADED[src]) {
appendscript(src);
}
checkrun();
}
function appendscript(src, text, reload, charset) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
try {
if(src) {
scriptNode.src = src;
scriptNode.onloadDone = false;
scriptNode.onload = function () {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
};
scriptNode.onreadystatechange = function () {
if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode.onloadDone) {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
}
};
} else if(text){
scriptNode.text = text;
}
document.getElementsByTagName('head')[0].appendChild(scriptNode);
} catch(e) {}
}
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}
function ajaxupdateevents(obj, tagName) {
tagName = tagName ? tagName : 'A';
var objs = obj.getElementsByTagName(tagName);
for(k in objs) {
var o = objs[k];
ajaxupdateevent(o);
}
}
function ajaxupdateevent(o) {
if(typeof o == 'object' && o.getAttribute) {
if(o.getAttribute('ajaxtarget')) {
if(!o.id) o.id = Math.random();
var ajaxevent = o.getAttribute('ajaxevent') ? o.getAttribute('ajaxevent') : 'click';
var ajaxurl = o.getAttribute('ajaxurl') ? o.getAttribute('ajaxurl') : o.href;
_attachEvent(o, ajaxevent, newfunction('ajaxget', ajaxurl, o.getAttribute('ajaxtarget'), o.getAttribute('ajaxwaitid'), o.getAttribute('ajaxloading'), o.getAttribute('ajaxdisplay')));
if(o.getAttribute('ajaxfunc')) {
o.getAttribute('ajaxfunc').match(/(\w+)\((.+?)\)/);
_attachEvent(o, ajaxevent, newfunction(RegExp.$1, RegExp.$2));
}
}
}
}
function ajaxget(url, showid, waitid, loading, display, recall) {
waitid = typeof waitid == 'undefined' || waitid === null ? showid : waitid;
var x = new Ajax();
x.setLoading(loading);
x.setWaitId(waitid);
x.display = typeof display == 'undefined' || display == null ? '' : display;
x.showId = $(showid);
if(url.substr(strlen(url) - 1) == '#') {
url = url.substr(0, strlen(url) - 1);
x.autogoto = 1;
}
var url = url + '&inajax=1&ajaxtarget=' + showid;
x.get(url, function(s, x) {
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
x.showId.style.display = x.display;
ajaxinnerhtml(x.showId, s);
ajaxupdateevents(x.showId);
if(x.autogoto) scroll(0, x.showId.offsetTop);
}
}
ajaxerror = null;
if(recall && typeof recall == 'function') {
recall();
} else if(recall) {
eval(recall);
}
if(!evaled) evalscript(s);
});
}
function ajaxpost(formid, showid, waitid, showidclass, submitbtn, recall) {
var waitid = typeof waitid == 'undefined' || waitid === null ? showid : (waitid !== '' ? waitid : '');
var showidclass = !showidclass ? '' : showidclass;
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
var formtarget = $(formid).target;
var handleResult = function() {
var s = '';
var evaled = false;
showloading('none');
try {
s = $(ajaxframeid).contentWindow.document.XMLDocument.text;
} catch(e) {
try {
s = $(ajaxframeid).contentWindow.document.documentElement.firstChild.wholeText;
} catch(e) {
try {
s = $(ajaxframeid).contentWindow.document.documentElement.firstChild.nodeValue;
} catch(e) {
s = '内部错误,无法显示此内容';
}
}
}
if(s != '' && s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(showidclass) {
if(showidclass != 'onerror') {
$(showid).className = showidclass;
} else {
showError(s);
ajaxerror = true;
}
}
if(submitbtn) {
submitbtn.disabled = false;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
ajaxinnerhtml($(showid), s);
}
ajaxerror = null;
if($(formid)) $(formid).target = formtarget;
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
if(!evaled) evalscript(s);
ajaxframe.loading = 0;
$('append_parent').removeChild(ajaxframe.parentNode);
};
if(!ajaxframe) {
var div = document.createElement('div');
div.style.display = 'none';
div.innerHTML = '<iframe name="' + ajaxframeid + '" id="' + ajaxframeid + '" loading="1"></iframe>';
$('append_parent').appendChild(div);
ajaxframe = $(ajaxframeid);
} else if(ajaxframe.loading) {
return false;
}
_attachEvent(ajaxframe, 'load', handleResult);
showloading();
$(formid).target = ajaxframeid;
var action = $(formid).getAttribute('action');
action = hostconvert(action);
$(formid).action = action.replace(/\&inajax\=1/g, '')+'&inajax=1';
$(formid).submit();
if(submitbtn) {
submitbtn.disabled = true;
}
doane();
return false;
}
function ajaxmenu(ctrlObj, timeout, cache, duration, pos, recall, idclass, contentclass) {
if(!ctrlObj.getAttribute('mid')) {
var ctrlid = ctrlObj.id;
if(!ctrlid) {
ctrlObj.id = 'ajaxid_' + Math.random();
}
} else {
var ctrlid = ctrlObj.getAttribute('mid');
if(!ctrlObj.id) {
ctrlObj.id = 'ajaxid_' + Math.random();
}
}
var menuid = ctrlid + '_menu';
var menu = $(menuid);
if(isUndefined(timeout)) timeout = 3000;
if(isUndefined(cache)) cache = 1;
if(isUndefined(pos)) pos = '43';
if(isUndefined(duration)) duration = timeout > 0 ? 0 : 3;
if(isUndefined(idclass)) idclass = 'p_pop';
if(isUndefined(contentclass)) contentclass = 'p_opt';
var func = function() {
showMenu({'ctrlid':ctrlObj.id,'menuid':menuid,'duration':duration,'timeout':timeout,'pos':pos,'cache':cache,'layer':2});
if(typeof recall == 'function') {
recall();
} else {
eval(recall);
}
};
if(menu) {
if(menu.style.display == '') {
hideMenu(menuid);
} else {
func();
}
} else {
menu = document.createElement('div');
menu.id = menuid;
menu.style.display = 'none';
menu.className = idclass;
menu.innerHTML = '<div class="' + contentclass + '" id="' + menuid + '_content"></div>';
$('append_parent').appendChild(menu);
var url = (!isUndefined(ctrlObj.href) ? ctrlObj.href : ctrlObj.attributes['href'].value);
url += (url.indexOf('?') != -1 ? '&' :'?') + 'ajaxmenu=1';
ajaxget(url, menuid + '_content', 'ajaxwaitid', '', '', func);
}
doane();
}
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function showPreview(val, id) {
var showObj = $(id);
if(showObj) {
showObj.innerHTML = val.replace(/\n/ig, "<bupdateseccoder />");
}
}
function showloading(display, waiting) {
var display = display ? display : 'block';
var waiting = waiting ? waiting : '请稍候...';
$('ajaxwaitid').innerHTML = waiting;
$('ajaxwaitid').style.display = display;
}
function ajaxinnerhtml(showid, s) {
if(showid.tagName != 'TBODY') {
showid.innerHTML = s;
} else {
while(showid.firstChild) {
showid.firstChild.parentNode.removeChild(showid.firstChild);
}
var div1 = document.createElement('DIV');
div1.id = showid.id+'_div';
div1.innerHTML = '<table><tbody id="'+showid.id+'_tbody">'+s+'</tbody></table>';
$('append_parent').appendChild(div1);
var trs = div1.getElementsByTagName('TR');
var l = trs.length;
for(var i=0; i<l; i++) {
showid.appendChild(trs[0]);
}
var inputs = div1.getElementsByTagName('INPUT');
var l = inputs.length;
for(var i=0; i<l; i++) {
showid.appendChild(inputs[0]);
}
div1.parentNode.removeChild(div1);
}
}
function doane(event, preventDefault, stopPropagation) {
var preventDefault = isUndefined(preventDefault) ? 1 : preventDefault;
var stopPropagation = isUndefined(stopPropagation) ? 1 : stopPropagation;
e = event ? event : window.event;
if(!e) {
e = getEvent();
}
if(!e) {
return null;
}
if(preventDefault) {
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
if(stopPropagation) {
if(e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
return e;
}
function loadcss(cssname) {
if(!CSSLOADED[cssname]) {
if(!$('css_' + cssname)) {
css = document.createElement('link');
css.id = 'css_' + cssname,
css.type = 'text/css';
css.rel = 'stylesheet';
css.href = 'data/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
var headNode = document.getElementsByTagName("head")[0];
headNode.appendChild(css);
} else {
$('css_' + cssname).href = 'data/cache/style_' + STYLEID + '_' + cssname + '.css?' + VERHASH;
}
CSSLOADED[cssname] = 1;
}
}
function showMenu(v) {
var ctrlid = isUndefined(v['ctrlid']) ? v : v['ctrlid'];
var showid = isUndefined(v['showid']) ? ctrlid : v['showid'];
var menuid = isUndefined(v['menuid']) ? showid + '_menu' : v['menuid'];
var ctrlObj = $(ctrlid);
var menuObj = $(menuid);
if(!menuObj) return;
var mtype = isUndefined(v['mtype']) ? 'menu' : v['mtype'];
var evt = isUndefined(v['evt']) ? 'mouseover' : v['evt'];
var pos = isUndefined(v['pos']) ? '43' : v['pos'];
var layer = isUndefined(v['layer']) ? 1 : v['layer'];
var duration = isUndefined(v['duration']) ? 2 : v['duration'];
var timeout = isUndefined(v['timeout']) ? 250 : v['timeout'];
var maxh = isUndefined(v['maxh']) ? 600 : v['maxh'];
var cache = isUndefined(v['cache']) ? 1 : v['cache'];
var drag = isUndefined(v['drag']) ? '' : v['drag'];
var dragobj = drag && $(drag) ? $(drag) : menuObj;
var fade = isUndefined(v['fade']) ? 0 : v['fade'];
var cover = isUndefined(v['cover']) ? 0 : v['cover'];
var zindex = isUndefined(v['zindex']) ? JSMENU['zIndex']['menu'] : v['zindex'];
var ctrlclass = isUndefined(v['ctrlclass']) ? '' : v['ctrlclass'];
var winhandlekey = isUndefined(v['win']) ? '' : v['win'];
zindex = cover ? zindex + 500 : zindex;
if(typeof JSMENU['active'][layer] == 'undefined') {
JSMENU['active'][layer] = [];
}
for(i in EXTRAFUNC['showmenu']) {
try {
eval(EXTRAFUNC['showmenu'][i] + '()');
} catch(e) {}
}
if(evt == 'click' && in_array(menuid, JSMENU['active'][layer]) && mtype != 'win') {
hideMenu(menuid, mtype);
return;
}
if(mtype == 'menu') {
hideMenu(layer, mtype);
}
if(ctrlObj) {
if(!ctrlObj.getAttribute('initialized')) {
ctrlObj.setAttribute('initialized', true);
ctrlObj.unselectable = true;
ctrlObj.outfunc = typeof ctrlObj.onmouseout == 'function' ? ctrlObj.onmouseout : null;
ctrlObj.onmouseout = function() {
if(this.outfunc) this.outfunc();
if(duration < 3 && !JSMENU['timer'][menuid]) {
JSMENU['timer'][menuid] = setTimeout(function () {
hideMenu(menuid, mtype);
}, timeout);
}
};
ctrlObj.overfunc = typeof ctrlObj.onmouseover == 'function' ? ctrlObj.onmouseover : null;
ctrlObj.onmouseover = function(e) {
doane(e);
if(this.overfunc) this.overfunc();
if(evt == 'click') {
clearTimeout(JSMENU['timer'][menuid]);
JSMENU['timer'][menuid] = null;
} else {
for(var i in JSMENU['timer']) {
if(JSMENU['timer'][i]) {
clearTimeout(JSMENU['timer'][i]);
JSMENU['timer'][i] = null;
}
}
}
};
}
}
if(!menuObj.getAttribute('initialized')) {
menuObj.setAttribute('initialized', true);
menuObj.ctrlkey = ctrlid;
menuObj.mtype = mtype;
menuObj.layer = layer;
menuObj.cover = cover;
if(ctrlObj && ctrlObj.getAttribute('fwin')) {menuObj.scrolly = true;}
menuObj.style.position = 'absolute';
menuObj.style.zIndex = zindex + layer;
menuObj.onclick = function(e) {
return doane(e, 0, 1);
};
if(duration < 3) {
if(duration > 1) {
menuObj.onmouseover = function() {
clearTimeout(JSMENU['timer'][menuid]);
JSMENU['timer'][menuid] = null;
};
}
if(duration != 1) {
menuObj.onmouseout = function() {
JSMENU['timer'][menuid] = setTimeout(function () {
hideMenu(menuid, mtype);
}, timeout);
};
}
}
if(cover) {
var coverObj = document.createElement('div');
coverObj.id = menuid + '_cover';
coverObj.style.position = 'absolute';
coverObj.style.zIndex = menuObj.style.zIndex - 1;
coverObj.style.left = coverObj.style.top = '0px';
coverObj.style.width = '100%';
coverObj.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
coverObj.style.backgroundColor = '#000';
coverObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=50)';
coverObj.style.opacity = 0.5;
coverObj.onclick = function () { hideMenu(); };
$('append_parent').appendChild(coverObj);
_attachEvent(window, 'load', function () {
coverObj.style.height = Math.max(document.documentElement.clientHeight, document.body.offsetHeight) + 'px';
}, document);
}
}
if(drag) {
dragobj.style.cursor = 'move';
dragobj.onmousedown = function(event) {try{dragMenu(menuObj, event, 1);}catch(e){}};
}
if(cover) $(menuid + '_cover').style.display = '';
if(fade) {
var O = 0;
var fadeIn = function(O) {
if(O > 100) {
clearTimeout(fadeInTimer);
return;
}
menuObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + O + ')';
menuObj.style.opacity = O / 100;
O += 20;
var fadeInTimer = setTimeout(function () {
fadeIn(O);
}, 40);
};
fadeIn(O);
menuObj.fade = true;
} else {
menuObj.fade = false;
}
menuObj.style.display = '';
if(ctrlObj && ctrlclass) {
ctrlObj.className += ' ' + ctrlclass;
menuObj.setAttribute('ctrlid', ctrlid);
menuObj.setAttribute('ctrlclass', ctrlclass);
}
if(pos != '*') {
setMenuPosition(showid, menuid, pos);
}
if(BROWSER.ie && BROWSER.ie < 7 && winhandlekey && $('fwin_' + winhandlekey)) {
$(menuid).style.left = (parseInt($(menuid).style.left) - parseInt($('fwin_' + winhandlekey).style.left)) + 'px';
$(menuid).style.top = (parseInt($(menuid).style.top) - parseInt($('fwin_' + winhandlekey).style.top)) + 'px';
}
if(maxh && menuObj.scrollHeight > maxh) {
menuObj.style.height = maxh + 'px';
if(BROWSER.opera) {
menuObj.style.overflow = 'auto';
} else {
menuObj.style.overflowY = 'auto';
}
}
if(!duration) {
setTimeout('hideMenu(\'' + menuid + '\', \'' + mtype + '\')', timeout);
}
if(!in_array(menuid, JSMENU['active'][layer])) JSMENU['active'][layer].push(menuid);
menuObj.cache = cache;
if(layer > JSMENU['layer']) {
JSMENU['layer'] = layer;
}
}
var delayShowST = null;
function delayShow(ctrlObj, call, time) {
if(typeof ctrlObj == 'object') {
var ctrlid = ctrlObj.id;
call = call || function () { showMenu(ctrlid); };
}
var time = isUndefined(time) ? 500 : time;
delayShowST = setTimeout(function () {
if(typeof call == 'function') {
call();
} else {
eval(call);
}
}, time);
if(!ctrlObj.delayinit) {
_attachEvent(ctrlObj, 'mouseout', function() {clearTimeout(delayShowST);});
ctrlObj.delayinit = 1;
}
}
var dragMenuDisabled = false;
function dragMenu(menuObj, e, op) {
e = e ? e : window.event;
if(op == 1) {
if(dragMenuDisabled || in_array(e.target ? e.target.tagName : e.srcElement.tagName, ['TEXTAREA', 'INPUT', 'BUTTON', 'SELECT'])) {
return;
}
JSMENU['drag'] = [e.clientX, e.clientY];
JSMENU['drag'][2] = parseInt(menuObj.style.left);
JSMENU['drag'][3] = parseInt(menuObj.style.top);
document.onmousemove = function(e) {try{dragMenu(menuObj, e, 2);}catch(err){}};
document.onmouseup = function(e) {try{dragMenu(menuObj, e, 3);}catch(err){}};
doane(e);
}else if(op == 2 && JSMENU['drag'][0]) {
var menudragnow = [e.clientX, e.clientY];
menuObj.style.left = (JSMENU['drag'][2] + menudragnow[0] - JSMENU['drag'][0]) + 'px';
menuObj.style.top = (JSMENU['drag'][3] + menudragnow[1] - JSMENU['drag'][1]) + 'px';
doane(e);
}else if(op == 3) {
JSMENU['drag'] = [];
document.onmousemove = null;
document.onmouseup = null;
}
}
function setMenuPosition(showid, menuid, pos) {
var showObj = $(showid);
var menuObj = menuid ? $(menuid) : $(showid + '_menu');
if(isUndefined(pos) || !pos) pos = '43';
var basePoint = parseInt(pos.substr(0, 1));
var direction = parseInt(pos.substr(1, 1));
var important = pos.indexOf('!') != -1 ? 1 : 0;
var sxy = 0, sx = 0, sy = 0, sw = 0, sh = 0, ml = 0, mt = 0, mw = 0, mcw = 0, mh = 0, mch = 0, bpl = 0, bpt = 0;
if(!menuObj || (basePoint > 0 && !showObj)) return;
if(showObj) {
sxy = fetchOffset(showObj);
sx = sxy['left'];
sy = sxy['top'];
sw = showObj.offsetWidth;
sh = showObj.offsetHeight;
}
mw = menuObj.offsetWidth;
mcw = menuObj.clientWidth;
mh = menuObj.offsetHeight;
mch = menuObj.clientHeight;
switch(basePoint) {
case 1:
bpl = sx;
bpt = sy;
break;
case 2:
bpl = sx + sw;
bpt = sy;
break;
case 3:
bpl = sx + sw;
bpt = sy + sh;
break;
case 4:
bpl = sx;
bpt = sy + sh;
break;
}
switch(direction) {
case 0:
menuObj.style.left = (document.body.clientWidth - menuObj.clientWidth) / 2 + 'px';
mt = (document.documentElement.clientHeight - menuObj.clientHeight) / 2;
break;
case 1:
ml = bpl - mw;
mt = bpt - mh;
break;
case 2:
ml = bpl;
mt = bpt - mh;
break;
case 3:
ml = bpl;
mt = bpt;
break;
case 4:
ml = bpl - mw;
mt = bpt;
break;
}
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
if(!important) {
if(in_array(direction, [1, 4]) && ml < 0) {
ml = bpl;
if(in_array(basePoint, [1, 4])) ml += sw;
} else if(ml + mw > scrollLeft + document.body.clientWidth && sx >= mw) {
ml = bpl - mw;
if(in_array(basePoint, [2, 3])) {
ml -= sw;
} else if(basePoint == 4) {
ml += sw;
}
}
if(in_array(direction, [1, 2]) && mt < 0) {
mt = bpt;
if(in_array(basePoint, [1, 2])) mt += sh;
} else if(mt + mh > scrollTop + document.documentElement.clientHeight && sy >= mh) {
mt = bpt - mh;
if(in_array(basePoint, [3, 4])) mt -= sh;
}
}
if(pos.substr(0, 3) == '210') {
ml += 69 - sw / 2;
mt -= 5;
if(showObj.tagName == 'TEXTAREA') {
ml -= sw / 2;
mt += sh / 2;
}
}
if(direction == 0 || menuObj.scrolly) {
if(BROWSER.ie && BROWSER.ie < 7) {
if(direction == 0) mt += scrollTop;
} else {
if(menuObj.scrolly) mt -= scrollTop;
menuObj.style.position = 'fixed';
}
}
if(ml) menuObj.style.left = ml + 'px';
if(mt) menuObj.style.top = mt + 'px';
if(direction == 0 && BROWSER.ie && !document.documentElement.clientHeight) {
menuObj.style.position = 'absolute';
menuObj.style.top = (document.body.clientHeight - menuObj.clientHeight) / 2 + 'px';
}
if(menuObj.style.clip && !BROWSER.opera) {
menuObj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
function hideMenu(attr, mtype) {
attr = isUndefined(attr) ? '' : attr;
mtype = isUndefined(mtype) ? 'menu' : mtype;
if(attr == '') {
for(var i = 1; i <= JSMENU['layer']; i++) {
hideMenu(i, mtype);
}
return;
} else if(typeof attr == 'number') {
for(var j in JSMENU['active'][attr]) {
hideMenu(JSMENU['active'][attr][j], mtype);
}
return;
}else if(typeof attr == 'string') {
var menuObj = $(attr);
if(!menuObj || (mtype && menuObj.mtype != mtype)) return;
var ctrlObj = '', ctrlclass = '';
if((ctrlObj = $(menuObj.getAttribute('ctrlid'))) && (ctrlclass = menuObj.getAttribute('ctrlclass'))) {
var reg = new RegExp(' ' + ctrlclass);
ctrlObj.className = ctrlObj.className.replace(reg, '');
}
clearTimeout(JSMENU['timer'][attr]);
var hide = function() {
if(menuObj.cache) {
if(menuObj.style.visibility != 'hidden') {
menuObj.style.display = 'none';
if(menuObj.cover) $(attr + '_cover').style.display = 'none';
}
}else {
menuObj.parentNode.removeChild(menuObj);
if(menuObj.cover) $(attr + '_cover').parentNode.removeChild($(attr + '_cover'));
}
var tmp = [];
for(var k in JSMENU['active'][menuObj.layer]) {
if(attr != JSMENU['active'][menuObj.layer][k]) tmp.push(JSMENU['active'][menuObj.layer][k]);
}
JSMENU['active'][menuObj.layer] = tmp;
};
if(menuObj.fade) {
var O = 100;
var fadeOut = function(O) {
if(O == 0) {
clearTimeout(fadeOutTimer);
hide();
return;
}
menuObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + O + ')';
menuObj.style.opacity = O / 100;
O -= 20;
var fadeOutTimer = setTimeout(function () {
fadeOut(O);
}, 40);
};
fadeOut(O);
} else {
hide();
}
}
}
function getCurrentStyle(obj, cssproperty, csspropertyNS) {
if(obj.style[cssproperty]){
return obj.style[cssproperty];
}
if (obj.currentStyle) {
return obj.currentStyle[cssproperty];
} else if (document.defaultView.getComputedStyle(obj, null)) {
var currentStyle = document.defaultView.getComputedStyle(obj, null);
var value = currentStyle.getPropertyValue(csspropertyNS);
if(!value){
value = currentStyle[cssproperty];
}
return value;
} else if (window.getComputedStyle) {
var currentStyle = window.getComputedStyle(obj, "");
return currentStyle.getPropertyValue(csspropertyNS);
}
}
function fetchOffset(obj, mode) {
var left_offset = 0, top_offset = 0, mode = !mode ? 0 : mode;
if(obj.getBoundingClientRect && !mode) {
var rect = obj.getBoundingClientRect();
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
if(document.documentElement.dir == 'rtl') {
scrollLeft = scrollLeft + document.documentElement.clientWidth - document.documentElement.scrollWidth;
}
left_offset = rect.left + scrollLeft - document.documentElement.clientLeft;
top_offset = rect.top + scrollTop - document.documentElement.clientTop;
}
if(left_offset <= 0 || top_offset <= 0) {
left_offset = obj.offsetLeft;
top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
position = getCurrentStyle(obj, 'position', 'position');
if(position == 'relative') {
continue;
}
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
}
return {'left' : left_offset, 'top' : top_offset};
}
function showTip(ctrlobj) {
$F('_showTip', arguments);
}
function showPrompt(ctrlid, evt, msg, timeout) {
$F('_showPrompt', arguments);
}
function showCreditPrompt() {
$F('_showCreditPrompt', []);
}
var showDialogST = null;
function showDialog(msg, mode, t, func, cover, funccancel, leftmsg, confirmtxt, canceltxt, closetime, locationtime) {
clearTimeout(showDialogST);
cover = isUndefined(cover) ? (mode == 'info' ? 0 : 1) : cover;
leftmsg = isUndefined(leftmsg) ? '' : leftmsg;
mode = in_array(mode, ['confirm', 'notice', 'info', 'right']) ? mode : 'alert';
var menuid = 'fwin_dialog';
var menuObj = $(menuid);
confirmtxtdefault = '确定';
closetime = isUndefined(closetime) ? '' : closetime;
closefunc = function () {
if(typeof func == 'function') func();
else eval(func);
hideMenu(menuid, 'dialog');
};
if(closetime) {
leftmsg = closetime + ' 秒后窗口关闭';
showDialogST = setTimeout(closefunc, closetime * 1000);
}
locationtime = isUndefined(locationtime) ? '' : locationtime;
if(locationtime) {
leftmsg = locationtime + ' 秒后页面跳转';
showDialogST = setTimeout(closefunc, locationtime * 1000);
confirmtxtdefault = '立即跳转';
}
confirmtxt = confirmtxt ? confirmtxt : confirmtxtdefault;
canceltxt = canceltxt ? canceltxt : '取消';
if(menuObj) hideMenu('fwin_dialog', 'dialog');
menuObj = document.createElement('div');
menuObj.style.display = 'none';
menuObj.className = 'fwinmask';
menuObj.id = menuid;
$('append_parent').appendChild(menuObj);
var hidedom = '';
if(!BROWSER.ie) {
hidedom = '<style type="text/css">object{visibility:hidden;}</style>';
}
var s = hidedom + '<table cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"></td><td class="t_r"></td></tr><tr><td class="m_l"> </td><td class="m_c"><h3 class="flb"><em>';
s += t ? t : '提示信息';
s += '</em><span><a href="javascript:;" id="fwin_dialog_close" class="flbc" onclick="hideMenu(\'' + menuid + '\', \'dialog\')" title="关闭">关闭</a></span></h3>';
if(mode == 'info') {
s += msg ? msg : '';
} else {
s += '<div class="c altw"><div class="' + (mode == 'alert' ? 'alert_error' : (mode == 'right' ? 'alert_right' : 'alert_info')) + '"><p>' + msg + '</p></div></div>';
s += '<p class="o pns">' + (leftmsg ? '<span class="z xg1">' + leftmsg + '</span>' : '') + '<button id="fwin_dialog_submit" value="true" class="pn pnc"><strong>'+confirmtxt+'</strong></button>';
s += mode == 'confirm' ? '<button id="fwin_dialog_cancel" value="true" class="pn" onclick="hideMenu(\'' + menuid + '\', \'dialog\')"><strong>'+canceltxt+'</strong></button>' : '';
s += '</p>';
}
s += '</td><td class="m_r"></td></tr><tr><td class="b_l"></td><td class="b_c"></td><td class="b_r"></td></tr></table>';
menuObj.innerHTML = s;
if($('fwin_dialog_submit')) $('fwin_dialog_submit').onclick = function() {
if(typeof func == 'function') func();
else eval(func);
hideMenu(menuid, 'dialog');
};
if($('fwin_dialog_cancel')) {
$('fwin_dialog_cancel').onclick = function() {
if(typeof funccancel == 'function') funccancel();
else eval(funccancel);
hideMenu(menuid, 'dialog');
};
$('fwin_dialog_close').onclick = $('fwin_dialog_cancel').onclick;
}
showMenu({'mtype':'dialog','menuid':menuid,'duration':3,'pos':'00','zindex':JSMENU['zIndex']['dialog'],'cache':0,'cover':cover});
try {
if($('fwin_dialog_submit')) $('fwin_dialog_submit').focus();
} catch(e) {}
}
function showWindow(k, url, mode, cache, menuv) {
mode = isUndefined(mode) ? 'get' : mode;
cache = isUndefined(cache) ? 1 : cache;
var menuid = 'fwin_' + k;
var menuObj = $(menuid);
var drag = null;
var loadingst = null;
var hidedom = '';
if(disallowfloat && disallowfloat.indexOf(k) != -1) {
if(BROWSER.ie) url += (url.indexOf('?') != -1 ? '&' : '?') + 'referer=' + escape(location.href);
location.href = url;
doane();
return;
}
var fetchContent = function() {
if(mode == 'get') {
menuObj.url = url;
url += (url.search(/\?/) > 0 ? '&' : '?') + 'infloat=yes&handlekey=' + k;
url += cache == -1 ? '&t='+(+ new Date()) : '';
ajaxget(url, 'fwin_content_' + k, null, '', '', function() {initMenu();show();});
} else if(mode == 'post') {
menuObj.act = $(url).action;
ajaxpost(url, 'fwin_content_' + k, '', '', '', function() {initMenu();show();});
}
if(parseInt(BROWSER.ie) != 6) {
loadingst = setTimeout(function() {showDialog('', 'info', '<img src="' + IMGDIR + '/loading.gif"> 请稍候...')}, 500);
}
};
var initMenu = function() {
clearTimeout(loadingst);
var objs = menuObj.getElementsByTagName('*');
var fctrlidinit = false;
for(var i = 0; i < objs.length; i++) {
if(objs[i].id) {
objs[i].setAttribute('fwin', k);
}
if(objs[i].className == 'flb' && !fctrlidinit) {
if(!objs[i].id) objs[i].id = 'fctrl_' + k;
drag = objs[i].id;
fctrlidinit = true;
}
}
};
var show = function() {
hideMenu('fwin_dialog', 'dialog');
v = {'mtype':'win','menuid':menuid,'duration':3,'pos':'00','zindex':JSMENU['zIndex']['win'],'drag':typeof drag == null ? '' : drag,'cache':cache};
for(k in menuv) {
v[k] = menuv[k];
}
showMenu(v);
};
if(!menuObj) {
menuObj = document.createElement('div');
menuObj.id = menuid;
menuObj.className = 'fwinmask';
menuObj.style.display = 'none';
$('append_parent').appendChild(menuObj);
evt = ' style="cursor:move" onmousedown="dragMenu($(\'' + menuid + '\'), event, 1)" ondblclick="hideWindow(\'' + k + '\')"';
if(!BROWSER.ie) {
hidedom = '<style type="text/css">object{visibility:hidden;}</style>';
}
menuObj.innerHTML = hidedom + '<table cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"' + evt + '></td><td class="t_r"></td></tr><tr><td class="m_l"' + evt + ')"> </td><td class="m_c" id="fwin_content_' + k + '">'
+ '</td><td class="m_r"' + evt + '"></td></tr><tr><td class="b_l"></td><td class="b_c"' + evt + '></td><td class="b_r"></td></tr></table>';
if(mode == 'html') {
$('fwin_content_' + k).innerHTML = url;
initMenu();
show();
} else {
fetchContent();
}
} else if((mode == 'get' && (url != menuObj.url || cache != 1)) || (mode == 'post' && $(url).action != menuObj.act)) {
fetchContent();
} else {
show();
}
doane();
}
function showError(msg) {
var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig;
msg = msg.replace(p, '');
if(msg !== '') {
showDialog(msg, 'alert', '错误信息', null, true, null, '', '', '', 3);
}
}
function hideWindow(k, all, clear) {
all = isUndefined(all) ? 1 : all;
clear = isUndefined(clear) ? 1 : clear;
hideMenu('fwin_' + k, 'win');
if(clear && $('fwin_' + k)) {
$('append_parent').removeChild($('fwin_' + k));
}
if(all) {
hideMenu();
}
}
function AC_FL_RunContent() {
var str = '';
var ret = AC_GetArgs(arguments, "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
if(BROWSER.ie && !BROWSER.opera) {
str += '<object ';
for (var i in ret.objAttrs) {
str += i + '="' + ret.objAttrs[i] + '" ';
}
str += '>';
for (var i in ret.params) {
str += '<param name="' + i + '" value="' + ret.params[i] + '" /> ';
}
str += '</object>';
} else {
str += '<embed ';
for (var i in ret.embedAttrs) {
str += i + '="' + ret.embedAttrs[i] + '" ';
}
str += '></embed>';
}
return str;
}
function AC_GetArgs(args, classid, mimeType) {
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i = 0; i < args.length; i = i + 2){
var currArg = args[i].toLowerCase();
switch (currArg){
case "classid":break;
case "pluginspage":ret.embedAttrs[args[i]] = 'http://www.macromedia.com/go/getflashplayer';break;
case "src":ret.embedAttrs[args[i]] = args[i+1];ret.params["movie"] = args[i+1];break;
case "codebase":ret.objAttrs[args[i]] = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0';break;
case "onafterupdate":case "onbeforeupdate":case "onblur":case "oncellchange":case "onclick":case "ondblclick":case "ondrag":case "ondragend":
case "ondragenter":case "ondragleave":case "ondragover":case "ondrop":case "onfinish":case "onfocus":case "onhelp":case "onmousedown":
case "onmouseup":case "onmouseover":case "onmousemove":case "onmouseout":case "onkeypress":case "onkeydown":case "onkeyup":case "onload":
case "onlosecapture":case "onpropertychange":case "onreadystatechange":case "onrowsdelete":case "onrowenter":case "onrowexit":case "onrowsinserted":case "onstart":
case "onscroll":case "onbeforeeditfocus":case "onactivate":case "onbeforedeactivate":case "ondeactivate":case "type":
case "id":ret.objAttrs[args[i]] = args[i+1];break;
case "width":case "height":case "align":case "vspace": case "hspace":case "class":case "title":case "accesskey":case "name":
case "tabindex":ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];break;
default:ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
}
}
ret.objAttrs["classid"] = classid;
if(mimeType) {
ret.embedAttrs["type"] = mimeType;
}
return ret;
}
function simulateSelect(selectId, widthvalue) {
var selectObj = $(selectId);
if(!selectObj) return;
if(BROWSER.other) {
if(selectObj.getAttribute('change')) {
selectObj.onchange = function () {eval(selectObj.getAttribute('change'));}
}
return;
}
var widthvalue = widthvalue ? widthvalue : 70;
var defaultopt = selectObj.options[0] ? selectObj.options[0].innerHTML : '';
var defaultv = '';
var menuObj = document.createElement('div');
var ul = document.createElement('ul');
var handleKeyDown = function(e) {
e = BROWSER.ie ? event : e;
if(e.keyCode == 40 || e.keyCode == 38) doane(e);
};
var selectwidth = (selectObj.getAttribute('width', i) ? selectObj.getAttribute('width', i) : widthvalue) + 'px';
var tabindex = selectObj.getAttribute('tabindex', i) ? selectObj.getAttribute('tabindex', i) : 1;
for(var i = 0; i < selectObj.options.length; i++) {
var li = document.createElement('li');
li.innerHTML = selectObj.options[i].innerHTML;
li.k_id = i;
li.k_value = selectObj.options[i].value;
if(selectObj.options[i].selected) {
defaultopt = selectObj.options[i].innerHTML;
defaultv = selectObj.options[i].value;
li.className = 'current';
selectObj.setAttribute('selecti', i);
}
li.onclick = function() {
if($(selectId + '_ctrl').innerHTML != this.innerHTML) {
var lis = menuObj.getElementsByTagName('li');
lis[$(selectId).getAttribute('selecti')].className = '';
this.className = 'current';
$(selectId + '_ctrl').innerHTML = this.innerHTML;
$(selectId).setAttribute('selecti', this.k_id);
$(selectId).options.length = 0;
$(selectId).options[0] = new Option('', this.k_value);
eval(selectObj.getAttribute('change'));
}
hideMenu(menuObj.id);
return false;
};
ul.appendChild(li);
}
selectObj.options.length = 0;
selectObj.options[0]= new Option('', defaultv);
selectObj.style.display = 'none';
selectObj.outerHTML += '<a href="javascript:;" id="' + selectId + '_ctrl" style="width:' + selectwidth + '" tabindex="' + tabindex + '">' + defaultopt + '</a>';
menuObj.id = selectId + '_ctrl_menu';
menuObj.className = 'sltm';
menuObj.style.display = 'none';
menuObj.style.width = selectwidth;
menuObj.appendChild(ul);
$('append_parent').appendChild(menuObj);
$(selectId + '_ctrl').onclick = function(e) {
$(selectId + '_ctrl_menu').style.width = selectwidth;
showMenu({'ctrlid':(selectId == 'loginfield' ? 'account' : selectId + '_ctrl'),'menuid':selectId + '_ctrl_menu','evt':'click','pos':'43'});
doane(e);
};
$(selectId + '_ctrl').onfocus = menuObj.onfocus = function() {
_attachEvent(document.body, 'keydown', handleKeyDown);
};
$(selectId + '_ctrl').onblur = menuObj.onblur = function() {
_detachEvent(document.body, 'keydown', handleKeyDown);
};
$(selectId + '_ctrl').onkeyup = function(e) {
e = e ? e : window.event;
value = e.keyCode;
if(value == 40 || value == 38) {
if(menuObj.style.display == 'none') {
$(selectId + '_ctrl').onclick();
} else {
lis = menuObj.getElementsByTagName('li');
selecti = selectObj.getAttribute('selecti');
lis[selecti].className = '';
if(value == 40) {
selecti = parseInt(selecti) + 1;
} else if(value == 38) {
selecti = parseInt(selecti) - 1;
}
if(selecti < 0) {
selecti = lis.length - 1
} else if(selecti > lis.length - 1) {
selecti = 0;
}
lis[selecti].className = 'current';
selectObj.setAttribute('selecti', selecti);
lis[selecti].parentNode.scrollTop = lis[selecti].offsetTop;
}
} else if(value == 13) {
var lis = menuObj.getElementsByTagName('li');
lis[selectObj.getAttribute('selecti')].onclick();
} else if(value == 27) {
hideMenu(menuObj.id);
}
};
}
function switchTab(prefix, current, total, activeclass) {
$F('_switchTab', arguments);
}
function imageRotate(imgid, direct) {
$F('_imageRotate', arguments);
}
function thumbImg(obj, method) {
if(!obj) {
return;
}
obj.onload = null;
file = obj.src;
zw = obj.offsetWidth;
zh = obj.offsetHeight;
if(zw < 2) {
if(!obj.id) {
obj.id = 'img_' + Math.random();
}
setTimeout("thumbImg($('" + obj.id + "'), " + method + ")", 100);
return;
}
zr = zw / zh;
method = !method ? 0 : 1;
if(method) {
fixw = obj.getAttribute('_width');
fixh = obj.getAttribute('_height');
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
}
if(zh > fixh) {
zh = fixh;
zw = zh * zr;
}
} else {
fixw = typeof imagemaxwidth == 'undefined' ? '600' : imagemaxwidth;
if(zw > fixw) {
zw = fixw;
zh = zw / zr;
obj.style.cursor = 'pointer';
if(!obj.onclick) {
obj.onclick = function() {
zoom(obj, obj.src);
};
}
}
}
obj.width = zw;
obj.height = zh;
}
var zoomstatus = 1;
function zoom(obj, zimg, nocover, pn) {
$F('_zoom', arguments);
}
function showselect(obj, inpid, t, rettype) {
$F('_showselect', arguments);
}
function showColorBox(ctrlid, layer, k, bgcolor) {
$F('_showColorBox', arguments);
}
function ctrlEnter(event, btnId, onlyEnter) {
if(isUndefined(onlyEnter)) onlyEnter = 0;
if((event.ctrlKey || onlyEnter) && event.keyCode == 13) {
$(btnId).click();
return false;
}
return true;
}
function parseurl(str, mode, parsecode) {
if(isUndefined(parsecode)) parsecode = true;
if(parsecode) str= str.replace(/\s*\[code\]([\s\S]+?)\[\/code\]\s*/ig, function($1, $2) {return codetag($2);});
str = str.replace(/([^>=\]"'\/@]|^)((((https?|ftp|gopher|news|telnet|rtsp|mms|callto|bctp|ed2k|thunder|qqdl|synacast):\/\/))([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&;~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w>=\]"'\/@]|^)((www\.)([\w\-]+\.)*[:\.@\-\w\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&;~`@':+!#]*)*)/ig, mode == 'html' ? '$1<a href="$2" target="_blank">$2</a>' : '$1[url]$2[/url]');
str = str.replace(/([^\w->=\]:"'\.\/]|^)(([\-\.\w]+@[\.\-\w]+(\.\w+)+))/ig, mode == 'html' ? '$1<a href="mailto:$2">$2</a>' : '$1[email]$2[/email]');
if(parsecode) {
for(var i = 0; i <= DISCUZCODE['num']; i++) {
str = str.replace("[\tDISCUZ_CODE_" + i + "\t]", DISCUZCODE['html'][i]);
}
}
return str;
}
function codetag(text) {
DISCUZCODE['num']++;
if(typeof wysiwyg != 'undefined' && wysiwyg) text = text.replace(/<br[^\>]*>/ig, '\n').replace(/<(\/|)[A-Za-z].*?>/ig, '');
DISCUZCODE['html'][DISCUZCODE['num']] = '[code]' + text + '[/code]';
return '[\tDISCUZ_CODE_' + DISCUZCODE['num'] + '\t]';
}
function saveUserdata(name, data) {
if(BROWSER.ie){
if(data.length < 54889) {
with(document.documentElement) {
setAttribute("value", data);
save('Discuz_' + name);
}
}
} else if(window.localStorage){
localStorage.setItem('Discuz_' + name, data);
} else if(window.sessionStorage){
sessionStorage.setItem('Discuz_' + name, data);
}
setcookie('clearUserdata', '', -1);
}
function loadUserdata(name) {
if(BROWSER.ie){
with(document.documentElement) {
load('Discuz_' + name);
return getAttribute("value");
}
} else if(window.localStorage){
return localStorage.getItem('Discuz_' + name);
} else if(window.sessionStorage){
return sessionStorage.getItem('Discuz_' + name);
}
}
function initTab(frameId, type) {
$F('_initTab', arguments);
}
function openDiy(){
window.location.href = ((window.location.href + '').replace(/[\?\&]diy=yes/g, '').split('#')[0] + ( window.location.search && window.location.search.indexOf('?diy=yes') < 0 ? '&diy=yes' : '?diy=yes'));
}
function hasClass(elem, className) {
return elem.className && (" " + elem.className + " ").indexOf(" " + className + " ") != -1;
}
function runslideshow() {
$F('_runslideshow', []);
}
function toggle_collapse(objname, noimg, complex, lang) {
$F('_toggle_collapse', arguments);
}
function updatestring(str1, str2, clear) {
str2 = '_' + str2 + '_';
return clear ? str1.replace(str2, '') : (str1.indexOf(str2) == -1 ? str1 + str2 : str1);
}
function getClipboardData() {
window.document.clipboardswf.SetVariable('str', CLIPBOARDSWFDATA);
}
function setCopy(text, msg) {
$F('_setCopy', arguments);
}
function copycode(obj) {
$F('_copycode', arguments);
}
function showdistrict(container, elems, totallevel, changelevel) {
$F('_showdistrict', arguments);
}
function setDoodle(fid, oid, url, tid, from) {
$F('_setDoodle', arguments);
}
function initSearchmenu(searchform) {
var searchtxt = $(searchform + '_txt');
if(!searchtxt) {
searchtxt = $(searchform);
}
var tclass = searchtxt.className;
searchtxt.className = tclass + ' xg1';
searchtxt.onfocus = function () {
if(searchtxt.value == '请输入搜索内容') {
searchtxt.value = '';
searchtxt.className = tclass;
}
};
searchtxt.onblur = function () {
if(searchtxt.value == '' ) {
searchtxt.value = '请输入搜索内容';
searchtxt.className = tclass + ' xg1';
}
};
if(!$(searchform + '_type_menu')) return false;
var o = $(searchform + '_type');
var a = $(searchform + '_type_menu').getElementsByTagName('a');
for(var i=0; i<a.length; i++){
if(a[i].className == 'curtype'){
o.innerHTML = a[i].innerHTML;
$(searchform + '_mod').value = a[i].rel;
}
a[i].onclick = function(){
o.innerHTML = this.innerHTML;
$(searchform + '_mod').value = this.rel;
};
}
}
function searchFocus(obj) {
if(obj.value == '请输入搜索内容') {
obj.value = '';
}
}
function extstyle(css) {
$F('_extstyle', arguments);
}
function widthauto(obj) {
$F('_widthauto', arguments);
}
var secST = new Array();
function updatesecqaa(idhash) {
$F('_updatesecqaa', arguments);
}
function updateseccode(idhash, play) {
$F('_updateseccode', arguments);
}
function checksec(type, idhash, showmsg, recall) {
$F('_checksec', arguments);
}
function createPalette(colorid, id, func) {
$F('_createPalette', arguments);
}
function cardInit() {
var cardShow = function (obj) {
if(BROWSER.ie && BROWSER.ie < 7 && obj.href.indexOf('username') != -1) {
return;
}
pos = obj.getAttribute('c') == '1' ? '43' : obj.getAttribute('c');
USERCARDST = setTimeout(function() {ajaxmenu(obj, 500, 1, 2, pos, null, 'p_pop card');}, 250);
};
var a = document.body.getElementsByTagName('a');
for(var i = 0;i < a.length;i++){
if(a[i].getAttribute('c')) {
a[i].setAttribute('mid', hash(a[i].href));
a[i].onmouseover = function() {cardShow(this)};
a[i].onmouseout = function() {clearTimeout(USERCARDST);};
}
}
}
function navShow(id) {
var mnobj = $('snav_mn_' + id);
if(!mnobj) {
return;
}
var uls = $('mu').getElementsByTagName('ul');
for(i = 0;i < uls.length;i++) {
if(uls[i].className != 'cl current') {
uls[i].style.display = 'none';
}
}
if(mnobj.className != 'cl current') {
showMenu({'ctrlid':'mn_' + id,'menuid':'snav_mn_' + id,'pos':'*'});
mnobj.className = 'cl floatmu';
mnobj.style.width = ($('nv').clientWidth) + 'px';
mnobj.style.display = '';
}
}
function strLenCalc(obj, checklen, maxlen) {
var v = obj.value, charlen = 0, maxlen = !maxlen ? 200 : maxlen, curlen = maxlen, len = strlen(v);
for(var i = 0; i < v.length; i++) {
if(v.charCodeAt(i) < 0 || v.charCodeAt(i) > 255) {
curlen -= charset == 'utf-8' ? 2 : 1;
}
}
if(curlen >= len) {
$(checklen).innerHTML = curlen - len;
} else {
obj.value = mb_cutstr(v, maxlen, true);
}
}
function noticeTitle() {
NOTICETITLE = {'State':0, 'oldTitle':document.title, flashNumber:0, sleep:15};
if(!getcookie('noticeTitle')) {
window.setInterval('noticeTitleFlash();', 500);
} else {
window.setTimeout('noticeTitleFlash();', 500);
}
setcookie('noticeTitle', 1, 600);
}
function noticeTitleFlash() {
if(NOTICETITLE.flashNumber < 5 || NOTICETITLE.flashNumber > 4 && !NOTICETITLE['State']) {
document.title = (NOTICETITLE['State'] ? '【 】' : '【新提醒】') + NOTICETITLE['oldTitle'];
NOTICETITLE['State'] = !NOTICETITLE['State'];
}
NOTICETITLE.flashNumber = NOTICETITLE.flashNumber < NOTICETITLE.sleep ? ++NOTICETITLE.flashNumber : 0;
}
function relatedlinks(rlinkmsgid) {
$F('_relatedlinks', arguments);
}
function con_handle_response(response) {
return response;
}
function showTopLink() {
if($('ft')){
var viewPortHeight = parseInt(document.documentElement.clientHeight);
var scrollHeight = parseInt(document.body.getBoundingClientRect().top);
var basew = parseInt($('ft').clientWidth);
var sw = $('scrolltop').clientWidth;
if (basew < 1000) {
var left = parseInt(fetchOffset($('ft'))['left']);
left = left < sw ? left * 2 - sw : left;
$('scrolltop').style.left = ( basew + left ) + 'px';
} else {
$('scrolltop').style.left = 'auto';
$('scrolltop').style.right = 0;
}
if (BROWSER.ie && BROWSER.ie < 7) {
$('scrolltop').style.top = viewPortHeight - scrollHeight - 150 + 'px';
}
if (scrollHeight < -100) {
$('scrolltop').style.visibility = 'visible';
} else {
$('scrolltop').style.visibility = 'hidden';
}
}
}
function showCreditmenu() {
$F('_showCreditmenu', []);
}
function showUpgradeinfo() {
showMenu({'ctrlid':'g_upmine', 'pos':'21'});
}
function addFavorite(url, title) {
try {
window.external.addFavorite(url, title);
} catch (e){
try {
window.sidebar.addPanel(title, url, '');
} catch (e) {
showDialog("请按 Ctrl+D 键添加到收藏夹", 'notice');
}
}
}
function setHomepage(sURL) {
if(BROWSER.ie){
document.body.style.behavior = 'url(#default#homepage)';
document.body.setHomePage(sURL);
} else {
showDialog("非 IE 浏览器请手动将本站设为首页", 'notice');
doane();
}
}
function smilies_show(id, smcols, seditorkey) {
$F('_smilies_show', arguments, 'smilies');
}
if(typeof IN_ADMINCP == 'undefined') {
if(creditnotice != '' && getcookie('creditnotice')) {
_attachEvent(window, 'load', showCreditPrompt, document);
}
if(typeof showusercard != 'undefined' && showusercard == 1) {
_attachEvent(window, 'load', cardInit, document);
}
}
if(BROWSER.ie) {
document.documentElement.addBehavior("#default#userdata");
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_blog.js 15155 2010-08-19 08:16:19Z monkey $
*/
function validate_ajax(obj) {
var subject = $('subject');
if (subject) {
var slen = strlen(subject.value);
if (slen < 1 || slen > 80) {
alert("标题长度(1~80字符)不符合要求");
subject.focus();
return false;
}
}
if($('seccode')) {
var code = $('seccode').value;
var x = new Ajax();
x.get('cp.php?ac=common&op=seccode&code=' + code, function(s){
s = trim(s);
if(s.indexOf('succeed') == -1) {
alert(s);
$('seccode').focus();
return false;
} else {
edit_save();
obj.form.submit();
return true;
}
});
} else {
edit_save();
obj.form.submit();
return true;
}
}
function edit_album_show(id) {
var obj = $('uchome-edit-'+id);
if(id == 'album') {
$('uchome-edit-pic').style.display = 'none';
}
if(id == 'pic') {
$('uchome-edit-album').style.display = 'none';
}
if(obj.style.display == '') {
obj.style.display = 'none';
} else {
obj.style.display = '';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_uploadpic.js 17964 2010-11-09 01:11:24Z monkey $
*/
var attachexts = new Array();
var attachwh = new Array();
var insertType = 1;
var thumbwidth = parseInt(60);
var thumbheight = parseInt(60);
var extensions = 'jpg,jpeg,gif,png';
var forms;
var nowUid = 0;
var albumid = 0;
var uploadStat = 0;
var picid = 0;
var nowid = 0;
var mainForm;
var successState = false;
function delAttach(id) {
$('attachbody').removeChild($('attach_' + id).parentNode.parentNode.parentNode);
if($('attachbody').innerHTML == '') {
addAttach();
}
$('localimgpreview_' + id + '_menu') ? document.body.removeChild($('localimgpreview_' + id + '_menu')) : null;
}
function addAttach() {
newnode = $('attachbodyhidden').rows[0].cloneNode(true);
var id = nowid;
var tags;
tags = newnode.getElementsByTagName('form');
for(i in tags) {
if(tags[i].id == 'upload') {
tags[i].id = 'upload_' + id;
}
}
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach') {
tags[i].id = 'attach_' + id;
tags[i].name = 'attach';
tags[i].onchange = function() {insertAttach(id)};
tags[i].unselectable = 'on';
}
if(tags[i].id == 'albumid') {
tags[i].id = 'albumid_' + id;
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile') {
tags[i].id = 'localfile_' + id;
}
}
nowid++;
$('attachbody').appendChild(newnode);
}
addAttach();
function insertAttach(id) {
var localimgpreview = '';
var path = $('attach_' + id).value;
var ext = getExt(path);
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
if(path == '') {
return;
}
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类扩展名的图片');
return;
}
attachexts[id] = inArray(ext, ['gif', 'jpg', 'jpeg', 'png']) ? 2 : 1;
var inhtml = '<table cellspacing="0" cellpadding="0" class="up_row"><tr>';
if(typeof no_insert=='undefined') {
localfile += ' <a href="javascript:;" class="xi2" title="点击这里插入内容中当前光标的位置" onclick="insertAttachimgTag(' + id + ');return false;">[插入]</a>';
}
inhtml += '<td><strong>' + localfile +'</strong>';
inhtml += '</td><td class="d">图片描述<br/><textarea name="pic_title" cols="40" rows="2" class="pt"></textarea>';
inhtml += '</td><td class="o"><span id="showmsg' + id + '"><a href="javascript:;" onclick="delAttach(' + id + ');return false;" class="xi2">[删除]</a></span>';
inhtml += '</td></tr></table>';
$('localfile_' + id).innerHTML = inhtml;
$('attach_' + id).style.display = 'none';
addAttach();
}
function getPath(obj){
if (obj) {
if (BROWSER.ie && BROWSER.ie < 7) {
obj.select();
return document.selection.createRange().text;
} else if(BROWSER.firefox) {
if (obj.files) {
return obj.files.item(0).getAsDataURL();
}
return obj.value;
} else {
return '';
}
return obj.value;
}
}
function inArray(needle, haystack) {
if(typeof needle == 'string') {
for(var i in haystack) {
if(haystack[i] == needle) {
return true;
}
}
}
return false;
}
function insertAttachimgTag(id) {
edit_insert('[imgid=' + id + ']');
}
function uploadSubmit(obj) {
obj.disabled = true;
mainForm = obj.form;
forms = $('attachbody').getElementsByTagName("FORM");
albumid = $('uploadalbum').value;
upload();
}
function start_upload() {
$('btnupload').disabled = true;
mainForm = $('albumresultform');
forms = $('attachbody').getElementsByTagName("FORM");
upload();
}
function upload() {
if(typeof(forms[nowUid]) == 'undefined') return false;
var nid = forms[nowUid].id.split('_');
nid = nid[1];
if(nowUid>0) {
var upobj = $('showmsg'+nowid);
if(uploadStat==1) {
upobj.innerHTML = '上传成功';
successState = true;
var InputNode;
try {
var InputNode = document.createElement("<input type=\"hidden\" id=\"picid_" + picid + "\" value=\""+ nowid +"\" name=\"picids["+picid+"]\">");
} catch(e) {
var InputNode = document.createElement("input");
InputNode.setAttribute("name", "picids["+picid+"]");
InputNode.setAttribute("type", "hidden");
InputNode.setAttribute("id", "picid_" + picid);
InputNode.setAttribute("value", nowid);
}
mainForm.appendChild(InputNode);
} else {
upobj.style.color = "#f00";
upobj.innerHTML = '上传失败 '+uploadStat;
}
}
if($('showmsg'+nid) != null) {
$('showmsg'+nid).innerHTML = '上传中,请等待(<a href="javascript:;" onclick="forms[nowUid].submit();">重试</a>)';
$('albumid_'+nid).value = albumid;
forms[nowUid].submit();
} else if(nowUid+1 == forms.length) {
if(typeof (no_insert) != 'undefined') {
var albumidcheck = parseInt(parent.albumid);
$('opalbumid').value = isNaN(albumidcheck)? 0 : albumid;
if(!successState) return false;
}
window.onbeforeunload = null;
mainForm.submit();
}
nowid = nid;
nowUid++;
uploadStat = 0;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_upload.js 18682 2010-12-01 03:35:10Z zhangguosheng $
*/
var nowid = 0;
var extensions = '';
function addAttach() {
var newnode = $('upload').cloneNode(true);
var id = nowid;
var tags;
newnode.id = 'upload_' + id;
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'attach') {
tags[i].id = 'attach_' + id;
tags[i].name = 'attach';
tags[i].onchange = function() {this.form.action = this.form.action.replace(/catid\=\d/, 'catid='+$('catid').value);insertAttach(id)};
tags[i].unselectable = 'on';
}
}
tags = newnode.getElementsByTagName('span');
for(i in tags) {
if(tags[i].id == 'localfile') {
tags[i].id = 'localfile_' + id;
}
}
nowid++;
$('attachbody').appendChild(newnode);
}
function insertAttach(id) {
var path = $('attach_' + id).value;
if(path == '') {
return;
}
var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig");
if(extensions != '' && (re.exec(extensions) == null || ext == '')) {
alert('对不起,不支持上传此类文件');
return;
}
var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1);
$('localfile_' + id).innerHTML = localfile + ' 上传中...';
$('attach_' + id).style.display = 'none';
$('upload_' + id).action += '&attach_target_id=' + id;
$('upload_' + id).submit();
addAttach();
}
function deleteAttach(attachid, url) {
ajaxget(url);
$('attach_list_' + attachid).style.display = 'none';
}
function setConver(attach) {
$('conver').value = attach;
}
addAttach(); | JavaScript |
function xmlobj() {
var obj = new Object();
obj.createXMLDoc = function(xmlstring) {
var xmlobj = false;
if(window.DOMParser && document.implementation && document.implementation.createDocument) {
try{
var domparser = new DOMParser();
xmlobj = domparser.parseFromString(xmlstring, 'text/xml');
} catch(e) {
}
} else if(window.ActiveXObject) {
var versions = ["MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "Microsoft.XmlDom"];
for(var i=0; i<versions.length; i++) {
try {
xmlobj = new ActiveXObject(versions[i]);
if(xmlobj) {
xmlobj.async = false;
xmlobj.loadXML(xmlstring);
}
} catch(e) {}
}
}
return xmlobj;
};
obj.xml2json = function(xmlobj, node) {
var nodeattr = node.attributes;
if(nodeattr != null) {
if(nodeattr.length && xmlobj == null) {
xmlobj = new Object();
}
for(var i = 0;i < nodeattr.length;i++) {
xmlobj[nodeattr[i].name] = nodeattr[i].value;
}
}
var nodetext = "text";
if(node.text == null) {
nodetext = "textContent";
}
var nodechilds = node.childNodes;
if(nodechilds != null) {
if(nodechilds.length && xmlobj == null) {
xmlobj = new Object();
}
for(var i = 0;i < nodechilds.length;i++) {
if(nodechilds[i].tagName != null) {
if(nodechilds[i].childNodes[0] != null && nodechilds[i].childNodes.length <= 1 && (nodechilds[i].childNodes[0].nodeType == 3 || nodechilds[i].childNodes[0].nodeType == 4)) {
if(xmlobj[nodechilds[i].tagName] == null) {
xmlobj[nodechilds[i].tagName] = nodechilds[i][nodetext];
} else {
if(typeof(xmlobj[nodechilds[i].tagName]) == "object" && xmlobj[nodechilds[i].tagName].length) {
xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length] = nodechilds[i][nodetext];
} else {
xmlobj[nodechilds[i].tagName] = [xmlobj[nodechilds[i].tagName]];
xmlobj[nodechilds[i].tagName][1] = nodechilds[i][nodetext];
}
}
} else {
if(nodechilds[i].childNodes.length) {
if(xmlobj[nodechilds[i].tagName] == null) {
xmlobj[nodechilds[i].tagName] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName], nodechilds[i]);
} else {
if(xmlobj[nodechilds[i].tagName].length) {
xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName][xmlobj[nodechilds[i].tagName].length-1], nodechilds[i]);
} else {
xmlobj[nodechilds[i].tagName] = [xmlobj[nodechilds[i].tagName]];
xmlobj[nodechilds[i].tagName][1] = new Object();
this.xml2json(xmlobj[nodechilds[i].tagName][1], nodechilds[i]);
}
}
} else {
xmlobj[nodechilds[i].tagName] = nodechilds[i][nodetext];
}
}
}
}
}
};
return obj;
}
var xml = new xmlobj();
var xmlpar = xml.createXMLDoc(forum_optionlist);
var forum_optionlist_obj = new Object();
xml.xml2json(forum_optionlist_obj, xmlpar);
function changeselectthreadsort(selectchoiceoptionid, optionid, type) {
if(selectchoiceoptionid == '0') {
return;
}
var soptionid = 's' + optionid;
var sselectchoiceoptionid = 's' + selectchoiceoptionid;
forum_optionlist = forum_optionlist_obj['forum_optionlist'];
var choicesarr = forum_optionlist[soptionid]['schoices'];
var lastcount = 1;
var name = issearch = id = nameid = '';
if(type == 'search') {
issearch = ', \'search\'';
name = ' name="searchoption[' + optionid + '][value]"';
id = 'id="' + forum_optionlist[soptionid]['sidentifier'] + '"';
} else {
name = ' name="typeoption[' + forum_optionlist[soptionid]['sidentifier'] + ']"';
id = 'id="typeoption_' + forum_optionlist[soptionid]['sidentifier'] + '"';
}
if((choicesarr[sselectchoiceoptionid]['slevel'] == 1 || type == 'search') && choicesarr[sselectchoiceoptionid]['scount'] == 1) {
nameid = name + ' ' + id;
}
var selectoption = '<select' + nameid + ' class="ps vm" onchange="changeselectthreadsort(this.value, \'' + optionid + '\'' + issearch + ');checkoption(\'' + forum_optionlist[soptionid]['sidentifier'] + '\', \'' + forum_optionlist[soptionid]['srequired'] + '\', \'' + forum_optionlist[soptionid]['stype'] + '\')"><option value="0">请选择</option>';
for(var i in choicesarr) {
nameid = '';
if((choicesarr[sselectchoiceoptionid]['slevel'] == 1 || type == 'search') && choicesarr[i]['scount'] == choicesarr[sselectchoiceoptionid]['scount']) {
nameid = name + ' ' + id;
}
if(choicesarr[i]['sfoptionid'] != '0') {
var patrn1 = new RegExp("^" + choicesarr[i]['sfoptionid'] + "\\.", 'i');
var patrn2 = new RegExp("^" + choicesarr[i]['sfoptionid'] + "$", 'i');
if(selectchoiceoptionid.match(patrn1) == null && selectchoiceoptionid.match(patrn2) == null) {
continue;
}
}
if(choicesarr[i]['scount'] != lastcount) {
if(parseInt(choicesarr[i]['scount']) >= (parseInt(choicesarr[sselectchoiceoptionid]['scount']) + parseInt(choicesarr[sselectchoiceoptionid]['slevel']))) {
break;
}
selectoption += '</select>' + "\r\n" + '<select' + nameid + ' class="ps vm" onchange="changeselectthreadsort(this.value, \'' + optionid + '\'' + issearch + ');checkoption(\'' + forum_optionlist[soptionid]['sidentifier'] + '\', \'' + forum_optionlist[soptionid]['srequired'] + '\', \'' + forum_optionlist[soptionid]['stype'] + '\')"><option value="0">请选择</option>';
lastcount = parseInt(choicesarr[i]['scount']);
}
var patrn1 = new RegExp("^" + choicesarr[i]['soptionid'] + "\\.", 'i');
var patrn2 = new RegExp("^" + choicesarr[i]['soptionid'] + "$", 'i');
var isnext = '';
if(parseInt(choicesarr[i]['slevel']) != 1) {
isnext = '»';
}
if(selectchoiceoptionid.match(patrn1) != null || selectchoiceoptionid.match(patrn2) != null) {
selectoption += "\r\n" + '<option value="' + choicesarr[i]['soptionid'] + '" selected="selected">' + choicesarr[i]['scontent'] + isnext + '</option>';
} else {
selectoption += "\r\n" + '<option value="' + choicesarr[i]['soptionid'] + '">' + choicesarr[i]['scontent'] + isnext + '</option>';
}
}
selectoption += '</select>';
if(type == 'search') {
selectoption += "\r\n" + '<input type="hidden" name="searchoption[' + optionid + '][type]" value="select">';
}
$('select_' + forum_optionlist[soptionid]['sidentifier']).innerHTML = selectoption;
}
function checkoption(identifier, required, checktype, checkmaxnum, checkminnum, checkmaxlength) {
if(checktype != 'image' && checktype != 'select' && !$('typeoption_' + identifier) || !$('check' + identifier)) {
return true;
}
var ce = $('check' + identifier);
ce.innerHTML = '';
if(checktype == 'select') {
if(required != '0' && $('typeoption_' + identifier) == null) {
warning(ce, '必填项目没有填写');
return false;
} else if(required == '0' && ($('typeoption_' + identifier) == null || $('typeoption_' + identifier).value == '0')) {
ce.innerHTML = '<img src="' + IMGDIR + '/check_error.gif" width="16" height="16" class="vm" /> 请选择下一级';
ce.className = "warning";
return true;
}
}
if(checktype == 'image') {
var checkvalue = $('sortaid_' + identifier).value;
} else {
var checkvalue = $('typeoption_' + identifier).value;
}
if(required != '0') {
if(checkvalue == '' || checkvalue == '0') {
warning(ce, '必填项目没有填写');
return false;
} else {
ce.innerHTML = '<img src="' + IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
}
}
if(checkvalue) {
if((checktype == 'number' || checktype == 'range') && isNaN(checkvalue)) {
warning(ce, '数字填写不正确');
return false;
} else if(checktype == 'email' && !(/^[\-\.\w]+@[\.\-\w]+(\.\w+)+$/.test(checkvalue))) {
warning(ce, '邮件地址不正确');
return false;
} else if((checktype == 'text' || checktype == 'textarea') && checkmaxlength != '0' && mb_strlen(checkvalue) > checkmaxlength) {
warning(ce, '填写项目长度过长');
return false;
} else if((checktype == 'number' || checktype == 'range')) {
if(checkmaxnum != '0' && parseInt(checkvalue) > parseInt(checkmaxnum)) {
warning(ce, '大于设置最大值');
return false;
} else if(checkminnum != '0' && parseInt(checkvalue) < parseInt(checkminnum)) {
warning(ce, '小于设置最小值');
return false;
}
} else {
ce.innerHTML = '<img src="' + IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
}
}
return true;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_slide.js 4479 2010-02-27 10:40:20Z liyulong $
*/
if(isUndefined(sliderun)) {
var sliderun = 1;
function slide() {
var s = new Object();
s.slideId = Math.random();
s.slideSpeed = slideSpeed;
s.size = slideImgsize;
s.imgs = slideImgs;
s.imgLoad = new Array();
s.imgnum = slideImgs.length;
s.imgLinks = slideImgLinks;
s.imgTexts = slideImgTexts;
s.slideBorderColor = slideBorderColor;
s.slideBgColor = slideBgColor;
s.slideSwitchColor = slideSwitchColor;
s.slideSwitchbgColor = slideSwitchbgColor;
s.slideSwitchHiColor = slideSwitchHiColor;
s.currentImg = 0;
s.prevImg = 0;
s.imgLoaded = 0;
s.st = null;
s.loadImage = function () {
if(!s.imgnum) {
return;
}
s.size[0] = parseInt(s.size[0]);
s.size[1] = parseInt(s.size[1]);
document.write('<div class="slideouter" id="outer_'+s.slideId+'" style="cursor:pointer;position:absolute;width:'+(s.size[0]-2)+'px;height:'+(s.size[1]-2)+'px;border:1px solid '+s.slideBorderColor+'"></div>');
document.write('<table cellspacing="0" cellpadding="0" style="cursor:pointer;width:'+s.size[0]+'px;height:'+s.size[1]+'px;table-layout:fixed;overflow:hidden;background:'+s.slideBgColor+';text-align:center"><tr><td valign="middle" style="padding:0" id="slide_'+s.slideId+'">');
document.write((typeof IMGDIR == 'undefined' ? '' : '<img src="'+IMGDIR+'/loading.gif" />') + '<br /><span id="percent_'+s.slideId+'">0%</span></td></tr></table>');
document.write('<div id="switch_'+s.slideId+'" style="position:absolute;margin-left:1px;margin-top:-18px"></div>');
$('outer_' + s.slideId).onclick = s.imageLink;
for(i = 1;i < s.imgnum;i++) {
switchdiv = document.createElement('div');
switchdiv.id = 'switch_' + i + '_' + s.slideId;
switchdiv.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=70)';
switchdiv.style.opacity = 0.7;
switchdiv.style.styleFloat = 'left';
switchdiv.style.cssFloat = 'left';
switchdiv.style.cursor = 'pointer';
switchdiv.style.width = '17px';
switchdiv.style.height = '17px';
switchdiv.style.overflow = 'hidden';
switchdiv.style.fontWeight = 'bold';
switchdiv.style.textAlign = 'center';
switchdiv.style.fontSize = '9px';
switchdiv.style.color = s.slideSwitchColor;
switchdiv.style.borderRight = '1px solid ' + s.slideBorderColor;
switchdiv.style.borderTop = '1px solid ' + s.slideBorderColor;
switchdiv.style.backgroundColor = s.slideSwitchbgColor;
switchdiv.className = 'slideswitch';
switchdiv.i = i;
switchdiv.onclick = function () {
s.switchImage(this);
};
switchdiv.innerHTML = i;
$('switch_'+s.slideId).appendChild(switchdiv);
s.imgLoad[i] = new Image();
s.imgLoad[i].src = s.imgs[i];
s.imgLoad[i].onerror = function () { s.imgLoaded++; };
}
s.loadCheck();
};
s.imageLink = function () {
window.open(s.imgLinks[s.currentImg]);
};
s.switchImage = function (obj) {
s.showImage(obj.i);
s.interval();
};
s.loadCheck = function () {
for(i = 1;i < s.imgnum;i++) {
if(s.imgLoad[i].complete && !s.imgLoad[i].status) {
s.imgLoaded++;
s.imgLoad[i].status = 1;
if(s.imgLoad[i].width > s.size[0] || s.imgLoad[i].height > s.size[1]) {
zr = s.imgLoad[i].width / s.imgLoad[i].height;
if(zr > 1) {
s.imgLoad[i].height = s.size[1];
s.imgLoad[i].width = s.size[1] * zr;
} else {
s.imgLoad[i].width = s.size[0];
s.imgLoad[i].height = s.size[0] / zr;
if(s.imgLoad[i].height > s.size[1]) {
s.imgLoad[i].height = s.size[1];
s.imgLoad[i].width = s.size[1] * zr;
}
}
}
}
}
if(s.imgLoaded < s.imgnum - 1) {
$('percent_' + s.slideId).innerHTML = (parseInt(s.imgLoad.length / s.imgnum * 100)) + '%';
setTimeout(function () { s.loadCheck(); }, 100);
} else {
for(i = 1;i < s.imgnum;i++) {
s.imgLoad[i].onclick = s.imageLink;
s.imgLoad[i].title = s.imgTexts[i];
}
s.showImage();
s.interval();
}
};
s.interval = function () {
clearInterval(s.st);
s.st = setInterval(function () { s.showImage(); }, s.slideSpeed);
};
s.showImage = function (i) {
if(!i) {
s.currentImg++;
s.currentImg = s.currentImg < s.imgnum ? s.currentImg : 1;
} else {
s.currentImg = i;
}
if(s.prevImg) {
$('switch_' + s.prevImg + '_' + s.slideId).style.backgroundColor = s.slideSwitchbgColor;
}
$('switch_' + s.currentImg + '_' + s.slideId).style.backgroundColor = s.slideSwitchHiColor;
$('slide_' + s.slideId).innerHTML = '';
$('slide_' + s.slideId).appendChild(s.imgLoad[s.currentImg]);
s.prevImg = s.currentImg;
};
s.loadImage();
}
}
slide(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_friendselector.js 22000 2011-04-19 14:35:46Z svn_project_zhangjie $
*/
(function() {
friendSelector = function(parameter) {
this.dataSource = {};
this.selectUser = {};
this.prompterUser = [];
this.showObj = $(isUndefined(parameter['showId']) ? 'selectorBox' : parameter['showId']);
if(!this.showObj) return;
this.handleObj = $(isUndefined(parameter['searchId']) ? 'valueId' : parameter['searchId']);
this.showType = isUndefined(parameter['showType']) ? 0 : parameter['showType'];
this.searchStr = null;
this.selectNumber = 0;
this.maxSelectNumber = isUndefined(parameter['maxSelectNumber']) ? 0 : parseInt(parameter['maxSelectNumber']);
this.allNumber = 0;
this.handleKey = isUndefined(parameter['handleKey']) ? 'this' : parameter['handleKey'];
this.selectTabId = isUndefined(parameter['selectTabId']) ? 'selectTabId' : parameter['selectTabId'];
this.unSelectTabId = isUndefined(parameter['unSelectTabId']) ? 'unSelectTabId' : parameter['unSelectTabId'];
this.maxSelectTabId = isUndefined(parameter['maxSelectTabId']) ? 'maxSelectTabId' : parameter['maxSelectTabId'];
this.formId = isUndefined(parameter['formId']) ? '' : parameter['formId'];
this.filterUser = isUndefined(parameter['filterUser']) ? {} : parameter['filterUser'];
this.showAll = true;
this.newPMUser = {};
this.interlaced = true;
this.handover = true;
this.parentKeyCode = 0;
this.pmSelBoxState = 0;
this.selBoxObj = isUndefined(parameter['selBox']) ? null : $(parameter['selBox']);
this.containerBoxObj = isUndefined(parameter['selBoxMenu']) ? null : $(parameter['selBoxMenu']);
this.imgBtn = null;
this.initialize();
return this;
};
friendSelector.prototype = {
addDataSource : function(data, clear) {
if(typeof data == 'object') {
var userData = data['userdata'];
clear = isUndefined(clear) ? 0: clear;
if(clear) {
this.showObj.innerHTML = "";
if(this.showType == 3) {
this.selBoxObj.innerHTML = '';
}
this.allNumber = 0;
this.dataSource = {};
}
for(var i in userData) {
if(typeof this.filterUser[i] != 'undefined') {
continue;
}
var append = clear ? true : false;
if(typeof this.dataSource[i] == 'undefined') {
this.dataSource[i] = userData[i];
append = true;
this.allNumber++;
}
if(append) {
this.interlaced = !this.interlaced;
if(this.showType == 3) {
this.append(i, 0, 1);
} else {
this.append(i);
}
}
}
if(this.showType == 1) {
this.showSelectNumber();
} else if(this.showType == 2) {
if(this.newPMUser) {
window.setInterval(this.handleKey+".handoverCSS()", 400);
}
}
}
},
addFilterUser : function(data) {
var filterData = {};
if(typeof data != 'object') {
filterData[data] = data;
} else if(typeof data == 'object') {
filterData = data;
} else {
return false;
}
for(var id in filterData) {
this.filterUser[filterData[id]] = filterData[id];
}
return true;
},
handoverCSS : function() {
for(var uid in this.newPMUser) {
$('avt_'+uid).className = this.handover ? 'avt newpm' : 'avt';
}
this.handover = !this.handover;
},
handleEvent : function(key, event) {
var username = '';
this.searchStr = '';
if(key != '') {
if(event.keyCode == 188 || event.keyCode == 13 || event.keyCode == 59) {
if(this.showType == 3) {
if(event.keyCode == 13) {
var currentnum = this.getCurrentPrompterUser();
if(currentnum != -1) {
key = this.dataSource[this.prompterUser[currentnum]]['username'];
}
}
if(this.parentKeyCode != 229) {
this.selectUserName(this.trim(key));
this.showObj.style.display = 'none';
$(this.handleObj.id+'_menu').style.display = 'none';
this.showObj.innerHTML = "";
}
}
} else if(event.keyCode == 38 || event.keyCode == 40) {
} else {
if(this.showType == 3) {
this.showObj.innerHTML = "";
var result = false;
var reg = new RegExp(key, "ig");
this.searchStr = key;
this.prompterUser = [];
for(var uid in this.dataSource) {
username = this.dataSource[uid]['username'];
if(username.match(reg)) {
this.prompterUser.push(uid);
this.append(uid, 1);
result = true;
}
}
if(!result) {
$(this.handleObj.id+'_menu').style.display = 'none';
} else {
showMenu({'showid':this.showObj.id, 'duration':3, 'pos':'43'});
showMenu({'showid':this.handleObj.id, 'duration':3, 'pos':'43'});
}
}
}
} else if(this.showType != 3) {
this.showObj.innerHTML = "";
for(var uid in this.dataSource) {
this.append(uid);
}
} else {
$(this.handleObj.id+'_menu').style.display = 'none';
this.showObj.innerHTML = "";
}
},
selectUserName:function(userName) {
this.handleObj.value = '';
if(userName != '') {
var uid = this.isFriend(userName);
if(uid && typeof this.selectUser[uid] == 'undefined' || uid === 0 && typeof this.selectUser[userName] == 'undefined') {
var spanObj = document.createElement("span");
if(uid) {
this.selectUser[uid] = this.dataSource[uid];
spanObj.id = 'uid' + uid;
if($('chk'+uid) != null) {
$('chk'+uid).checked = true;
}
} else {
var id = 'str' + Math.floor(Math.random() * 10000);
spanObj.id = id;
this.selectUser[userName] = userName;
}
this.selectNumber++;
spanObj.innerHTML= '<a href="javascript:;" class="x" onclick="'+this.handleKey+'.delSelUser(\''+(spanObj.id)+'\');">删除</a><em class="z" title="' + userName + '">' + userName + '</em><input type="hidden" name="users[]" value="'+userName+'" uid="uid'+uid+'" />';
this.handleObj.parentNode.insertBefore(spanObj, this.handleObj);
this.showObj.style.display = 'none';
} else {
alert('已经存在'+userName);
}
}
},
delSelUser:function(id) {
id = isUndefined(id) ? 0 : id;
var uid = id.substring(0, 3) == 'uid' ? parseInt(id.substring(3)) : 0;
var spanObj;
if(uid) {
spanObj = $(id);
delete this.selectUser[uid];
if($('chk'+uid) != null) {
$('chk'+uid).checked = false;
}
} else if(id.substring(0, 3) == 'str') {
spanObj = $(id);
delete this.selectUser[spanObj.getElementsByTagName('input')[0].value];
}
if(spanObj != null) {
this.selectNumber--;
spanObj.parentNode.removeChild(spanObj);
}
},
trim:function(str) {
return str.replace(/\s|,|;/g, '');
},
isFriend:function(userName) {
var id = 0;
for(var uid in this.dataSource) {
if(this.dataSource[uid]['username'] === userName) {
id = uid;
break;
}
}
return id;
},
directionKeyDown : function(event) {},
clearDataSource : function() {
this.dataSource = {};
this.selectUser = {};
},
showUser : function(type) {
this.showObj.innerHTML = '';
type = isUndefined(type) ? 0 : parseInt(type);
this.showAll = true;
if(type == 1) {
for(var uid in this.selectUser) {
this.append(uid);
}
this.showAll = false;
} else {
for(var uid in this.dataSource) {
if(type == 2) {
if(typeof this.selectUser[uid] != 'undefined') {
continue;
}
this.showAll = false;
}
this.append(uid);
}
}
if(this.showType == 1) {
for(var i = 0; i < 3; i++) {
$('showUser_'+i).className = '';
}
$('showUser_'+type).className = 'a brs';
}
},
append : function(uid, filtrate, form) {
filtrate = isUndefined(filtrate) ? 0 : filtrate;
form = isUndefined(form) ? 0 : form;
var liObj = document.createElement("li");
var username = this.dataSource[uid]['username'];
liObj.userid = this.dataSource[uid]['uid'];
if(typeof this.selectUser[uid] != 'undefined') {
liObj.className = "a";
}
if(filtrate) {
var reg = new RegExp("(" + this.searchStr + ")","ig");
username = username.replace(reg , "<strong>$1</strong>");
}
if(this.showType == 1) {
liObj.innerHTML = '<a href="javascript:;" id="' + liObj.userid + '" onclick="' + this.handleKey + '.select(this.id)" class="cl"><span class="avt brs" style="background-image: url(' + this.dataSource[uid]['avatar'] + ');"><span></span></span><span class="d">' + username + '</span></a>';
} else if(this.showType == 2) {
if(this.dataSource[uid]['new'] && typeof this.newPMUser[uid] == 'undefined') {
this.newPMUser[uid] = uid;
}
liObj.className = this.interlaced ? 'alt' : '';
liObj.innerHTML = '<div id="avt_' + liObj.userid + '" class="avt"><a href="home.php?mod=spacecp&ac=pm&op=showmsg&handlekey=showmsg_' + liObj.userid + '&touid=' + liObj.userid + '&pmid='+this.dataSource[uid]['pmid']+'&daterange='+this.dataSource[uid]['daterange']+'" title="'+username+'" id="avatarmsg_' + liObj.userid + '" onclick="'+this.handleKey+'.delNewFlag(' + liObj.userid + ');showWindow(\'showMsgBox\', this.href, \'get\', 0);"><img src="' + this.dataSource[uid]['avatar'] + '" alt="'+username+'" /></a></div><p><a class="xg1" href="home.php?mod=spacecp&ac=pm&op=showmsg&handlekey=showmsg_' + liObj.userid + '&touid=' + liObj.userid + '&pmid='+this.dataSource[uid]['pmid']+'&daterange='+this.dataSource[uid]['daterange']+'" title="'+username+'" id="usernamemsg_' + liObj.userid + '" onclick="'+this.handleKey+'.delNewFlag(' + liObj.userid + ');showWindow(\'showMsgBox\', this.href, \'get\', 0);">'+username+'</a></p>';
} else {
if(form) {
var checkstate = typeof this.selectUser[uid] == 'undefined' ? '' : ' checked="checked" ';
liObj.innerHTML = '<label><input type="checkbox" name="selUsers[]" id="chk'+uid+'" value="'+ this.dataSource[uid]['username'] +'" onclick="if(this.checked) {' + this.handleKey + '.selectUserName(this.value);} else {' + this.handleKey + '.delSelUser(\'uid'+uid+'\');}" '+checkstate+' class="pc" /> <span class="xi2">' + username + '</span></label>';
this.selBoxObj.appendChild(liObj);
return true;
} else {
liObj.innerHTML = '<a href="javascript:;" username="' + this.dataSource[uid]['username'] + '" onmouseover="' + this.handleKey + '.mouseOverPrompter(this);" onclick="' + this.handleKey + '.selectUserName(this.getAttribute(\'username\'));$(\'username\').focus();" class="cl" id="prompter_' + uid + '">' + username + '</a>';
}
}
this.showObj.appendChild(liObj);
},
select : function(uid) {
uid = parseInt(uid);
if(uid){
var select = false;
if(typeof this.selectUser[uid] == 'undefined') {
if(this.maxSelectNumber && this.selectNumber >= this.maxSelectNumber) {
alert('最多只允许选择'+this.maxSelectNumber+'个用户');
return false;
}
this.selectUser[uid] = this.dataSource[uid];
this.selectNumber++;
if(this.showType == '1') {
$(uid).parentNode.className = 'a';
}
select = true;
} else {
delete this.selectUser[uid];
this.selectNumber--;
$(uid).parentNode.className = '';
}
if(this.formId != '') {
var formObj = $(this.formId);
var opId = 'selUids_' + uid;
if(select) {
var inputObj = document.createElement("input");
inputObj.type = 'hidden';
inputObj.id = opId;
inputObj.name = 'uids[]';
inputObj.value = uid;
formObj.appendChild(inputObj);
} else {
formObj.removeChild($(opId));
}
}
if(this.showType == 1) {
this.showSelectNumber();
}
}
},
delNewFlag : function(uid) {
delete this.newPMUser[uid];
},
showSelectNumber:function() {
if($(this.selectTabId) != null && typeof $(this.selectTabId) != 'undefined') {
$(this.selectTabId).innerHTML = this.selectNumber;
}
if($(this.unSelectTabId) != null && typeof $(this.unSelectTabId) != 'undefined') {
$(this.unSelectTabId).innerHTML = this.allNumber - this.selectNumber;
}
if($(this.maxSelectTabId) != null && this.maxSelectNumber && typeof $(this.maxSelectTabId) != 'undefined') {
$(this.maxSelectTabId).innerHTML = this.maxSelectNumber -this.selectNumber;
}
},
getCurrentPrompterUser:function() {
var len = this.prompterUser.length;
var selectnum = -1;
if(len) {
for(var i = 0; i < len; i++) {
var obj = $('prompter_' + this.prompterUser[i]);
if(obj != null && obj.className == 'a') {
selectnum = i;
}
}
}
return selectnum;
},
mouseOverPrompter:function(obj) {
var len = this.prompterUser.length;
if(len) {
for(var i = 0; i < len; i++) {
$('prompter_' + this.prompterUser[i]).className = 'cl';
}
obj.className = 'a';
}
},
initialize:function() {
var instance = this;
this.handleObj.onkeyup = function(event) {
event = event ? event : window.event;
instance.handleEvent(this.value, event);
};
if(this.showType == 3) {
this.handleObj.onkeydown = function(event) {
event = event ? event : window.event;
instance.parentKeyCode = event.keyCode;
instance.showObj.style.display = '';
if(event.keyCode == 8 && this.value == '') {
var preNode = this.previousSibling;
if(preNode.tagName == 'SPAN') {
var uid = preNode.getElementsByTagName('input')[0].getAttribute('uid');
if(parseInt(uid.substring(3))) {
instance.delSelUser(uid);
} else {
delete instance.selectUser[preNode.getElementsByTagName('input')[0].value];
instance.selectNumber--;
this.parentNode.removeChild(preNode);
}
}
} else if(event.keyCode == 38) {
if(!instance.prompterUser.length) {
doane(event);
}
var currentnum = instance.getCurrentPrompterUser();
if(currentnum != -1) {
var nextnum = (currentnum == 0) ? (instance.prompterUser.length-1) : currentnum - 1;
$('prompter_' + instance.prompterUser[currentnum]).className = "cl";
$('prompter_' + instance.prompterUser[nextnum]).className = "a";
} else {
$('prompter_' + instance.prompterUser[0]).className = "a";
}
} else if(event.keyCode == 40) {
if(!instance.prompterUser.length) {
doane(event);
}
var currentnum = instance.getCurrentPrompterUser();
if(currentnum != -1) {
var nextnum = (currentnum == (instance.prompterUser.length - 1)) ? 0 : currentnum + 1;
$('prompter_' + instance.prompterUser[currentnum]).className = "cl";
$('prompter_' + instance.prompterUser[nextnum]).className = "a";
} else {
$('prompter_' + instance.prompterUser[0]).className = "a";
}
} else if(event.keyCode == 13) {
doane(event);
}
if(typeof instance != "undefined" && instance.pmSelBoxState) {
instance.pmSelBoxState = 0;
instance.changePMBoxImg(instance.imgBtn);
instance.containerBoxObj.style.display = 'none';
}
};
}
},
changePMBoxImg:function(obj) {
var btnImg = new Image();
btnImg.src = IMGDIR + '/' + (this.pmSelBoxState ? 'icon_top.gif' : 'icon_down.gif');
if(obj != null) {
obj.src = btnImg.src;
}
},
showPMFriend:function(boxId, listId, obj) {
this.pmSelBoxState = !this.pmSelBoxState;
this.imgBtn = obj;
this.changePMBoxImg(obj);
if(this.pmSelBoxState) {
this.selBoxObj.innerHTML = '';
for(var uid in this.dataSource) {
this.append(uid, 0, 1);
}
}
this.containerBoxObj.style.display = this.pmSelBoxState ? '' : 'none';
this.showObj.innerHTML = "";
},
showPMBoxUser:function() {
this.selBoxObj.innerHTML = '';
for(var uid in this.dataSource) {
this.append(uid, 0, 1);
}
},
extend:function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_viewthread.js 22866 2011-05-27 06:23:56Z zhangguosheng $
*/
var replyreload = '', attachimgST = new Array(), zoomgroup = new Array(), zoomgroupinit = new Array();
function attachimggroup(pid) {
if(!zoomgroupinit[pid]) {
for(i = 0;i < aimgcount[pid].length;i++) {
zoomgroup['aimg_' + aimgcount[pid][i]] = pid;
}
zoomgroupinit[pid] = true;
}
}
function attachimgshow(pid, onlyinpost) {
onlyinpost = !onlyinpost ? false : onlyinpost;
aimgs = aimgcount[pid];
aimgcomplete = 0;
loadingcount = 0;
for(i = 0;i < aimgs.length;i++) {
obj = $('aimg_' + aimgs[i]);
if(!obj) {
aimgcomplete++;
continue;
}
if(onlyinpost && obj.getAttribute('inpost') || !onlyinpost) {
if(!obj.status) {
obj.status = 1;
if(obj.getAttribute('file')) obj.src = obj.getAttribute('file');
loadingcount++;
} else if(obj.status == 1) {
if(obj.complete) {
obj.status = 2;
} else {
loadingcount++;
}
} else if(obj.status == 2) {
aimgcomplete++;
if(obj.getAttribute('thumbImg')) {
thumbImg(obj);
}
}
if(loadingcount >= 10) {
break;
}
}
}
if(aimgcomplete < aimgs.length) {
setTimeout(function () {
attachimgshow(pid, onlyinpost);
}, 100);
}
}
function attachimglstshow(pid, islazy) {
var aimgs = aimgcount[pid];
if(typeof aimgcount == 'object' && $('imagelistthumb_' + pid)) {
for(pid in aimgcount) {
var imagelist = '';
for(i = 0;i < aimgcount[pid].length;i++) {
if(!$('aimg_' + aimgcount[pid][i]) || $('aimg_' + aimgcount[pid][i]).getAttribute('inpost')) {
continue;
}
imagelist += '<div class="pattimg">' +
'<a class="pattimg_zoom" href="javascript:;" onclick="zoom($(\'aimg_' + aimgcount[pid][i] + '\'), attachimggetsrc(\'aimg_' + aimgcount[pid][i] + '\'))" title="点击放大">点击放大</a>' +
'<img ' + (islazy ? 'file' : 'src') + '="forum.php?mod=image&aid=' + aimgcount[pid][i] + '&size=100x100&key=' + imagelistkey + '&atid=' + tid + '" width="100" height="100" /></div>';
}
if($('imagelistthumb_' + pid)) {
$('imagelistthumb_' + pid).innerHTML = imagelist;
}
}
}
}
function attachimggetsrc(img) {
return $(img).getAttribute('zoomfile') ? $(img).getAttribute('zoomfile') : $(img).getAttribute('file');
}
function attachimglst(pid, op, islazy) {
if(!op) {
$('imagelist_' + pid).style.display = 'none';
$('imagelistthumb_' + pid).style.display = '';
} else {
$('imagelistthumb_' + pid).style.display = 'none';
$('imagelist_' + pid).style.display = '';
if(islazy) {
o = new lazyload();
o.showImage();
} else {
attachimgshow(pid);
}
}
doane();
}
function attachimginfo(obj, infoobj, show, event) {
objinfo = fetchOffset(obj);
if(show) {
$(infoobj).style.left = objinfo['left'] + 'px';
$(infoobj).style.top = obj.offsetHeight < 40 ? (objinfo['top'] + obj.offsetHeight) + 'px' : objinfo['top'] + 'px';
$(infoobj).style.display = '';
} else {
if(BROWSER.ie) {
$(infoobj).style.display = 'none';
return;
} else {
var mousex = document.body.scrollLeft + event.clientX;
var mousey = document.documentElement.scrollTop + event.clientY;
if(mousex < objinfo['left'] || mousex > objinfo['left'] + objinfo['width'] || mousey < objinfo['top'] || mousey > objinfo['top'] + objinfo['height']) {
$(infoobj).style.display = 'none';
}
}
}
}
function signature(obj) {
if(obj.style.maxHeightIE != '') {
var height = (obj.scrollHeight > parseInt(obj.style.maxHeightIE)) ? obj.style.maxHeightIE : obj.scrollHeight + 'px';
if(obj.innerHTML.indexOf('<IMG ') == -1) {
obj.style.maxHeightIE = '';
}
return height;
}
}
function tagshow(event) {
var obj = BROWSER.ie ? event.srcElement : event.target;
ajaxmenu(obj, 0, 1, 2);
}
function parsetag(pid) {
if(!$('postmessage_'+pid) || $('postmessage_'+pid).innerHTML.match(/<script[^\>]*?>/i)) {
return;
}
var havetag = false;
var tagfindarray = new Array();
var str = $('postmessage_'+pid).innerHTML.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3, $4) {
for(i in tagarray) {
if(tagarray[i] && $3.indexOf(tagarray[i]) != -1) {
havetag = true;
$3 = $3.replace(tagarray[i], '<h_ ' + i + '>');
tmp = $3.replace(/&[a-z]*?<h_ \d+>[a-z]*?;/ig, '');
if(tmp != $3) {
$3 = tmp;
} else {
tagfindarray[i] = tagarray[i];
tagarray[i] = '';
}
}
}
return $2 + $3;
});
if(havetag) {
$('postmessage_'+pid).innerHTML = str.replace(/<h_ (\d+)>/ig, function($1, $2) {
return '<span href=\"forum.php?mod=tag&name=' + tagencarray[$2] + '\" onclick=\"tagshow(event)\" class=\"t_tag\">' + tagfindarray[$2] + '</span>';
});
}
}
function setanswer(pid, from){
if(confirm('您确认要把该回复选为“最佳答案”吗?')){
if(BROWSER.ie) {
doane(event);
}
$('modactions').action='forum.php?mod=misc&action=bestanswer&tid=' + tid + '&pid=' + pid + '&from=' + from + '&bestanswersubmit=yes';
$('modactions').submit();
}
}
var authort;
function showauthor(ctrlObj, menuid) {
authort = setTimeout(function () {
showMenu({'menuid':menuid});
if($(menuid + '_ma').innerHTML == '') $(menuid + '_ma').innerHTML = ctrlObj.innerHTML;
}, 500);
if(!ctrlObj.onmouseout) {
ctrlObj.onmouseout = function() {
clearTimeout(authort);
}
}
}
function fastpostappendreply() {
if($('fastpostrefresh') != null) {
setcookie('fastpostrefresh', $('fastpostrefresh').checked ? 1 : 0, 2592000);
if($('fastpostrefresh').checked) {
location.href = 'forum.php?mod=redirect&tid='+tid+'&goto=lastpost&random=' + Math.random() + '#lastpost';
return;
}
}
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
$('fastpostsubmit').disabled = false;
if($('fastpostmessage')) {
$('fastpostmessage').value = '';
} else {
editdoc.body.innerHTML = BROWSER.firefox ? '<br />' : '';
}
if($('secanswer3')) {
$('checksecanswer3').innerHTML = '<img src="' + STATICURL + 'image/common/none.gif" width="17" height="17">';
$('secanswer3').value = '';
secclick3['secanswer3'] = 0;
}
if($('seccodeverify3')) {
$('checkseccodeverify3').innerHTML = '<img src="' + STATICURL + 'image/common/none.gif" width="17" height="17">';
$('seccodeverify3').value = '';
secclick3['seccodeverify3'] = 0;
}
showCreditPrompt();
}
function succeedhandle_fastpost(locationhref, message, param) {
var pid = param['pid'];
var tid = param['tid'];
var from = param['from'];
if(pid) {
ajaxget('forum.php?mod=viewthread&tid=' + tid + '&viewpid=' + pid + '&from=' + from, 'post_new', 'ajaxwaitid', '', null, 'fastpostappendreply()');
if(replyreload) {
var reloadpids = replyreload.split(',');
for(i = 1;i < reloadpids.length;i++) {
ajaxget('forum.php?mod=viewthread&tid=' + tid + '&viewpid=' + reloadpids[i] + '&from=' + from, 'post_' + reloadpids[i]);
}
}
$('fastpostreturn').className = '';
} else {
if(!message) {
message = '本版回帖需要审核,您的帖子将在通过审核后显示';
}
$('post_new').style.display = $('fastpostmessage').value = $('fastpostreturn').className = '';
$('fastpostreturn').innerHTML = message;
}
if(param['sechash']) {
updatesecqaa(param['sechash']);
updateseccode(param['sechash']);
}
if($('attach_tblheader')) {
$('attach_tblheader').style.display = 'none';
}
if($('attachlist')) {
$('attachlist').innerHTML = '';
}
}
function errorhandle_fastpost() {
$('fastpostsubmit').disabled = false;
}
function succeedhandle_comment(locationhref, message, param) {
ajaxget('forum.php?mod=misc&action=commentmore&tid=' + param['tid'] + '&pid=' + param['pid'], 'comment_' + param['pid']);
hideWindow('comment');
showCreditPrompt();
}
function succeedhandle_postappend(locationhref, message, param) {
ajaxget('forum.php?mod=viewthread&tid=' + param['tid'] + '&viewpid=' + param['pid'], 'post_' + param['pid']);
hideWindow('postappend');
}
function recommendupdate(n) {
if(getcookie('recommend')) {
var objv = n > 0 ? $('recommendv_add') : $('recommendv_subtract');
objv.innerHTML = parseInt(objv.innerHTML) + 1;
setTimeout(function () {
$('recommentc').innerHTML = parseInt($('recommentc').innerHTML) + n;
$('recommentv').style.display = 'none';
}, 1000);
setcookie('recommend', '');
}
}
function favoriteupdate() {
var obj = $('favoritenumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function shareupdate() {
var obj = $('sharenumber');
obj.innerHTML = parseInt(obj.innerHTML) + 1;
}
function switchrecommendv() {
display('recommendv');
display('recommendav');
}
function appendreply() {
newpos = fetchOffset($('post_new'));
document.documentElement.scrollTop = newpos['top'];
$('post_new').style.display = '';
$('post_new').id = '';
div = document.createElement('div');
div.id = 'post_new';
div.style.display = 'none';
div.className = '';
$('postlistreply').appendChild(div);
if($('postform')) {
$('postform').replysubmit.disabled = false;
}
showCreditPrompt();
}
function poll_checkbox(obj) {
if(obj.checked) {
p++;
for (var i = 0; i < $('poll').elements.length; i++) {
var e = $('poll').elements[i];
if(p == max_obj) {
if(e.name.match('pollanswers') && !e.checked) {
e.disabled = true;
}
}
}
} else {
p--;
for (var i = 0; i < $('poll').elements.length; i++) {
var e = $('poll').elements[i];
if(e.name.match('pollanswers') && e.disabled) {
e.disabled = false;
}
}
}
$('pollsubmit').disabled = p <= max_obj && p > 0 ? false : true;
}
function itemdisable(i) {
if($('itemt_' + i).className == 'z') {
$('itemt_' + i).className = 'z xg1';
$('itemc_' + i).value = '';
itemset(i);
} else {
$('itemt_' + i).className = 'z';
$('itemc_' + i).value = $('itemc_' + i).value > 0 ? $('itemc_' + i).value : 0;
}
}
function itemop(i, v) {
var h = v > 0 ? '-' + (v * 16) + 'px' : '0';
$('item_' + i).style.backgroundPosition = '10px ' + h;
}
function itemclk(i, v) {
$('itemc_' + i).value = v;
$('itemt_' + i).className = 'z';
}
function itemset(i) {
var v = $('itemc_' + i).value;
var h = v > 0 ? '-' + (v * 16) + 'px' : '0';
$('item_' + i).style.backgroundPosition = '10px ' + h;
}
function checkmgcmn(id) {
if($('mgc_' + id) && !$('mgc_' + id + '_menu').getElementsByTagName('li').length) {
$('mgc_' + id).innerHTML = '';
$('mgc_' + id).style.display = 'none';
}
}
function toggleRatelogCollapse(tarId, ctrlObj) {
if($(tarId).className == 'rate') {
$(tarId).className = 'rate rate_collapse';
setcookie('ratecollapse', 1, 2592000);
ctrlObj.innerHTML = '展开';
} else {
$(tarId).className = 'rate';
setcookie('ratecollapse', 0, -2592000);
ctrlObj.innerHTML = '收起';
}
}
function copyThreadUrl(obj) {
setCopy($('thread_subject').innerHTML.replace(/&/g, '&') + '\n' + obj.href + '\n', '帖子地址已经复制到剪贴板');
return false;
}
function replyNotice() {
var newurl = 'forum.php?mod=misc&action=replynotice&tid=' + tid + '&op=';
var replynotice = $('replynotice');
var status = replynotice.getAttribute("status");
if(status == 1) {
replynotice.href = newurl + 'receive';
replynotice.innerHTML = '接收回复通知';
replynotice.setAttribute("status", 0);
} else {
replynotice.href = newurl + 'ignore';
replynotice.innerHTML = '取消回复通知';
replynotice.setAttribute("status", 1);
}
}
var connect_share_loaded = 0;
function connect_share(connect_share_url, connect_uin) {
if(parseInt(discuz_uid) <= 0) {
return true;
} else {
if(connect_uin) {
setTimeout(function () {
if(!connect_share_loaded) {
showDialog('分享服务连接失败,请稍后再试。', 'notice');
$('append_parent').removeChild($('connect_load_js'));
}
}, 5000);
connect_load(connect_share_url);
} else {
showDialog($('connect_share_unbind').innerHTML, 'info', '请先绑定QQ账号');
}
return false;
}
}
function connect_load(src) {
var e = document.createElement('script');
e.type = "text/javascript";
e.id = 'connect_load_js';
e.src = src + '&_r=' + Math.random();
e.async = true;
$('append_parent').appendChild(e);
}
function connect_show_dialog(title, html, type) {
var type = type ? type : 'info';
showDialog(html, type, title, null, 0);
}
function connect_get_thread() {
connect_thread_info.subject = $('connect_thread_title').value;
if ($('postmessage_' + connect_thread_info.post_id)) {
connect_thread_info.html_content = preg_replace(["'"], ['%27'], encodeURIComponent(preg_replace(['本帖最后由 .*? 于 .*? 编辑',' ','<em onclick="copycode\\(\\$\\(\'code0\'\\)\\);">复制代码</em>'], ['',' ', ''], $('postmessage_' + connect_thread_info.post_id).innerHTML)));
}
return connect_thread_info;
}
function lazyload(className) {
var obj = this;
lazyload.className = className;
this.getOffset = function (el, isLeft) {
var retValue = 0 ;
while (el != null ) {
retValue += el["offset" + (isLeft ? "Left" : "Top" )];
el = el.offsetParent;
}
return retValue;
};
this.initImages = function (ele) {
lazyload.imgs = [];
var eles = lazyload.className ? $C(lazyload.className, ele) : [document.body];
for (var i = 0; i < eles.length; i++) {
var imgs = eles[i].getElementsByTagName('IMG');
for(var j = 0; j < imgs.length; j++) {
if(imgs[j].getAttribute('file') && !imgs[j].getAttribute('lazyloaded')) {
if(this.getOffset(imgs[j]) > document.documentElement.clientHeight) {
lazyload.imgs.push(imgs[j]);
} else {
imgs[j].setAttribute('src', imgs[j].getAttribute('file'));
}
}
}
}
};
this.showImage = function() {
this.initImages();
if(!lazyload.imgs.length) return false;
var imgs = [];
var scrollTop = Math.max(document.documentElement.scrollTop , document.body.scrollTop);
for (var i=0; i<lazyload.imgs.length; i++) {
var img = lazyload.imgs[i];
var offsetTop = this.getOffset(img);
if (offsetTop > document.documentElement.clientHeight && (offsetTop - scrollTop < document.documentElement.clientHeight)) {
img.setAttribute('src', img.getAttribute('file') ? img.getAttribute('file') : img.getAttribute('src'));
img.setAttribute('lazyloaded', true);
} else {
imgs.push(img);
}
}
lazyload.imgs = imgs;
return true;
};
this.initImages();
_attachEvent(window, 'scroll', function(){obj.showImage();});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common_diy.js 22487 2011-05-10 03:46:05Z zhangguosheng $
*/
String.prototype.property2js = function(){
var t = this.replace(/-([a-z])/g, function($0, $1) {return $1.toUpperCase();});
return t;
};
function styleCss(n) {
if(typeof n == "number") {
var _s = document.styleSheets[n];
} else {
return false;
}
this.sheet = _s;
this.rules = _s.cssRules ? _s.cssRules : _s.rules;
};
styleCss.prototype.indexOf = function(selector) {
for(var i = 0; i < this.rules.length; i++) {
if (typeof(this.rules[i].selectorText) == 'undefined') continue;
if(this.rules[i].selectorText == selector) {
return i;
}
}
return -1;
};
styleCss.prototype.removeRule = function(n) {
if(typeof n == "number") {
if(n < this.rules.length) {
this.sheet.removeRule ? this.sheet.removeRule(n) : this.sheet.deleteRule(n);
}
} else {
var i = this.indexOf(n);
if (i>0) this.sheet.removeRule ? this.sheet.removeRule(i) : this.sheet.deleteRule(i);
}
};
styleCss.prototype.addRule = function(selector, styles, n, porperty) {
var i = this.indexOf(selector);
var s = '';
var reg = '';
if (i != -1) {
reg = new RegExp('^'+porperty+'.*;','i');
s = this.getRule(selector);
if (s) {
s = s.replace(selector,'').replace('{', '').replace('}', '').replace(/ /g, ' ').replace(/^ | $/g,'');
s = (s != '' && s.substr(-1,1) != ';') ? s+ ';' : s;
s = s.toLowerCase().replace(reg, '');
if (s.length == 1) s = '';
}
this.removeRule(i);
}
s = s.indexOf('!important') > -1 || s.indexOf('! important') > -1 ? s : s.replace(/;/g,' !important;');
s = s + styles;
if (typeof n == 'undefined' || !isNaN(n)) {
n = this.rules.length;
}
if (this.sheet.insertRule) {
this.sheet.insertRule(selector+'{'+s+'}', n);
} else {
if (s) this.sheet.addRule(selector, s, n);
}
};
styleCss.prototype.setRule = function(selector, attribute, value) {
var i = this.indexOf(selector);
if(-1 == i) return false;
this.rules[i].style[attribute] = value;
return true;
};
styleCss.prototype.getRule = function(selector, attribute) {
var i = this.indexOf(selector);
if(-1 == i) return '';
var value = '';
if (typeof attribute == 'undefined') {
value = typeof this.rules[i].cssText != 'undefined' ? this.rules[i].cssText : this.rules[i].style['cssText'];
} else {
value = this.rules[i].style[attribute];
}
return typeof value != 'undefined' ? value : '';
};
styleCss.prototype.removeAllRule = function(noSearch) {
var num = this.rules.length;
var j = 0;
for(var i = 0; i < num; i ++) {
var selector = this.rules[this.rules.length - 1 - j].selectorText;
if(noSearch == 1) {
this.sheet.removeRule ? this.sheet.removeRule(this.rules.length - 1 - j) : this.sheet.deleteRule(this.rules.length - 1 - j);
} else {
j++;
}
}
};
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (element, index) {
var length = this.length;
if (index == null) {
index = 0;
} else {
index = (!isNaN(index) ? index : parseInt(index));
if (index < 0) index = length + index;
if (index < 0) index = 0;
}
for (var i = index; i < length; i++) {
var current = this[i];
if (!(typeof(current) === 'undefined') || i in this) {
if (current === element) return i;
}
}
return -1;
};
}
if (!Array.prototype.filter){
Array.prototype.filter = function(fun , thisp){
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++){
if (i in this){
var val = this[i];
if (fun.call(thisp, val, i, this)) res.push(val);
}
}
return res;
};
}
var Util = {
event: function(event){
Util.e = event || window.event;
Util.e.aim = Util.e.target || Util.e.srcElement;
if (!Util.e.preventDefault) {
Util.e.preventDefault = function(){
Util.e.returnValue = false;
};
}
if (!Util.e.stopPropagation) {
Util.e.stopPropagation = function(){
Util.e.cancelBubble = true;
};
}
if (typeof Util.e.layerX == "undefined") {
Util.e.layerX = Util.e.offsetX;
}
if (typeof Util.e.layerY == "undefined") {
Util.e.layerY = Util.e.offsetY;
}
if (typeof Util.e.which == "undefined") {
Util.e.which = Util.e.button;
}
return Util.e;
},
url: function(s){
var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1');
if (/\\\\$/.test(s2)) {
s2 += ' ';
}
return "url('" + s2 + "')";
},
trimUrl : function(s){
var s2 = s.toLowerCase().replace(/url\(|\"|\'|\)/g,'');
return s2;
},
swapDomNodes: function(a, b){
var afterA = a.nextSibling;
if (afterA == b) {
swapDomNodes(b, a);
return;
}
var aParent = a.parentNode;
b.parentNode.replaceChild(a, b);
aParent.insertBefore(b, afterA);
},
hasClass: function(el, name){
return el && el.nodeType == 1 && el.className.split(/\s+/).indexOf(name) != -1;
},
addClass: function(el, name){
el.className += this.hasClass(el, name) ? '' : ' ' + name;
},
removeClass: function(el, name){
var names = el.className.split(/\s+/);
el.className = names.filter(function(n){
return name != n;
}).join(' ');
},
getTarget: function(e, attributeName, value){
var target = e.target || e.srcElement;
while (target != null) {
if (attributeName == 'className') {
if (this.hasClass(target, value)) {
return target;
}
}else if (target[attributeName] == value) {
return target;
}
target = target.parentNode;
}
return false;
},
getOffset:function (el, isLeft) {
var retValue = 0 ;
while (el != null ) {
retValue += el["offset" + (isLeft ? "Left" : "Top" )];
el = el.offsetParent;
}
return retValue;
},
insertBefore: function (newNode, targetNode) {
var parentNode = targetNode.parentNode;
var next = targetNode.nextSibling;
if (targetNode.id && targetNode.id.indexOf('temp')>-1) {
parentNode.insertBefore(newNode,targetNode);
} else if (!next) {
parentNode.appendChild(newNode);
} else {
parentNode.insertBefore(newNode,targetNode);
}
},
insertAfter : function (newNode, targetNode) {
var parentNode = targetNode.parentNode;
var next = targetNode.nextSibling;
if (next) {
parentNode.insertBefore(newNode,next);
} else {
parentNode.appendChild(newNode);
}
},
getScroll: function () {
var t, l, w, h;
if (document.documentElement && document.documentElement.scrollTop) {
t = document.documentElement.scrollTop;
l = document.documentElement.scrollLeft;
w = document.documentElement.scrollWidth;
h = document.documentElement.scrollHeight;
} else if (document.body) {
t = document.body.scrollTop;
l = document.body.scrollLeft;
w = document.body.scrollWidth;
h = document.body.scrollHeight;
}
return {t: t, l: l, w: w, h: h};
},
hide:function (ele){
if (typeof ele == 'string') {ele = $(ele);}
if (ele){ele.style.display = 'none';}
},
show:function (ele){
if (typeof ele == 'string') {ele = $(ele);}
if (ele) {
this.removeClass(ele, 'hide');
ele.style.display = '';
}
},
cancelSelect : function () {
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
},
getSelectText : function () {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
} else {
t = '';
}
return t;
},
toggleEle : function (ele) {
ele = (typeof ele !='object') ? $(ele) : ele;
if (!ele) return false;
var value = this.getFinallyStyle(ele,'display');
if (value =='none') {
this.show(ele);
this.hide($('uploadmsg_button'));
} else {
this.hide(ele);
this.show($('uploadmsg_button'));
}
},
getFinallyStyle : function (ele,property) {
ele = (typeof ele !='object') ? $(ele) : ele;
var style = (typeof(ele['currentStyle']) == 'undefined') ? window.getComputedStyle(ele,null)[property] : ele['currentStyle'][property];
if (typeof style == 'undefined' && property == 'backgroundPosition') {
style = ele['currentStyle']['backgroundPositionX'] + ' ' +ele['currentStyle']['backgroundPositionY'];
}
return style;
},
recolored:function (){
var b = document.body;
b.style.zoom = b.style.zoom=="1"?"100%":"1";
},
getRandom : function (len,type) {
len = len < 0 ? 0 : len;
type = type && type<=3? type : 3;
var str = '';
for (var i = 0; i < len; i++) {
var j = Math.ceil(Math.random()*type);
if (j == 1) {
str += Math.ceil(Math.random()*9);
} else if (j == 2) {
str += String.fromCharCode(Math.ceil(Math.random()*25+65));
} else {
str += String.fromCharCode(Math.ceil(Math.random()*25+97));
}
}
return str;
},
fade : function(obj,timer,ftype,cur,fn) {
if (this.stack == undefined) {this.stack = [];}
obj = typeof obj == 'string' ? $(obj) : obj;
if (!obj) return false;
for (var i=0;i<this.stack.length;i++) {
if (this.stack[i] == obj && (cur == 0 || cur == 100)) return false;
}
if (cur == 0 || cur == 100) {this.stack.push(obj);}
ftype = ftype != 'in' && ftype != 'out' ? 'out' : ftype;
timer = timer || 400;
var step = 100/(timer/20);
obj.style.filter = 'Alpha(opacity=' + cur + ')';
obj.style.opacity = cur / 100;
cur = ftype == 'in' ? cur + step : cur - step ;
var fadeTimer = (function(){
return setTimeout(function () {
Util.fade(obj, timer, ftype, cur, fn);
}, 20);
})();
this[ftype == 'in' ? 'show' : 'hide'](obj);
if(ftype == 'in' && cur >= 100 || ftype == 'out' && cur <= 0) {
clearTimeout(fadeTimer);
for (i=0;i<this.stack.length;i++) {
if (this.stack[i] == obj ) {
this.stack.splice(i,1);break;
}
}
fn = fn || function(){};
fn(obj);
}
return obj;
},
fadeIn : function (obj,timer,fn) {
return this.fade(obj, timer, 'in', 0, fn);
},
fadeOut : function (obj,timer,fn) {
return this.fade(obj, timer, 'out', 100, fn);
},
getStyle : function (ele) {
if (ele) {
var s = ele.getAttribute('style') || '';
return typeof s == 'object' ? s.cssText : s;
}
return false;
},
setStyle : function (ele,cssText) {
if (ele) {
var s = ele.getAttribute('style') || '';
return typeof s == 'object' ? s.cssText = cssText : ele.setAttribute('style',cssText);
}
return false;
},
getText : function (ele) {
var t = ele.innerText ? ele.innerText : ele.textContent;
return !t ? '' : t;
},
rgb2hex : function (color) {
if (!color) return '';
var reg = new RegExp('(\\d+)[, ]+(\\d+)[, ]+(\\d+)','g');
var rgb = reg.exec(color);
if (rgb == null) rgb = [0,0,0,0];
var red = rgb[1], green = rgb[2], blue = rgb[3];
var decColor = 65536 * parseInt(red) + 256 * parseInt(green) + parseInt(blue);
var hex = decColor.toString(16).toUpperCase();
var pre = new Array(6 - hex.length + 1).join('0');
hex = pre + hex;
return hex;
},
formatColor : function (color) {
return color == '' || color.indexOf('#')>-1 || color.toLowerCase() == 'transparent' ? color : '#'+Util.rgb2hex(color);
}
};
(function(){
Frame = function(name, className, top, left, moveable){
this.name = name;
this.top = top;
this.left = left;
this.moveable = moveable ? true : false;
this.columns = [];
this.className = className;
this.titles = [];
if (typeof Frame._init == 'undefined') {
Frame.prototype.addColumn = function (column) {
if (column instanceof Column) {
this.columns[column.name] = column;
}
};
Frame.prototype.addFrame = function(columnId, frame) {
if (frame instanceof Frame || frame instanceof Tab){
this.columns[columnId].children.push(frame);
}
};
Frame.prototype.addBlock = function(columnId, block) {
if (block instanceof Block){
this.columns[columnId].children.push(block);
}
};
}
Frame._init = true;
};
Column = function (name, className) {
this.name = name;
this.className = className;
this.children = [];
};
Tab = function (name, className, top, left, moveable) {
Frame.apply(this, arguments);
};
Tab.prototype = new Frame();
Block = function(name, className, top, left) {
this.name = name;
this.top = top;
this.left = left;
this.className = className;
this.titles = [];
};
Drag = function () {
this.data = [];
this.scroll = {};
this.menu = [];
this.data = [];
this.allBlocks = [];
this.overObj = '';
this.dragObj = '';
this.dragObjFrame = '';
this.overObjFrame = '';
this.isDragging = false;
this.layout = 2;
this.frameClass = 'frame';
this.blockClass = 'block';
this.areaClass = 'area';
this.moveableArea = [];
this.moveableColumn = 'column';
this.moveableObject = 'move-span';
this.titleClass = 'title';
this.hideClass = 'hide';
this.titleTextClass = 'titletext';
this.frameTitleClass = 'frame-title',
this.tabClass = 'frame-tab';
this.tabActivityClass = 'tabactivity';
this.tabTitleClass = 'tab-title';
this.tabContentClass = 'tb-c';
this.moving = 'moving';
this.contentClass = 'dxb_bc';
this.tmpBoxElement = null ;
this.dargRelative = {};
this.scroll = {};
this.menu = [];
this.rein = [];
this.newFlag = false;
this.isChange = false;
this.fn = '';
this._replaceFlag = false;
this.sampleMode = false;
this.sampleBlocks = null;
this.advancedStyleSheet = null;
};
Drag.prototype = {
getTmpBoxElement : function () {
if (!this.tmpBoxElement) {
this.tmpBoxElement = document.createElement("div");
this.tmpBoxElement.id = 'tmpbox';
this.tmpBoxElement.className = "tmpbox" ;
this.tmpBoxElement.style.width = this.overObj.offsetWidth-4+"px";
this.tmpBoxElement.style.height = this.overObj.offsetHeight-4+"px";
} else if (this.overObj && this.overObj.offsetWidth > 0) {
this.tmpBoxElement.style.width = this.overObj.offsetWidth-4+"px";
}
return this.tmpBoxElement;
},
getPositionStr : function (){
this.initPosition();
var start = '<?xml version="1.0" encoding="ISO-8859-1"?><root>';
var end ="</root>";
var str = "";
for (var i in this.data) {
if (typeof this.data[i] == 'function') continue;
str += '<item id="' + i + '">';
for (var j in this.data[i]) {
if (!(this.data[i][j] instanceof Frame || this.data[i][j] instanceof Tab)) continue;
str += this._getFrameXML(this.data[i][j]);
}
str += '</item>';
}
return start + str + end;
},
_getFrameXML : function (frame) {
if (!(frame instanceof Frame || frame instanceof Tab) || frame.name.indexOf('temp') > 0) return '';
var itemId = frame instanceof Tab ? 'tab' : 'frame';
var Cstr = "";
var name = frame.name;
var frameAttr = this._getAttrXML(frame);
var columns = frame['columns'];
for (var j in columns) {
if (columns[j] instanceof Column) {
var Bstr = '';
var colChildren = columns[j].children;
for (var k in colChildren) {
if (k == 'attr' || typeof colChildren[k] == 'function' || colChildren[k].name.indexOf('temp') > 0) continue;
if (colChildren[k] instanceof Block) {
Bstr += '<item id="block`' + colChildren[k]['name'] + '">';
Bstr += this._getAttrXML(colChildren[k]);
Bstr += '</item>';
} else if (colChildren[k] instanceof Frame || colChildren[k] instanceof Tab) {
Bstr += this._getFrameXML(colChildren[k]);
}
}
var columnAttr = this._getAttrXML(columns[j]);
Cstr += '<item id="column`' + j + '">' + columnAttr + Bstr + '</item>';
}
}
return '<item id="' + itemId + '`' + name + '">' + frameAttr + Cstr + '</item>';
},
_getAttrXML : function (obj) {
var attrXml = '<item id="attr">';
var trimAttr = ['left', 'top'];
var xml = '';
if (obj instanceof Frame || obj instanceof Tab || obj instanceof Block || obj instanceof Column) {
for (var i in obj) {
if (i == 'titles') {
xml += this._getTitlesXML(obj[i]);
}
if (!(typeof obj[i] == 'object' || typeof obj[i] == 'function')) {
if (trimAttr.indexOf(i) >= 0) continue;
xml += '<item id="' + i + '"><![CDATA[' + obj[i] + ']]></item>';
}
}
}else {
xml += '';
}
return attrXml + xml + '</item>';
},
_getTitlesXML : function (titles) {
var xml = '<item id="titles">';
for (var i in titles) {
if (typeof titles[i] == 'function') continue;
xml += '<item id="'+i+'">';
for (var j in titles[i]) {
if (typeof titles[i][j] == 'function') continue;
xml += '<item id="'+j+'"><![CDATA[' + titles[i][j] + ']]></item>';
}
xml += '</item>';
}
xml += '</item>';
return xml;
},
getCurrentOverObj : function (e) {
var _clientX = parseInt(this.dragObj.style.left);
var _clientY = parseInt(this.dragObj.style.top);
var max = 10000000;
for (var i in this.data) {
for (var j in this.data[i]) {
if (!(this.data[i][j] instanceof Frame || this.data[i][j] instanceof Tab)) continue;
var min = this._getMinDistance(this.data[i][j], max);
if (min.distance < max) {
var id = min.id;
max = min.distance;
}
}
}
return $(id);
},
_getMinDistance : function (ele, max) {
if(ele.name==this.dragObj.id) return {"id":ele.name, "distance":max};
var _clientX = parseInt(this.dragObj.style.left);
var _clientY = parseInt(this.dragObj.style.top);
var id;
var isTabInTab = Util.hasClass(this.dragObj, this.tabClass) && Util.hasClass($(ele.name).parentNode.parentNode, this.tabClass);
if (ele instanceof Frame || ele instanceof Tab) {
if (ele.moveable && !isTabInTab) {
var isTab = Util.hasClass(this.dragObj, this.tabClass);
var isFrame = Util.hasClass(this.dragObj, this.frameClass);
var isBlock = Util.hasClass(this.dragObj, this.blockClass) && Util.hasClass($(ele.name).parentNode, this.moveableColumn);
if ( isTab || isFrame || isBlock) {
var _Y = ele['top'] - _clientY;
var _X = ele['left'] - _clientX;
var distance = Math.sqrt(Math.pow(_X, 2) + Math.pow(_Y, 2));
if (distance < max) {
max = distance;
id = ele.name;
}
}
}
for (var i in ele['columns']) {
var column = ele['columns'][i];
if (column instanceof Column) {
for (var j in column['children']) {
if ((column['children'][j] instanceof Tab || column['children'][j] instanceof Frame || column['children'][j] instanceof Block)) {
var min = this._getMinDistance(column['children'][j], max);
if (min.distance < max) {
id = min.id;
max = min.distance;
}
}
}
}
}
return {"id":id, "distance":max};
} else {
if (isTabInTab) return {'id': ele['name'], 'distance': max};
var _Y = ele['top'] - _clientY;
var _X = ele['left'] - _clientX;
var distance = Math.sqrt(Math.pow(_X, 2) + Math.pow(_Y, 2));
if (distance < max) {
return {'id': ele['name'], 'distance': distance};
} else {
return {'id': ele['name'], 'distance': max};
}
}
},
getObjByName : function (name, data) {
if (!name) return false;
data = data || this.data;
if ( data instanceof Frame) {
if (data.name == name) {
return data;
} else {
var d = this.getObjByName(name,data['columns']);
if (name == d.name) return d;
}
} else if (data instanceof Block) {
if (data.name == name) return data;
} else if (typeof data == 'object') {
for (var i in data) {
var d = this.getObjByName(name, data[i]);
if (name == d.name) return d;
}
}
return false;
},
initPosition : function () {
this.data = [],this.allBlocks = [];
var blocks = $C(this.blockClass);
for(var i = 0; i < blocks.length; i++) {
if (blocks[i]['id'].indexOf('temp') < 0) {
this.checkEdit(blocks[i]);
this.allBlocks.push(blocks[i]['id'].replace('portal_block_',''));
}
}
var areaLen = this.moveableArea.length;
for (var j = 0; j < areaLen; j++ ) {
var area = this.moveableArea[j];
var areaData = [];
if (typeof area == 'object') {
this.checkTempDiv(area.id);
var frames = area.childNodes;
for (var i in frames) {
if (typeof(frames[i]) != 'object') continue;
if (Util.hasClass(frames[i], this.frameClass) || Util.hasClass(frames[i], this.blockClass)
|| Util.hasClass(frames[i], this.tabClass) || Util.hasClass(frames[i], this.moveableObject)) {
areaData.push(this.initFrame(frames[i]));
}
}
this.data[area.id] = areaData;
}
}
this._replaceFlag = true;
},
removeBlockPointer : function(e) {this.removeBlock(e);},
toggleContent : function (e) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('_edit_toggle','');
} else {
id = e;
}
var obj = this.getObjByName(id);
var display = '';
if (obj instanceof Block || obj instanceof Tab) {
display = $(id+'_content').style.display;
Util.toggleEle(id+'_content');
} else {
var col = obj.columns;
for (var i in col) {
display = $(i).style.display;
Util.toggleEle($(i));
}
}
if(display != '') {
e.aim.src=STATICURL+'/image/common/fl_collapsed_no.gif';
} else {
e.aim.src=STATICURL+'/image/common/fl_collapsed_yes.gif';
}
},
checkEdit : function (ele) {
if (!ele || Util.hasClass(ele, 'temp') || ele.getAttribute('noedit')) return false;
var id = ele.id;
var _method = this;
if (!$(id+'_edit')) {
var _method = this;
var dom = document.createElement('div');
dom.className = 'edit hide';
dom.id = id+'_edit';
dom.innerHTML = '<span id="'+id+'_edit_menu">编辑</span>';
ele.appendChild(dom);
$(id+'_edit_menu').onclick = function (e){Drag.prototype.toggleMenu.call(_method, e, this);};
}
ele.onmouseover = function (e) {Drag.prototype.showEdit.call(_method,e);};
ele.onmouseout = function (e) {Drag.prototype.hideEdit.call(_method,e);};
},
initFrame : function (frameEle) {
if (typeof(frameEle) != 'object') return '';
var frameId = frameEle.id;
if(!this.sampleMode) {
this.checkEdit(frameEle);
}
var moveable = Util.hasClass(frameEle, this.moveableObject);
var frameObj = '';
if (Util.hasClass(frameEle, this.tabClass)) {
this._initTabActivity(frameEle);
frameObj = new Tab(frameId, frameEle.className, Util.getOffset(frameEle,false), Util.getOffset(frameEle,true), moveable);
} else if (Util.hasClass(frameEle, this.frameClass) || Util.hasClass(frameEle, this.moveableObject)) {
if (Util.hasClass(frameEle, this.frameClass) && !this._replaceFlag) this._replaceFrameColumn(frameEle);
frameObj = new Frame(frameId, frameEle.className, Util.getOffset(frameEle,false), Util.getOffset(frameEle,true), moveable);
}
this._initColumn(frameObj, frameEle);
return frameObj;
},
_initColumn : function (frameObj,frameEle) {
var columns = frameEle.children;
if (Util.hasClass(frameEle.parentNode.parentNode,this.tabClass)) {
var col2 = $(frameEle.id+'_content').children;
var len = columns.length;
for (var i in col2) {
if (typeof(col2[i]) == 'object') columns[len+i] = col2[i];
}
}
for (var i in columns) {
if (typeof(columns[i]) != 'object') continue;
if (Util.hasClass(columns[i], this.titleClass)) {
this._initTitle(frameObj, columns[i]);
}
this._initEleTitle(frameObj, frameEle);
if (Util.hasClass(columns[i], this.moveableColumn)) {
var columnId = columns[i].id;
var column = new Column(columnId, columns[i].className);
frameObj.addColumn(column);
this.checkTempDiv(columnId);
var elements = columns[i].children;
var eleLen = elements.length;
for (var j = 0; j < eleLen; j++) {
var ele = elements[j];
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
var frameObj2 = this.initFrame(ele);
frameObj.addFrame(columnId, frameObj2);
} else if (Util.hasClass(ele, this.blockClass) || Util.hasClass(ele, this.moveableObject)) {
var block = new Block(ele.id, ele.className, Util.getOffset(ele, false), Util.getOffset(ele, true));
for (var k in ele.children) {
if (Util.hasClass(ele.children[k], this.titleClass)) this._initTitle(block, ele.children[k]);
}
this._initEleTitle(block, ele);
frameObj.addBlock(columnId, block);
}
}
}
}
},
_initTitle : function (obj, ele) {
if (Util.hasClass(ele, this.titleClass)) {
obj.titles['className'] = [ele.className];
obj.titles['style'] = {};
if (ele.style.backgroundImage) obj.titles['style']['background-image'] = ele.style.backgroundImage;
if (ele.style.backgroundRepeat) obj.titles['style']['background-repeat'] = ele.style.backgroundRepeat;
if (ele.style.backgroundColor) obj.titles['style']['background-color'] = ele.style.backgroundColor;
if (obj instanceof Tab) {
obj.titles['switchType'] = [];
obj.titles['switchType'][0] = ele.getAttribute('switchtype') ? ele.getAttribute('switchtype') : 'click';
}
var ch = ele.children;
for (var k in ch) {
if (Util.hasClass(ch[k], this.titleTextClass)){
this._getTitleData(obj, ch[k], 'first');
} else if (typeof ch[k] == 'object' && !Util.hasClass(ch[k], this.moveableObject)) {
this._getTitleData(obj, ch[k]);
}
}
}
},
_getTitleData : function (obj, ele, i) {
var shref = '',ssize = '',sfloat = '',scolor = '',smargin = '',stext = '', src = '';
var collection = ele.getElementsByTagName('a');
if (collection.length > 0) {
shref = collection[0]['href'];
scolor = collection[0].style['color'];
}
collection = ele.getElementsByTagName('img');
if (collection.length > 0) {
src = collection[0]['src'];
}
stext = Util.getText(ele);
if (stext || src) {
scolor = scolor ? scolor : ele.style['color'];
sfloat = ele.style['styleFloat'] ? ele.style['styleFloat'] : ele.style['cssFloat'] ;
sfloat = sfloat == undefined ? '' : sfloat;
var margin_ = sfloat == '' ? 'left' : sfloat;
smargin = parseInt(ele.style[('margin-'+margin_).property2js()]);
smargin = smargin ? smargin : '';
ssize = parseInt(ele.style['fontSize']);
ssize = ssize ? ssize : '';
var data = {'text':stext, 'href':shref,'color':scolor, 'float':sfloat, 'margin':smargin, 'font-size':ssize, 'className':ele.className, 'src':src};
if (i) {
obj.titles[i] = data;
} else {
obj.titles.push(data);
}
}
},
_initEleTitle : function (obj,ele) {
if (Util.hasClass(ele, this.moveableObject)) {
if (obj.titles['first'] && obj.titles['first']['text']) {
var title = obj.titles['first']['text'];
} else {
var title = obj.name;
}
}
},
showEdit : function (e) {
e = Util.event(e);
var targetObject = Util.getTarget(e,'className',this.moveableObject);
if (targetObject) {
Util.show(targetObject.id + '_edit');
targetObject.style.backgroundColor="#fffacd";
} else {
var targetFrame = Util.getTarget(e,'className',this.frameClass);
if (typeof targetFrame == 'object') {
Util.show(targetFrame.id + '_edit');
targetFrame.style.backgroundColor="#fffacd";
}
}
},
hideEdit : function (e) {
e = Util.event(e);
var targetObject = Util.getTarget(e,'className',this.moveableObject);
var targetFrame = Util.getTarget(e,'className',this.frameClass);
if (typeof targetFrame == 'object') {
Util.hide(targetFrame.id + '_edit');
targetFrame.style.backgroundColor = '';
}
if (typeof targetObject == 'object') {
Util.hide(targetObject.id + '_edit');
targetObject.style.backgroundColor = '';
}
},
toggleMenu : function (e, obj) {
e = Util.event(e);
e.stopPropagation();
var objPara = {'top' : Util.getOffset( obj, false),'left' : Util.getOffset( obj, true),
'width' : obj['offsetWidth'], 'height' : obj['offsetHeight']};
var dom = $('edit_menu');
if (dom) {
if (objPara.top + objPara.height == Util.getOffset(dom, false) && objPara.left == Util.getOffset(dom, true)) {
dom.parentNode.removeChild(dom);
} else {
dom.style.top = objPara.top + objPara.height + 'px';
dom.style.left = objPara.left + 'px';
dom.innerHTML = this._getMenuHtml(e, obj);
}
} else {
var html = this._getMenuHtml(e, obj);
if (html != '') {
dom = document.createElement('div');
dom.id = 'edit_menu';
dom.className = 'edit-menu';
dom.style.top = objPara.top + objPara.height + 'px';
dom.style.left = objPara.left + 'px';
dom.innerHTML = html;
document.body.appendChild(dom);
var _method = this;
document.body.onclick = function(e){Drag.prototype.removeMenu.call(_method, e);};
}
}
},
_getMenuHtml : function (e,obj) {
var id = obj.id.replace('_edit_menu','');
var html = '<ul>';
if (typeof this.menu[id] == 'object') html += this._getMenuHtmlLi(id, this.menu[id]);
if (Util.hasClass($(id),this.tabClass) && typeof this.menu['tab'] == 'object') html += this._getMenuHtmlLi(id, this.menu['tab']);
if (Util.hasClass($(id),this.frameClass) && typeof this.menu['frame'] == 'object') html += this._getMenuHtmlLi(id, this.menu['frame']);
if (Util.hasClass($(id),this.blockClass) && typeof this.menu['block'] == 'object') html += this._getMenuHtmlLi(id, this.menu['block']);
if (typeof this.menu['default'] == 'object' && this.getObjByName(id)) html += this._getMenuHtmlLi(id, this.menu['default']);
html += '</ul>';
return html == '<ul></ul>' ? '' : html;
},
_getMenuHtmlLi : function (id, cmds) {
var li = '';
var len = cmds.length;
for (var i=0; i<len; i++) {
li += '<li class="mitem" id="cmd_'+id+'" onclick='+"'"+cmds[i]['cmd']+"'"+'>'+cmds[i]['cmdName']+'</li>';
}
return li;
},
removeMenu : function (e) {
var dom = $('edit_menu');
if (dom) dom.parentNode.removeChild(dom);
document.body.onclick = '';
},
addMenu : function (objId,cmdName,cmd) {
if (typeof this.menu[objId] == 'undefined') this.menu[objId] = [];
this.menu[objId].push({'cmdName':cmdName, 'cmd':cmd});
},
setDefalutMenu : function () {},
setSampleMenu : function () {},
getPositionKey : function (n) {
this.initPosition();
n = parseInt(n);
var i = 0;
for (var k in this.position) {
if (i++ >= n) break;
}
return k;
},
checkTempDiv : function (_id) {
if(_id) {
var id = _id+'_temp';
var dom = $(id);
if (dom == null || typeof dom == 'undefined') {
dom = document.createElement("div");
dom.className = this.moveableObject+' temp';
dom.id = id;
$(_id).appendChild(dom);
}
}
},
_setCssPosition : function (ele, value) {
while (ele && ele.parentNode && ele.id != 'ct') {
if (Util.hasClass(ele,this.frameClass) || Util.hasClass(ele,this.tabClass)) ele.style.position = value;
ele = ele.parentNode;
}
},
initDragObj : function (e) {
e = Util.event(e);
var target = Util.getTarget(e,'className',this.moveableObject);
if (!target) {return false;}
if (this.overObj != target && target.id !='tmpbox') {
this.overObj = target;
this.overObj.style.cursor = 'move';
}
},
dragStart : function (e) {
e = Util.event(e);
if (e.aim['id'] && e.aim['id'].indexOf && e.aim['id'].indexOf('_edit') > 0) return false;
if(e.which != 1 ) {return false;}
this.overObj = this.dragObj = Util.getTarget(e,'className',this.moveableObject);
if (!this.dragObj || Util.hasClass(this.dragObj,'temp')) {return false;}
if (!this.getTmpBoxElement()) return false;
this.getRelative();
this._setCssPosition(this.dragObj.parentNode.parentNode, "static");
var offLeft = Util.getOffset( this.dragObj, true );
var offTop = Util.getOffset( this.dragObj, false );
var offWidth = this.dragObj['offsetWidth'];
this.dragObj.style.position = 'absolute';
this.dragObj.style.left = offLeft + "px";
this.dragObj.style.top = offTop - 3 + "px";
this.dragObj.style.width = offWidth + 'px';
this.dragObj.lastMouseX = e.clientX;
this.dragObj.lastMouseY = e.clientY;
Util.insertBefore(this.tmpBoxElement,this.overObj);
Util.addClass(this.dragObj,this.moving);
this.dragObj.style.zIndex = 500 ;
this.scroll = Util.getScroll();
var _method = this;
document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);};
},
getRelative : function () {
this.dargRelative = {'up': this.dragObj.previousSibling, 'down': this.dragObj.nextSibling};
},
resetObj : function (e) {
if (this.dragObj){
e = Util.event(e);
var p = Util.getScroll();
var _t = p.t - this.scroll.t;
var _l = p.l - this.scroll.l;
var t = parseInt(this.dragObj.style.top);
var l = parseInt(this.dragObj.style.left);
t += _t;
l += _l;
this.dragObj.style.top =t+'px';
this.dragObj.style.left =l+'px';
this.scroll = Util.getScroll();
}
},
drag : function (e) {
e = Util.event(e);
if(!this.isDragging) {
this.dragObj.style.filter = "alpha(opacity=60)" ;
this.dragObj.style.opacity = 0.6 ;
this.isDragging = true ;
}
var _clientX = e.clientX;
var _clientY = e.clientY;
if (this.dragObj.lastMouseX == _clientX && this.dragObj.lastMouseY == _clientY) return false ;
var _lastY = parseInt(this.dragObj.style.top);
var _lastX = parseInt(this.dragObj.style.left);
_lastX = isNaN(_lastX) ? 0 :_lastX;
_lastY = isNaN(_lastY) ? 0 :_lastY;
var newX, newY;
newY = _lastY + _clientY - this.dragObj.lastMouseY;
newX = _lastX + _clientX - this.dragObj.lastMouseX;
this.dragObj.style.left = newX +"px ";
this.dragObj.style.top = newY + "px ";
this.dragObj.lastMouseX = _clientX;
this.dragObj.lastMouseY = _clientY;
var obj = this.getCurrentOverObj(e);
if (obj && this.overObj != obj) {
this.overObj = obj;
this.getTmpBoxElement();
Util.insertBefore(this.tmpBoxElement, this.overObj);
this.dragObjFrame = this.dragObj.parentNode.parentNode;
this.overObjFrame = this.overObj.parentNode.parentNode;
}
Util.cancelSelect();
},
_pushTabContent : function (tab, ele){
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
var dom = $(ele.id+'_content');
if (!dom) {
dom = document.createElement('div');
dom.id = ele.id+'_content';
dom.className = Util.hasClass(ele, this.frameClass) ? this.contentClass+' cl '+ele.className.substr(ele.className.lastIndexOf(' ')+1) : this.contentClass+' cl';
}
var frame = this.getObjByName(ele.id);
if (frame) {
for (var i in frame['columns']) {
if (frame['columns'][i] instanceof Column) dom.appendChild($(i));
}
} else {
var children = ele.childNodes;
var arrDom = [];
for (var i in children) {
if (typeof children[i] != 'object') continue;
if (Util.hasClass(children[i],this.moveableColumn) || Util.hasClass(children[i],this.tabContentClass)) {
arrDom.push(children[i]);
}
}
var len = arrDom.length;
for (var i = 0; i < len; i++) {
dom.appendChild(arrDom[i]);
}
}
$(tab.id+'_content').appendChild(dom);
} else if (Util.hasClass(ele, this.blockClass)) {
if ($(ele.id+'_content')) $(tab.id+'_content').appendChild($(ele.id+'_content'));
}
},
_popTabContent : function (tab, ele){
if (Util.hasClass(ele, this.frameClass) || Util.hasClass(ele, this.tabClass)) {
Util.removeClass(ele, this.tabActivityClass);
var eleContent = $(ele.id+'_content');
if (!eleContent) return false;
var children = eleContent.childNodes;
var arrEle = [];
for (var i in children) {
if (typeof children[i] == 'object') arrEle.push(children[i]);
}
var len = arrEle.length;
for (var i = 0; i < len; i++) {
ele.appendChild(arrEle[i]);
}
children = '';
$(tab.id+'_content').removeChild(eleContent);
} else if (Util.hasClass(ele, this.blockClass)) {
if ($(ele.id+'_content')) Util.show($(ele.id+'_content'));
if ($(ele.id+'_content')) ele.appendChild($(ele.id+'_content'));
}
},
_initTabActivity : function (ele) {
if (!Util.hasClass(ele,this.tabClass)) return false;
var tabs = $(ele.id+'_title').childNodes;
var arrTab = [];
for (var i in tabs) {
if (typeof tabs[i] != 'object') continue;
var tabId = tabs[i].id;
if (Util.hasClass(tabs[i],this.frameClass) || Util.hasClass(tabs[i],this.tabClass)) {
if (!this._replaceFlag) this._replaceFrameColumn(tabs[i]);
if (!$(tabId + '_content')) {
var arrColumn = [];
for (var j in tabs[i].childNodes) {
if (Util.hasClass(tabs[i].childNodes[j], this.moveableColumn)) arrColumn.push(tabs[i].childNodes[j]);
}
var frameContent = document.createElement('div');
frameContent.id = tabId + '_content';
frameContent.className = Util.hasClass(tabs[i], this.frameClass) ? this.contentClass+' cl '+tabs[i].className.substr(tabs[i].className.lastIndexOf(' ')+1) : this.contentClass+' cl';
var colLen = arrColumn.length;
for (var k = 0; k < colLen; k++) {
frameContent.appendChild(arrColumn[k]);
}
}
arrTab.push(tabs[i]);
} else if (Util.hasClass(tabs[i],this.blockClass)) {
var frameContent = $(tabId+'_content');
if (frameContent) {
frameContent = Util.hasClass(frameContent.parentNode,this.blockClass) ? frameContent : '';
} else {
frameContent = document.createElement('div');
frameContent.id = tabId+'_content';
}
arrTab.push(tabs[i]);
}
if (frameContent) $(ele.id + '_content').appendChild(frameContent);
}
var len = arrTab.length;
for (var i = 0; i < len; i++) {
Util[i > 0 ? 'hide' : 'show']($(arrTab[i].id+'_content'));
}
},
dragEnd : function (e) {
e = Util.event(e);
if(!this.dragObj) {return false;}
document.onscroll = function(){};
window.onscroll = function(){};
document.onmousemove = function(e){};
document.onmouseup = '';
if (this.tmpBoxElement.parentNode) {
if (this.tmpBoxElement.parentNode == document.body) {
document.body.removeChild(this.tmpBoxElement);
document.body.removeChild(this.dragObj);
this.fn = '';
} else {
Util.removeClass(this.dragObj,this.moving);
this.dragObj.style.display = 'none';
this.dragObj.style.width = '' ;
this.dragObj.style.top = '';
this.dragObj.style.left = '';
this.dragObj.style.zIndex = '';
this.dragObj.style.position = 'relative';
this.dragObj.style.backgroundColor = '';
this.isDragging = false ;
this.tmpBoxElement.parentNode.replaceChild(this.dragObj, this.tmpBoxElement);
Util.fadeIn(this.dragObj);
this.tmpBoxElement='';
this._setCssPosition(this.dragObjFrame, 'relative');
this.doEndDrag();
this.initPosition();
if (!(this.dargRelative.up == this.dragObj.previousSibling && this.dargRelative.down == this.dragObj.nextSibling)) {
this.setClose();
}
this.dragObjFrame = this.overObjFrame = null;
}
}
this.newFlag = false;
if (typeof this.fn == 'function') {this.fn();}
},
doEndDrag : function () {
if (!Util.hasClass(this.dragObjFrame, this.tabClass) && Util.hasClass(this.overObjFrame, this.tabClass)) {
this._pushTabContent(this.overObjFrame, this.dragObj);
}else if (Util.hasClass(this.dragObjFrame, this.tabClass) && !Util.hasClass(this.overObjFrame, this.tabClass)) {
this._popTabContent(this.dragObjFrame, this.dragObj);
}else if (Util.hasClass(this.dragObjFrame, this.tabClass) && Util.hasClass(this.overObjFrame, this.tabClass)) {
if (this.dragObjFrame != this.overObjFrame) {
this._popTabContent(this.dragObjFrame, this.dragObj);
this._pushTabContent(this.overObjFrame, this.dragObj);
}
} else {
}
},
_replaceFrameColumn : function (ele,flag) {
var children = ele.childNodes;
var fcn = ele.className.match(/(frame-[\w-]*)/);
if (!fcn) return false;
var frameClassName = fcn[1];
for (var i in children) {
if (Util.hasClass(children[i], this.moveableColumn)) {
var className = children[i].className;
className = className.replace(' col-l', ' '+frameClassName+'-l');
className = className.replace(' col-r', ' '+frameClassName+'-r');
className = className.replace(' col-c', ' '+frameClassName+'-c');
className = className.replace(' mn', ' '+frameClassName+'-l');
className = className.replace(' sd', ' '+frameClassName+'-r');
children[i].className = className;
}
}
},
stopCmd : function () {
this.rein.length > 0 ? this.rein.pop()() : '';
},
setClose : function () {
if (!this.isChange) {
window.onbeforeunload = function() {
return '您的数据已经修改,退出将无法保存您的修改。';
};
}
this.isChange = true;
},
clearClose : function () {
this.isChange = false;
window.onbeforeunload = function () {};
},
_getMoveableArea : function (ele) {
ele = ele ? ele : document.body;
this.moveableArea = $C(this.areaClass, ele, 'div');
},
initMoveableArea : function () {
var _method = this;
this._getMoveableArea();
var len = this.moveableArea.length;
for (var i = 0; i < len; i++) {
var el = this.moveableArea[i];
if (el == null || typeof el == 'undefined') return false;
el.ondragstart = function (e) {return false;};
el.onmouseover = function (e) {Drag.prototype.initDragObj.call(_method, e);};
el.onmousedown = function (e) {Drag.prototype.dragStart.call(_method, e);};
el.onmouseup = function (e) {Drag.prototype.dragEnd.call(_method, e);};
el.onclick = function (e) {e = Util.event(e);e.preventDefault();};
}
if ($('contentframe')) $('contentframe').ondragstart = function (e) {return false;};
},
disableAdvancedStyleSheet : function () {
if(this.advancedStyleSheet) {
this.advancedStyleSheet.disabled = true;
}
},
enableAdvancedStyleSheet : function () {
if(this.advancedStyleSheet) {
this.advancedStyleSheet.disabled = false;
}
},
getStyleSheetIndex : function (name) {
var index = -1;
var all = document.styleSheets;
for (var i=0;i<all.length;i++) {
var ownerNode = all[i].ownerNode || all[i].owningElement;
if (ownerNode.id && ownerNode.id == name) {
index = i;
break;
}
}
return index;
},
init : function (sampleMode) {
this.initCommon();
this.setSampleMode(sampleMode);
if(!this.sampleMode) {
this.initAdvanced();
} else {
this.initSample();
}
return true;
},
initAdvanced : function () {
this.initMoveableArea();
this.initPosition();
this.setDefalutMenu();
this.enableAdvancedStyleSheet();
this.showControlPanel();
this.initTips();
if(this.goonDIY) this.goonDIY();
this.openfn();
},
openfn : function () {
var openfn = loadUserdata('openfn');
if(openfn) {
if(typeof openfn == 'function') {
openfn();
} else {
eval(openfn);
}
saveUserdata('openfn', '');
}
},
initCommon : function () {
var index = this.getStyleSheetIndex('diy_common');
this.advancedStyleSheet = index != -1 ? document.styleSheets[index] : null;
this.menu = [];
},
initSample : function () {
this._getMoveableArea();
this.initPosition();
this.sampleBlocks = $C(this.blockClass);
this.initSampleBlocks();
this.disableAdvancedStyleSheet('diy_common');
this.setSampleMenu();
this.disableAdvancedStyleSheet();
this.hideControlPanel();
},
initSampleBlocks : function () {
if(this.sampleBlocks) {
for(var i = 0; i < this.sampleBlocks.length; i++){
this.checkEdit(this.sampleBlocks[i]);
}
}
},
setSampleMode : function (sampleMode) {
if(loadUserdata('diy_advance_mode')) {
this.sampleMode = '';
} else {
this.sampleMode = sampleMode;
saveUserdata('diy_advance_mode', sampleMode ? '' : '1');
}
},
hideControlPanel : function() {
Util.show('samplepanel');
Util.hide('controlpanel');
Util.hide('diy-tg');
},
showControlPanel : function() {
Util.hide('samplepanel');
Util.show('controlpanel');
Util.show('diy-tg');
},
checkHasFrame : function (obj) {
obj = !obj ? this.data : obj;
for (var i in obj) {
if (obj[i] instanceof Frame && obj[i].className.indexOf('temp') < 0 ) {
return true;
} else if (typeof obj[i] == 'object') {
if (this.checkHasFrame(obj[i])) return true;
}
}
return false;
},
deleteFrame : function (name) {
if (typeof name == 'string') {
if (typeof window['c'+name+'_frame'] == 'object' && !BROWSER.ie) delete window['c'+name+'_frame'];
} else {
for(var i = 0,L = name.length;i < L;i++) {
if (typeof window['c'+name[i]+'_frame'] == 'object' && !BROWSER.ie) delete window['c'+name[i]+'_frame'];
}
}
},
saveViewTip : function (tipname) {
if(tipname) {
saveUserdata(tipname, '1');
Util.hide(tipname);
}
doane();
},
initTips : function () {
var tips = ['diy_backup_tip'];
for(var i = 0; i < tips.length; i++) {
if(tips[i] && !loadUserdata(tips[i])) {
Util.show(tips[i]);
}
}
},
extend : function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
DIY = function() {
this.frames = [];
this.isChange = false;
this.spacecss = [];
this.style = 't1';
this.currentDiy = 'body';
this.opSet = [];
this.opPointer = 0;
this.backFlag = false;
this.styleSheet = {} ;
this.scrollHeight = 0 ;
};
DIY.prototype = {
init : function (mod) {
drag.init(mod);
this.style = document.diyform.style.value;
if (this.style == '') {
var reg = RegExp('topic\(.*)\/style\.css');
var href = $('style_css') ? $('style_css').href : '';
var arr = reg.exec(href);
this.style = arr && arr.length > 1 ? arr[1] : '';
}
this.currentLayout = typeof document.diyform.currentlayout == 'undefined' ? '' : document.diyform.currentlayout.value;
this.initStyleSheet();
if (this.styleSheet.rules) this.initDiyStyle();
},
initStyleSheet : function () {
var all = document.styleSheets;
for (var i=0;i<all.length;i++) {
var ownerNode = all[i].ownerNode || all[i].owningElement;
if (ownerNode.id == 'diy_style') {
this.styleSheet = new styleCss(i);
return true;
}
}
},
initDiyStyle : function (css) {
var allCssText = css || $('diy_style').innerHTML;
allCssText = allCssText ? allCssText.replace(/\n|\r|\t| /g,'') : '';
var random = Math.random(), rules = '';
var reg = new RegExp('(.*?) ?\{(.*?)\}','g');
while((rules = reg.exec(allCssText))) {
var selector = this.checkSelector(rules[1]);
var cssText = rules[2];
var cssarr = cssText.split(';');
var l = cssarr.length;
for (var k = 0; k < l; k++) {
var attribute = trim(cssarr[k].substr(0, cssarr[k].indexOf(':')).toLowerCase());
var value = cssarr[k].substr(cssarr[k].indexOf(':')+1).toLowerCase();
if (!attribute || !value) continue;
if (!this.spacecss[selector]) this.spacecss[selector] = [];
this.spacecss[selector][attribute] = value;
if (css) this.setStyle(selector, attribute, value, random);
}
}
},
checkSelector : function (selector) {
var s = selector.toLowerCase();
if (s.toLowerCase().indexOf('body') > -1) {
var body = BROWSER.ie ? 'BODY' : 'body';
selector = selector.replace(/body/i,body);
}
if (s.indexOf(' a') > -1) {
selector = BROWSER.ie ? selector.replace(/ [aA]/,' A') : selector.replace(/ [aA]/,' a');
}
return selector;
},
initPalette : function (id) {
var bgcolor = '',selector = '',bgimg = '',bgrepeat = '', bgposition = '', bgattachment = '', bgfontColor = '', bglinkColor = '', i = 0;
var repeat = ['repeat','no-repeat','repeat-x','repeat-y'];
var attachment = ['scroll','fixed'];
var position = ['left top','center top','right top','left center','center center','right center','left bottom','center bottom','right bottom'];
var position_ = ['0% 0%','50% 0%','100% 0%','0% 50%','50% 50%','100% 50%','0% 100%','50% 100%','100% 100%'];
selector = this.getSelector(id);
bgcolor = Util.formatColor(this.styleSheet.getRule(selector,'backgroundColor'));
bgimg = this.styleSheet.getRule(selector,'backgroundImage');
bgrepeat = this.styleSheet.getRule(selector,'backgroundRepeat');
bgposition = this.styleSheet.getRule(selector,'backgroundPosition');
bgattachment = this.styleSheet.getRule(selector,'backgroundAttachment');
bgfontColor = Util.formatColor(this.styleSheet.getRule(selector,'color'));
bglinkColor = Util.formatColor(this.styleSheet.getRule(this.getSelector(selector+' a'),'color'));
var selectedIndex = 0;
for (i=0;i<repeat.length;i++) {
if (bgrepeat == repeat[i]) selectedIndex= i;
}
$('repeat_mode').selectedIndex = selectedIndex;
for (i=0;i<attachment.length;i++) {
$('rabga'+i).checked = (bgattachment == attachment[i] ? true : false);
}
var flag = '';
for (i=0;i<position.length;i++) {
var className = bgposition == position[i] ? 'red' : '';
$('bgimgposition'+i).className = className;
flag = flag ? flag : className;
}
if (flag != 'red') {
for (i=0;i<position_.length;i++) {
className = bgposition == position_[i] ? 'red' : '';
$('bgimgposition'+i).className = className;
}
}
$('colorValue').value = bgcolor;
if ($('cbpb')) $('cbpb').style.backgroundColor = bgcolor;
$('textColorValue').value = bgfontColor;
if ($('ctpb')) $('ctpb').style.backgroundColor = bgfontColor;
$('linkColorValue').value = bglinkColor;
if ($('clpb')) $('clpb').style.backgroundColor = bglinkColor;
Util.show($('currentimgdiv'));
Util.hide($('diyimages'));
if ($('selectalbum')) $('selectalbum').disabled = 'disabled';
bgimg = bgimg != '' && bgimg != 'none' ? bgimg.replace(/url\(['|"]{0,1}/,'').replace(/['|"]{0,1}\)/,'') : 'static/image/common/nophotosmall.gif';
$('currentimg').src = bgimg;
},
changeBgImgDiv : function () {
Util.hide($('currentimgdiv'));
Util.show($('diyimages'));
if ($('selectalbum')) $('selectalbum').disabled = '';
},
getSpacecssStr : function() {
var css = '';
var selectors = ['body', '#hd','#ct', 'BODY'];
for (var i in this.spacecss) {
var name = i.split(' ')[0];
if(selectors.indexOf(name) == -1 && !drag.getObjByName(name.substr(1))) {
for(var k in this.spacecss) {
if (k.indexOf(i) > -1) {
this.spacecss[k] = [];
}
}
continue;
}
var rule = this.spacecss[i];
if (typeof rule == "function") continue;
var one = '';
rule = this.formatCssRule(rule);
for (var j in rule) {
var content = this.spacecss[i][j];
if (content && typeof content == "string" && content.length > 0) {
content = this.trimCssImportant(content);
content = content ? content + ' !important;' : ';';
one += j + ":" + content;
}
}
if (one == '') continue;
css += i + " {" + one + "}";
}
return css;
},
formatCssRule : function (rule) {
var arr = ['top', 'right', 'bottom', 'left'], i = 0;
if (typeof rule['margin-top'] != 'undefined') {
var margin = rule['margin-bottom'];
if (margin && margin == rule['margin-top'] && margin == rule['margin-right'] && margin == rule['margin-left']) {
rule['margin'] = margin;
for(i=0;i<arr.length;i++) {
delete rule['margin-'+arr[i]];
}
} else {
delete rule['margin'];
}
}
var border = '', borderb = '', borderr = '', borderl = '';
if (typeof rule['border-top-color'] != 'undefined' || typeof rule['border-top-width'] != 'undefined' || typeof rule['border-top-style'] != 'undefined') {
var format = function (css) {
css = css.join(' ').replace(/!( ?)important/g,'').replace(/ /g,' ').replace(/^ | $/g,'');
return css ? css + ' !important' : '';
};
border = format([rule['border-top-color'], rule['border-top-width'], rule['border-top-style']]);
borderr = format([rule['border-right-color'], rule['border-right-width'], rule['border-right-style']]);
borderb = format([rule['border-bottom-color'], rule['border-bottom-width'], rule['border-bottom-style']]);
borderl = format([rule['border-left-color'], rule['border-left-width'], rule['border-left-style']]);
} else if (typeof rule['border-top'] != 'undefined') {
border = rule['border-top'];borderr = rule['border-right'];borderb = rule['border-bottom'];borderl = rule['border-left'];
}
if (border) {
if (border == borderb && border == borderr && border == borderl) {
rule['border'] = border;
for(i=0;i<arr.length;i++) {
delete rule['border-'+arr[i]];
}
} else {
rule['border-top'] = border;rule['border-right'] = borderr;rule['border-bottom'] = borderb;rule['border-left'] = borderl;
delete rule['border'];
}
for(i=0;i<arr.length;i++) {
delete rule['border-'+arr[i]+'-color'];delete rule['border-'+arr[i]+'-width'];delete rule['border-'+arr[i]+'-style'];
}
}
return rule;
},
changeLayout : function (newLayout) {
if (this.currentLayout == newLayout) return false;
var data = $('layout'+newLayout).getAttribute('data');
var dataArr = data.split(' ');
var currentLayoutLength = this.currentLayout.length;
var newLayoutLength = newLayout.length;
if (newLayoutLength == currentLayoutLength){
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
if (typeof(dataArr[2]) != 'undefined') $('frame1_right').style.width = dataArr[2]+'px';
} else if (newLayoutLength > currentLayoutLength) {
var block = this.getRandomBlockName();
var dom = document.createElement('div');
dom.id = 'frame1_right';
dom.className = drag.moveableColumn + ' z';
dom.appendChild($(block));
$('frame1').appendChild(dom);
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
dom.style.width = dataArr[2]+'px';
} else if (newLayoutLength < currentLayoutLength) {
var _length = drag.data['diypage'][0]['columns']['frame1_right']['children'].length;
var tobj = $('frame1_center_temp');
for (var i = 0; i < _length; i++) {
var name = drag.data['diypage'][0]['columns']['frame1_right']['children'][i].name;
if (name.indexOf('temp') < 0) $('frame1_center').insertBefore($(name),tobj);
}
$('frame1').removeChild($('frame1_right'));
$('frame1_left').style.width = dataArr[0]+'px';
$('frame1_center').style.width = dataArr[1]+'px';
}
var className = $('layout'+this.currentLayout).className;
$('layout'+this.currentLayout).className = '';
$('layout'+newLayout).className = className;
this.currentLayout = newLayout;
drag.initPosition();
drag.setClose();
},
getRandomBlockName : function () {
var left = drag.data['diypage'][0]['columns']['frame1_left']['children'];
if (left.length > 2) {
var block = left[0];
} else {
var block = drag.data['diypage'][0]['columns']['frame1_center']['children'][0];
}
return block.name;
},
changeStyle : function (t) {
if (t == '') return false;
$('style_css').href=STATICURL+t+"/style.css";
if (!this.backFlag) {
var oldData = [this.style];
var newData = [t];
var random = Math.random();
this.addOpRecord ('this.changeStyle', newData, oldData, random);
}
var arr = t.split("/");
this.style = arr[arr.length-1];
drag.setClose();
},
setCurrentDiy : function (type) {
if (type) {
$('diy_tag_'+this.currentDiy).className = '';
this.currentDiy = type;
$('diy_tag_'+this.currentDiy).className = 'activity';
this.initPalette(this.currentDiy);
}
},
hideBg : function () {
var random = Math.random();
this.setStyle(this.currentDiy, 'background-image', '', random);
this.setStyle(this.currentDiy, 'background-color', '', random);
if (this.currentDiy == 'hd') this.setStyle(this.currentDiy, 'height', '', random);
this.initPalette(this.currentDiy);
},
toggleHeader : function () {
var random = Math.random();
if ($('header_hide_cb').checked) {
this.setStyle('#hd', 'height', '260px', random);
this.setStyle('#hd', 'background-image', 'none', random);
this.setStyle('#hd', 'border-width', '0px', random);
} else {
this.setStyle('#hd', 'height', '', random);
this.setStyle('#hd', 'background-image', '', random);
this.setStyle('#hd', 'border-width', '', random);
}
},
setBgImage : function (value) {
var path = typeof value == "string" ? value : value.src;
if (path.indexOf('.thumb') > 0) {
path = path.substring(0,path.indexOf('.thumb'));
}
if (path == '' || path == 'undefined') return false;
var random = Math.random();
this.setStyle(this.currentDiy, 'background-image', Util.url(path), random);
this.setStyle(this.currentDiy, 'background-repeat', 'repeat', random);
if (this.currentDiy == 'hd') {
var _method = this;
var img = new Image();
img.onload = function () {
if (parseInt(img.height) < 140) {
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'background-repeat', 'repeat', random);
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'height', '', random);
} else {
DIY.prototype.setStyle.call(_method, _method.currentDiy, 'height', img.height+"px", random);
}
};
img.src = path;
}
},
setBgRepeat : function (value) {
var repeat = ['repeat','no-repeat','repeat-x','repeat-y'];
if (typeof repeat[value] == 'undefined') {return false;}
this.setStyle(this.currentDiy, 'background-repeat', repeat[value]);
},
setBgAttachment : function (value) {
var attachment = ['scroll','fixed'];
if (typeof attachment[value] == 'undefined') {return false;}
this.setStyle(this.currentDiy, 'background-attachment', attachment[value]);
},
setBgColor : function (color) {
this.setStyle(this.currentDiy, 'background-color', color);
},
setTextColor : function (color) {
this.setStyle(this.currentDiy, 'color', color);
},
setLinkColor : function (color) {
this.setStyle(this.currentDiy + ' a', 'color', color);
},
setBgPosition : function (id) {
var td = $(id);
var i = id.substr(id.length-1);
var position = ['left top','center top','right top','left center','center center','right center','left bottom','center bottom','right bottom'];
td.className = 'red';
for (var j=0;j<9;j++) {
if (i != j) {
$('bgimgposition'+j).className = '';
}
}
this.setStyle(this.currentDiy, 'background-position', position[i]);
},
getSelector : function (currentDiv) {
var arr = currentDiv.split(' ');
currentDiv = arr[0];
var link = '';
if (arr.length > 1) {
link = (arr[arr.length-1].toLowerCase() == 'a') ? link = ' '+arr.pop() : '';
currentDiv = arr.join(' ');
}
var selector = '';
switch(currentDiv) {
case 'blocktitle' :
selector = '#ct .move-span .blocktitle';
break;
case 'body' :
case 'BODY' :
selector = BROWSER.ie ? 'BODY' : 'body';
break;
default :
selector = currentDiv.indexOf("#")>-1 ? currentDiv : "#"+currentDiv;
}
var rega = BROWSER.ie ? ' A' : ' a';
selector = (selector+link).replace(/ a/i,rega);
return selector;
},
setStyle : function (currentDiv, property, value, random, num){
property = trim(property).toLowerCase();
var propertyJs = property.property2js();
if (typeof value == 'undefined') value = '';
var selector = this.getSelector(currentDiv);
if (!this.backFlag) {
var rule = this.styleSheet.getRule(selector,propertyJs);
rule = rule.replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");
var oldData = [currentDiv, property, rule];
var newData = [currentDiv, property, value];
if (typeof random == 'undefined') random = Math.random();
this.addOpRecord ('this.setStyle', newData, oldData, random);
}
value = this.trimCssImportant(value);
value = value ? value + ' !important' : '';
var pvalue = value ? property+':'+value : '';
this.styleSheet.addRule(selector,pvalue,num,property);
Util.recolored();
if (typeof this.spacecss[selector] == 'undefined') {
this.spacecss[selector] = [];
}
this.spacecss[selector][property] = value;
drag.setClose();
},
trimCssImportant : function (value) {
if (value instanceof Array) value = value.join(' ');
return value ? value.replace(/!( ?)important/g,'').replace(/ /g,' ').replace(/^ | $/g,'') : '';
},
removeCssSelector : function (selector) {
for (var i in this.spacecss) {
if (typeof this.spacecss[i] == "function") continue;
if (i.indexOf(selector) > -1) {
this.styleSheet.removeRule(i);
this.spacecss[i] = [];
}
}
},
undo : function () {
if (this.opSet.length == 0) return false;
var oldData = '';
if (this.opPointer <= 0) {return '';}
var step = this.opSet[--this.opPointer];
var random = step['random'];
var cmd = step['cmd'].split(',');
var cmdNum = cmd.length;
if (cmdNum >1) {
for (var i=0; i<cmdNum; i++) {
oldData = typeof step['oldData'][i] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['oldData'][i].join('","') + '"';
this.backFlag = true;
eval(cmd[i]+'('+oldData+')');
this.backFlag = false;
}
} else {
oldData = typeof step['oldData'] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['oldData'].join('","') + '"';
this.backFlag = true;
eval(cmd+'('+oldData+')');
this.backFlag = false;
}
$('button_redo').className = '';
if (this.opPointer == 0) {
$('button_undo').className = 'unusable';
drag.isChange = false;
drag.clearClose();
return '';
} else if (random == this.opSet[this.opPointer-1]['random']) {
this.undo();
return '';
} else {
return '';
}
},
redo : function () {
if (this.opSet.length == 0) return false;
var newData = '',random = '';
if (this.opPointer >= this.opSet.length) return '';
var step = this.opSet[this.opPointer++];
random = step['random'];
var cmd = step['cmd'].split(',');
var cmdNum = cmd.length;
if (cmdNum >1) {
for (var i=0; i<cmdNum; i++) {
newData = typeof step['newData'][i] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['newData'][i].join('","') + '"';
this.backFlag = true;
eval(cmd[i]+'('+newData+')');
this.backFlag = false;
}
}else {
newData = typeof step['newData'] == 'undefined' || step['oldData'] == '' ? '' : '"' + step['newData'].join('","') + '"';
this.backFlag = true;
eval(cmd+'('+newData+')');
this.backFlag = false;
}
$('button_undo').className = '';
if (this.opPointer == this.opSet.length) {
$('button_redo').className = 'unusable';
return '';
} else if(random == this.opSet[this.opPointer]['random']){
this.redo();
}
},
addOpRecord : function (cmd, newData, oldData, random) {
if (this.opPointer == 0) this.opSet = [];
this.opSet[this.opPointer++] = {'cmd':cmd, 'newData':newData, 'oldData':oldData, 'random':random};
$('button_undo').className = '';
$('button_redo').className = 'unusable';
Util.show('recover_button');
},
recoverStyle : function () {
var random = Math.random();
for (var selector in this.spacecss){
var style = this.spacecss[selector];
if (typeof style == "function") {continue;}
for (var attribute in style) {
if (typeof style[attribute] == "function") {continue;}
this.setStyle(selector,attribute,'',random);
}
}
Util.hide('recover_button');
drag.setClose();
this.initPalette(this.currentDiy);
},
uploadSubmit : function (){
if (document.uploadpic.attach.value.length<3) {
alert('请选择您要上传的图片');
return false;
}
if (document.uploadpic.albumid != null) document.uploadpic.albumid.value = $('selectalbum').value;
return true;
},
save : function () {
return false;
},
cancel : function () {
var flag = false;
if (this.isChange) {
flag = confirm(this.cancelConfirm ? this.cancelConfirm : '退出将不会保存您刚才的设置。是否确认退出?');
}
if (!this.isChange || flag) {
location.href = location.href.replace(/[\?|\&]diy\=yes/g,'');
}
},
extend : function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
}
};
})(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home_drag.js 17522 2010-10-20 13:57:03Z monkey $
*/
var Drags = [];
var nDrags = 1;
var mouseOffset = null;
var iMouseDown = false;
var lMouseState = false;
var dragObject = null;
var DragDrops = [];
var curTarget = null;
var lastTarget = null;
var dragHelper = null;
var tempDiv = null;
var rootParent = null;
var rootSibling = null;
var D1Target = null;
Number.prototype.NaN0=function(){return isNaN(this)?0:this;};
function CreateDragContainer(){
var cDrag = DragDrops.length;
DragDrops[cDrag] = [];
for(var i=0; i<arguments.length; i++){
var cObj = arguments[i];
DragDrops[cDrag].push(cObj);
cObj.setAttribute('DropObj', cDrag);
for(var j=0; j<cObj.childNodes.length; j++){
if(cObj.childNodes[j].nodeName=='#text') continue;
cObj.childNodes[j].setAttribute('DragObj', cDrag);
}
}
}
function getPosition(e){
var left = 0;
var top = 0;
while (e.offsetParent){
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
e = e.offsetParent;
}
left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
top += e.offsetTop + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
return {x:left, y:top};
}
function mouseCoords(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
};
}
function writeHistory(object, message){
if(!object || !object.parentNode || typeof object.parentNode.getAttribute == 'unknown' || !object.parentNode.getAttribute) return;
var historyDiv = object.parentNode.getAttribute('history');
if(historyDiv){
historyDiv = document.getElementById(historyDiv);
historyDiv.appendChild(document.createTextNode(object.id+': '+message));
historyDiv.appendChild(document.createElement('BR'));
historyDiv.scrollTop += 50;
}
}
function getMouseOffset(target, ev){
ev = ev || window.event;
var docPos = getPosition(target);
var mousePos = mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}
function mouseMove(ev){
ev = ev || window.event;
var target = ev.target || ev.srcElement;
var mousePos = mouseCoords(ev);
if(Drags[0]){
if(lastTarget && (target!==lastTarget)){
writeHistory(lastTarget, 'Mouse Out Fired');
var origClass = lastTarget.getAttribute('origClass');
if(origClass) lastTarget.className = origClass;
}
var dragObj = target.getAttribute('DragObj');
if(dragObj!=null){
if(target!=lastTarget){
writeHistory(target, 'Mouse Over Fired');
var oClass = target.getAttribute('overClass');
if(oClass){
target.setAttribute('origClass', target.className);
target.className = oClass;
}
}
if(iMouseDown && !lMouseState){
writeHistory(target, 'Start Dragging');
curTarget = target;
rootParent = curTarget.parentNode;
rootSibling = curTarget.nextSibling;
mouseOffset = getMouseOffset(target, ev);
for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);
dragHelper.appendChild(curTarget.cloneNode(true));
dragHelper.style.display = 'block';
var dragClass = curTarget.getAttribute('dragClass');
if(dragClass){
dragHelper.firstChild.className = dragClass;
}
dragHelper.firstChild.removeAttribute('DragObj');
var dragConts = DragDrops[dragObj];
curTarget.setAttribute('startWidth', parseInt(curTarget.offsetWidth));
curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
curTarget.style.display = 'none';
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
var pos = getPosition(dragConts[i]);
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
for(var j=0; j<dragConts[i].childNodes.length; j++){
with(dragConts[i].childNodes[j]){
if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;
var pos = getPosition(dragConts[i].childNodes[j]);
setAttribute('startWidth', parseInt(offsetWidth));
setAttribute('startHeight', parseInt(offsetHeight));
setAttribute('startLeft', pos.x);
setAttribute('startTop', pos.y);
}
}
}
}
}
if(curTarget){
dragHelper.style.top = (mousePos.y - mouseOffset.y)+"px";
dragHelper.style.left = (mousePos.x - mouseOffset.x)+"px";
var dragConts = DragDrops[curTarget.getAttribute('DragObj')];
var activeCont = null;
var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);
for(var i=0; i<dragConts.length; i++){
with(dragConts[i]){
if((parseInt(getAttribute('startLeft')) < xPos) &&
(parseInt(getAttribute('startTop')) < yPos) &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
activeCont = dragConts[i];
break;
}
}
}
if(activeCont){
if(activeCont!=curTarget.parentNode){
writeHistory(curTarget, 'Moved into '+activeCont.id);
}
var beforeNode = null;
for(var i=activeCont.childNodes.length-1; i>=0; i--){
with(activeCont.childNodes[i]){
if(nodeName=='#text') continue;
if(curTarget != activeCont.childNodes[i] &&
((parseInt(getAttribute('startLeft')) + parseInt(getAttribute('startWidth'))) > xPos) &&
((parseInt(getAttribute('startTop')) + parseInt(getAttribute('startHeight'))) > yPos)){
beforeNode = activeCont.childNodes[i];
}
}
}
if(beforeNode){
if(beforeNode!=curTarget.nextSibling){
writeHistory(curTarget, 'Inserted Before '+beforeNode.id);
activeCont.insertBefore(curTarget, beforeNode);
}
} else {
if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
writeHistory(curTarget, 'Inserted at end of '+activeCont.id);
activeCont.appendChild(curTarget);
}
}
setTimeout(function(){
var contPos = getPosition(activeCont);
activeCont.setAttribute('startWidth', parseInt(activeCont.offsetWidth));
activeCont.setAttribute('startHeight', parseInt(activeCont.offsetHeight));
activeCont.setAttribute('startLeft', contPos.x);
activeCont.setAttribute('startTop', contPos.y);}, 5);
if(curTarget.style.display!=''){
writeHistory(curTarget, 'Made Visible');
curTarget.style.display = '';
curTarget.style.visibility = 'hidden';
}
} else {
if(curTarget.style.display!='none'){
writeHistory(curTarget, 'Hidden');
curTarget.style.display = 'none';
}
}
}
lMouseState = iMouseDown;
lastTarget = target;
}
if(dragObject){
dragObject.style.position = 'absolute';
dragObject.style.top = mousePos.y - mouseOffset.y;
dragObject.style.left = mousePos.x - mouseOffset.x;
}
lMouseState = iMouseDown;
if(curTarget || dragObject) return false;
}
function mouseUp(ev){
if(Drags[0]){
if(curTarget){
writeHistory(curTarget, 'Mouse Up Fired');
dragHelper.style.display = 'none';
if(curTarget.style.display == 'none'){
if(rootSibling){
rootParent.insertBefore(curTarget, rootSibling);
} else {
rootParent.appendChild(curTarget);
}
}
curTarget.style.display = '';
curTarget.style.visibility = 'visible';
}
curTarget = null;
}
dragObject = null;
iMouseDown = false;
}
function mouseDown(ev){
mousedown(ev);
ev = ev || window.event;
var target = ev.target || ev.srcElement;
iMouseDown = true;
if(Drags[0]){
if(lastTarget){
writeHistory(lastTarget, 'Mouse Down Fired');
}
}
if(target.onmousedown || target.getAttribute('DragObj')){
return false;
}
}
function makeDraggable(item){
if(!item) return;
item.onmousedown = function(ev){
dragObject = this;
mouseOffset = getMouseOffset(this, ev);
return false;
}
}
function init_drag2(){
document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup = mouseUp;
Drags[0] = $('Drags0');
if(Drags[0]){
CreateDragContainer($('DragContainer0'));
}
if(Drags[0]){
var cObj = $('applistcontent');
dragHelper = document.createElement('div');
dragHelper.style.cssName = "apps dragable";
dragHelper.style.cssText = 'position:absolute;display:none;width:374px;';
cObj.parentNode.insertBefore(dragHelper, cObj);
}
}
function mousedown(evnt){
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: smilies.js 21444 2011-03-25 10:12:35Z lifangming $
*/
function _smilies_show(id, smcols, seditorkey) {
if(seditorkey && !$(seditorkey + 'sml_menu')) {
var div = document.createElement("div");
div.id = seditorkey + 'sml_menu';
div.style.display = 'none';
div.className = 'sllt';
$('append_parent').appendChild(div);
var div = document.createElement("div");
div.id = id;
div.style.overflow = 'hidden';
$(seditorkey + 'sml_menu').appendChild(div);
}
if(typeof smilies_type == 'undefined') {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
scriptNode.src = 'data/cache/common_smilies_var.js?' + VERHASH;
$('append_parent').appendChild(scriptNode);
if(BROWSER.ie) {
scriptNode.onreadystatechange = function() {
smilies_onload(id, smcols, seditorkey);
};
} else {
scriptNode.onload = function() {
smilies_onload(id, smcols, seditorkey);
};
}
} else {
smilies_onload(id, smcols, seditorkey);
}
}
function smilies_onload(id, smcols, seditorkey) {
seditorkey = !seditorkey ? '' : seditorkey;
smile = getcookie('smile').split('D');
if(typeof smilies_type == 'object') {
if(smile[0] && smilies_array[smile[0]]) {
CURRENTSTYPE = smile[0];
} else {
for(i in smilies_array) {
CURRENTSTYPE = i;break;
}
}
smiliestype = '<div id="'+id+'_tb" class="tb tb_s cl"><ul>';
for(i in smilies_type) {
key = i.substring(1);
if(smilies_type[i][0]) {
smiliestype += '<li ' + (CURRENTSTYPE == key ? 'class="current"' : '') + ' id="'+seditorkey+'stype_'+key+'" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', '+key+', 1, \'' + seditorkey + '\');if(CURRENTSTYPE) {$(\''+seditorkey+'stype_\'+CURRENTSTYPE).className=\'\';}this.className=\'current\';CURRENTSTYPE='+key+';doane(event);"><a href="javascript:;" hidefocus="true">'+smilies_type[i][0]+'</a></li>';
}
}
smiliestype += '</ul></div>';
$(id).innerHTML = smiliestype + '<div id="' + id + '_data"></div><div class="sllt_p" id="' + id + '_page"></div>';
smilies_switch(id, smcols, CURRENTSTYPE, smile[1], seditorkey);
smilies_fastdata = '';
if(seditorkey == 'fastpost' && $('fastsmilies') && smilies_fast) {
var j = 0;
for(i = 0;i < smilies_fast.length; i++) {
if(j == 0) {
smilies_fastdata += '<tr>';
}
j = ++j > 3 ? 0 : j;
s = smilies_array[smilies_fast[i][0]][smilies_fast[i][1]][smilies_fast[i][2]];
smilieimg = STATICURL + 'image/smiley/' + smilies_type['_' + smilies_fast[i][0]][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smilies_fastdata += s ? '<td onmouseover="smilies_preview(\'' + seditorkey + '\', \'fastsmiliesdiv\', this, ' + s[5] + ')" onmouseout="$(\'smilies_preview\').style.display = \'none\'" onclick="' + (typeof wysiwyg != 'undefined' ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'" id="' + seditorkey + 'smilie_' + s[0] + '_td"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
}
$('fastsmilies').innerHTML = '<table cellspacing="0" cellpadding="0"><tr>' + smilies_fastdata + '</tr></table>';
}
}
}
function smilies_switch(id, smcols, type, page, seditorkey) {
page = page ? page : 1;
if(!smilies_array[type] || !smilies_array[type][page]) return;
setcookie('smile', type + 'D' + page, 31536000);
smiliesdata = '<table id="' + id + '_table" cellpadding="0" cellspacing="0"><tr>';
j = k = 0;
img = [];
for(i in smilies_array[type][page]) {
if(j >= smcols) {
smiliesdata += '<tr>';
j = 0;
}
s = smilies_array[type][page][i];
smilieimg = STATICURL + 'image/smiley/' + smilies_type['_' + type][1] + '/' + s[2];
img[k] = new Image();
img[k].src = smilieimg;
smiliesdata += s && s[0] ? '<td onmouseover="smilies_preview(\'' + seditorkey + '\', \'' + id + '\', this, ' + s[5] + ')" onclick="' + (typeof wysiwyg != 'undefined' ? 'insertSmiley(' + s[0] + ')': 'seditor_insertunit(\'' + seditorkey + '\', \'' + s[1].replace(/'/, '\\\'') + '\')') +
'" id="' + seditorkey + 'smilie_' + s[0] + '_td"><img id="smilie_' + s[0] + '" width="' + s[3] +'" height="' + s[4] +'" src="' + smilieimg + '" alt="' + s[1] + '" />' : '<td>';
j++;k++;
}
smiliesdata += '</table>';
smiliespage = '';
if(smilies_array[type].length > 2) {
prevpage = ((prevpage = parseInt(page) - 1) < 1) ? smilies_array[type].length - 1 : prevpage;
nextpage = ((nextpage = parseInt(page) + 1) == smilies_array[type].length) ? 1 : nextpage;
smiliespage = '<div class="z"><a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + prevpage + ', \'' + seditorkey + '\');doane(event);">上页</a>' +
'<a href="javascript:;" onclick="smilies_switch(\'' + id + '\', \'' + smcols + '\', ' + type + ', ' + nextpage + ', \'' + seditorkey + '\');doane(event);">下页</a></div>' +
page + '/' + (smilies_array[type].length - 1);
}
$(id + '_data').innerHTML = smiliesdata;
$(id + '_page').innerHTML = smiliespage;
$(id + '_tb').style.width = smcols*(16+parseInt(s[3])) + 'px';
}
function smilies_preview(seditorkey, id, obj, w) {
var menu = $('smilies_preview');
if(!menu) {
menu = document.createElement('div');
menu.id = 'smilies_preview';
menu.className = 'sl_pv';
menu.style.display = 'none';
$('append_parent').appendChild(menu);
}
menu.innerHTML = '<img width="' + w + '" src="' + obj.childNodes[0].src + '" />';
mpos = fetchOffset($(id + '_data'));
spos = fetchOffset(obj);
pos = spos['left'] >= mpos['left'] + $(id + '_data').offsetWidth / 2 ? '13' : '24';
showMenu({'ctrlid':obj.id,'showid':id + '_data','menuid':menu.id,'pos':pos,'layer':3});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: register.js 22639 2011-05-16 07:05:16Z lifangming $
*/
var lastusername = '', lastpassword = '', lastemail = '', lastinvitecode = '', stmp = new Array();
function errormessage(id, msg) {
if($(id)) {
showInputTip();
msg = !msg ? '' : msg;
if($('tip_' + id)) {
if(msg == 'succeed') {
msg = '';
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
$('tip_' + id).parentNode.className += ' p_right';
} else if(msg !== '') {
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
}
}
if($('chk_' + id)) {
$('chk_' + id).innerHTML = msg;
}
$(id).className = !msg ? $(id).className.replace(/ er/, '') : $(id).className + ' er';
}
}
function addFormEvent(formid, focus){
var si = 0;
var formNode = $(formid).getElementsByTagName('input');
for(i = 0;i < formNode.length;i++) {
if(formNode[i].name == '') {
formNode[i].name = formNode[i].id;
stmp[si] = i;
si++;
}
if(formNode[i].type == 'text' || formNode[i].type == 'password'){
formNode[i].onfocus = function(){
showInputTip(!this.id ? this.name : this.id);
}
}
}
if(!si) {
return;
}
formNode[stmp[0]].onblur = function () {
checkusername(formNode[stmp[0]].id);
};
formNode[stmp[1]].onblur = function () {
if(formNode[stmp[1]].value == '') {
errormessage(formNode[stmp[1]].id, '请填写密码');
}else{
errormessage(formNode[stmp[1]].id, 'succeed');
}
checkpassword(formNode[stmp[1]].id, formNode[stmp[2]].id);
};
formNode[stmp[2]].onblur = function () {
if(formNode[stmp[2]].value == '') {
errormessage(formNode[stmp[2]].id, '请再次输入密码');
}
checkpassword(formNode[stmp[1]].id, formNode[stmp[2]].id);
};
formNode[stmp[3]].onclick = function (event) {
emailMenu(event, formNode[stmp[3]].id);
};
formNode[stmp[3]].onkeyup = function (event) {
emailMenu(event, formNode[stmp[3]].id);
};
formNode[stmp[3]].onkeydown = function (event) {
emailMenuOp(4, event, formNode[stmp[3]].id);
};
formNode[stmp[3]].onblur = function () {
if(formNode[stmp[3]].value == '') {
errormessage(formNode[stmp[3]].id, '请输入邮箱地址');
}
emailMenuOp(3, null, formNode[stmp[3]].id);
};
stmp['email'] = formNode[stmp[3]].id;
try {
if(focus) {
$('invitecode').focus();
} else {
formNode[stmp[0]].focus();
}
} catch(e) {}
}
function showInputTip(id) {
var p_tips = $('registerform').getElementsByTagName('i');
for(i = 0;i < p_tips.length;i++){
if(p_tips[i].className == 'p_tip'){
p_tips[i].style.display = 'none';
}
}
if($('tip_' + id)) {
$('tip_' + id).style.display = 'block';
}
}
function showbirthday(){
var el = $('birthday');
var birthday = el.value;
el.length=0;
el.options.add(new Option('日', ''));
for(var i=0;i<28;i++){
el.options.add(new Option(i+1, i+1));
}
if($('birthmonth').value!="2"){
el.options.add(new Option(29, 29));
el.options.add(new Option(30, 30));
switch($('birthmonth').value){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":{
el.options.add(new Option(31, 31));
}
}
} else if($('birthyear').value!="") {
var nbirthyear=$('birthyear').value;
if(nbirthyear%400==0 || (nbirthyear%4==0 && nbirthyear%100!=0)) el.options.add(new Option(29, 29));
}
el.value = birthday;
}
function trim(str) {
return str.replace(/^\s*(.*?)[\s\n]*$/g, '$1');
}
var emailMenuST = null, emailMenui = 0, emaildomains = ['qq.com', '163.com', 'sina.com', 'sohu.com', 'yahoo.cn', 'gmail.com', 'hotmail.com'];
function emailMenuOp(op, e, id) {
if(op == 3 && BROWSER.ie && BROWSER.ie < 7) {
checkemail(id);
}
if(!$('emailmore_menu')) {
return;
}
if(op == 1) {
$('emailmore_menu').style.display = 'none';
} else if(op == 2) {
showMenu({'ctrlid':'emailmore','pos': '13!'});
} else if(op == 3) {
emailMenuST = setTimeout(function () {
emailMenuOp(1, id);
checkemail(id);
}, 500);
} else if(op == 4) {
e = e ? e : window.event;
var obj = $(id);
if(e.keyCode == 13) {
var v = obj.value.indexOf('@') != -1 ? obj.value.substring(0, obj.value.indexOf('@')) : obj.value;
obj.value = v + '@' + emaildomains[emailMenui];
doane(e);
}
} else if(op == 5) {
var as = $('emailmore_menu').getElementsByTagName('a');
for(i = 0;i < as.length;i++){
as[i].className = '';
}
}
}
function emailMenu(e, id) {
if(BROWSER.ie && BROWSER.ie < 7) {
return;
}
e = e ? e : window.event;
var obj = $(id);
if(obj.value.indexOf('@') != -1) {
$('emailmore_menu').style.display = 'none';
return;
}
var value = e.keyCode;
var v = obj.value;
if(!obj.value.length) {
emailMenuOp(1);
return;
}
if(value == 40) {
emailMenui++;
if(emailMenui >= emaildomains.length) {
emailMenui = 0;
}
} else if(value == 38) {
emailMenui--;
if(emailMenui < 0) {
emailMenui = emaildomains.length - 1;
}
} else if(value == 13) {
$('emailmore_menu').style.display = 'none';
return;
}
if(!$('emailmore_menu')) {
menu = document.createElement('div');
menu.id = 'emailmore_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
$('append_parent').appendChild(menu);
}
var s = '<ul>';
for(var i = 0; i < emaildomains.length; i++) {
s += '<li><a href="javascript:;" onmouseover="emailMenuOp(5)" ' + (emailMenui == i ? 'class="a" ' : '') + 'onclick="$(stmp[\'email\']).value=this.innerHTML;display(\'emailmore_menu\');checkemail(stmp[\'email\']);">' + v + '@' + emaildomains[i] + '</a></li>';
}
s += '</ul>';
$('emailmore_menu').innerHTML = s;
emailMenuOp(2);
}
function checksubmit() {
var p_chks = $('registerform').getElementsByTagName('kbd');
for(i = 0;i < p_chks.length;i++){
if(p_chks[i].className == 'p_chk'){
p_chks[i].innerHTML = '';
}
}
ajaxpost('registerform', 'returnmessage4', 'returnmessage4', 'onerror');
return;
}
function checkusername(id) {
errormessage(id);
var username = trim($(id).value);
if($('tip_' + id).parentNode.className.match(/ p_right/) && (username == '' || username == lastusername)) {
return;
} else {
lastusername = username;
}
if(username.match(/<|"/ig)) {
errormessage(id, '用户名包含敏感字符');
return;
}
var unlen = username.replace(/[^\x00-\xff]/g, "**").length;
if(unlen < 3 || unlen > 15) {
errormessage(id, unlen < 3 ? '用户名小于 3 个字符' : '用户名超过 15 个字符');
return;
}
var x = new Ajax();
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkusername&username=' + (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(username) : username), function(s) {
errormessage(id, s);
});
}
function checkpassword(id1, id2) {
if(!$(id1).value && !$(id2).value) {
return;
}
errormessage(id2);
if($(id1).value != $(id2).value) {
errormessage(id2, '两次输入的密码不一致');
} else {
errormessage(id2, 'succeed');
}
}
function checkemail(id) {
errormessage(id);
var email = trim($(id).value);
if($(id).parentNode.className.match(/ p_right/) && (email == '' || email == lastemail)) {
return;
} else {
lastemail = email;
}
if(email.match(/<|"/ig)) {
errormessage(id, 'Email 包含敏感字符');
return;
}
var x = new Ajax();
$('tip_' + id).parentNode.className = $('tip_' + id).parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkemail&email=' + email, function(s) {
errormessage(id, s);
});
}
function checkinvite() {
errormessage('invitecode');
var invitecode = trim($('invitecode').value);
if(invitecode == '' || invitecode == lastinvitecode) {
return;
} else {
lastinvitecode = invitecode;
}
if(invitecode.match(/<|"/ig)) {
errormessage('invitecode', '邀请码包含敏感字符');
return;
}
var x = new Ajax();
$('tip_invitecode').parentNode.className = $('tip_invitecode').parentNode.className.replace(/ p_right/, '');
x.get('forum.php?mod=ajax&inajax=yes&infloat=register&handlekey=register&ajaxmenu=1&action=checkinvitecode&invitecode=' + invitecode, function(s) {
errormessage('invitecode', s);
});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: md5.js 15149 2010-08-19 08:02:46Z monkey $
*/
var hexcase = 0;
var chrsz = 8;
function hex_md5(s){
return binl2hex(core_md5(str2binl(s), s.length * chrsz));
}
function core_md5(x, len) {
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function safe_add(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt) {
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str) {
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz) {
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
}
return bin;
}
function binl2hex(binarray) {
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++) {
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) + hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 22522 2011-05-11 03:12:47Z monkey $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum', data);
}
function switchFullMode() {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
}
ajaxget('forum.php?mod=ajax&action=editor&cedit=yes' + (!fid ? '' : '&fid=' + fid), 'fastposteditor');
return false;
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('您确认要把此主题从热点主题中移除么?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['展开', '收起'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' && theform.subject.value == '') {
s = '抱歉,您尚未输入标题或内容';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = '您的标题超过 80 个字符的限制';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = '您的帖子长度不符合要求。\n\n当前长度: ' + mb_strlen(theform.message.value) + ' ' + '字节\n系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v ? 0 : 1);};
setcookie('atarget', v, (v ? 2592000 : -1));
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum');
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('没有可以恢复的数据!', 'info');
}
return;
}
if(!quiet && !confirm('此操作将覆盖当前帖子内容,确定要恢复数据吗?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
if($('separatorline')) {
var table = $('separatorline').parentNode;
} else {
var table = $('forum_' + fid);
}
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">有新回复的主题,点击查看', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: calendar.js 21580 2011-04-01 02:22:19Z svn_project_zhangjie $
*/
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute; z-index:100000;" onclick="doane(event)">';
s += '<div style="width: 210px;"><table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;">';
s += '<tr align="center" id="calendar_week"><td><a href="javascript:;" onclick="refreshcalendar(yy, mm-1)" title="上一月">«</a></td><td colspan="5" style="text-align: center"><a href="javascript:;" onclick="showdiv(\'year\');doane(event)" class="dropmenu" title="点击选择年份" id="year"></a> - <a id="month" class="dropmenu" title="点击选择月份" href="javascript:;" onclick="showdiv(\'month\');doane(event)"></a></td><td><A href="javascript:;" onclick="refreshcalendar(yy, mm+1)" title="下一月">»</A></td></tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute" class="pns"><td colspan="4" align="left"><input type="text" size="1" value="" id="hour" class="px vm" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'> 点 <input type="text" size="1" value="" id="minute" class="px vm" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'> 分</td><td align="right" colspan="3"><button class="pn" onclick="confirmcalendar();"><em>确定</em></button></td></tr>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="doane(event)" style="display: none;z-index:100001;"><div class="col">';
for(var k = 2020; k >= 1931; k--) {
s += k != 2020 && k % 10 == 0 ? '</div><div class="col">' : '';
s += '<a href="javascript:;" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="calendar_today"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="doane(event)" style="display: none;z-index:100001;">';
for(var k = 1; k <= 12; k++) {
s += '<a href="javascript:;" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'"><span' + (today.getMonth()+1 == k ? ' class="calendar_today"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
if(BROWSER.ie && BROWSER.ie < 7) {
s += '<iframe id="calendariframe" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_year" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<iframe id="calendariframe_month" frameborder="0" style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
}
var div = document.createElement('div');
div.innerHTML = s;
$('append_parent').appendChild(div);
document.onclick = function(event) {
closecalendar(event);
};
$('calendar').onclick = function(event) {
doane(event);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
};
}
function closecalendar(event) {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.display = 'none';
$('calendariframe_year').style.display = 'none';
$('calendariframe_month').style.display = 'none';
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
if(!addtime) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.display = 'none';
}
}
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
}
function confirmcalendar() {
if(addtime && controlid.value === '') {
controlid.value = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value);
}
closecalendar();
}
function initclosecalendar() {
var e = getEvent();
var aim = e.target || e.srcElement;
while (aim.parentNode != document.body) {
if (aim.parentNode.id == 'append_parent') {
aim.onclick = function () {closecalendar(e);};
}
aim = aim.parentNode;
}
}
function showcalendar(event, controlid1, addtime1, startdate1, enddate1) {
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
var p = fetchOffset(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['left']+'px';
$('calendar').style.top = (p['top'] + 20)+'px';
doane(event);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = 'calendar_default';
$('calendar_year_' + today.getFullYear()).className = 'calendar_today';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = 'calendar_default';
$('calendar_month_' + (today.getMonth() + 1)).className = 'calendar_today';
}
$('calendar_year_' + currday.getFullYear()).className = 'calendar_checked';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'calendar_checked';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe').style.top = $('calendar').style.top;
$('calendariframe').style.left = $('calendar').style.left;
$('calendariframe').style.width = $('calendar').offsetWidth;
$('calendariframe').style.height = $('calendar').offsetHeight;
$('calendariframe').style.display = 'block';
}
initclosecalendar();
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.innerHTML = '<a href="javascript:;" onclick="settime(' + d + ');return false">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'calendar_expire';
} else {
dd.className = 'calendar_default';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'calendar_today';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'calendar_checked';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = fetchOffset($(id));
$('calendar_' + id).style.left = p['left']+'px';
$('calendar_' + id).style.top = (p['top'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
if(BROWSER.ie && BROWSER.ie < 7) {
$('calendariframe_' + id).style.top = $('calendar_' + id).style.top;
$('calendariframe_' + id).style.left = $('calendar_' + id).style.left;
$('calendariframe_' + id).style.width = $('calendar_' + id).offsetWidth;
$('calendariframe_' + id ).style.height = $('calendar_' + id).offsetHeight;
$('calendariframe_' + id).style.display = 'block';
}
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
if(!BROWSER.other) {
loadcss('forum_calendar');
loadcalendar();
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: home.js 22765 2011-05-20 03:06:12Z zhengqingpeng $
*/
var note_step = 0;
var note_oldtitle = document.title;
var note_timer;
function addSort(obj) {
if (obj.value == 'addoption') {
showWindow('addoption', 'home.php?mod=spacecp&ac=blog&op=addoption&handlekey=addoption&oid='+obj.id);
}
}
function addOption(sid, aid) {
var obj = $(aid);
var newOption = $(sid).value;
$(sid).value = "";
if (newOption!=null && newOption!='') {
var newOptionTag=document.createElement('option');
newOptionTag.text=newOption;
newOptionTag.value="new:" + newOption;
try {
obj.add(newOptionTag, obj.options[0]);
} catch(ex) {
obj.add(newOptionTag, obj.selecedIndex);
}
obj.value="new:" + newOption;
} else {
obj.value=obj.options[0].value;
}
}
function blogAddOption(sid, aid) {
var obj = $(aid);
var newOption = $(sid).value;
newOption = newOption.replace(/^\s+|\s+$/g,"");
$(sid).value = "";
if (newOption!=null && newOption!='') {
var newOptionTag=document.createElement('option');
newOptionTag.text=newOption;
newOptionTag.value="new:" + newOption;
try {
obj.add(newOptionTag, obj.options[0]);
} catch(ex) {
obj.add(newOptionTag, obj.selecedIndex);
}
obj.value="new:" + newOption;
return true;
} else {
alert('分类名不能为空!');
return false;
}
}
function blogCancelAddOption(aid) {
var obj = $(aid);
obj.value=obj.options[0].value;
}
function checkAll(form, name) {
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name.match(name)) {
e.checked = form.elements['chkall'].checked;
}
}
}
function cnCode(str) {
str = str.replace(/<\/?[^>]+>|\[\/?.+?\]|"/ig, "");
str = str.replace(/\s{2,}/ig, ' ');
return BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(str) : str;
}
function getExt(path) {
return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function resizeImg(id,size) {
var theImages = $(id).getElementsByTagName('img');
for (i=0; i<theImages.length; i++) {
theImages[i].onload = function() {
if (this.width > size) {
this.style.width = size + 'px';
if (this.parentNode.tagName.toLowerCase() != 'a') {
var zoomDiv = document.createElement('div');
this.parentNode.insertBefore(zoomDiv,this);
zoomDiv.appendChild(this);
zoomDiv.style.position = 'relative';
zoomDiv.style.cursor = 'pointer';
this.title = '点击图片,在新窗口显示原始尺寸';
var zoom = document.createElement('img');
zoom.src = 'image/zoom.gif';
zoom.style.position = 'absolute';
zoom.style.marginLeft = size -28 + 'px';
zoom.style.marginTop = '5px';
this.parentNode.insertBefore(zoom,this);
zoomDiv.onmouseover = function() {
zoom.src = 'image/zoom_h.gif';
};
zoomDiv.onmouseout = function() {
zoom.src = 'image/zoom.gif';
};
zoomDiv.onclick = function() {
window.open(this.childNodes[1].src);
};
}
}
}
}
}
function zoomTextarea(id, zoom) {
zoomSize = zoom ? 10 : -10;
obj = $(id);
if(obj.rows + zoomSize > 0 && obj.cols + zoomSize * 3 > 0) {
obj.rows += zoomSize;
obj.cols += zoomSize * 3;
}
}
function ischeck(id, prefix) {
form = document.getElementById(id);
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.name.match(prefix) && e.checked) {
if(confirm("您确定要执行本操作吗?")) {
return true;
} else {
return false;
}
}
}
alert('请选择要操作的对象');
return false;
}
function copyRow(tbody) {
var add = false;
var newnode;
if($(tbody).rows.length == 1 && $(tbody).rows[0].style.display == 'none') {
$(tbody).rows[0].style.display = '';
newnode = $(tbody).rows[0];
} else {
newnode = $(tbody).rows[0].cloneNode(true);
add = true;
}
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
if(add) {
$(tbody).appendChild(newnode);
}
}
function delRow(obj, tbody) {
if($(tbody).rows.length == 1) {
var trobj = obj.parentNode.parentNode;
tags = trobj.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
trobj.style.display='none';
} else {
$(tbody).removeChild(obj.parentNode.parentNode);
}
}
function insertWebImg(obj) {
if(checkImage(obj.value)) {
insertImage(obj.value);
obj.value = 'http://';
} else {
alert('图片地址不正确');
}
}
function checkFocus(target) {
var obj = $(target);
if(!obj.hasfocus) {
obj.focus();
}
}
function insertImage(text) {
text = "\n[img]" + text + "[/img]\n";
insertContent('message', text);
}
function insertContent(target, text) {
var obj = $(target);
selection = document.selection;
checkFocus(target);
if(!isUndefined(obj.selectionStart)) {
var opn = obj.selectionStart + 0;
obj.value = obj.value.substr(0, obj.selectionStart) + text + obj.value.substr(obj.selectionEnd);
} else if(selection && selection.createRange) {
var sel = selection.createRange();
sel.text = text;
sel.moveStart('character', -strlen(text));
} else {
obj.value += text;
}
}
function checkImage(url) {
var re = /^http\:\/\/.{5,200}\.(jpg|gif|png)$/i;
return url.match(re);
}
function quick_validate(obj) {
if($('seccode')) {
var code = $('seccode').value;
var x = new Ajax();
x.get('cp.php?ac=common&op=seccode&code=' + code, function(s){
s = trim(s);
if(s != 'succeed') {
alert(s);
$('seccode').focus();
return false;
} else {
obj.form.submit();
return true;
}
});
} else {
obj.form.submit();
return true;
}
}
function stopMusic(preID, playerID) {
var musicFlash = preID.toString() + '_' + playerID.toString();
if($(musicFlash)) {
$(musicFlash).SetVariable('closePlayer', 1);
}
}
function showFlash(host, flashvar, obj, shareid) {
var flashAddr = {
'youku.com' : 'http://player.youku.com/player.php/sid/FLASHVAR=/v.swf',
'ku6.com' : 'http://player.ku6.com/refer/FLASHVAR/v.swf',
'youtube.com' : 'http://www.youtube.com/v/FLASHVAR',
'5show.com' : 'http://www.5show.com/swf/5show_player.swf?flv_id=FLASHVAR',
'sina.com.cn' : 'http://vhead.blog.sina.com.cn/player/outer_player.swf?vid=FLASHVAR',
'sohu.com' : 'http://v.blog.sohu.com/fo/v4/FLASHVAR',
'mofile.com' : 'http://tv.mofile.com/cn/xplayer.swf?v=FLASHVAR',
'music' : 'FLASHVAR',
'flash' : 'FLASHVAR'
};
var flash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="480" height="400">'
+ '<param name="movie" value="FLASHADDR" />'
+ '<param name="quality" value="high" />'
+ '<param name="bgcolor" value="#FFFFFF" />'
+ '<param name="allowScriptAccess" value="none" />'
+ '<param name="allowNetworking" value="internal" />'
+ '<embed width="480" height="400" menu="false" quality="high" src="FLASHADDR" type="application/x-shockwave-flash" />'
+ '</object>';
var videoFlash = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="480" height="450">'
+ '<param value="transparent" name="wmode"/>'
+ '<param value="FLASHADDR" name="movie" />'
+ '<embed src="FLASHADDR" wmode="transparent" allowfullscreen="true" type="application/x-shockwave-flash" width="480" height="450"></embed>'
+ '</object>';
var musicFlash = '<object id="audioplayer_SHAREID" height="24" width="290" data="' + STATICURL + 'image/common/player.swf" type="application/x-shockwave-flash">'
+ '<param value="' + STATICURL + 'image/common/player.swf" name="movie"/>'
+ '<param value="autostart=yes&bg=0xCDDFF3&leftbg=0x357DCE&lefticon=0xF2F2F2&rightbg=0xF06A51&rightbghover=0xAF2910&righticon=0xF2F2F2&righticonhover=0xFFFFFF&text=0x357DCE&slider=0x357DCE&track=0xFFFFFF&border=0xFFFFFF&loader=0xAF2910&soundFile=FLASHADDR" name="FlashVars"/>'
+ '<param value="high" name="quality"/>'
+ '<param value="false" name="menu"/>'
+ '<param value="#FFFFFF" name="bgcolor"/>'
+ '</object>';
var musicMedia = '<object height="64" width="290" data="FLASHADDR" type="audio/x-ms-wma">'
+ '<param value="FLASHADDR" name="src"/>'
+ '<param value="1" name="autostart"/>'
+ '<param value="true" name="controller"/>'
+ '</object>';
var flashHtml = videoFlash;
var videoMp3 = true;
if('' == flashvar) {
alert('音乐地址错误,不能为空');
return false;
}
if('music' == host) {
var mp3Reg = new RegExp('.mp3$', 'ig');
var flashReg = new RegExp('.swf$', 'ig');
flashHtml = musicMedia;
videoMp3 = false;
if(mp3Reg.test(flashvar)) {
videoMp3 = true;
flashHtml = musicFlash;
} else if(flashReg.test(flashvar)) {
videoMp3 = true;
flashHtml = flash;
}
}
flashvar = encodeURI(flashvar);
if(flashAddr[host]) {
var flash = flashAddr[host].replace('FLASHVAR', flashvar);
flashHtml = flashHtml.replace(/FLASHADDR/g, flash);
flashHtml = flashHtml.replace(/SHAREID/g, shareid);
}
if(!obj) {
$('flash_div_' + shareid).innerHTML = flashHtml;
return true;
}
if($('flash_div_' + shareid)) {
$('flash_div_' + shareid).style.display = '';
$('flash_hide_' + shareid).style.display = '';
obj.style.display = 'none';
return true;
}
if(flashAddr[host]) {
var flashObj = document.createElement('div');
flashObj.id = 'flash_div_' + shareid;
obj.parentNode.insertBefore(flashObj, obj);
flashObj.innerHTML = flashHtml;
obj.style.display = 'none';
var hideObj = document.createElement('div');
hideObj.id = 'flash_hide_' + shareid;
var nodetxt = document.createTextNode("收起");
hideObj.appendChild(nodetxt);
obj.parentNode.insertBefore(hideObj, obj);
hideObj.style.cursor = 'pointer';
hideObj.onclick = function() {
if(true == videoMp3) {
stopMusic('audioplayer', shareid);
flashObj.parentNode.removeChild(flashObj);
hideObj.parentNode.removeChild(hideObj);
} else {
flashObj.style.display = 'none';
hideObj.style.display = 'none';
}
obj.style.display = '';
};
}
}
function userapp_open() {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=common&op=getuserapp&inajax=1', function(s){
$('my_userapp').innerHTML = s;
$('a_app_more').className = 'fold';
$('a_app_more').innerHTML = '收起';
$('a_app_more').onclick = function() {
userapp_close();
};
});
}
function userapp_close() {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=common&op=getuserapp&subop=off&inajax=1', function(s){
$('my_userapp').innerHTML = s;
$('a_app_more').className = 'unfold';
$('a_app_more').innerHTML = '展开';
$('a_app_more').onclick = function() {
userapp_open();
};
});
}
function startMarquee(h, speed, delay, sid) {
var t = null;
var p = false;
var o = $(sid);
o.innerHTML += o.innerHTML;
o.onmouseover = function() {p = true};
o.onmouseout = function() {p = false};
o.scrollTop = 0;
function start() {
t = setInterval(scrolling, speed);
if(!p) {
o.scrollTop += 2;
}
}
function scrolling() {
if(p) return;
if(o.scrollTop % h != 0) {
o.scrollTop += 2;
if(o.scrollTop >= o.scrollHeight/2) o.scrollTop = 0;
} else {
clearInterval(t);
setTimeout(start, delay);
}
}
setTimeout(start, delay);
}
function readfeed(obj, id) {
if(Cookie.get("read_feed_ids")) {
var fcookie = Cookie.get("read_feed_ids");
fcookie = id + ',' + fcookie;
} else {
var fcookie = id;
}
Cookie.set("read_feed_ids", fcookie, 48);
obj.className = 'feedread';
}
function showreward() {
if(Cookie.get('reward_notice_disable')) {
return false;
}
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getreward', function(s){
if(s) {
msgwin(s, 2000);
}
});
}
function msgwin(s, t) {
var msgWinObj = $('msgwin');
if(!msgWinObj) {
var msgWinObj = document.createElement("div");
msgWinObj.id = 'msgwin';
msgWinObj.style.display = 'none';
msgWinObj.style.position = 'absolute';
msgWinObj.style.zIndex = '100000';
$('append_parent').appendChild(msgWinObj);
}
msgWinObj.innerHTML = s;
msgWinObj.style.display = '';
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)';
msgWinObj.style.opacity = 0;
var sTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
pbegin = sTop + (document.documentElement.clientHeight / 2);
pend = sTop + (document.documentElement.clientHeight / 5);
setTimeout(function () {showmsgwin(pbegin, pend, 0, t)}, 10);
msgWinObj.style.left = ((document.documentElement.clientWidth - msgWinObj.clientWidth) / 2) + 'px';
msgWinObj.style.top = pbegin + 'px';
}
function showmsgwin(b, e, a, t) {
step = (b - e) / 10;
var msgWinObj = $('msgwin');
newp = (parseInt(msgWinObj.style.top) - step);
if(newp > e) {
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + a + ')';
msgWinObj.style.opacity = a / 100;
msgWinObj.style.top = newp + 'px';
setTimeout(function () {showmsgwin(b, e, a += 10, t)}, 10);
} else {
msgWinObj.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
msgWinObj.style.opacity = 1;
setTimeout('displayOpacity(\'msgwin\', 100)', t);
}
}
function displayOpacity(id, n) {
if(!$(id)) {
return;
}
if(n >= 0) {
n -= 10;
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + n + ')';
$(id).style.opacity = n / 100;
setTimeout('displayOpacity(\'' + id + '\',' + n + ')', 50);
} else {
$(id).style.display = 'none';
$(id).style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)';
$(id).style.opacity = 1;
}
}
function urlto(url) {
window.location.href = url;
}
function explode(sep, string) {
return string.split(sep);
}
function selector(pattern, context) {
var re = new RegExp('([a-z0-9]*)([\.#:]*)(.*|$)', 'ig');
var match = re.exec(pattern);
var conditions = cc = [];
if (match[2] == '#') conditions.push(['id', '=', match[3]]);
else if(match[2] == '.') conditions.push(['className', '~=', match[3]]);
else if(match[2] == ':') conditions.push(['type', '=', match[3]]);
var s = match[3].replace(/\[(.*)\]/g,'$1').split('@');
for(var i=0; i<s.length; i++) {
if (cc = /([\w]+)([=^%!$~]+)(.*)$/.exec(s[i]))
conditions.push([cc[1], cc[2], cc[3]]);
}
var list = conditions[0] && conditions[0][0] == 'id' ? [document.getElementById(conditions[0][2])] : (context || document).getElementsByTagName(match[1] || "*");
if(!list || !list.length) return [];
if(conditions) {
var elements = [];
var attrMapping = {'for': 'htmlFor', 'class': 'className'};
for(var i=0; i<list.length; i++) {
var pass = true;
for(var j=0; j<conditions.length; j++) {
var attr = attrMapping[conditions[j][0]] || conditions[j][0];
var val = list[i][attr] || (list[i].getAttribute ? list[i].getAttribute(attr) : '');
var pattern = null;
if(conditions[j][1] == '=') {
pattern = new RegExp('^'+conditions[j][2]+'$', 'i');
} else if(conditions[j][1] == '^=') {
pattern = new RegExp('^' + conditions[j][2], 'i');
} else if(conditions[j][1] == '$=') {
pattern = new RegExp(conditions[j][2] + '$', 'i');
} else if(conditions[j][1] == '%=') {
pattern = new RegExp(conditions[j][2], 'i');
} else if(conditions[j][1] == '~=') {
pattern = new RegExp('(^|[ ])' + conditions[j][2] + '([ ]|$)', 'i');
}
if(pattern && !pattern.test(val)) {
pass = false;
break;
}
}
if(pass) elements.push(list[i]);
}
return elements;
} else {
return list;
}
}
function showBlock(cid, oid) {
if(parseInt(cid)) {
var listObj = $(oid);
var x = new Ajax();
x.get('portal.php?mod=cp&ac=block&operation=getblock&classid='+cid, function(s){
listObj.innerHTML = s;
})
}
}
function resizeTx(obj){
var oid = obj.id + '_limit';
if(!BROWSER.ie) obj.style.height = 0;
obj.style.height = obj.scrollHeight + 'px';
if($(oid)) $(oid).style.display = obj.scrollHeight > 30 ? '':'none';
}
function showFace(showid, target, dropstr) {
if($(showid + '_menu') != null) {
$(showid+'_menu').style.display = '';
} else {
var faceDiv = document.createElement("div");
faceDiv.id = showid+'_menu';
faceDiv.className = 'p_pop facel';
faceDiv.style.position = 'absolute';
faceDiv.style.zIndex = 1001;
var faceul = document.createElement("ul");
for(i=1; i<31; i++) {
var faceli = document.createElement("li");
faceli.innerHTML = '<img src="' + STATICURL + 'image/smiley/comcom/'+i+'.gif" onclick="insertFace(\''+showid+'\','+i+', \''+ target +'\', \''+dropstr+'\')" style="cursor:pointer; position:relative;" />';
faceul.appendChild(faceli);
}
faceDiv.appendChild(faceul);
$('append_parent').appendChild(faceDiv)
}
setMenuPosition(showid, 0);
doane();
_attachEvent(document.body, 'click', function(){if($(showid+'_menu')) $(showid+'_menu').style.display = 'none';});
}
function insertFace(showid, id, target, dropstr) {
var faceText = '[em:'+id+':]';
if($(target) != null) {
insertContent(target, faceText);
if(dropstr) {
$(target).value = $(target).value.replace(dropstr, "");
}
}
}
function wall_add(id) {
var obj = $('comment_ul');
var newdl = document.createElement("dl");
newdl.id = 'comment_'+id+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+id, function(s){
newdl.innerHTML = s;
});
obj.insertBefore(newdl, obj.firstChild);
if($('comment_message')) {
$('comment_message').value= '';
}
showCreditPrompt();
}
function share_add(sid) {
var obj = $('share_ul');
var newli = document.createElement("li");
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=share&inajax=1&sid='+sid, function(s){
newli.innerHTML = s;
});
obj.insertBefore(newli, obj.firstChild);
$('share_link').value = 'http://';
$('share_general').value = '';
showCreditPrompt();
}
function comment_add(id) {
var obj = $('comment_ul');
var newdl = document.createElement("dl");
newdl.id = 'comment_'+id+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+id, function(s){
newdl.innerHTML = s;
});
if($('comment_prepend')){
obj = obj.firstChild;
while (obj && obj.nodeType != 1){
obj = obj.nextSibling;
}
obj.parentNode.insertBefore(newdl, obj);
} else {
obj.appendChild(newdl);
}
if($('comment_message')) {
$('comment_message').value= '';
}
if($('comment_replynum')) {
var a = parseInt($('comment_replynum').innerHTML);
var b = a + 1;
$('comment_replynum').innerHTML = b + '';
}
showCreditPrompt();
}
function comment_edit(cid) {
var obj = $('comment_'+ cid +'_li');
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+ cid, function(s){
obj.innerHTML = s;
});
}
function comment_delete(cid) {
var obj = $('comment_'+ cid +'_li');
obj.style.display = "none";
if($('comment_replynum')) {
var a = parseInt($('comment_replynum').innerHTML);
var b = a - 1;
$('comment_replynum').innerHTML = b + '';
}
}
function share_delete(sid) {
var obj = $('share_'+ sid +'_li');
obj.style.display = "none";
}
function friend_delete(uid) {
var obj = $('friend_'+ uid +'_li');
if(obj != null) obj.style.display = "none";
var obj2 = $('friend_tbody_'+uid);
if(obj2 != null) obj2.style.display = "none";
}
function friend_changegroup(id, result) {
if(result) {
var ids = explode('_', id);
var uid = ids[1];
var obj = $('friend_group_'+ uid);
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getfriendgroup&uid='+uid, function(s){
obj.innerHTML = s;
});
}
}
function friend_changegroupname(group) {
var obj = $('friend_groupname_'+ group);
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=getfriendname&inajax=1&group='+group, function(s){
obj.innerHTML = s;
});
}
function post_add(pid, result) {
if(result) {
var obj = $('post_ul');
var newli = document.createElement("div");
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=post', function(s){
newli.innerHTML = s;
});
obj.appendChild(newli);
if($('message')) {
$('message').value= '';
newnode = $('quickpostimg').rows[0].cloneNode(true);
tags = newnode.getElementsByTagName('input');
for(i in tags) {
if(tags[i].name == 'pics[]') {
tags[i].value = 'http://';
}
}
var allRows = $('quickpostimg').rows;
while(allRows.length) {
$('quickpostimg').removeChild(allRows[0]);
}
$('quickpostimg').appendChild(newnode);
}
if($('post_replynum')) {
var a = parseInt($('post_replynum').innerHTML);
var b = a + 1;
$('post_replynum').innerHTML = b + '';
}
showCreditPrompt();
}
}
function post_edit(id, result) {
if(result) {
var ids = explode('_', id);
var pid = ids[1];
var obj = $('post_'+ pid +'_li');
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=post&pid='+ pid, function(s){
obj.innerHTML = s;
});
}
}
function post_delete(id, result) {
if(result) {
var ids = explode('_', id);
var pid = ids[1];
var obj = $('post_'+ pid +'_li');
obj.style.display = "none";
if($('post_replynum')) {
var a = parseInt($('post_replynum').innerHTML);
var b = a - 1;
$('post_replynum').innerHTML = b + '';
}
}
}
function poke_send(id, result) {
if(result) {
var ids = explode('_', id);
var uid = ids[1];
if($('poke_'+ uid)) {
$('poke_'+ uid).style.display = "none";
}
showCreditPrompt();
}
}
function myfriend_post(uid) {
if($('friend_'+uid)) {
$('friend_'+uid).innerHTML = '<p>你们现在是好友了,接下来,您还可以:<a href="home.php?mod=space&do=wall&uid='+uid+'" class="xi2" target="_blank">给TA留言</a> ,或者 <a href="home.php?mod=spacecp&ac=poke&op=send&uid='+uid+'&handlekey=propokehk_'+uid+'" id="a_poke_'+uid+'" class="xi2" onclick="showWindow(this.id, this.href, \'get\', 0, {\'ctrlid\':this.id,\'pos\':\'13\'});">打个招呼</a></p>';
}
showCreditPrompt();
}
function myfriend_ignore(id) {
var ids = explode('_', id);
var uid = ids[1];
$('friend_tbody_'+uid).style.display = "none";
}
function mtag_join(tagid, result) {
if(result) {
location.reload();
}
}
function picView(albumid) {
if(albumid == 'none') {
$('albumpic_body').innerHTML = '';
} else {
ajaxget('home.php?mod=misc&ac=ajax&op=album&id='+albumid+'&ajaxdiv=albumpic_body', 'albumpic_body');
}
}
function resend_mail(mid) {
if(mid) {
var obj = $('sendmail_'+ mid +'_li');
obj.style.display = "none";
}
}
function userapp_delete(id, result) {
if(result) {
var ids = explode('_', id);
var appid = ids[1];
$('space_app_'+appid).style.display = "none";
}
}
function docomment_get(doid, key) {
var showid = key + '_' + doid;
var opid = key + '_do_a_op_'+doid;
$(showid).style.display = '';
$(showid).className = 'cmt brm';
ajaxget('home.php?mod=spacecp&ac=doing&op=getcomment&handlekey=msg_'+doid+'&doid='+doid+'&key='+key, showid);
if($(opid)) {
$(opid).innerHTML = '收起';
$(opid).onclick = function() {
docomment_colse(doid, key);
}
}
showCreditPrompt();
}
function docomment_colse(doid, key) {
var showid = key + '_' + doid;
var opid = key + '_do_a_op_'+doid;
$(showid).style.display = 'none';
$(showid).style.className = '';
$(opid).innerHTML = '回复';
$(opid).onclick = function() {
docomment_get(doid, key);
}
}
function docomment_form(doid, id, key) {
var showid = key + '_form_'+doid+'_'+id;
var divid = key +'_'+ doid;
var url = 'home.php?mod=spacecp&ac=doing&op=docomment&handlekey=msg_'+id+'&doid='+doid+'&id='+id+'&key='+key;
if(parseInt(discuz_uid)) {
ajaxget(url, showid);
if($(divid)) {
$(divid).style.display = '';
}
} else {
showWindow(divid, url);
}
}
function docomment_form_close(doid, id, key) {
var showid = key + '_form_' + doid + '_' + id;
var opid = key + '_do_a_op_' + doid;
$(showid).innerHTML = '';
$(showid).style.display = 'none';
var liObj = $(key+'_'+doid).getElementsByTagName('li');
if(!liObj.length) {
$(key+'_'+doid).style.display = 'none';
if($(opid)) {
$(opid).innerHTML = '回复';
$(opid).onclick = function () {
docomment_get(doid, key);
}
}
}
}
function feedcomment_get(feedid) {
var showid = 'feedcomment_'+feedid;
var opid = 'feedcomment_a_op_'+feedid;
$(showid).style.display = '';
ajaxget('home.php?mod=spacecp&ac=feed&op=getcomment&feedid='+feedid+'&handlekey=feedhk_'+feedid, showid);
if($(opid) != null) {
$(opid).innerHTML = '收起';
$(opid).onclick = function() {
feedcomment_close(feedid);
}
}
}
function feedcomment_add(cid, feedid) {
var obj = $('comment_ol_'+feedid);
var newdl = document.createElement("dl");
newdl.id = 'comment_'+cid+'_li';
newdl.className = 'bbda cl';
var x = new Ajax();
x.get('home.php?mod=misc&ac=ajax&op=comment&inajax=1&cid='+cid, function(s){
newdl.innerHTML = s;
});
obj.appendChild(newdl);
$('feedmessage_'+feedid).value= '';
showCreditPrompt();
}
function feedcomment_close(feedid) {
var showid = 'feedcomment_'+feedid;
var opid = 'feedcomment_a_op_'+feedid;
$(showid).style.display = 'none';
$(showid).style.className = '';
$(opid).innerHTML = '评论';
$(opid).onclick = function() {
feedcomment_get(feedid);
}
}
function feed_post_result(feedid, result) {
if(result) {
location.reload();
}
}
function feed_more_show(feedid) {
var showid = 'feed_more_'+feedid;
var opid = 'feed_a_more_'+feedid;
$(showid).style.display = '';
$(showid).className = 'sub_doing';
$(opid).innerHTML = '« 收起列表';
$(opid).onclick = function() {
feed_more_close(feedid);
}
}
function feed_more_close(feedid) {
var showid = 'feed_more_'+feedid;
var opid = 'feed_a_more_'+feedid;
$(showid).style.display = 'none';
$(opid).innerHTML = '» 更多动态';
$(opid).onclick = function() {
feed_more_show(feedid);
}
}
function poll_post_result(id, result) {
if(result) {
var aObj = $('__'+id).getElementsByTagName("a");
window.location.href = aObj[0].href;
}
}
function show_click(idtype, id, clickid) {
ajaxget('home.php?mod=spacecp&ac=click&op=show&clickid='+clickid+'&idtype='+idtype+'&id='+id, 'click_div');
showCreditPrompt();
}
function feed_menu(feedid, show) {
var obj = $('a_feed_menu_'+feedid);
if(obj) {
if(show) {
obj.style.display='block';
} else {
obj.style.display='none';
}
}
var obj = $('feedmagic_'+feedid);
if(obj) {
if(show) {
obj.style.display='block';
} else {
obj.style.display='none';
}
}
}
function showbirthday(){
var el = $('birthday');
var birthday = el.value;
el.length=0;
el.options.add(new Option('日', ''));
for(var i=0;i<28;i++){
el.options.add(new Option(i+1, i+1));
}
if($('birthmonth').value!="2"){
el.options.add(new Option(29, 29));
el.options.add(new Option(30, 30));
switch($('birthmonth').value){
case "1":
case "3":
case "5":
case "7":
case "8":
case "10":
case "12":{
el.options.add(new Option(31, 31));
}
}
} else if($('birthyear').value!="") {
var nbirthyear=$('birthyear').value;
if(nbirthyear%400==0 || (nbirthyear%4==0 && nbirthyear%100!=0)) el.options.add(new Option(29, 29));
}
el.value = birthday;
}
function magicColor(elem, t) {
t = t || 10;
elem = (elem && elem.constructor == String) ? $(elem) : elem;
if(!elem){
setTimeout(function(){magicColor(elem, t-1);}, 400);
return;
}
if(window.mcHandler == undefined) {
window.mcHandler = {elements:[]};
window.mcHandler.colorIndex = 0;
window.mcHandler.run = function(){
var color = ["#CC0000","#CC6D00","#CCCC00","#00CC00","#0000CC","#00CCCC","#CC00CC"][(window.mcHandler.colorIndex++) % 7];
for(var i = 0, L=window.mcHandler.elements.length; i<L; i++)
window.mcHandler.elements[i].style.color = color;
}
}
window.mcHandler.elements.push(elem);
if(window.mcHandler.timer == undefined) {
window.mcHandler.timer = setInterval(window.mcHandler.run, 500);
}
}
function passwordShow(value) {
if(value==4) {
$('span_password').style.display = '';
$('tb_selectgroup').style.display = 'none';
} else if(value==2) {
$('span_password').style.display = 'none';
$('tb_selectgroup').style.display = '';
} else {
$('span_password').style.display = 'none';
$('tb_selectgroup').style.display = 'none';
}
}
function getgroup(gid) {
if(gid) {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=privacy&inajax=1&op=getgroup&gid='+gid, function(s){
s = s + ' ';
$('target_names').innerHTML += s;
});
}
}
function pmsendappend() {
$('pm_append').style.display = '';
$('pm_append').id = '';
div = document.createElement('div');
div.id = 'pm_append';
div.style.display = 'none';
$('pm_ul').appendChild(div);
$('replymessage').value = '';
showCreditPrompt();
}
function succeedhandle_pmsend(locationhref, message, param) {
ajaxget('home.php?mod=spacecp&ac=pm&op=viewpmid&pmid=' + param['pmid'], 'pm_append', 'ajaxwaitid', '', null, 'pmsendappend()');
}
function getchatpmappendmember() {
var users = document.getElementsByName('users[]');
var appendmember = '';
if(users.length) {
var comma = '';
for(var i = 0; i < users.length; i++) {
appendmember += comma + users[i].value;
if(!comma) {
comma = ',';
}
}
}
if($('username').value) {
appendmember = appendmember ? (appendmember + ',' + $('username').value) : $('username').value;
}
var href = $('a_appendmember').href + '&memberusername=' + appendmember;
showWindow('a_appendmember', href, 'get', 0);
}
function markreadpm(markreadids) {
var markreadidarr = markreadids.split(',');
if(markreadidarr.length > 0) {
for(var i = 0; i < markreadidarr.length; i++) {
$(markreadidarr[i]).className = 'bbda cl';
}
}
}
function setpmstatus(form) {
var ids_gpmid = new Array();
var ids_plid = new Array();
var type = '';
var requesturl = '';
var markreadids = new Array();
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if(e.id && e.id.match('a_delete') && e.checked) {
var idarr = new Array();
idarr = e.id.split('_');
if(idarr[1] == 'deleteg') {
ids_gpmid.push(idarr[2]);
markreadids.push('gpmlist_' + idarr[2]);
} else if(idarr[1] == 'delete') {
ids_plid.push(idarr[2]);
markreadids.push('pmlist_' + idarr[2]);
}
}
}
if(ids_gpmid.length > 0) {
requesturl += '&gpmids=' + ids_gpmid.join(',');
}
if(ids_plid.length > 0) {
requesturl += '&plids=' + ids_plid.join(',');
}
if(requesturl) {
ajaxget('home.php?mod=spacecp&ac=pm&op=setpmstatus' + requesturl, '', 'ajaxwaitid', '', 'none', 'markreadpm(\''+ markreadids.join(',') +'\')');
}
}
function changedeletedpm(pmid) {
$('pmlist_' + pmid).style.display = 'none';
var membernum = parseInt($('membernum').innerHTML);
$('membernum').innerHTML = membernum - 1;
}
function changeOrderRange(id) {
if(!$(id)) return false;
var url = window.location.href;
var a = $(id).getElementsByTagName('a');
for(var i = 0; i < a.length; i++) {
a[i].onclick = function () {
if(url.indexOf("&orderby=") == -1) {
url += "&orderby=" + this.id;
} else {
url = url.replace(/orderby=.*/, "orderby=" + this.id);
}
window.location = url;
return false;
}
}
}
function addBlockLink(id, tag) {
if(!$(id)) return false;
var a = $(id).getElementsByTagName(tag);
var taglist = {'A':1, 'INPUT':1, 'IMG':1};
for(var i = 0, len = a.length; i < len; i++) {
a[i].onmouseover = function () {
if(this.className.indexOf(' hover') == -1) {
this.className = this.className + ' hover';
}
};
a[i].onmouseout = function () {
this.className = this.className.replace(' hover', '');
};
a[i].onclick = function (e) {
e = e ? e : window.event;
var target = e.target || e.srcElement;
if(!taglist[target.tagName]) {
window.location.href = $(this.id + '_a').href;
}
};
}
}
function checkSynSignature() {
if($('to_signhtml').value == '1') {
$('syn_signature').className = 'syn_signature';
$('to_signhtml').value = '0';
} else {
$('syn_signature').className = 'syn_signature_check';
$('to_signhtml').value = '1';
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: portal_diy.js 22076 2011-04-21 06:22:09Z zhangguosheng $
*/
var drag = new Drag();
drag.extend({
'getBlocksTimer' : '',
'blocks' : [],
'blockDefaultClass' : [{'key':'选择样式','value':''},{'key':'无边框且无边距','value':'cl_block_bm'},{'key':'样式1','value':'xbs_1'},{'key':'样式2','value':'xbs xbs_2'},{'key':'样式3','value':'xbs xbs_3'},{'key':'样式4','value':'xbs xbs_4'},{'key':'样式5','value':'xbs xbs_5'},{'key':'样式6','value':'xbs xbs_6'},{'key':'样式7','value':'xbs xbs_7'}],
'frameDefaultClass' : [{'key':'选择样式','value':''},{'key':'无边框且无边距','value':'cl_frame_bm'},{'key':'无边框框架','value':'xfs xfs_nbd'},{'key':'样式1','value':'xfs xfs_1'},{'key':'样式2','value':'xfs xfs_2'},{'key':'样式3','value':'xfs xfs_3'},{'key':'样式4','value':'xfs xfs_4'},{'key':'样式5','value':'xfs xfs_5'}],
setDefalutMenu : function () {
this.addMenu('default','标题','drag.openTitleEdit(event)');
this.addMenu('default','样式','drag.openStyleEdit(event)');
this.addMenu('default', '删除', 'drag.removeBlock(event)');
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
this.addMenu('frame', '导出', 'drag.frameExport(event)');
this.addMenu('tab', '导出', 'drag.frameExport(event)');
},
setSampleMenu : function () {
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
this.addMenu('block', '数据', 'drag.openBlockEdit(event,"data")');
this.addMenu('block', '更新', 'drag.blockForceUpdate(event)');
},
openBlockEdit : function (e,op) {
e = Util.event(e);
op = (op=='data') ? 'data' : 'block';
var bid = e.aim.id.replace('cmd_portal_block_','');
this.removeMenu();
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op='+op+'&bid='+bid+'&tpl='+document.diyform.template.value, 'get', -1);
},
getDiyClassName : function (id,index) {
var obj = this.getObjByName(id);
var ele = $(id);
var eleClassName = ele.className.replace(/ {2,}/g,' ');
var className = '',srcClassName = '';
if (obj instanceof Block) {
className = eleClassName.split(this.blockClass+' ');
srcClassName = this.blockClass;
} else if(obj instanceof Tab) {
className = eleClassName.split(this.tabClass+' ');
srcClassName = this.tabClass;
} else if(obj instanceof Frame) {
className = eleClassName.split(this.frameClass+' ');
srcClassName = this.frameClass;
}
if (index != null && index<className.length) {
className = className[index].replace(/^ | $/g,'');
} else {
className.push(srcClassName);
}
return className;
},
getOption : function (arr,value) {
var html = '';
for (var i in arr) {
if (typeof arr[i] == 'function') continue;
var selected = arr[i]['value'] == value ? ' selected="selected"' : '';
html += '<option value="'+arr[i]['value']+'"'+selected+'>'+arr[i]['key']+'</option>';
}
return html;
},
getRule : function (selector,attr) {
selector = spaceDiy.checkSelector(selector);
var value = (!selector || !attr) ? '' : spaceDiy.styleSheet.getRule(selector, attr);
return value;
},
openStyleEdit : function (e) {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
var obj = this.getObjByName(id);
var objType = obj instanceof Block ? 1 : 0;
var bgcolor = '',bgimage = '',bgrepeat = '',html = '',diyClassName = '',fontcolor = '',fontsize = '',linkcolor = '',linkfontsize = '';
var bdtstyle = '',bdtwidth = '',bdtcolor = '',bdrstyle = '',bdrwidth = '',bdrcolor = '',bdbstyle = '',bdbwidth = '',bdbcolor = '',bdlstyle = '',bdlwidth = '',bdlcolor = '';
var margint = '',marginr = '',marginb = '',marginl = '',cmargint = '',cmarginr = '',cmarginb = '',cmarginl ='';
var selector = '#'+id;
bgcolor = this.getRule(selector, 'backgroundColor');
bgimage = this.getRule(selector, 'backgroundImage');
bgrepeat = this.getRule(selector, 'backgroundRepeat');
bgimage = bgimage && bgimage != 'none' ? Util.trimUrl(bgimage) : '';
fontcolor = this.getRule(selector+' .'+this.contentClass, 'color');
fontsize = this.getRule(selector+' .'+this.contentClass, 'fontSize').replace('px','');
var linkSelector = spaceDiy.checkSelector(selector+ ' .'+this.contentClass+' a');
linkcolor = this.getRule(linkSelector, 'color');
linkfontsize = this.getRule(linkSelector, 'fontSize').replace('px','');
fontcolor = Util.formatColor(fontcolor);
linkcolor = Util.formatColor(linkcolor);
bdtstyle = this.getRule(selector, 'borderTopStyle');
bdrstyle = this.getRule(selector, 'borderRightStyle');
bdbstyle = this.getRule(selector, 'borderBottomStyle');
bdlstyle = this.getRule(selector, 'borderLeftStyle');
bdtwidth = this.getRule(selector, 'borderTopWidth');
bdrwidth = this.getRule(selector, 'borderRightWidth');
bdbwidth = this.getRule(selector, 'borderBottomWidth');
bdlwidth = this.getRule(selector, 'borderLeftWidth');
bdtcolor = this.getRule(selector, 'borderTopColor');
bdrcolor = this.getRule(selector, 'borderRightColor');
bdbcolor = this.getRule(selector, 'borderBottomColor');
bdlcolor = this.getRule(selector, 'borderLeftColor');
bgcolor = Util.formatColor(bgcolor);
bdtcolor = Util.formatColor(bdtcolor);
bdrcolor = Util.formatColor(bdrcolor);
bdbcolor = Util.formatColor(bdbcolor);
bdlcolor = Util.formatColor(bdlcolor);
margint = this.getRule(selector, 'marginTop').replace('px','');
marginr = this.getRule(selector, 'marginRight').replace('px','');
marginb = this.getRule(selector, 'marginBottom').replace('px','');
marginl = this.getRule(selector, 'marginLeft').replace('px','');
if (objType == 1) {
selector = selector + ' .'+this.contentClass;
cmargint = this.getRule(selector, 'marginTop').replace('px','');
cmarginr = this.getRule(selector, 'marginRight').replace('px','');
cmarginb = this.getRule(selector, 'marginBottom').replace('px','');
cmarginl = this.getRule(selector, 'marginLeft').replace('px','');
}
diyClassName = this.getDiyClassName(id,0);
var widtharr = [];
for (var k=0;k<11;k++) {
var key = k+'px';
widtharr.push({'key':key,'value':key});
}
var bigarr = [];
for (var k=0;k<31;k++) {
key = k+'px';
bigarr.push({'key':key,'value':key});
}
var repeatarr = [{'key':'平铺','value':'repeat'},{'key':'不平铺','value':'no-repeat'},{'key':'横向平铺','value':'repeat-x'},{'key':'纵向平铺','value':'repeat-y'}];
var stylearr = [{'key':'无样式','value':'none'},{'key':'实线','value':'solid'},{'key':'点线','value':'dotted'},{'key':'虚线','value':'dashed'}];
var table = '<table class="tfm">';
table += '<tr><th>字体</th><td><input type="text" id="fontsize" class="px p_fre vm" value="'+fontsize+'" size="2" />px <input type="text" id="fontcolor" class="px p_fre vm" value="'+fontcolor+'" size="2" />';
table += getColorPalette(id+'_fontPalette', 'fontcolor' ,fontcolor)+'</td></tr>';
table += '<tr><th>链接</th><td><input type="text" id="linkfontsize" class="px p_fre vm" value="'+linkfontsize+'" size="2" />px <input type="text" id="linkcolor" class="px p_fre vm" value="'+linkcolor+'" size="2" />';
table += getColorPalette(id+'_linkPalette', 'linkcolor' ,linkcolor)+'</td></tr>';
var ulclass = 'borderul', opchecked = '';
if (bdtwidth != '' || bdtcolor != '' ) {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>边框</th><td><ul id="borderul" class="'+ulclass+'">';
table += '<li><label>上</label><select class="ps vm" id="bdtwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdtwidth)+'</select>';
table += ' <select class="ps vm" id="bdtstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdtstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdtcolor" class="px p_fre vm" value="'+bdtcolor+'" size="7" />';
table += getColorPalette(id+'_bdtPalette', 'bdtcolor' ,bdtcolor)+'</li>';
table += '<li class="bordera mtn"><label>右</label><select class="ps vm" id="bdrwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdrwidth)+'</select>';
table += ' <select class="ps vm" id="bdrstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdrstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdrcolor" class="px p_fre vm" value="'+bdrcolor+'" size="7" />';
table += getColorPalette(id+'_bdrPalette', 'bdrcolor' ,bdrcolor)+'</li>';
table += '<li class="bordera mtn"><label>下</label><select class="ps vm" id="bdbwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdbwidth)+'</select>';
table += ' <select class="ps vm" id="bdbstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdbstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdbcolor" class="px p_fre vm" value="'+bdbcolor+'" size="7" />';
table += getColorPalette(id+'_bdbPalette', 'bdbcolor' ,bdbcolor)+'</li>';
table += '<li class="bordera mtn"><label>左</label><select class="ps vm" id="bdlwidth" ><option value="">大小</option>'+this.getOption(widtharr,bdlwidth)+'</select>';
table += ' <select class="ps vm" id="bdlstyle" ><option value="">样式</option>'+this.getOption(stylearr,bdlstyle)+'</select>';
table += ' 颜色 <input type="text" id="bdlcolor" class="px p_fre vm" value="'+bdlcolor+'" size="7" />';
table += getColorPalette(id+'_bdlPalette', 'bdlcolor' ,bdlcolor)+'</li>';
table += '</ul><p class="ptm"><label><input id="borderop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'borderul\').className = $(\'borderul\').className == \'borderul\' ? \'borderula\' : \'borderul\'">分别设置</label></p></td></tr>';
bigarr = [];
for (k=-20;k<31;k++) {
key = k+'px';
bigarr.push({'key':key,'value':key});
}
ulclass = 'borderul', opchecked = '';
if (margint != '') {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>外边距</th><td><div id="margindiv" class="'+ulclass+'"><span><label>上</label> <input type="text" id="margint" class="px p_fre vm" value="'+margint+'" size="1"/>px </span>';
table += '<span class="bordera"><label>右</label> <input type="text" id="marginr" class="px p_fre vm" value="'+marginr+'" size="1" />px </span>';
table += '<span class="bordera"><label>下</label> <input type="text" id="marginb" class="px p_fre vm" value="'+marginb+'" size="1" />px </span>';
table += '<span class="bordera"><label>左</label> <input type="text" id="marginl" class="px p_fre vm" value="'+marginl+'" size="1" />px</span>';
table += '</div><p class="ptm"><label><input id="marginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'margindiv\').className = $(\'margindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'">分别设置</label></p></td></tr>';
if (objType == 1) {
ulclass = 'borderul', opchecked = '';
if (cmargint != '') {
ulclass = 'borderula';
opchecked = ' checked="checked"';
}
table += '<tr><th>内边距</th><td><div id="cmargindiv" class="'+ulclass+'"><span><label>上</label> <input class="px p_fre" id="cmargint" value="'+cmargint+'" size="1" />px </span>';
table += '<span class="bordera"><label>右</label> <input class="px p_fre" id="cmarginr" value="'+cmarginr+'" size="1" />px </span>';
table += '<span class="bordera"><label>下</label> <input class="px p_fre" id="cmarginb" value="'+cmarginb+'" size="1" />px </span>';
table += '<span class="bordera"><label>左</label> <input class="px p_fre" id="cmarginl" value="'+cmarginl+'" size="1" />px </span>';
table += '</div><p class="ptm"><label><input id="cmarginop" type="checkbox" value="1" class="pc"'+opchecked+' onclick="$(\'cmargindiv\').className = $(\'cmargindiv\').className == \'borderul\' ? \'borderula\' : \'borderul\'"> 分别设置</label></p></td></tr>';
}
table += '<tr><th>背景颜色</th><td><input type="text" id="bgcolor" class="px p_fre vm" value="'+bgcolor+'" size="4" />';
table += getColorPalette(id+'_bgcPalette', 'bgcolor' ,bgcolor)+'</td></tr>';
table += '<tr><th>背景图片</th><td><input type="text" id="bgimage" class="px p_fre vm" value="'+bgimage+'" size="25" /> <select class="ps vm" id="bgrepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>';
var classarr = objType == 1 ? this.blockDefaultClass : this.frameDefaultClass;
table += '<tr><th>指定class</th><td><input type="text" id="diyClassName" class="px p_fre" value="'+diyClassName+'" size="8" /> <select class="ps vm" id="bgrepeat" onchange="$(\'diyClassName\').value=this.value;" >'+this.getOption(classarr, diyClassName)+'</select></td></tr>';
table += '</table>';
var wname = objType ? '模块' : '框架';
html = '<div class="c diywin" style="width:450px;position:relative;">'+table+'</div>';
var h = '<h3 class="flb"><em>编辑'+wname+'样式</em><span><a href="javascript:;" class="flbc" onclick="drag.closeStyleEdit(\''+id+'\');return false;" title="关闭">\n\
关闭</a></span></h3>';
var f = '<p class="o pns"><button onclick="drag.saveStyle(\''+id+'\');drag.closeStyleEdit(\''+id+'\');" class="pn pnc" value="true">\n\
<strong>确定</strong></button><button onclick="drag.closeStyleEdit(\''+id+'\')" class="pn" value="true"><strong>取消</strong></button></p>';
this.removeMenu(e);
showWindow('eleStyle',h + html + f, 'html', 0);
},
closeStyleEdit : function (id) {
this.deleteFrame([id+'_bgcPalette',id+'_bdtPalette',id+'_bdrPalette',id+'_bdbPalette',id+'_bdlPalette',id+'_fontPalette',id+'_linkPalette']);
hideWindow('eleStyle');
},
saveStyle : function (id) {
var className = this.getDiyClassName(id);
var diyClassName = $('diyClassName').value;
$(id).className = diyClassName+' '+className[2]+' '+className[1];
var obj = this.getObjByName(id);
var objType = obj instanceof Block ? 1 : 0;
if (objType == 1) this.saveBlockClassName(id,diyClassName);
var selector = '#'+id;
var random = Math.random();
spaceDiy.setStyle(selector, 'background-color', $('bgcolor').value, random);
var bgimage = $('bgimage').value && $('bgimage') != 'none' ? Util.url($('bgimage').value) : '';
var bgrepeat = bgimage ? $('bgrepeat').value : '';
if ($('bgcolor').value != '' && bgimage == '') bgimage = 'none';
spaceDiy.setStyle(selector, 'background-image', bgimage, random);
spaceDiy.setStyle(selector, 'background-repeat', bgrepeat, random);
spaceDiy.setStyle(selector+' .'+this.contentClass, 'color', $('fontcolor').value, random);
spaceDiy.setStyle(selector+' .'+this.contentClass, 'font-size', this.formatValue('fontsize'), random);
spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'color', $('linkcolor').value, random);
var linkfontsize = parseInt($('linkfontsize').value);
linkfontsize = isNaN(linkfontsize) ? '' : linkfontsize+'px';
spaceDiy.setStyle(spaceDiy.checkSelector(selector+' .'+this.contentClass+' a'), 'font-size', this.formatValue('linkfontsize'), random);
if ($('borderop').checked) {
var bdtwidth = $('bdtwidth').value,bdrwidth = $('bdrwidth').value,bdbwidth = $('bdbwidth').value,bdlwidth = $('bdlwidth').value;
var bdtstyle = $('bdtstyle').value,bdrstyle = $('bdrstyle').value,bdbstyle = $('bdbstyle').value,bdlstyle = $('bdlstyle').value;
var bdtcolor = $('bdtcolor').value,bdrcolor = $('bdrcolor').value,bdbcolor = $('bdbcolor').value,bdlcolor = $('bdlcolor').value;
} else {
bdlwidth = bdbwidth = bdrwidth = bdtwidth = $('bdtwidth').value;
bdlstyle = bdbstyle = bdrstyle = bdtstyle = $('bdtstyle').value;
bdlcolor = bdbcolor = bdrcolor = bdtcolor = $('bdtcolor').value;
}
spaceDiy.setStyle(selector, 'border', '', random);
spaceDiy.setStyle(selector, 'border-top-width', bdtwidth, random);
spaceDiy.setStyle(selector, 'border-right-width', bdrwidth, random);
spaceDiy.setStyle(selector, 'border-bottom-width', bdbwidth, random);
spaceDiy.setStyle(selector, 'border-left-width', bdlwidth, random);
spaceDiy.setStyle(selector, 'border-top-style', bdtstyle, random);
spaceDiy.setStyle(selector, 'border-right-style', bdrstyle, random);
spaceDiy.setStyle(selector, 'border-bottom-style', bdbstyle, random);
spaceDiy.setStyle(selector, 'border-left-style', bdlstyle, random);
spaceDiy.setStyle(selector, 'border-top-color', bdtcolor, random);
spaceDiy.setStyle(selector, 'border-right-color', bdrcolor, random);
spaceDiy.setStyle(selector, 'border-bottom-color', bdbcolor, random);
spaceDiy.setStyle(selector, 'border-left-color', bdlcolor, random);
if ($('marginop').checked) {
var margint = this.formatValue('margint'),marginr = this.formatValue('marginr'), marginb = this.formatValue('marginb'), marginl = this.formatValue('marginl');
} else {
marginl = marginb = marginr = margint = this.formatValue('margint');
}
spaceDiy.setStyle(selector, 'margin-top',margint, random);
spaceDiy.setStyle(selector, 'margin-right', marginr, random);
spaceDiy.setStyle(selector, 'margin-bottom', marginb, random);
spaceDiy.setStyle(selector, 'margin-left', marginl, random);
if (objType == 1) {
if ($('cmarginop').checked) {
var cmargint = this.formatValue('cmargint'),cmarginr = this.formatValue('cmarginr'), cmarginb = this.formatValue('cmarginb'), cmarginl = this.formatValue('cmarginl');
} else {
cmarginl = cmarginb = cmarginr = cmargint = this.formatValue('cmargint');
}
selector = selector + ' .'+this.contentClass;
spaceDiy.setStyle(selector, 'margin-top', cmargint, random);
spaceDiy.setStyle(selector, 'margin-right', cmarginr, random);
spaceDiy.setStyle(selector, 'margin-bottom', cmarginb, random);
spaceDiy.setStyle(selector, 'margin-left', cmarginl, random);
}
this.setClose();
},
formatValue : function(id) {
var value = '';
if ($(id)) {
value = parseInt($(id).value);
value = isNaN(value) ? '' : value+'px';
}
return value;
},
saveBlockClassName : function(id,className){
if (!$('saveblockclassname')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="saveblockclassname" method="post" action=""><input type="hidden" name="classname" value="" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="saveclassnamesubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('saveblockclassname').action = 'portal.php?mod=portalcp&ac=block&op=saveblockclassname&bid='+id.replace('portal_block_','');
document.forms.saveblockclassname.classname.value = className;
ajaxpost('saveblockclassname','ajaxwaitid');
},
closeTitleEdit : function (fid) {
this.deleteFrame(fid+'bgPalette_0');
for (var i = 0 ; i<=10; i++) {
this.deleteFrame(fid+'Palette_'+i);
}
hideWindow('frameTitle');
},
openTitleEdit : function (e) {
if (typeof e == 'object') {
e = Util.event(e);
var fid = e.aim.id.replace('cmd_','');
} else {
fid = e;
}
var obj = this.getObjByName(fid);
var titlename = obj instanceof Block ? '模块' : '框架';
var repeatarr = [{'key':'平铺','value':'repeat'},{'key':'不平铺','value':'no-repeat'},{'key':'横向平铺','value':'repeat-x'},{'key':'纵向平铺','value':'repeat-y'}];
var len = obj.titles.length;
var bgimage = obj.titles.style && obj.titles.style['background-image'] ? obj.titles.style['background-image'] : '';
bgimage = bgimage != 'none' ? Util.trimUrl(bgimage) : '';
var bgcolor = obj.titles.style && obj.titles.style['background-color'] ? obj.titles.style['background-color'] : '';
bgcolor = Util.formatColor(bgcolor);
var bgrepeat = obj.titles.style && obj.titles.style['background-repeat'] ? obj.titles.style['background-repeat'] : '';
var common = '<table class="tfm">';
common += '<tr><th>背景图片:</th><td><input type="text" id="titleBgImage" class="px p_fre" value="'+bgimage+'" /> <select class="ps vm" id="titleBgRepeat" >'+this.getOption(repeatarr,bgrepeat)+'</select></td></tr>';
common += '<tr><th>背景颜色:</th><td><input type="text" id="titleBgColor" class="px p_fre" value="'+bgcolor+'" size="7" />';
common += getColorPalette(fid+'bgPalette_0', 'titleBgColor' ,bgcolor)+'</td></tr>';
if (obj instanceof Tab) {
var switchArr = [{'key':'点击','value':'click'},{'key':'滑过','value':'mouseover'}];
var switchType = obj.titles['switchType'] ? obj.titles['switchType'][0] : 'click';
common += '<tr><th>切换类型:</th><td><select class="ps" id="switchType" >'+this.getOption(switchArr,switchType)+'</select></td></tr>';
}
common += '</table><hr class="l">';
var li = '';
li += '<div id="titleInput_0"><table class="tfm"><tr><th>'+titlename+'标题:</th><td><input type="text" id="titleText_0" class="px p_fre" value="`title`" /></td></tr>';
li += '<tr><th>链接:</th><td><input type="text" id="titleLink_0" class="px p_fre" value="`link`" /></td></tr>';
li += '<tr><th>图片:</th><td><input type="text" id="titleSrc_0" class="px p_fre" value="`src`" /></td></tr>';
li += '<tr><th>位置:</th><td><select id="titleFloat_0" class="ps vm"><option value="" `left`>居左</option><option value="right" `right`>居右</option></select>';
li += ' 偏移量: <input type="text" id="titleMargin_0" class="px p_fre vm" value="`margin`" size="2" />px</td></tr>';
li += '<tr><th>字体:</th><td><select class="ps vm" id="titleSize_0" ><option value="">大小</option>`size`</select>';
li += ' 颜色: <input type="text" id="titleColor_0" class="px p_fre vm" value="`color`" size="4" />';
li += getColorPalette(fid+'Palette_0', 'titleColor_0' ,'`color`');
li += '</td></tr><tr><td colspan="2"><hr class="l"></td></tr></table></div>';
var html = '';
if (obj.titles['first']) {
html = this.getTitleHtml(obj, 'first', li);
}
for (var i = 0; i < len; i++ ) {
html += this.getTitleHtml(obj, i, li);
}
if (!html) {
var bigarr = [];
for (var k=7;k<27;k++) {
var key = k+'px';
bigarr.push({'key':key,'value':key});
}
var ssize = this.getOption(bigarr,ssize);
html = li.replace('`size`', ssize).replace(/`\w+`/g, '');
}
var c = len + 1;
html = '<div class="c diywin" style="width:450px;height:400px; overflow:auto;"><table cellspacing="0" cellpadding="0" class="tfm pns"><tr><th></th><td><button type="button" id="addTitleInput" class="pn" onclick="drag.addTitleInput('+c+');"><em>添加新标题</em></button></td></tr></table><div id="titleEdit">'+html+common+'</div></div>';
var h = '<h3 class="flb"><em>编辑'+titlename+'标题</em><span><a href="javascript:;" class="flbc" onclick="drag.closeTitleEdit(\''+fid+'\');return false;" title="关闭">\n\
关闭</a></span></h3>';
var f = '<p class="o pns"><button onclick="drag.saveTitleEdit(\''+fid+'\');drag.closeTitleEdit(\''+fid+'\');" class="pn pnc" value="true">\n\
<strong>确定</strong></button><button onclick="drag.closeTitleEdit(\''+fid+'\')" class="pn" value="true"><strong>取消</strong></button></p>';
this.removeMenu(e);
showWindow('frameTitle',h + html + f, 'html', 0);
},
getTitleHtml : function (obj, i, li) {
var shtml = '',stitle = '',slink = '',sfloat = '',ssize = '',scolor = '',margin = '',src = '';
var c = i == 'first' ? '0' : i+1;
stitle = obj.titles[i]['text'] ? obj.titles[i]['text'] : '';
slink = obj.titles[i]['href'] ? obj.titles[i]['href'] : '';
sfloat = obj.titles[i]['float'] ? obj.titles[i]['float'] : '';
margin = obj.titles[i]['margin'] ? obj.titles[i]['margin'] : '';
ssize = obj.titles[i]['font-size'] ? obj.titles[i]['font-size']+'px' : '';
scolor = obj.titles[i]['color'] ? obj.titles[i]['color'] : '';
src = obj.titles[i]['src'] ? obj.titles[i]['src'] : '';
var bigarr = [];
for (var k=7;k<27;k++) {
var key = k+'px';
bigarr.push({'key':key,'value':key});
}
ssize = this.getOption(bigarr,ssize);
shtml = li.replace(/_0/g, '_' + c).replace('`title`', stitle).replace('`link`', slink).replace('`size`', ssize).replace('`src`',src);
var left = sfloat == '' ? 'selected' : '';
var right = sfloat == 'right' ? 'selected' : '';
scolor = Util.formatColor(scolor);
shtml = shtml.replace(/`color`/g, scolor).replace('`left`', left).replace('`right`', right).replace('`margin`', margin);
return shtml;
},
addTitleInput : function (c) {
if (c > 10) return false;
var pre = $('titleInput_'+(c-1));
var dom = document.createElement('div');
dom.className = 'tfm';
var exp = new RegExp('_'+(c-1), 'g');
dom.id = 'titleInput_'+c;
dom.innerHTML = pre.innerHTML.replace(exp, '_'+c);
Util.insertAfter(dom, pre);
$('addTitleInput').onclick = function () {drag.addTitleInput(c+1)};
},
saveTitleEdit : function (fid) {
var obj = this.getObjByName(fid);
var ele = $(fid);
var children = ele.childNodes;
var title = first = '';
var hastitle = 0;
var c = 0;
for (var i in children) {
if (typeof children[i] == 'object' && Util.hasClass(children[i], this.titleClass)) {
title = children[i];
break;
}
}
if (title) {
var arrDel = [];
for (var i in title.childNodes) {
if (typeof title.childNodes[i] == 'object' && Util.hasClass(title.childNodes[i], this.titleTextClass)) {
first = title.childNodes[i];
this._createTitleHtml(first, c);
if (first.innerHTML != '') hastitle = 1;
} else if (typeof title.childNodes[i] == 'object' && !Util.hasClass(title.childNodes[i], this.moveableObject)) {
arrDel.push(title.childNodes[i]);
}
}
for (var i = 0; i < arrDel.length; i++) {
title.removeChild(arrDel[i]);
}
} else {
var className = obj instanceof Tab ? this.tabClass : obj instanceof Frame ? 'frame' : obj instanceof Block ? 'block' : '';
title = document.createElement('div');
title.className = className + 'title' + ' '+ this.titleClass;
ele.insertBefore(title,ele.firstChild);
}
if (!first) {
var first = document.createElement('span');
first.className = this.titleTextClass;
this._createTitleHtml(first, c);
if (first.innerHTML != '') {
title.insertBefore(first, title.firstChild);
hastitle = 1;
}
}
while ($('titleText_'+(++c))) {
var dom = document.createElement('span');
dom.className = 'subtitle';
this._createTitleHtml(dom, c);
if (dom.innerHTML != '') {
if (dom.innerHTML) Util.insertAfter(dom, first);
first = dom;
hastitle = 1;
}
}
var titleBgImage = $('titleBgImage').value;
titleBgImage = titleBgImage && titleBgImage != 'none' ? Util.url(titleBgImage) : '';
if ($('titleBgColor').value != '' && titleBgImage == '') titleBgImage = 'none';
title.style['backgroundImage'] = titleBgImage;
if (titleBgImage) {
title.style['backgroundRepeat'] = $('titleBgRepeat').value;
}
title.style['backgroundColor'] = $('titleBgColor').value;
if ($('switchType')) {
title.switchType = [];
title.switchType[0] = $('switchType').value ? $('switchType').value : 'click';
title.setAttribute('switchtype',title.switchType[0]);
}
obj.titles = [];
if (hastitle == 1) {
this._initTitle(obj,title);
} else {
if (!(obj instanceof Tab)) title.parentNode.removeChild(title);
title = '';
this.initPosition();
}
if (obj instanceof Block) this.saveBlockTitle(fid,title);
this.setClose();
},
_createTitleHtml : function (ele,tid) {
var html = '',img = '';
tid = '_' + tid ;
var ttext = $('titleText'+tid).value;
var tlink = $('titleLink'+tid).value;
var tfloat = $('titleFloat'+tid).value;
var tmargin_ = tfloat != '' ? tfloat : 'left';
var tmargin = $('titleMargin'+tid).value;
var tsize = $('titleSize'+tid).value;
var tcolor = $('titleColor'+tid).value;
var src = $('titleSrc'+tid).value;
var divStyle = 'float:'+tfloat+';margin-'+tmargin_+':'+tmargin+'px;font-size:'+tsize;
var aStyle = 'color:'+tcolor+';';
if (src) {
img = '<img class="vm" src="'+src+'" alt="'+ttext+'" />';
}
if (ttext || img) {
if (tlink) {
Util.setStyle(ele, divStyle);
html = '<a href='+tlink+' target="_blank" style="'+aStyle+'">'+img+ttext+'</a>';
} else {
Util.setStyle(ele, divStyle+';'+aStyle);
html = img+ttext;
}
}
ele.innerHTML = html;
return true;
},
saveBlockTitle : function (id,title) {
if (!$('saveblocktitle')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="saveblocktitle" method="post" action=""><input type="hidden" name="title" value="" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="savetitlesubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('saveblocktitle').action = 'portal.php?mod=portalcp&ac=block&op=saveblocktitle&bid='+id.replace('portal_block_','');
var html = !title ? '' : title.outerHTML;
document.forms.saveblocktitle.title.value = html;
ajaxpost('saveblocktitle','ajaxwaitid');
},
removeBlock : function (e, flag) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var obj = this.getObjByName(id);
if (!flag) {
if (!confirm('您确实要删除吗,删除以后将不可恢复')) return false;
}
if (obj instanceof Block) {
this.delBlock(id);
} else if (obj instanceof Frame) {
this.delFrame(obj);
}
$(id).parentNode.removeChild($(id));
var content = $(id+'_content');
if(content) {
content.parentNode.removeChild(content);
}
this.setClose();
this.initPosition();
this.initChkBlock();
},
delBlock : function (bid) {
spaceDiy.removeCssSelector('#'+bid);
this.stopSlide(bid);
},
delFrame : function (frame) {
spaceDiy.removeCssSelector('#'+frame.name);
for (var i in frame['columns']) {
if (frame['columns'][i] instanceof Column) {
var children = frame['columns'][i]['children'];
for (var j in children) {
if (children[j] instanceof Frame) {
this.delFrame(children[j]);
} else if (children[j] instanceof Block) {
this.delBlock(children[j]['name']);
}
}
}
}
this.setClose();
},
initChkBlock : function (data) {
if (typeof name == 'undefined' || data == null ) data = this.data;
if ( data instanceof Frame) {
this.initChkBlock(data['columns']);
} else if (data instanceof Block) {
var el = $('chk'+data.name);
if (el != null) el.checked = true;
} else if (typeof data == 'object') {
for (var i in data) {
this.initChkBlock(data[i]);
}
}
},
getBlockData : function (blockname) {
var bid = this.dragObj.id;
var eleid = bid;
if (bid.indexOf('portal_block_') != -1) {
eleid = 0;
}else {
bid = 0;
}
showWindow('showblock', 'portal.php?mod=portalcp&ac=block&op=block&classname='+blockname+'&bid='+bid+'&eleid='+eleid+'&tpl='+document.diyform.template.value,'get',-1);
drag.initPosition();
this.fn = '';
return true;
},
stopSlide : function (id) {
if (typeof slideshow == 'undefined' || typeof slideshow.entities == 'undefined') return false;
var slidebox = $C('slidebox',$(id));
if(slidebox && slidebox.length > 0) {
if(slidebox[0].id) {
var timer = slideshow.entities[slidebox[0].id].timer;
if(timer) clearTimeout(timer);
slideshow.entities[slidebox[0].id] = '';
}
}
},
blockForceUpdate : function (e,all) {
if ( typeof e !== 'string') {
e = Util.event(e);
var id = e.aim.id.replace('cmd_','');
} else {
var id = e;
}
if ($(id) == null) return false;
var bid = id.replace('portal_block_', '');
var bcontent = $(id+'_content');
if (!bcontent) {
bcontent = document.createElement('div');
bcontent.id = id+'_content';
bcontent.className = this.contentClass;
}
this.stopSlide(id);
var height = Util.getFinallyStyle(bcontent, 'height');
bcontent.style.lineHeight = height == 'auto' ? '' : (height == '0px' ? '20px' : height);
bcontent.innerHTML = '<center>正在加载内容...</center>';
var x = new Ajax();
x.get('portal.php?mod=portalcp&ac=block&op=getblock&forceupdate=1&inajax=1&bid='+bid+'&tpl='+document.diyform.template.value, function(s) {
var obj = document.createElement('div');
obj.innerHTML = s;
bcontent.parentNode.removeChild(bcontent);
$(id).innerHTML = obj.childNodes[0].innerHTML;
evalscript(s);
if(s.indexOf('runslideshow()') != -1) {runslideshow();}
drag.initPosition();
if (all) {drag.getBlocks();}
});
},
frameExport : function (e) {
var flag = true;
if (drag.isChange) {
flag = confirm('您已经做过修改,请保存后再做导出,否则导出的数据将不包括您这次所做的修改。');
}
if (flag) {
if ( typeof e == 'object') {
e = Util.event(e);
var frame = e.aim.id.replace('cmd_','');
} else {
frame = e == undefined ? '' : e;
}
if (!$('frameexport')){
var dom = document.createElement('div');
dom.innerHTML = '<form id="frameexport" method="post" action="" target="_blank"><input type="hidden" name="frame" value="" />\n\
<input type="hidden" name="tpl" value="'+document.diyform.template.value+'" />\n\
<input type="hidden" name="formhash" value="'+document.diyform.formhash.value+'" /><input type="hidden" name="exportsubmit" value="true"/></form>';
$('append_parent').appendChild(dom.childNodes[0]);
}
$('frameexport').action = 'portal.php?mod=portalcp&ac=diy&op=export';
document.forms.frameexport.frame.value = frame;
document.forms.frameexport.submit();
}
doane();
},
openFrameImport : function (type) {
type = type || 0;
showWindow('showimport','portal.php?mod=portalcp&ac=diy&op=import&tpl='+document.diyform.template.value+'&type='+type, 'get');
},
endBlockForceUpdateBatch : function () {
if($('allupdate')) {
$('allupdate').innerHTML = '已操作完成。';
$('fwin_dialog_submit').style.display = '';
$('fwin_dialog_cancel').style.display = 'none';
}
this.initPosition();
},
getBlocks : function () {
if (this.blocks.length == 0) {
this.endBlockForceUpdateBatch();
}
if (this.blocks.length > 0) {
var cur = this.blocksLen - this.blocks.length;
if($('allupdate')) {
$('allupdate').innerHTML = '共<span style="color:blue">'+this.blocksLen+'</span>个模块,正在更新第<span style="color:red">'+cur+'</span>个,已完成<span style="color:red">'+(parseInt(cur / this.blocksLen * 100)) + '%</span>';
var bid = 'portal_block_'+this.blocks.pop();
this.blockForceUpdate(bid,true);
}
}
},
blockForceUpdateBatch : function (blocks) {
if (blocks) {
this.blocks = blocks;
} else {
this.initPosition();
this.blocks = this.allBlocks;
}
this.blocksLen = this.blocks.length;
showDialog('<div id="allupdate" style="width:350px;line-height:28px;">开始更新...</div>','confirm','更新模块数据', '', true, 'drag.endBlockForceUpdateBatch()');
var wait = function() {
if($('fwin_dialog_submit')) {
$('fwin_dialog_submit').style.display = 'none';
setTimeout(function(){drag.getBlocks()},500);
} else {
setTimeout(wait,100);
}
};
wait();
doane();
},
clearAll : function () {
if (confirm('您确实要清空页面上所在DIY数据吗,清空以后将不可恢复')) {
for (var i in this.data) {
for (var j in this.data[i]) {
if (typeof(this.data[i][j]) == 'object' && this.data[i][j].name.indexOf('_temp')<0) {
this.delFrame(this.data[i][j]);
$(this.data[i][j].name).parentNode.removeChild($(this.data[i][j].name));
}
}
}
this.initPosition();
this.setClose();
}
doane();
},
createObj : function (e,objType,contentType) {
if (objType == 'block' && !this.checkHasFrame()) {alert("提示:未找到框架,请先添加框架。");spaceDiy.getdiy('frame');return false;}
e = Util.event(e);
if(e.which != 1 ) {return false;}
var html = '',offWidth = 0;
if (objType == 'frame') {
html = this.getFrameHtml(contentType);
offWidth = 600;
} else if (objType == 'block') {
html = this.getBlockHtml(contentType);
offWidth = 200;
this.fn = function (e) {drag.getBlockData(contentType);};
} else if (objType == 'tab') {
html = this.getTabHtml(contentType);
offWidth = 300;
}
var ele = document.createElement('div');
ele.innerHTML = html;
ele = ele.childNodes[0];
document.body.appendChild(ele);
this.dragObj = this.overObj = ele;
if (!this.getTmpBoxElement()) return false;
var scroll = Util.getScroll();
this.dragObj.style.position = 'absolute';
this.dragObj.style.left = e.clientX + scroll.l - 60 + "px";
this.dragObj.style.top = e.clientY + scroll.t - 10 + "px";
this.dragObj.style.width = offWidth + 'px';
this.dragObj.style.cursor = 'move';
this.dragObj.lastMouseX = e.clientX;
this.dragObj.lastMouseY = e.clientY;
Util.insertBefore(this.tmpBoxElement,this.overObj);
Util.addClass(this.dragObj,this.moving);
this.dragObj.style.zIndex = 500 ;
this.scroll = Util.getScroll();
this.newFlag = true;
var _method = this;
document.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
window.onscroll = function(){Drag.prototype.resetObj.call(_method, e);};
document.onmousemove = function (e){Drag.prototype.drag.call(_method, e);};
document.onmouseup = function (e){Drag.prototype.dragEnd.call(_method, e);};
},
getFrameHtml : function (type) {
var id = 'frame'+Util.getRandom(6);
var className = [this.frameClass,this.moveableObject].join(' ');
className = className + ' cl frame-' + type;
var str = '<div id="'+id+'" class="'+className+'">';
str += '<div id="'+id+'_title" class="'+this.titleClass+' '+this.frameTitleClass+'"><span class="'+this.titleTextClass+'">'+type+'框架</span></div>';
var cols = type.split('-');
var clsl='',clsc='',clsr='';
clsl = ' frame-'+type+'-l';
clsc = ' frame-'+type+'-c';
clsr = ' frame-'+type+'-r';
var len = cols.length;
if (len == 1) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsc+'"></div>';
} else if (len == 2) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+ '"></div>';
str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsr+ '"></div>';
} else if (len == 3) {
str += '<div id="'+id+'_left" class="'+this.moveableColumn+clsl+'"></div>';
str += '<div id="'+id+'_center" class="'+this.moveableColumn+clsc+'"></div>';
str += '<div id="'+id+'_right" class="'+this.moveableColumn+clsr+'"></div>';
}
str += '</div>';
return str;
},
getTabHtml : function () {
var id = 'tab'+Util.getRandom(6);
var className = [this.tabClass,this.moveableObject].join(' ');
className = className + ' cl';
var titleClassName = [this.tabTitleClass, this.titleClass, this.moveableColumn, 'cl'].join(' ');
var str = '<div id="'+id+'" class="'+className+'">';
str += '<div id="'+id+'_title" class="'+titleClassName+'"><span class="'+this.titleTextClass+'">tab标签</span></div>';
str += '<div id="'+id+'_content" class="'+this.tabContentClass+'"></div>';
str += '</div>';
return str;
},
getBlockHtml : function () {
var id = 'block'+Util.getRandom(6);
var str = '<div id="'+id+'" class="block move-span"></div>';
str += '</div>';
return str;
},
setClose : function () {
if(this.sampleMode) {
return true;
} else {
if (!this.isChange) {
window.onbeforeunload = function() {
return '您的数据已经修改,退出将无法保存您的修改。';
};
}
this.isChange = true;
spaceDiy.enablePreviewButton();
}
},
clearClose : function () {
this.isChange = false;
this.isClearClose = true;
window.onbeforeunload = function () {};
},
goonDIY : function () {
if ($('prefile').value == '1') {
showDialog('<div style="line-height:28px;">按继续按钮将打开暂存数据并DIY,<br />按删除按钮将删除暂存数据。</div>','confirm','是否继续暂存数据的DIY?', function(){location.replace(location.href+'&preview=yes');}, true, 'spaceDiy.cancelDIY()', '', '继续', '删除');
} else if (location.search.indexOf('preview=yes') > -1) {
spaceDiy.enablePreviewButton();
} else {
spaceDiy.disablePreviewButton();
}
setInterval(function(){spaceDiy.save('savecache', 1);},180000);
}
});
var spaceDiy = new DIY();
spaceDiy.extend({
save : function (optype,rejs) {
optype = typeof optype == 'undefined' ? '' : optype;
if (optype == 'savecache' && !drag.isChange) {return false;}
var tplpre = document.diyform.template.value.split(':');
if (!optype) {
if (['portal/portal_topic_content', 'portal/list', 'portal/view'].indexOf(tplpre[0]) == -1) {
if (document.diyform.template.value.indexOf(':') > -1 && !document.selectsave) {
var schecked = '',dchecked = '';
if (document.diyform.savemod.value == '1') {
dchecked = ' checked';
} else {
schecked = ' checked';
}
showDialog('<form name="selectsave" action="" method="get"><label><input type="radio" value="0" name="savemod"'+schecked+' />应用于此类全部页面</label>\n\
<label><input type="radio" value="1" name="savemod"'+dchecked+' />只应用于本页面</label></form>','notice', '', spaceDiy.save);
return false;
}
if (document.selectsave) {
if (document.selectsave.savemod[0].checked) {
document.diyform.savemod.value = document.selectsave.savemod[0].value;
} else {
document.diyform.savemod.value = document.selectsave.savemod[1].value;
}
}
} else {
document.diyform.savemod.value = 1;
}
} else if (optype == 'savecache') {
if (!drag.isChange) return false;
this.checkPreview_form();
document.diyform.rejs.value = rejs ? 0 : 1;
} else if (optype =='preview') {
if (drag.isChange) {
optype = 'savecache';
} else {
this.checkPreview_form();
$('preview_form').submit();
return false;
}
}
document.diyform.action = document.diyform.action.replace(/[&|\?]inajax=1/, '');
document.diyform.optype.value = optype;
document.diyform.spacecss.value = spaceDiy.getSpacecssStr();
document.diyform.style.value = spaceDiy.style;
document.diyform.layoutdata.value = drag.getPositionStr();
document.diyform.gobackurl.value = spaceDiy.cancelDiyUrl();
drag.clearClose();
if (optype == 'savecache') {
document.diyform.handlekey.value = 'diyform';
ajaxpost('diyform','ajaxwaitid','ajaxwaitid','onerror');
} else {
saveUserdata('diy_advance_mode', '');
document.diyform.submit();
}
},
checkPreview_form : function () {
if (!$('preview_form')) {
var dom = document.createElement('div');
var search = '';
var sarr = location.search.replace('?','').split('&');
for (var i = 0;i<sarr.length;i++){
var kv = sarr[i].split('=');
if (kv.length>1 && kv[0] != 'diy') {
search += '<input type="hidden" value="'+kv[1]+'" name="'+kv[0]+'" />';
}
}
search += '<input type="hidden" value="yes" name="preview" />';
dom.innerHTML = '<form action="'+location.href+'" target="_bloak" method="get" id="preview_form">'+search+'</form>';
var form = dom.getElementsByTagName('form');
$('append_parent').appendChild(form[0]);
}
},
cancelDiyUrl : function () {
return location.href.replace(/[\?|\&]diy\=yes/g,'').replace(/[\?|\&]preview=yes/,'');
},
cancel : function () {
saveUserdata('diy_advance_mode', '');
if (drag.isClearClose) {
showDialog('<div style="line-height:28px;">是否保留暂存数据?<br />按确定按钮将保留暂存数据,按取消按钮将删除暂存数据。</div>','confirm','保留暂存数据', function(){location.href = spaceDiy.cancelDiyUrl();}, true, function(){window.onunload=function(){spaceDiy.cancelDIY()};location.href = spaceDiy.cancelDiyUrl();});
} else {
location.href = this.cancelDiyUrl();
}
},
recover : function() {
if (confirm('您确定要恢复到上一版本保存的结果吗?')) {
drag.clearClose();
document.diyform.recover.value = '1';
document.diyform.gobackurl.value = location.href.replace(/(\?diy=yes)|(\&diy=yes)/,'').replace(/[\?|\&]preview=yes/,'');
document.diyform.submit();
}
doane();
},
enablePreviewButton : function () {
if ($('preview')){
$('preview').className = '';
if(drag.isChange) {
$('diy_preview').onclick = function () {spaceDiy.save('savecache');return false;};
} else {
$('diy_preview').onclick = function () {spaceDiy.save('preview');return false;};
}
Util.show($('savecachemsg'))
}
},
disablePreviewButton : function () {
if ($('preview')) {
$('preview').className = 'unusable';
$('diy_preview').onclick = function () {return false;};
}
},
cancelDIY : function () {
this.disablePreviewButton();
document.diyform.optype.value = 'canceldiy';
var x = new Ajax();
x.post($('diyform').action+'&inajax=1','optype=canceldiy&diysubmit=1&template='+document.diyform.template.value+'&savemod='+document.diyform.savemod.value+'&formhash='+document.diyform.formhash.value,function(s){});
},
switchBlockclass : function(blockclass) {
var navs = $('contentblockclass_nav').getElementsByTagName('a');
var contents = $('contentblockclass').getElementsByTagName('ul');
for(var i=0; i<navs.length; i++) {
if(navs[i].id=='bcnav_'+blockclass) {
navs[i].className = 'a';
} else {
navs[i].className = '';
}
}
for(var i=0; i<contents.length; i++) {
if(contents[i].id=='contentblockclass_'+blockclass) {
contents[i].style.display = '';
} else {
contents[i].style.display = 'none';
}
}
},
getdiy : function (type) {
if (type) {
var nav = $('controlnav').children;
for (var i in nav) {
if (nav[i].className == 'current') {
nav[i].className = '';
var contentid = 'content'+nav[i].id.replace('nav', '');
if ($(contentid)) $(contentid).style.display = 'none';
}
}
$('nav'+type).className = 'current';
if (type == 'start' || type == 'frame') {
$('content'+type).style.display = 'block';
return true;
}
if(type == 'blockclass' && $('content'+type).innerHTML !='') {
$('content'+type).style.display = 'block';
return true;
}
var para = '&op='+type;
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
para += '&' + arguments[i] + '=' + arguments[++i];
}
}
var ajaxtarget = type == 'diy' ? 'diyimages' : '';
var x = new Ajax();
x.showId = ajaxtarget;
x.get('portal.php?mod=portalcp&ac=diy'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s, x) {
if (s) {
if (typeof cpb_frame == 'object' && !BROWSER.ie) {delete cpb_frame;}
if (!$('content'+type)) {
var dom = document.createElement('div');
dom.id = 'content'+type;
$('controlcontent').appendChild(dom);
}
$('content'+type).innerHTML = s;
$('content'+type).style.display = 'block';
if (type == 'diy') {
spaceDiy.setCurrentDiy(spaceDiy.currentDiy);
if (spaceDiy.styleSheet.rules.length > 0) {
Util.show('recover_button');
}
}
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
ajaxupdateevents($(x.showId));
}
}
if(!evaled) evalscript(s);
}
});
}
}
});
spaceDiy.init(1);
function succeedhandle_diyform (url, message, values) {
if (values['rejs'] == '1') {
document.diyform.rejs.value = '';
parent.$('preview_form').submit();
}
spaceDiy.enablePreviewButton();
return false;
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: common_extra.js 22925 2011-06-01 10:23:08Z liulanbo $
*/
function _relatedlinks(rlinkmsgid) {
if(!$(rlinkmsgid) || $(rlinkmsgid).innerHTML.match(/<script[^\>]*?>/i)) {
return;
}
var alink = new Array(), ignore = new Array();
var i = 0;
var msg = $(rlinkmsgid).innerHTML;
msg = msg.replace(/(<ignore_js_op\>[\s|\S]*?<\/ignore_js_op\>)/ig, function($1) {
ignore[i] = $1;
i++;
return '#ignore_js_op '+(i - 1)+'#';
});
i = 0;
msg = msg.replace(/(<a.*?<\/a\>)/ig, function($1) {
alink[i] = $1;
i++;
return '#alink '+(i - 1)+'#';
});
var relatedid = new Array();
msg = msg.replace(/(^|>)([^<]+)(?=<|$)/ig, function($1, $2, $3) {
for(var j = 0; j > -1; j++) {
if(relatedlink[j] && !relatedid[j]) {
var ra = '<a href="'+relatedlink[j]['surl']+'" target="_blank" class="relatedlink">'+relatedlink[j]['sname']+'</a>';
var $rtmp = $3;
$3 = $3.replace(relatedlink[j]['sname'], ra);
if($3 != $rtmp) {
relatedid[j] = 1;
}
} else {
break;
}
}
return $2 + $3;
});
for(var k in alink) {
msg = msg.replace('#alink '+k+'#', alink[k]);
}
for(var l in ignore) {
msg = msg.replace('#ignore_js_op '+l+'#', ignore[l]);
}
$(rlinkmsgid).innerHTML = msg;
}
function _updatesecqaa(idhash) {
if($('secqaa_' + idhash)) {
$('secqaaverify_' + idhash).value = '';
if(secST['qaa_' + idhash]) {
clearTimeout(secST['qaa_' + idhash]);
}
$('checksecqaaverify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/none.gif" width="16" height="16" class="vm" />';
ajaxget('misc.php?mod=secqaa&action=update&idhash=' + idhash, 'secqaa_' + idhash, null, '', '', function() {
secST['qaa_' + idhash] = setTimeout(function() {$('secqaa_' + idhash).innerHTML = '<span class="xi2 cur1" onclick="updatesecqaa(\''+idhash+'\')">刷新验证问答</span>';}, 180000);
});
}
}
function _updateseccode(idhash, play) {
if(isUndefined(play)) {
if($('seccode_' + idhash)) {
$('seccodeverify_' + idhash).value = '';
if(secST['code_' + idhash]) {
clearTimeout(secST['code_' + idhash]);
}
$('checkseccodeverify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/none.gif" width="16" height="16" class="vm" />';
ajaxget('misc.php?mod=seccode&action=update&idhash=' + idhash, 'seccode_' + idhash, null, '', '', function() {
secST['code_' + idhash] = setTimeout(function() {$('seccode_' + idhash).innerHTML = '<span class="xi2 cur1" onclick="updateseccode(\''+idhash+'\')">刷新验证码</span>';}, 180000);
});
}
} else {
eval('window.document.seccodeplayer_' + idhash + '.SetVariable("isPlay", "1")');
}
}
function _checksec(type, idhash, showmsg, recall) {
var showmsg = !showmsg ? 0 : showmsg;
var secverify = $('sec' + type + 'verify_' + idhash).value;
if(!secverify) {
return;
}
var x = new Ajax('XML', 'checksec' + type + 'verify_' + idhash);
x.loading = '';
$('checksec' + type + 'verify_' + idhash).innerHTML = '<img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" />';
x.get('misc.php?mod=sec' + type + '&action=check&inajax=1&&idhash=' + idhash + '&secverify=' + (BROWSER.ie && document.charset == 'utf-8' ? encodeURIComponent(secverify) : secverify), function(s){
var obj = $('checksec' + type + 'verify_' + idhash);
obj.style.display = '';
if(s.substr(0, 7) == 'succeed') {
obj.innerHTML = '<img src="'+ IMGDIR + '/check_right.gif" width="16" height="16" class="vm" />';
if(showmsg) {
recall(1);
}
} else {
obj.innerHTML = '<img src="'+ IMGDIR + '/check_error.gif" width="16" height="16" class="vm" />';
if(showmsg) {
if(type == 'code') {
showError('验证码错误,请重新填写');
} else if(type == 'qaa') {
showError('验证问答错误,请重新填写');
}
recall(0);
}
}
});
}
function _setDoodle(fid, oid, url, tid, from) {
if(tid == null) {
hideWindow(fid);
} else {
$(tid).style.display = '';
$(fid).style.display = 'none';
}
var doodleText = '[img]'+url+'[/img]';
if($(oid) != null) {
if(from == "editor") {
insertImage(url);
} else if(from == "fastpost") {
seditor_insertunit('fastpost', doodleText);
} else if(from == "forumeditor") {
if(wysiwyg) {
insertText('<img src="' + url + '" border="0" alt="" />', false);
} else {
insertText(doodleText, strlen(doodleText), 0);
}
} else {
insertContent(oid, doodleText);
}
}
}
function _showdistrict(container, elems, totallevel, changelevel) {
var getdid = function(elem) {
var op = elem.options[elem.selectedIndex];
return op['did'] || op.getAttribute('did') || '0';
};
var pid = changelevel >= 1 && elems[0] && $(elems[0]) ? getdid($(elems[0])) : 0;
var cid = changelevel >= 2 && elems[1] && $(elems[1]) ? getdid($(elems[1])) : 0;
var did = changelevel >= 3 && elems[2] && $(elems[2]) ? getdid($(elems[2])) : 0;
var coid = changelevel >= 4 && elems[3] && $(elems[3]) ? getdid($(elems[3])) : 0;
var url = "home.php?mod=misc&ac=ajax&op=district&container="+container
+"&province="+elems[0]+"&city="+elems[1]+"&district="+elems[2]+"&community="+elems[3]
+"&pid="+pid + "&cid="+cid+"&did="+did+"&coid="+coid+'&level='+totallevel+'&handlekey='+container+'&inajax=1'+(isUndefined(changelevel) ? '&showdefault=1' : '');
ajaxget(url, container, '');
}
function _copycode(obj) {
if(!obj) return false;
if(window.getSelection) {
var sel = window.getSelection();
if (sel.setBaseAndExtent) {
sel.setBaseAndExtent(obj, 0, obj, 1);
} else {
var rng = document.createRange();
rng.selectNodeContents(obj);
sel.addRange(rng);
}
} else {
var rng = document.body.createTextRange();
rng.moveToElementText(obj);
rng.select();
}
setCopy(BROWSER.ie ? obj.innerText.replace(/\r\n\r\n/g, '\r\n') : obj.textContent, '代码已复制到剪贴板');
}
function _setCopy(text, msg){
if(BROWSER.ie) {
var r = clipboardData.setData('Text', text);
if(r) {
if(msg) {
showPrompt(null, null, '<span>' + msg + '</span>', 1500);
}
} else {
showDialog('<div class="c"><div style="width: 200px; text-align: center;">复制失败,请选择“允许访问”</div></div>', 'alert');
}
} else {
var msg = '<div class="c"><div style="width: 200px; text-align: center; text-decoration:underline;">点此复制到剪贴板</div>' +
AC_FL_RunContent('id', 'clipboardswf', 'name', 'clipboardswf', 'devicefont', 'false', 'width', '200', 'height', '40', 'src', STATICURL + 'image/common/clipboard.swf', 'menu', 'false', 'allowScriptAccess', 'sameDomain', 'swLiveConnect', 'true', 'wmode', 'transparent', 'style' , 'margin-top:-20px') + '</div>';
showDialog(msg, 'info');
text = text.replace(/[\xA0]/g, ' ');
CLIPBOARDSWFDATA = text;
}
}
function _showselect(obj, inpid, t, rettype) {
var showselect_row = function (inpid, s, v, notime, rettype) {
if(v >= 0) {
if(!rettype) {
var notime = !notime ? 0 : 1;
var t = today.getTime();
t += 86400000 * v;
var d = new Date();
d.setTime(t);
var month = d.getMonth() + 1;
month = month < 10 ? '0' + month : month;
var day = d.getDate();
day = day < 10 ? '0' + day : day;
var hour = d.getHours();
hour = hour < 10 ? '0' + hour : hour;
var minute = d.getMinutes();
minute = minute < 10 ? '0' + minute : minute;
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + d.getFullYear() + '-' + month + '-' + day + (!notime ? ' ' + hour + ':' + minute: '') + '\'">' + s + '</a>';
} else {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'' + v + '\'">' + s + '</a>';
}
} else if(v == -1) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').focus()">' + s + '</a>';
} else if(v == -2) {
return '<a href="javascript:;" onclick="$(\'' + inpid + '\').onclick()">' + s + '</a>';
}
};
if(!obj.id) {
var t = !t ? 0 : t;
var rettype = !rettype ? 0 : rettype;
obj.id = 'calendarexp_' + Math.random();
div = document.createElement('div');
div.id = obj.id + '_menu';
div.style.display = 'none';
div.className = 'p_pop';
$('append_parent').appendChild(div);
s = '';
if(!t) {
s += showselect_row(inpid, '一天', 1, 0, rettype);
s += showselect_row(inpid, '一周', 7, 0, rettype);
s += showselect_row(inpid, '一个月', 30, 0, rettype);
s += showselect_row(inpid, '三个月', 90, 0, rettype);
s += showselect_row(inpid, '自定义', -2);
} else {
if($(t)) {
var lis = $(t).getElementsByTagName('LI');
for(i = 0;i < lis.length;i++) {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = this.innerHTML;$(\''+obj.id+'_menu\').style.display=\'none\'">' + lis[i].innerHTML + '</a>';
}
s += showselect_row(inpid, '自定义', -1);
} else {
s += '<a href="javascript:;" onclick="$(\'' + inpid + '\').value = \'0\'">永久</a>';
s += showselect_row(inpid, '7 天', 7, 1, rettype);
s += showselect_row(inpid, '14 天', 14, 1, rettype);
s += showselect_row(inpid, '一个月', 30, 1, rettype);
s += showselect_row(inpid, '三个月', 90, 1, rettype);
s += showselect_row(inpid, '半年', 182, 1, rettype);
s += showselect_row(inpid, '一年', 365, 1, rettype);
s += showselect_row(inpid, '自定义', -1);
}
}
$(div.id).innerHTML = s;
}
showMenu({'ctrlid':obj.id,'evt':'click'});
if(BROWSER.ie && BROWSER.ie < 7) {
doane(event);
}
}
function _zoom(obj, zimg, nocover, pn) {
zimg = !zimg ? obj.src : zimg;
if(!zoomstatus) {
window.open(zimg, '', '');
return;
}
if(!obj.id) obj.id = 'img_' + Math.random();
var menuid = 'imgzoom';
var zoomid = menuid + '_zoom';
var imgtitle = !nocover && obj.title ? '<div class="ptn pbn">' + obj.title + '</div>' : '';
var cover = !nocover ? 1 : 0;
var pn = !pn ? 0 : 1;
var maxh = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) - 70;
var loadCheck = function (obj) {
if(obj.complete) {
var imgw = loading.width;
var imgh = loading.height;
var r = imgw / imgh;
var w = document.body.clientWidth * 0.95;
w = imgw > w ? w : imgw;
var h = w / r;
if(h > maxh) {
h = maxh;
w = h * r;
}
showimage(zimg, w, h, imgw, imgh);
} else {
setTimeout(function () { loadCheck(loading); }, 100);
}
};
var showloading = function (zimg, pn) {
if(!pn) {
if(!$(menuid + '_waiting')) {
waiting = document.createElement('img');
waiting.id = menuid + '_waiting';
waiting.src = IMGDIR + '/imageloading.gif';
waiting.style.opacity = '0.8';
waiting.style.filter = 'alpha(opacity=80)';
waiting.style.position = 'absolute';
waiting.style.zIndex = 100000;
$('append_parent').appendChild(waiting);
}
}
$(menuid + '_waiting').style.display = '';
$(menuid + '_waiting').style.left = (document.body.clientWidth - 42) / 2 + 'px';
$(menuid + '_waiting').style.top = ((document.documentElement.clientHeight - 42) / 2 + Math.max(document.documentElement.scrollTop, document.body.scrollTop)) + 'px';
loading = new Image();
setTimeout(function () { loadCheck(loading); }, 100);
if(!pn) {
$(menuid + '_zoomlayer').style.display = 'none';
}
loading.src = zimg;
};
var adjustpn = function(h) {
h = h < 90 ? 90 : h;
if($('zimg_prev')) {
$('zimg_prev').style.height= parseInt(h) + 'px';
}
if($('zimg_next')) {
$('zimg_next').style.height= parseInt(h) + 'px';
}
};
var showimage = function (zimg, w, h, imgw, imgh) {
$(menuid + '_waiting').style.display = 'none';
$(menuid + '_zoomlayer').style.display = '';
$(menuid + '_img').style.width = 'auto';
$(menuid + '_img').style.height = 'auto';
$(menuid).style.width = (w < 300 ? 300 : w + 20) + 'px';
mheight = h + 50;
$(menuid).style.height = mheight + 'px';
$(menuid + '_zoomlayer').style.height = (mheight < 120 ? 120 : mheight) + 'px';
$(menuid + '_img').innerHTML = '<img id="' + zoomid + '" src="' + zimg + '" width="' + w + '" height="' + h + '" w="' + imgw + '" h="' + imgh + '" />' + imgtitle;
if($(menuid + '_imglink')) {
$(menuid + '_imglink').href = zimg;
}
setMenuPosition('', menuid, '00');
adjustpn(h);
};
var adjust = function(e, a) {
if(!$(zoomid)) {
return;
}
var imgw = $(zoomid).getAttribute('w');
var imgh = $(zoomid).getAttribute('h');
var imgwstep = imgw / 10;
var imghstep = imgh / 10;
if(!a) {
if(!e) e = window.event;
if(e.altKey || e.shiftKey || e.ctrlKey) return;
if(e.wheelDelta <= 0 || e.detail > 0) {
if($(zoomid).width - imgwstep <= 200 || $(zoomid).height - imghstep <= 200) {
doane(e);return;
}
$(zoomid).width -= imgwstep;
$(zoomid).height -= imghstep;
} else {
if($(zoomid).width + imgwstep >= imgw) {
doane(e);return;
}
$(zoomid).width += imgwstep;
$(zoomid).height += imghstep;
}
} else {
$(zoomid).width = imgw;
$(zoomid).height = imgh;
}
$(menuid).style.width = (parseInt($(zoomid).width < 300 ? 300 : parseInt($(zoomid).width)) + 20) + 'px';
mheight = (parseInt($(zoomid).height) + 50);
$(menuid).style.height = mheight + 'px';
$(menuid + '_zoomlayer').style.height = (mheight < 120 ? 120 : mheight) + 'px';
adjustpn($(zoomid).height);
setMenuPosition('', menuid, '00');
doane(e);
};
if(!$(menuid) && !pn) {
menu = document.createElement('div');
menu.id = menuid;
if(cover) {
menu.innerHTML = '<div class="zoominner" id="' + menuid + '_zoomlayer" style="display:none"><p><span class="y"><a id="' + menuid + '_imglink" class="imglink" target="_blank" title="在新窗口打开">在新窗口打开</a><a id="' + menuid + '_adjust" href="javascipt:;" class="imgadjust" title="实际大小">实际大小</a>' +
'<a href="javascript:;" onclick="hideMenu()" class="imgclose" title="关闭">关闭</a></span>鼠标滚轮缩放图片</p>' +
'<div class="zimg_p" id="' + menuid + '_picpage"></div><div class="hm" id="' + menuid + '_img"></div></div>';
} else {
menu.innerHTML = '<div class="popupmenu_popup" id="' + menuid + '_zoomlayer" style="width:auto"><span class="right y"><a href="javascript:;" onclick="hideMenu()" class="flbc" style="width:20px;margin:0 0 2px 0">关闭</a></span>鼠标滚轮缩放图片<div class="zimg_p" id="' + menuid + '_picpage"></div><div class="hm" id="' + menuid + '_img"></div></div>';
}
if(BROWSER.ie || BROWSER.chrome){
menu.onmousewheel = adjust;
} else {
menu.addEventListener('DOMMouseScroll', adjust, false);
}
$('append_parent').appendChild(menu);
if($(menuid + '_adjust')) {
$(menuid + '_adjust').onclick = function(e) {adjust(e, 1)};
}
}
showloading(zimg, pn);
picpage = '';
$(menuid + '_picpage').innerHTML = '';
if(typeof zoomgroup == 'object' && zoomgroup[obj.id] && typeof aimgcount == 'object' && aimgcount[zoomgroup[obj.id]]) {
authorimgs = aimgcount[zoomgroup[obj.id]];
var aid = obj.id.substr(5), authorlength = authorimgs.length, authorcurrent = '';
if(authorlength > 1) {
for(i = 0; i < authorlength;i++) {
if(aid == authorimgs[i]) {
authorcurrent = i;
}
}
if(authorcurrent !== '') {
paid = authorcurrent > 0 ? authorimgs[authorcurrent - 1] : authorimgs[authorlength - 1];
picpage += ' <div id="zimg_prev" onmouseover="dragMenuDisabled=true;this.style.backgroundPosition=\'0 50px\'" onmouseout="dragMenuDisabled=false;this.style.backgroundPosition=\'0 -100px\';" onclick="zoom($(\'aimg_' + paid + '\'), $(\'aimg_' + paid + '\').getAttribute(\'zoomfile\'), 0, 1)" class="zimg_prev"><strong>上一张</strong></div> ';
paid = authorcurrent < authorlength - 1 ? authorimgs[authorcurrent + 1] : authorimgs[0];
picpage += ' <div id="zimg_next" onmouseover="dragMenuDisabled=true;this.style.backgroundPosition=\'100% 50px\'" onmouseout="dragMenuDisabled=false;this.style.backgroundPosition=\'100% -100px\';" onclick="zoom($(\'aimg_' + paid + '\'), $(\'aimg_' + paid + '\').getAttribute(\'zoomfile\'), 0, 1)" class="zimg_next"><strong>下一张</strong></div> ';
}
if(picpage) {
$(menuid + '_picpage').innerHTML = picpage;
}
}
}
showMenu({'ctrlid':obj.id,'menuid':menuid,'duration':3,'pos':'00','cover':cover,'drag':menuid,'maxh':''});
}
function _switchTab(prefix, current, total, activeclass) {
activeclass = !activeclass ? 'a' : activeclass;
for(var i = 1; i <= total;i++) {
var classname = ' '+$(prefix + '_' + i).className+' ';
$(prefix + '_' + i).className = classname.replace(' '+activeclass+' ','').substr(1);
$(prefix + '_c_' + i).style.display = 'none';
}
$(prefix + '_' + current).className = $(prefix + '_' + current).className + ' '+activeclass;
$(prefix + '_c_' + current).style.display = '';
}
function _initTab(frameId, type) {
if (typeof document['diyform'] == 'object' || $(frameId).className.indexOf('tab') < 0) return false;
type = type || 'click';
var tabs = $(frameId+'_title').childNodes;
var arrTab = [];
for(var i in tabs) {
if (tabs[i]['nodeType'] == 1 && tabs[i]['className'].indexOf('move-span') > -1) {
arrTab.push(tabs[i]);
}
}
var counter = 0;
var tab = document.createElement('ul');
tab.className = 'tb cl';
var len = arrTab.length;
for(var i = 0;i < len; i++) {
var tabId = arrTab[i].id;
if (hasClass(arrTab[i],'frame') || hasClass(arrTab[i],'tab')) {
var arrColumn = [];
for (var j in arrTab[i].childNodes) {
if (typeof arrTab[i].childNodes[j] == 'object' && !hasClass(arrTab[i].childNodes[j],'title')) arrColumn.push(arrTab[i].childNodes[j]);
}
var frameContent = document.createElement('div');
frameContent.id = tabId+'_content';
frameContent.className = hasClass(arrTab[i],'frame') ? 'content cl '+arrTab[i].className.substr(arrTab[i].className.lastIndexOf(' ')+1) : 'content cl';
var colLen = arrColumn.length;
for (var k = 0; k < colLen; k++) {
frameContent.appendChild(arrColumn[k]);
}
} else {
var frameContent = $(tabId+'_content');
frameContent = frameContent || document.createElement('div');
}
frameContent.style.display = counter ? 'none' : '';
$(frameId+'_content').appendChild(frameContent);
var li = document.createElement('li');
li.id = tabId;
li.className = counter ? '' : 'a';
var reg = new RegExp('style=\"(.*?)\"', 'gi');
var matchs = '', style = '', imgs = '';
while((matchs = reg.exec(arrTab[i].innerHTML))) {
if(matchs[1].substr(matchs[1].length,1) != ';') {
matchs[1] += ';';
}
style += matchs[1];
}
style = style ? ' style="'+style+'"' : '';
reg = new RegExp('(<img.*?>)', 'gi');
while((matchs = reg.exec(arrTab[i].innerHTML))) {
imgs += matchs[1];
}
li.innerHTML = arrTab[i]['innerText'] ? arrTab[i]['innerText'] : arrTab[i]['textContent'];
var a = arrTab[i].getElementsByTagName('a');
var href = a && a[0] ? a[0].href : 'javascript:;';
var onclick = type == 'click' ? ' onclick="return false;"' : '';
li.innerHTML = '<a href="' + href + '"' + onclick + ' onfocus="this.blur();" ' + style + '>' + imgs + li.innerHTML + '</a>';
_attachEvent(li, type, switchTabUl);
tab.appendChild(li);
$(frameId+'_title').removeChild(arrTab[i]);
counter++;
}
$(frameId+'_title').appendChild(tab);
}
function switchTabUl (e) {
e = e || window.event;
var aim = e.target || e.srcElement;
var tabId = aim.id;
var parent = aim.parentNode;
while(parent['nodeName'] != 'UL' && parent['nodeName'] != 'BODY') {
tabId = parent.id;
parent = parent.parentNode;
}
if(parent['nodeName'] == 'BODY') return false;
var tabs = parent.childNodes;
var len2 = tabs.length;
for(var j = 0; j < len2; j++) {
tabs[j].className = (tabs[j].id == tabId) ? 'a' : '';
var content = $(tabs[j].id+'_content');
if (content) content.style.display = tabs[j].id == tabId ? '' : 'none';
}
}
function slideshow(el) {
var obj = this;
if(!el.id) el.id = Math.random();
if(typeof slideshow.entities == 'undefined') {
slideshow.entities = {};
}
this.id = el.id;
if(slideshow.entities[this.id]) return false;
slideshow.entities[this.id] = this;
this.slideshows = [];
this.slidebar = [];
this.slideother = [];
this.slidebarup = '';
this.slidebardown = '';
this.slidenum = 0;
this.slidestep = 0;
this.container = el;
this.imgs = [];
this.imgLoad = [];
this.imgLoaded = 0;
this.imgWidth = 0;
this.imgHeight = 0;
this.getMEvent = function(ele, value) {
value = !value ? 'mouseover' : value;
var mevent = !ele ? '' : ele.getAttribute('mevent');
mevent = (mevent == 'click' || mevent == 'mouseover') ? mevent : value;
return mevent;
};
this.slideshows = $C('slideshow', el);
this.slideshows = this.slideshows.length>0 ? this.slideshows[0].childNodes : null;
this.slidebar = $C('slidebar', el);
this.slidebar = this.slidebar.length>0 ? this.slidebar[0] : null;
this.barmevent = this.getMEvent(this.slidebar);
this.slideother = $C('slideother', el);
this.slidebarup = $C('slidebarup', el);
this.slidebarup = this.slidebarup.length>0 ? this.slidebarup[0] : null;
this.barupmevent = this.getMEvent(this.slidebarup, 'click');
this.slidebardown = $C('slidebardown', el);
this.slidebardown = this.slidebardown.length>0 ? this.slidebardown[0] : null;
this.bardownmevent = this.getMEvent(this.slidebardown, 'click');
this.slidenum = parseInt(this.container.getAttribute('slidenum'));
this.slidestep = parseInt(this.container.getAttribute('slidestep'));
this.timestep = parseInt(this.container.getAttribute('timestep'));
this.timestep = !this.timestep ? 2500 : this.timestep;
this.index = this.length = 0;
this.slideshows = !this.slideshows ? filterTextNode(el.childNodes) : filterTextNode(this.slideshows);
this.length = this.slideshows.length;
for(i=0; i<this.length; i++) {
this.slideshows[i].style.display = "none";
_attachEvent(this.slideshows[i], 'mouseover', function(){obj.stop();});
_attachEvent(this.slideshows[i], 'mouseout', function(){obj.goon();});
}
for(i=0, L=this.slideother.length; i<L; i++) {
for(var j=0;j<this.slideother[i].childNodes.length;j++) {
if(this.slideother[i].childNodes[j].nodeType == 1) {
this.slideother[i].childNodes[j].style.display = "none";
}
}
}
if(!this.slidebar) {
if(!this.slidenum && !this.slidestep) {
this.container.parentNode.style.position = 'relative';
this.slidebar = document.createElement('div');
this.slidebar.className = 'slidebar';
this.slidebar.style.position = 'absolute';
this.slidebar.style.top = '5px';
this.slidebar.style.left = '4px';
this.slidebar.style.display = 'none';
var html = '<ul>';
for(var i=0; i<this.length; i++) {
html += '<li on'+this.barmevent+'="slideshow.entities[' + this.id + '].xactive(' + i + '); return false;">' + (i + 1).toString() + '</li>';
}
html += '</ul>';
this.slidebar.innerHTML = html;
this.container.parentNode.appendChild(this.slidebar);
this.controls = this.slidebar.getElementsByTagName('li');
}
} else {
this.controls = filterTextNode(this.slidebar.childNodes);
for(i=0; i<this.controls.length; i++) {
if(this.slidebarup == this.controls[i] || this.slidebardown == this.controls[i]) continue;
_attachEvent(this.controls[i], this.barmevent, function(){slidexactive()});
_attachEvent(this.controls[i], 'mouseout', function(){obj.goon();});
}
}
if(this.slidebarup) {
_attachEvent(this.slidebarup, this.barupmevent, function(){slidexactive('up')});
}
if(this.slidebardown) {
_attachEvent(this.slidebardown, this.bardownmevent, function(){slidexactive('down')});
}
this.activeByStep = function(index) {
var showindex = 0,i = 0;
if(index == 'down') {
showindex = this.index + 1;
if(showindex >= this.length) {
this.runRoll();
} else {
for (i = 0; i < this.slidestep; i++) {
if(showindex >= this.length) showindex = 0;
this.index = this.index - this.slidenum + 1;
if(this.index < 0) this.index = this.length - Math.abs(this.index);
this.active(showindex);
showindex++;
}
}
} else if (index == 'up') {
var tempindex = this.index;
showindex = this.index - this.slidenum;
if(showindex < 0) return false;
for (i = 0; i < this.slidestep; i++) {
if(showindex < 0) showindex = this.length - Math.abs(showindex);
this.active(showindex);
this.index = tempindex = tempindex - 1;
if(this.index <0) this.index = this.length - 1;
showindex--;
}
}
return false;
};
this.active = function(index) {
this.slideshows[this.index].style.display = "none";
this.slideshows[index].style.display = "block";
if(this.controls && this.controls.length > 0) {
this.controls[this.index].className = '';
this.controls[index].className = 'on';
}
for(var i=0,L=this.slideother.length; i<L; i++) {
this.slideother[i].childNodes[this.index].style.display = "none";
this.slideother[i].childNodes[index].style.display = "block";
}
this.index = index;
};
this.xactive = function(index) {
if(!this.slidenum && !this.slidestep) {
this.stop();
if(index == 'down') index = this.index == this.length-1 ? 0 : this.index+1;
if(index == 'up') index = this.index == 0 ? this.length-1 : this.index-1;
this.active(index);
} else {
this.activeByStep(index);
}
};
this.goon = function() {
this.stop();
var curobj = this;
this.timer = setTimeout(function () {
curobj.run();
}, this.timestep);
};
this.stop = function() {
clearTimeout(this.timer);
};
this.run = function() {
var index = this.index + 1 < this.length ? this.index + 1 : 0;
this.active(index);
var ss = this;
this.timer = setTimeout(function(){
ss.run();
}, this.timestep);
};
this.runRoll = function() {
for(var i = 0; i < this.slidenum; i++) {
if(this.slideshows[i] && typeof this.slideshows[i].style != 'undefined') this.slideshows[i].style.display = "block";
for(var j=0,L=this.slideother.length; j<L; j++) {
this.slideother[j].childNodes[i].style.display = "block";
}
}
this.index = this.slidenum - 1;
};
var imgs = this.slideshows.length ? this.slideshows[0].parentNode.getElementsByTagName('img') : [];
for(i=0, L=imgs.length; i<L; i++) {
this.imgs.push(imgs[i]);
this.imgLoad.push(new Image());
this.imgLoad[i].onerror = function (){obj.imgLoaded ++;};
this.imgLoad[i].src = this.imgs[i].src;
}
this.getSize = function () {
if(this.imgs.length == 0) return false;
var img = this.imgs[0];
this.imgWidth = img.width ? parseInt(img.width) : 0;
this.imgHeight = img.height ? parseInt(img.height) : 0;
var ele = img.parentNode;
while ((!this.imgWidth || !this.imgHeight) && !hasClass(ele,'slideshow') && ele != document.body) {
this.imgWidth = ele.style.width ? parseInt(ele.style.width) : 0;
this.imgHeight = ele.style.height ? parseInt(ele.style.height) : 0;
ele = ele.parentNode;
}
return true;
};
this.getSize();
this.checkLoad = function () {
var obj = this;
this.container.style.display = 'block';
for(i = 0;i < this.imgs.length;i++) {
if(this.imgLoad[i].complete && !this.imgLoad[i].status) {
this.imgLoaded++;
this.imgLoad[i].status = 1;
}
}
var percentEle = $(this.id+'_percent');
if(this.imgLoaded < this.imgs.length) {
if (!percentEle) {
var dom = document.createElement('div');
dom.id = this.id+"_percent";
dom.style.width = this.imgWidth ? this.imgWidth+'px' : '150px';
dom.style.height = this.imgHeight ? this.imgHeight+'px' : '150px';
dom.style.lineHeight = this.imgHeight ? this.imgHeight+'px' : '150px';
dom.style.backgroundColor = '#ccc';
dom.style.textAlign = 'center';
dom.style.top = '0';
dom.style.left = '0';
dom.style.marginLeft = 'auto';
dom.style.marginRight = 'auto';
this.slideshows[0].parentNode.appendChild(dom);
percentEle = dom;
}
el.parentNode.style.position = 'relative';
percentEle.innerHTML = (parseInt(this.imgLoaded / this.imgs.length * 100)) + '%';
setTimeout(function () {obj.checkLoad();}, 100);
} else {
if (percentEle) percentEle.parentNode.removeChild(percentEle);
if(this.slidebar) this.slidebar.style.display = '';
this.index = this.length - 1 < 0 ? 0 : this.length - 1;
if(this.slideshows.length > 0) {
if(!this.slidenum || !this.slidestep) {
this.run();
} else {
this.runRoll();
}
}
}
};
this.checkLoad();
}
function slidexactive(step) {
var e = getEvent();
var aim = e.target || e.srcElement;
var parent = aim.parentNode;
var xactivei = null, slideboxid = null,currentslideele = null;
currentslideele = hasClass(aim, 'slidebarup') || hasClass(aim, 'slidebardown') || hasClass(parent, 'slidebar') ? aim : null;
while(parent && parent != document.body) {
if(!currentslideele && hasClass(parent.parentNode, 'slidebar')) {
currentslideele = parent;
}
if(!currentslideele && (hasClass(parent.parentNode, 'slidebarup') || hasClass(parent.parentNode, 'slidebardown'))) {
currentslideele = parent.parentNode;
}
if(hasClass(parent, 'slidebox')) {
slideboxid = parent.id;
break;
}
parent = parent.parentNode;
}
var slidebar = $C('slidebar', parent);
var children = slidebar.length == 0 ? [] : filterTextNode(slidebar[0].childNodes);
if(currentslideele && (hasClass(currentslideele, 'slidebarup') || hasClass(currentslideele, 'slidebardown'))) {
xactivei = step;
} else {
for(var j=0,i=0,L=children.length;i<L;i++){
if(currentslideele && children[i] == currentslideele) {
xactivei = j;
break;
}
if(!hasClass(children[i], 'slidebarup') && !hasClass(children[i], 'slidebardown')) j++;
}
}
if(slideboxid != null && xactivei != null) slideshow.entities[slideboxid].xactive(xactivei);
}
function filterTextNode(list) {
var newlist = [];
for(var i=0; i<list.length; i++) {
if (list[i].nodeType == 1) {
newlist.push(list[i]);
}
}
return newlist;
}
function _runslideshow() {
var slideshows = $C('slidebox');
for(var i=0,L=slideshows.length; i<L; i++) {
new slideshow(slideshows[i]);
}
}
function _showTip(ctrlobj) {
if(!ctrlobj.id) {
ctrlobj.id = 'tip_' + Math.random();
}
menuid = ctrlobj.id + '_menu';
if(!$(menuid)) {
var div = document.createElement('div');
div.id = ctrlobj.id + '_menu';
div.className = 'tip tip_js';
div.style.display = 'none';
div.innerHTML = '<div class="tip_horn"></div><div class="tip_c">' + ctrlobj.getAttribute('tip') + '</div>';
$('append_parent').appendChild(div);
}
$(ctrlobj.id).onmouseout = function () { hideMenu('', 'prompt'); };
showMenu({'mtype':'prompt','ctrlid':ctrlobj.id,'pos':'210!','duration':2,'zindex':JSMENU['zIndex']['prompt']});
}
function _showPrompt(ctrlid, evt, msg, timeout) {
var menuid = ctrlid ? ctrlid + '_pmenu' : 'ntcwin';
var duration = timeout ? 0 : 3;
if($(menuid)) {
$(menuid).parentNode.removeChild($(menuid));
}
var div = document.createElement('div');
div.id = menuid;
div.className = ctrlid ? 'tip tip_js' : 'ntcwin';
div.style.display = 'none';
$('append_parent').appendChild(div);
if(ctrlid) {
msg = '<div id="' + ctrlid + '_prompt"><div class="tip_horn"></div><div class="tip_c">' + msg + '</div>';
} else {
msg = '<table cellspacing="0" cellpadding="0" class="popupcredit"><tr><td class="pc_l"> </td><td class="pc_c"><div class="pc_inner">' + msg +
'</td><td class="pc_r"> </td></tr></table>';
}
div.innerHTML = msg;
if(ctrlid) {
if(!timeout) {
evt = 'click';
}
if($(ctrlid)) {
if($(ctrlid).evt !== false) {
var prompting = function() {
showMenu({'mtype':'prompt','ctrlid':ctrlid,'evt':evt,'menuid':menuid,'pos':'210'});
};
if(evt == 'click') {
$(ctrlid).onclick = prompting;
} else {
$(ctrlid).onmouseover = prompting;
}
}
showMenu({'mtype':'prompt','ctrlid':ctrlid,'evt':evt,'menuid':menuid,'pos':'210','duration':duration,'timeout':timeout,'zindex':JSMENU['zIndex']['prompt']});
$(ctrlid).unselectable = false;
}
} else {
showMenu({'mtype':'prompt','pos':'00','menuid':menuid,'duration':duration,'timeout':timeout,'zindex':JSMENU['zIndex']['prompt']});
$(menuid).style.top = (parseInt($(menuid).style.top) - 100) + 'px';
}
}
function _showCreditPrompt() {
var notice = getcookie('creditnotice').split('D');
var basev = getcookie('creditbase').split('D');
var creditrule = decodeURI(getcookie('creditrule', 1)).replace(String.fromCharCode(9), ' ');
if(!discuz_uid || notice.length < 2 || notice[9] != discuz_uid) {
setcookie('creditnotice', '');
setcookie('creditrule', '');
return;
}
var creditnames = creditnotice.split(',');
var creditinfo = [];
var e;
for(var i = 0; i < creditnames.length; i++) {
e = creditnames[i].split('|');
creditinfo[e[0]] = [e[1], e[2]];
}
creditShow(creditinfo, notice, basev, 0, 1, creditrule);
}
function creditShow(creditinfo, notice, basev, bk, first, creditrule) {
var s = '', check = 0;
for(i = 1; i <= 8; i++) {
v = parseInt(Math.abs(parseInt(notice[i])) / 5) + 1;
if(notice[i] !== '0' && creditinfo[i]) {
s += '<span>' + creditinfo[i][0] + (notice[i] != 0 ? (notice[i] > 0 ? '<em>+' : '<em class="desc">') + notice[i] + '</em>' : '') + creditinfo[i][1] + '</span>';
}
if(notice[i] > 0) {
notice[i] = parseInt(notice[i]) - v;
basev[i] = parseInt(basev[i]) + v;
} else if(notice[i] < 0) {
notice[i] = parseInt(notice[i]) + v;
basev[i] = parseInt(basev[i]) - v;
}
if($('hcredit_' + i)) {
$('hcredit_' + i).innerHTML = basev[i];
}
}
for(i = 1; i <= 8; i++) {
if(notice[i] != 0) {
check = 1;
}
}
if(!s || first) {
setcookie('creditnotice', '');
setcookie('creditbase', '');
setcookie('creditrule', '');
if(!s) {
return;
}
}
if(!$('creditpromptdiv')) {
showPrompt(null, null, '<div id="creditpromptdiv">' + (creditrule ? '<i>' + creditrule + '</i> ' : '') + s + '</div>', 0);
} else {
$('creditpromptdiv').innerHTML = s;
}
setTimeout(function () {hideMenu(1, 'prompt');$('append_parent').removeChild($('ntcwin'));}, 1500);
}
function _showColorBox(ctrlid, layer, k, bgcolor) {
var tag1 = !bgcolor ? 'color' : 'backcolor', tag2 = !bgcolor ? 'forecolor' : 'backcolor';
if(!$(ctrlid + '_menu')) {
var menu = document.createElement('div');
menu.id = ctrlid + '_menu';
menu.className = 'p_pop colorbox';
menu.unselectable = true;
menu.style.display = 'none';
var coloroptions = ['Black', 'Sienna', 'DarkOliveGreen', 'DarkGreen', 'DarkSlateBlue', 'Navy', 'Indigo', 'DarkSlateGray', 'DarkRed', 'DarkOrange', 'Olive', 'Green', 'Teal', 'Blue', 'SlateGray', 'DimGray', 'Red', 'SandyBrown', 'YellowGreen', 'SeaGreen', 'MediumTurquoise', 'RoyalBlue', 'Purple', 'Gray', 'Magenta', 'Orange', 'Yellow', 'Lime', 'Cyan', 'DeepSkyBlue', 'DarkOrchid', 'Silver', 'Pink', 'Wheat', 'LemonChiffon', 'PaleGreen', 'PaleTurquoise', 'LightBlue', 'Plum', 'White'];
var colortexts = ['黑色', '赭色', '暗橄榄绿色', '暗绿色', '暗灰蓝色', '海军色', '靛青色', '墨绿色', '暗红色', '暗桔黄色', '橄榄色', '绿色', '水鸭色', '蓝色', '灰石色', '暗灰色', '红色', '沙褐色', '黄绿色', '海绿色', '间绿宝石', '皇家蓝', '紫色', '灰色', '红紫色', '橙色', '黄色', '酸橙色', '青色', '深天蓝色', '暗紫色', '银色', '粉色', '浅黄色', '柠檬绸色', '苍绿色', '苍宝石绿', '亮蓝色', '洋李色', '白色'];
var str = '';
for(var i = 0; i < 40; i++) {
str += '<input type="button" style="background-color: ' + coloroptions[i] + '"' + (typeof setEditorTip == 'function' ? ' onmouseover="setEditorTip(\'' + colortexts[i] + '\')" onmouseout="setEditorTip(\'\')"' : '') + ' onclick="'
+ (typeof wysiwyg == 'undefined' ? 'seditor_insertunit(\'' + k + '\', \'[' + tag1 + '=' + coloroptions[i] + ']\', \'[/' + tag1 + ']\')' : (ctrlid == editorid + '_tbl_param_4' ? '$(\'' + ctrlid + '\').value=\'' + coloroptions[i] + '\';hideMenu(2)' : 'discuzcode(\'' + tag2 + '\', \'' + coloroptions[i] + '\')'))
+ '" title="' + colortexts[i] + '" />' + (i < 39 && (i + 1) % 8 == 0 ? '<br />' : '');
}
menu.innerHTML = str;
$('append_parent').appendChild(menu);
}
showMenu({'ctrlid':ctrlid,'evt':'click','layer':layer});
}
function _toggle_collapse(objname, noimg, complex, lang) {
var obj = $(objname);
if(obj) {
obj.style.display = obj.style.display == '' ? 'none' : '';
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, objname, !obj.style.display);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
}
if(!noimg) {
var img = $(objname + '_img');
if(img.tagName != 'IMG') {
if(img.className.indexOf('_yes') == -1) {
img.className = img.className.replace(/_no/, '_yes');
if(lang) {
img.innerHTML = lang[0];
}
} else {
img.className = img.className.replace(/_yes/, '_no');
if(lang) {
img.innerHTML = lang[1];
}
}
} else {
img.src = img.src.indexOf('_yes.gif') == -1 ? img.src.replace(/_no\.gif/, '_yes\.gif') : img.src.replace(/_yes\.gif/, '_no\.gif');
}
img.blur();
}
if(complex) {
var objc = $(objname + '_c');
if(objc) {
objc.className = objc.className == 'umh' ? 'umh umn' : 'umh';
}
}
}
function _extstyle(css) {
if(!$('css_extstyle')) {
loadcss('extstyle');
}
$('css_extstyle').href = css ? css + '/style.css' : STATICURL + 'image/common/extstyle_none.css';
currentextstyle = css;
setcookie('extstyle', css, 86400 * 30);
if($('css_widthauto') && !$('css_widthauto').disabled) {
CSSLOADED['widthauto'] = 0;
loadcss('widthauto');
}
}
function _widthauto(obj) {
if($('css_widthauto')) {
CSSLOADED['widthauto'] = 1;
}
if(!CSSLOADED['widthauto'] || $('css_widthauto').disabled) {
if(!CSSLOADED['widthauto']) {
loadcss('widthauto');
} else {
$('css_widthauto').disabled = false;
}
HTMLNODE.className += ' widthauto';
setcookie('widthauto', 1, 86400 * 30);
obj.innerHTML = '切换到窄版';
} else {
$('css_widthauto').disabled = true;
HTMLNODE.className = HTMLNODE.className.replace(' widthauto', '');
setcookie('widthauto', -1, 86400 * 30);
obj.innerHTML = '切换到宽版';
}
hideMenu();
}
function _showCreditmenu() {
if(!$('extcreditmenu_menu')) {
menu = document.createElement('div');
menu.id = 'extcreditmenu_menu';
menu.style.display = 'none';
menu.className = 'p_pop';
menu.innerHTML = '<div class="p_opt"><img src="'+ IMGDIR + '/loading.gif" width="16" height="16" class="vm" /> 请稍候...</div>';
$('append_parent').appendChild(menu);
ajaxget($('extcreditmenu').href, 'extcreditmenu_menu', 'ajaxwaitid');
}
showMenu({'ctrlid':'extcreditmenu','ctrlclass':'a','duration':1});
}
function _imageRotate(imgid, direct) {
var image = $(imgid);
if(!image.getAttribute('deg')) {
var deg = 0;
image.setAttribute('ow', image.width);
image.setAttribute('oh', image.height);
if(BROWSER.ie) {
image.setAttribute('om', parseInt(image.currentStyle.marginBottom));
}
} else {
var deg = parseInt(image.getAttribute('deg'));
}
var ow = image.getAttribute('ow');
var oh = image.getAttribute('oh');
deg = direct == 1 ? deg - 90 : deg + 90;
if(deg > 270) {
deg = 0;
} else if(deg < 0) {
deg = 270;
}
image.setAttribute('deg', deg);
if(BROWSER.ie) {
if(!isNaN(image.getAttribute('om'))) {
image.style.marginBottom = (image.getAttribute('om') + (BROWSER.ie < 8 ? 0 : (deg == 90 || deg == 270 ? Math.abs(ow - oh) : 0))) + 'px';
}
image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (deg / 90) + ')';
} else {
switch(deg) {
case 90:var cow = oh, coh = ow, cx = 0, cy = -oh;break;
case 180:var cow = ow, coh = oh, cx = -ow, cy = -oh;break;
case 270:var cow = oh, coh = ow, cx = -ow, cy = 0;break;
}
var canvas = $(image.getAttribute('canvasid'));
if(!canvas) {
var i = document.createElement("canvas");
i.id = 'canva_' + Math.random();
image.setAttribute('canvasid', i.id);
image.parentNode.insertBefore(i, image);
canvas = $(i.id);
}
if(deg) {
var canvasContext = canvas.getContext('2d');
canvas.setAttribute('width', cow);
canvas.setAttribute('height', coh);
canvasContext.rotate(deg * Math.PI / 180);
canvasContext.drawImage(image, cx, cy, ow, oh);
image.style.display = 'none';
canvas.style.display = '';
} else {
image.style.display = '';
canvas.style.display = 'none';
}
}
}
function _createPalette(colorid, id, func) {
var iframe = "<iframe name=\"c"+colorid+"_frame\" src=\"\" frameborder=\"0\" width=\"210\" height=\"148\" scrolling=\"no\"></iframe>";
if (!$("c"+colorid+"_menu")) {
var dom = document.createElement('span');
dom.id = "c"+colorid+"_menu";
dom.style.display = 'none';
dom.innerHTML = iframe;
$('append_parent').appendChild(dom);
}
var base = document.getElementsByTagName('base');
var baseurl = base && base > 0 ? base[0].getAttribute('href') : '';
func = !func ? '' : '|' + func;
window.frames["c"+colorid+"_frame"].location.href = baseurl+STATICURL+"image/admincp/getcolor.htm?c"+colorid+"|"+id+func;
showMenu({'ctrlid':'c'+colorid});
var iframeid = "c"+colorid+"_menu";
_attachEvent(window, 'scroll', function(){hideMenu(iframeid);});
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum_moderate.js 21562 2011-03-31 08:40:33Z monkey $
*/
function modaction(action, pid, extra, mod) {
if(!action) {
return;
}
var mod = mod ? mod : 'forum.php?mod=topicadmin';
var extra = !extra ? '' : '&' + extra;
if(!pid && in_array(action, ['delpost', 'banpost'])) {
var checked = 0;
var pid = '';
for(var i = 0; i < $('modactions').elements.length; i++) {
if($('modactions').elements[i].name.match('topiclist')) {
checked = 1;
break;
}
}
} else {
var checked = 1;
}
if(!checked) {
alert('请选择需要操作的帖子');
} else {
$('modactions').action = mod + '&action='+ action +'&fid=' + fid + '&tid=' + tid + '&handlekey=mods&infloat=yes&nopost=yes' + (!pid ? '' : '&topiclist[]=' + pid) + extra + '&r' + Math.random();
showWindow('mods', 'modactions', 'post');
if(BROWSER.ie) {
doane(event);
}
hideMenu();
}
}
function modthreads(optgroup, operation) {
var operation = !operation ? '' : operation;
$('modactions').action = 'forum.php?mod=topicadmin&action=moderate&fid=' + fid + '&moderate[]=' + tid + '&handlekey=mods&infloat=yes&nopost=yes' + (optgroup != 3 && optgroup != 2 ? '&from=' + tid : '');
$('modactions').optgroup.value = optgroup;
$('modactions').operation.value = operation;
hideWindow('mods');
showWindow('mods', 'modactions', 'post', 0);
if(BROWSER.ie) {
doane(event);
}
}
function pidchecked(obj) {
if(obj.checked) {
try {
var inp = document.createElement('<input name="topiclist[]" />');
} catch(e) {
try {
var inp = document.createElement('input');
inp.name = 'topiclist[]';
} catch(e) {
return;
}
}
inp.id = 'topiclist_' + obj.value;
inp.value = obj.value;
inp.type = 'hidden';
$('modactions').appendChild(inp);
} else {
$('modactions').removeChild($('topiclist_' + obj.value));
}
}
var modclickcount = 0;
function modclick(obj, pid) {
if(obj.checked) {
modclickcount++;
} else {
modclickcount--;
}
$('mdct').innerHTML = modclickcount;
if(modclickcount > 0) {
var offset = fetchOffset(obj);
$('mdly').style.top = offset['top'] - 65 + 'px';
$('mdly').style.left = offset['left'] - 215 + 'px';
$('mdly').style.display = '';
} else {
$('mdly').style.display = 'none';
}
}
function resetmodcount() {
modclickcount = 0;
$('mdly').style.display = 'none';
}
function tmodclick(obj) {
if(obj.checked) {
modclickcount++;
} else {
modclickcount--;
}
$('mdct').innerHTML = modclickcount;
if(modclickcount > 0) {
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent).id != 'threadlist') {
top_offset += obj.offsetTop;
}
$('mdly').style.top = top_offset - 7 + 'px';
$('mdly').style.display = '';
} else {
$('mdly').style.display = 'none';
}
}
function tmodthreads(optgroup, operation) {
var checked = 0;
var operation = !operation ? '' : operation;
for(var i = 0; i < $('moderate').elements.length; i++) {
if($('moderate').elements[i].name.match('moderate') && $('moderate').elements[i].checked) {
checked = 1;
break;
}
}
if(!checked) {
alert('请选择需要操作的帖子');
} else {
$('moderate').optgroup.value = optgroup;
$('moderate').operation.value = operation;
showWindow('mods', 'moderate', 'post');
}
}
loadcss('forum_moderator'); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: seditor.js 21135 2011-03-16 06:24:11Z svn_project_zhangjie $
*/
function seditor_showimgmenu(seditorkey) {
var imgurl = $(seditorkey + '_image_param_1').value;
var width = parseInt($(seditorkey + '_image_param_2').value);
var height = parseInt($(seditorkey + '_image_param_3').value);
var extparams = '';
if(width || height) {
extparams = '=' + width + ',' + height
}
seditor_insertunit(seditorkey, '[img' + extparams + ']' + imgurl, '[/img]', null, 1);
$(seditorkey + '_image_param_1').value = '';
hideMenu();
}
function seditor_menu(seditorkey, tag) {
var sel = false;
if(!isUndefined($(seditorkey + 'message').selectionStart)) {
sel = $(seditorkey + 'message').selectionEnd - $(seditorkey + 'message').selectionStart;
} else if(document.selection && document.selection.createRange) {
$(seditorkey + 'message').focus();
var sel = document.selection.createRange();
$(seditorkey + 'message').sel = sel;
sel = sel.text ? true : false;
}
if(sel) {
seditor_insertunit(seditorkey, '[' + tag + ']', '[/' + tag + ']');
return;
}
var ctrlid = seditorkey + tag;
var menuid = ctrlid + '_menu';
if(!$(menuid)) {
switch(tag) {
case 'url':
str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" sautocomplete="off" style="width: 98%" value="" class="px" />' +
'<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />';
submitstr = "$('" + ctrlid + "_param_2').value !== '' ? seditor_insertunit('" + seditorkey + "', '[url='+$('" + ctrlid + "_param_1').value+']'+$('" + ctrlid + "_param_2').value, '[/url]', null, 1) : seditor_insertunit('" + seditorkey + "', '[url]'+$('" + ctrlid + "_param_1').value, '[/url]', null, 1);hideMenu();";
break;
case 'code':
case 'quote':
var tagl = {'quote' : '请输入要插入的引用', 'code' : '请输入要插入的代码'};
str = tagl[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>';
submitstr = "seditor_insertunit('" + seditorkey + "', '[" + tag + "]'+$('" + ctrlid + "_param_1').value, '[/" + tag + "]', null, 1);hideMenu();";
break;
case 'img':
str = '请输入图片地址:<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="px" onchange="loadimgsize(this.value, \'' + seditorkey + '\',\'' + tag + '\')" />' +
'<p class="mtm">宽(可选): <input type="text" id="' + ctrlid + '_param_2" style="width: 15%" value="" class="px" /> ' +
'高(可选): <input type="text" id="' + ctrlid + '_param_3" style="width: 15%" value="" class="px" /></p>';
submitstr = "seditor_insertunit('" + seditorkey + "', '[img' + ($('" + ctrlid + "_param_2').value !== '' && $('" + ctrlid + "_param_3').value !== '' ? '='+$('" + ctrlid + "_param_2').value+','+$('" + ctrlid + "_param_3').value : '')+']'+$('" + ctrlid + "_param_1').value, '[/img]', null, 1);hideMenu();";
break;
}
var menu = document.createElement('div');
menu.id = menuid;
menu.style.display = 'none';
menu.className = 'p_pof upf';
menu.style.width = '270px';
$('append_parent').appendChild(menu);
menu.innerHTML = '<span class="y"><a onclick="hideMenu()" class="flbc" href="javascript:;">关闭</a></span><div class="p_opt cl"><form onsubmit="' + submitstr + ';return false;" autocomplete="off"><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button><button type="button" onClick="hideMenu()" class="pn"><em>取消</em></button></div></form></div>';
}
showMenu({'ctrlid':ctrlid,'evt':'click','duration':3,'cache':0,'drag':1});
}
function seditor_insertunit(key, text, textend, moveend, selappend) {
if($(key + 'message')) {
$(key + 'message').focus();
}
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
selappend = isUndefined(selappend) ? 1 : selappend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($(key + 'message').selectionStart)) {
if(selappend) {
var opn = $(key + 'message').selectionStart + 0;
if(textend != '') {
text = text + $(key + 'message').value.substring($(key + 'message').selectionStart, $(key + 'message').selectionEnd) + textend;
}
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
if(!moveend) {
$(key + 'message').selectionStart = opn + strlen(text) - endlen;
$(key + 'message').selectionEnd = opn + strlen(text) - endlen;
}
} else {
text = text + textend;
$(key + 'message').value = $(key + 'message').value.substr(0, $(key + 'message').selectionStart) + text + $(key + 'message').value.substr($(key + 'message').selectionEnd);
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(!sel.text.length && $(key + 'message').sel) {
sel = $(key + 'message').sel;
$(key + 'message').sel = null;
}
if(selappend) {
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
sel.text = text + textend;
}
} else {
$(key + 'message').value += text;
}
hideMenu(2);
if(BROWSER.ie) {
doane();
}
}
function seditor_ctlent(event, script) {
if(event.ctrlKey && event.keyCode == 13 || event.altKey && event.keyCode == 83) {
eval(script);
}
}
function loadimgsize(imgurl, editor, p) {
var editor = !editor ? editorid : editor;
var s = new Object();
var p = !p ? '_image' : p;
s.img = new Image();
s.img.src = imgurl;
s.loadCheck = function () {
if(s.img.complete) {
$(editor + p + '_param_2').value = s.img.width ? s.img.width : '';
$(editor + p + '_param_3').value = s.img.height ? s.img.height : '';
} else {
setTimeout(function () {s.loadCheck();}, 100);
}
};
s.loadCheck();
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: logging.js 21541 2011-03-31 02:44:01Z monkey $
*/
function lsSubmit(op) {
var op = !op ? 0 : op;
if(op) {
$('lsform').cookietime.value = 2592000;
}
if($('ls_username').value == '' || $('ls_password').value == '') {
showWindow('login', 'member.php?mod=logging&action=login' + (op ? '&cookietime=1' : ''));
} else {
ajaxpost('lsform', 'return_ls', 'return_ls');
}
return false;
}
function errorhandle_ls(str, param) {
if(!param['type']) {
showError(str);
}
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: editor.js 22848 2011-05-26 01:36:50Z monkey $
*/
var editorcurrentheight = 400, editorminheight = 400, savedataInterval = 30, editbox = null, editwin = null, editdoc = null, editcss = null, savedatat = null, savedatac = 0, autosave = 1, framemObj = null, cursor = -1, stack = [], initialized = false, postSubmited = false, editorcontroltop = false, editorcontrolwidth = false, editorcontrolheight = false, editorisfull = 0, fulloldheight = 0, savesimplodemode = null;
function newEditor(mode, initialtext) {
wysiwyg = parseInt(mode);
if(!(BROWSER.ie || BROWSER.firefox || (BROWSER.opera >= 9))) {
allowswitcheditor = wysiwyg = 0;
}
if(!BROWSER.ie) {
$(editorid + '_paste').parentNode.style.display = 'none';
}
if(!allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
if(wysiwyg) {
if($(editorid + '_iframe')) {
editbox = $(editorid + '_iframe');
} else {
var iframe = document.createElement('iframe');
iframe.frameBorder = '0';
iframe.tabIndex = 2;
iframe.hideFocus = true;
iframe.style.display = 'none';
editbox = textobj.parentNode.appendChild(iframe);
editbox.id = editorid + '_iframe';
}
editwin = editbox.contentWindow;
editdoc = editwin.document;
writeEditorContents(isUndefined(initialtext) ? textobj.value : initialtext);
} else {
editbox = editwin = editdoc = textobj;
if(!isUndefined(initialtext)) {
writeEditorContents(initialtext);
}
addSnapshot(textobj.value);
}
setEditorEvents();
initEditor();
}
function setEditorTip(s) {
$(editorid + '_tip').innerHTML = ' ' + s;
}
function initEditor() {
if(BROWSER.other) {
$(editorid + '_controls').style.display = 'none';
return;
}
var buttons = $(editorid + '_controls').getElementsByTagName('a');
for(var i = 0; i < buttons.length; i++) {
if(buttons[i].id.indexOf(editorid + '_') != -1) {
buttons[i].href = 'javascript:;';
if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'fullswitcher') {
buttons[i].innerHTML = !editorisfull ? '全屏' : '返回';
buttons[i].onmouseover = function(e) {setEditorTip(editorisfull ? '恢复编辑器大小' : '全屏方式编辑');};
buttons[i].onclick = function(e) {editorfull();doane();}
} else if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'simple') {
buttons[i].innerHTML = !simplodemode ? '常用' : '高级';
buttons[i].onclick = function(e) {editorsimple();doane();}
} else {
_attachEvent(buttons[i], 'mouseover', function(e) {setEditorTip(BROWSER.ie ? window.event.srcElement.title : e.target.title);});
if(buttons[i].id.substr(buttons[i].id.indexOf('_') + 1) == 'url') {
buttons[i].onclick = function(e) {discuzcode('unlink');discuzcode('url');doane();};
} else {
if(!buttons[i].getAttribute('init')) {
buttons[i].onclick = function(e) {discuzcode(this.id.substr(this.id.indexOf('_') + 1));doane();};
}
}
}
buttons[i].onmouseout = function(e) {setEditorTip('');};
}
}
setUnselectable($(editorid + '_controls'));
textobj.onkeydown = function(e) {ctlent(e ? e : event)};
if(editorcontroltop === false && (BROWSER.ie && BROWSER.ie > 6 || !BROWSER.ie)) {
seteditorcontrolpos();
var obj = wysiwyg ? editwin.document.body.parentNode : $(editorid + '_textarea');
editorcontrolwidth = $(editorid + '_controls').clientWidth - 8;
ctrlmObj = document.createElement('div');
ctrlmObj.style.display = 'none';
ctrlmObj.style.height = $(editorid + '_controls').clientHeight + 'px';
ctrlmObj.id = editorid + '_controls_mask';
$(editorid + '_controls').parentNode.insertBefore(ctrlmObj, $(editorid + '_controls'));
_attachEvent(window, 'scroll', function () { editorcontrolpos(); }, document);
}
if($(editorid + '_fullswitcher') && BROWSER.ie && BROWSER.ie < 7) {
$(editorid + '_fullswitcher').onclick = function () {
showDialog('你的浏览器不支持此功能,请升级浏览器版本', 'notice', '友情提示');
};
$(editorid + '_fullswitcher').className = 'xg1';
}
if($(editorid + '_svdsecond') && savedatat === null) {
savedatac = savedataInterval;
autosave = !getcookie('editorautosave_' + editorid) || getcookie('editorautosave_' + editorid) == 1 ? 1 : 0;
savedataTime();
savedatat = setInterval("savedataTime()", 10000);
}
}
function savedataTime() {
if(!autosave) {
$(editorid + '_svdsecond').innerHTML = '<a title="点击开启自动保存" href="javascript:;" onclick="setAutosave()">开启自动保存</a> ';
return;
}
if(!savedatac) {
savedatac = savedataInterval;
saveData();
d = new Date();
var h = d.getHours();
var m = d.getMinutes();
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
setEditorTip('数据已于 ' + h + ':' + m + ' 保存');
}
$(editorid + '_svdsecond').innerHTML = '<a title="点击关闭自动保存" href="javascript:;" onclick="setAutosave()">' + savedatac + ' 秒后保存</a> ';
savedatac -= 10;
}
function setAutosave() {
autosave = !autosave;
setEditorTip(autosave ? '数据自动保存已开启' : '数据自动保存已关闭');
setcookie('editorautosave_' + editorid, autosave ? 1 : -1, 2592000);
savedataTime();
}
function unloadAutoSave() {
if(autosave) {
saveData();
}
}
function seteditorcontrolpos() {
var objpos = fetchOffset($(editorid + '_controls'));
editorcontroltop = objpos['top'];
}
function editorcontrolpos() {
if(editorisfull) {
return;
}
var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
if(scrollTop > editorcontroltop && editorcurrentheight > editorminheight) {
$(editorid + '_controls').style.position = 'fixed';
$(editorid + '_controls').style.top = '0px';
$(editorid + '_controls').style.width = editorcontrolwidth + 'px';
$(editorid + '_controls_mask').style.display = '';
} else {
$(editorid + '_controls').style.position = $(editorid + '_controls').style.top = $(editorid + '_controls').style.width = '';
$(editorid + '_controls_mask').style.display = 'none';
}
}
function editorsize(op, v) {
var obj = wysiwyg ? editwin.document.body.parentNode : $(editorid + '_textarea');
var editorheight = obj.clientHeight;
if(!v) {
if(op == '+') {
editorheight += 200;
} else{
editorheight -= 200;
}
} else {
editorheight = v;
}
editorcurrentheight = editorheight > editorminheight ? editorheight : editorminheight;
if($(editorid + '_iframe')) {
$(editorid + '_iframe').style.height = $(editorid + '_iframe').contentWindow.document.body.style.height = editorcurrentheight + 'px';
}
if(framemObj) {
framemObj.style.height = editorcurrentheight + 'px';
}
$(editorid + '_textarea').style.height = editorcurrentheight + 'px';
}
var editorsizepos = [];
function editorresize(e, op) {
op = !op ? 1 : op;
e = e ? e : window.event;
if(op == 1) {
if(wysiwyg) {
var objpos = fetchOffset($(editorid + '_iframe'));
framemObj = document.createElement('div');
framemObj.style.width = $(editorid + '_iframe').clientWidth + 'px';
framemObj.style.height = $(editorid + '_iframe').clientHeight + 'px';
framemObj.style.position = 'absolute';
framemObj.style.left = objpos['left'] + 'px';
framemObj.style.top = objpos['top'] + 'px';
$('append_parent').appendChild(framemObj);
} else {
framemObj = null;
}
editorsizepos = [e.clientY, editorcurrentheight, framemObj];
document.onmousemove = function(e) {try{editorresize(e, 2);}catch(err){}};
document.onmouseup = function(e) {try{editorresize(e, 3);}catch(err){}};
doane(e);
}else if(op == 2 && editorsizepos !== []) {
var dragnow = e.clientY;
editorsize('', editorsizepos[1] + dragnow - editorsizepos[0]);
doane(e);
}else if(op == 3) {
if(wysiwyg) {
$('append_parent').removeChild(editorsizepos[2]);
}
editorsizepos = [];
document.onmousemove = null;
document.onmouseup = null;
}
}
function editorfull(op) {
var op = !op ? 0 : op, control = $(editorid + '_controls'), area = $(editorid + '_textarea').parentNode, bbar = $(editorid + '_bbar'), iswysiwyg = wysiwyg;
if(op) {
var editorheight = document.documentElement.clientHeight - control.offsetHeight - bbar.offsetHeight - parseInt(getCurrentStyle(area, 'paddingTop', 'padding-top')) - parseInt(getCurrentStyle(area, 'paddingBottom', 'padding-bottom'));
area.style.position = 'fixed';
area.style.top = control.offsetHeight + 'px';
area.style.height = editorheight + 'px';
editorsize('', editorheight);
bbar.style.position = 'fixed';
bbar.style.top = (document.documentElement.clientHeight - bbar.offsetHeight) + 'px';
return;
}
if(iswysiwyg) {
switchEditor(0);
}
if(!editorisfull) {
savesimplodemode = 0;
if(simplodemode) {
savesimplodemode = 1;
editorsimple();
}
$(editorid + '_simple').style.visibility = 'hidden';
fulloldheight = editorcurrentheight;
document.body.style.overflow = 'hidden';
document.body.scroll = 'no';
control.style.position = 'fixed';
control.style.top = '0px';
control.style.left = '0px';
control.style.width = '100%';
control.style.minWidth = '800px';
area.style.backgroundColor = $(editorid + '_textarea') ? getCurrentStyle($(editorid + '_textarea'), 'backgroundColor', 'background-color') : '#fff';
$(editorid + '_switcher').style.paddingRight = '10px';
var editorheight = document.documentElement.clientHeight - control.offsetHeight - bbar.offsetHeight - parseInt(getCurrentStyle(area, 'paddingTop', 'padding-top')) - parseInt(getCurrentStyle(area, 'paddingBottom', 'padding-bottom'));
area.style.position = 'fixed';
area.style.top = control.offsetHeight + 'px';
area.style.left = '0px';
area.style.width = '100%';
area.style.height = editorheight + 'px';
editorsize('', editorheight);
bbar.style.position = 'fixed';
bbar.style.top = (document.documentElement.clientHeight - bbar.offsetHeight) + 'px';
bbar.style.left = '0px';
bbar.style.width = '100%';
control.style.zIndex = area.style.zIndex = bbar.style.zIndex = '200';
if($(editorid + '_resize')) {
$(editorid + '_resize').style.display = 'none';
}
window.onresize = function() { editorfull(1); };
editorisfull = 1;
} else {
if(savesimplodemode) {
editorsimple();
}
$(editorid + '_simple').style.visibility = 'visible';
window.onresize = null;
document.body.style.overflow = 'auto';
document.body.scroll = 'yes';
control.style.position = control.style.top = control.style.left = control.style.width = control.style.minWidth = control.style.zIndex =
area.style.position = area.style.top = area.style.left = area.style.width = area.style.height = area.style.zIndex =
bbar.style.position = bbar.style.top = bbar.style.left = bbar.style.width = bbar.style.zIndex = '';
editorheight = fulloldheight;
$(editorid + '_switcher').style.paddingRight = '0px';
editorsize('', editorheight);
if($(editorid + '_resize')) {
$(editorid + '_resize').style.display = '';
}
editorisfull = 0;
editorcontrolpos();
}
if(iswysiwyg) {
switchEditor(1);
}
$(editorid + '_fullswitcher').innerHTML = editorisfull ? '返回' : '全屏';
}
function editorsimple() {
if($(editorid + '_body').className == 'edt') {
v = 'none';
$(editorid + '_simple').innerHTML = '高级';
$(editorid + '_body').className = 'edt simpleedt';
$(editorid + '_adv_s0').className = 'b2r';
$(editorid + '_adv_s1').className = 'b2r';
$(editorid + '_adv_s2').className = 'b2r';
if(allowswitcheditor) {
$(editorid + '_switcher').style.display = 'none';
}
simplodemode = 1;
} else {
v = '';
$(editorid + '_simple').innerHTML = '常用';
$(editorid + '_body').className = 'edt';
$(editorid + '_adv_s0').className = 'b1r';
$(editorid + '_adv_s1').className = 'b1r';
$(editorid + '_adv_s2').className = 'b2r nbr';
if(allowswitcheditor) {
$(editorid + '_switcher').style.display = '';
}
simplodemode = 0;
}
setcookie('editormode_' + editorid, simplodemode ? 1 : -1, 2592000);
for(i = 1;i <= 9;i++) {
if($(editorid + '_adv_' + i)) {
$(editorid + '_adv_' + i).style.display = v;
}
}
}
function pasteWord(str) {
var mstest = /<\w[^>]* class="?[MsoNormal|xl]"?/gi;
if(mstest.test(str)){
str = str.replace(/<!--\[if[\s\S]+?<!\[endif\]-->/gi, "");
str = str.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3");
str = str.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, function ($1, $2, $3, $4) {
var style = '';
re = new RegExp('(^|[;\\s])color:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'color:' + match[2] + ';';
}
re = new RegExp('(^|[;\\s])text-indent:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'text-indent:' + parseInt(parseInt(match[2]) / 10) + 'em;';
}
re = new RegExp('(^|[;\\s])font-size:\\s*([^;]+);?', 'ig');
match = re.exec($3);
if(match != null) {
style += 'font-size:' + match[2] + ';';
}
if(style) {
style = ' style="' + style + '"';
}
return '<' + $2 + style + $4;
});
htstrml = str.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3");
str = str.replace(/<\\?\?xml[^>]*>/gi, "");
str = str.replace(/<\/?\w+:[^>]*>/gi, "");
str = str.replace(/ /, " ");
var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)", 'ig');
str = str.replace(re, "<div$2</div>");
if(!wysiwyg) {
str = html2bbcode(str);
}
insertText(str, str.length, 0);
}
}
function ctlent(event) {
if(postSubmited == false && (event.ctrlKey && event.keyCode == 13) || (event.altKey && event.keyCode == 83) && editorsubmit) {
if(in_array(editorsubmit.name, ['topicsubmit', 'replysubmit', 'editsubmit']) && !validate(editorform)) {
doane(event);
return;
}
postSubmited = true;
editorsubmit.disabled = true;
editorform.submit();
return;
}
if(event.keyCode == 9) {
doane(event);
}
if(event.keyCode == 8 && wysiwyg) {
var sel = getSel();
if(sel) {
insertText('', sel.length - 1, 0);
doane(event);
}
}
}
function checkFocus() {
var obj = wysiwyg ? (!BROWSER.chrome ? editwin.document.body : editwin) : textobj;
if(!obj.hasfocus) {
if(!BROWSER.safari || BROWSER.chrome) {
obj.focus();
}
try {
if(BROWSER.safari && !obj.safarifocus) {
var sel = editwin.getSelection();
var node = editdoc.body.lastChild;
var range = editdoc.createRange();
range.selectNodeContents(node);
sel.removeAllRanges();
sel.addRange(range);
obj.safarifocus = true;
}
} catch(e) {}
}
}
function checklength(theform) {
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!theform.parseurloff.checked ? parseurl(theform.message.value) : theform.message.value);
showDialog('当前长度: ' + mb_strlen(message) + ' 字节,' + (postmaxchars != 0 ? '系统限制: ' + postminchars + ' 到 ' + postmaxchars + ' 字节。' : ''), 'notice', '字数检查');
}
function setUnselectable(obj) {
if(BROWSER.ie && BROWSER.ie > 4 && typeof obj.tagName != 'undefined') {
if(obj.hasChildNodes()) {
for(var i = 0; i < obj.childNodes.length; i++) {
setUnselectable(obj.childNodes[i]);
}
}
if(obj.tagName != 'INPUT') {
obj.unselectable = 'on';
}
}
}
function writeEditorContents(text) {
if(wysiwyg) {
if(text == '' && (BROWSER.firefox || BROWSER.opera)) {
text = '<p></p>';
}
if(initialized && !(BROWSER.firefox && BROWSER.firefox >= '3' || BROWSER.opera)) {
editdoc.body.innerHTML = text;
} else {
text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
'<html><head id="editorheader"><meta http-equiv="Content-Type" content="text/html; charset=' + charset + '" />' +
(BROWSER.ie && BROWSER.ie > 7 ? '<meta http-equiv="X-UA-Compatible" content="IE=7" />' : '' ) +
'<link rel="stylesheet" type="text/css" href="data/cache/style_' + STYLEID + '_wysiwyg.css?' + VERHASH + '" />' +
(BROWSER.ie ? '<script>window.onerror = function() { return true; }</script>' : '') +
'</head><body>' + text + '</body></html>';
editdoc.designMode = allowhtml ? 'on' : 'off';
editdoc = editwin.document;
editdoc.open('text/html', 'replace');
editdoc.write(text);
editdoc.close();
if(!BROWSER.ie) {
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.text = 'window.onerror = function() { return true; }';
editdoc.getElementById('editorheader').appendChild(scriptNode);
}
editdoc.body.contentEditable = true;
editdoc.body.spellcheck = false;
initialized = true;
if(BROWSER.safari) {
editdoc.onclick = safariSel;
}
}
} else {
textobj.value = text;
}
setEditorStyle();
}
function safariSel(e) {
e = e.target;
if(e.tagName.match(/(img|embed)/i)) {
var sel = editwin.getSelection(),rng= editdoc.createRange(true);
rng.selectNode(e);
sel.removeAllRanges();
sel.addRange(rng);
}
}
function getEditorContents() {
return wysiwyg ? editdoc.body.innerHTML : editdoc.value;
}
function setEditorStyle() {
if(wysiwyg) {
textobj.style.display = 'none';
editbox.style.display = '';
editbox.className = textobj.className;
if(BROWSER.ie) {
editdoc.body.style.border = '0px';
editdoc.body.addBehavior('#default#userData');
try{$('subject').focus();} catch(e) {editwin.focus();}
}
if($(editorid + '_iframe')) {
$(editorid + '_iframe').style.height = $(editorid + '_iframe').contentWindow.document.body.style.height = editorcurrentheight + 'px';
}
} else {
var iframe = textobj.parentNode.getElementsByTagName('iframe')[0];
if(iframe) {
textobj.style.display = '';
iframe.style.display = 'none';
}
if(BROWSER.ie) {
try{
$('subject').focus();
} catch(e) {}
}
}
}
function setEditorEvents() {
if(wysiwyg) {
if(BROWSER.firefox || BROWSER.opera) {
editdoc.addEventListener('mouseup', function(e) {setContext();}, true);
editdoc.addEventListener('keyup', function(e) {setContext();}, true);
editwin.addEventListener('keydown', function(e) {ctlent(e);}, true);
} else if(editdoc.attachEvent) {
editdoc.body.attachEvent('onmouseup', setContext);
editdoc.body.attachEvent('onkeyup', setContext);
editdoc.body.attachEvent('onkeydown', ctlent);
}
}
editwin.onfocus = function(e) {this.hasfocus = true;};
editwin.onblur = function(e) {this.hasfocus = false;};
editwin.onclick = function(e) {this.safarifocus = true;}
}
function wrapTags(tagname, useoption, selection) {
if(isUndefined(selection)) {
var selection = getSel();
if(selection === false) {
selection = '';
} else {
selection += '';
}
}
if(useoption !== false) {
var opentag = '[' + tagname + '=' + useoption + ']';
} else {
var opentag = '[' + tagname + ']';
}
var closetag = '[/' + tagname + ']';
var text = opentag + selection + closetag;
insertText(text, strlen(opentag), strlen(closetag), in_array(tagname, ['code', 'quote', 'free', 'hide']) ? true : false);
}
function applyFormat(cmd, dialog, argument) {
if(wysiwyg) {
editdoc.execCommand(cmd, (isUndefined(dialog) ? false : dialog), (isUndefined(argument) ? true : argument));
return;
}
switch(cmd) {
case 'paste':
if(BROWSER.ie) {
var str = clipboardData.getData("TEXT");
insertText(str, str.length, 0);
}
break;
case 'bold':
case 'italic':
case 'underline':
case 'strikethrough':
wrapTags(cmd.substr(0, 1), false);
break;
case 'inserthorizontalrule':
insertText('[hr]', 4, 0);
break;
case 'justifyleft':
case 'justifycenter':
case 'justifyright':
wrapTags('align', cmd.substr(7));
break;
case 'fontname':
wrapTags('font', argument);
break;
case 'fontsize':
wrapTags('size', argument);
break;
case 'forecolor':
wrapTags('color', argument);
break;
case 'hilitecolor':
case 'backcolor':
wrapTags('backcolor', argument);
break;
}
}
function getCaret() {
if(wysiwyg) {
var obj = editdoc.body;
var s = document.selection.createRange();
s.setEndPoint('StartToStart', obj.createTextRange());
var matches1 = s.htmlText.match(/<\/p>/ig);
var matches2 = s.htmlText.match(/<br[^\>]*>/ig);
var fix = (matches1 ? matches1.length - 1 : 0) + (matches2 ? matches2.length : 0);
var pos = s.text.replace(/\r?\n/g, ' ').length;
if(matches3 = s.htmlText.match(/<img[^\>]*>/ig)) pos += matches3.length;
if(matches4 = s.htmlText.match(/<\/tr|table>/ig)) pos += matches4.length;
return [pos, fix];
} else {
checkFocus();
var sel = document.selection.createRange();
editbox.sel = sel;
}
}
function setCaret(pos) {
var obj = wysiwyg ? editdoc.body : editbox;
var r = obj.createTextRange();
r.moveStart('character', pos);
r.collapse(true);
r.select();
}
function isEmail(email) {
return email.length > 6 && /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/.test(email);
}
function insertAttachTag(aid) {
var txt = '[attach]' + aid + '[/attach]';
if(wysiwyg) {
insertText(txt, false);
} else {
insertText(txt, strlen(txt), 0);
}
}
function insertAttachimgTag(aid) {
if(wysiwyg) {
insertText('<img src="' + $('image_' + aid).src + '" border="0" aid="attachimg_' + aid + '" alt="" />', false);
} else {
var txt = '[attachimg]' + aid + '[/attachimg]';
insertText(txt, strlen(txt), 0);
}
}
function insertSmiley(smilieid) {
checkFocus();
var src = $('smilie_' + smilieid).src;
var code = $('smilie_' + smilieid).alt;
if(wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
insertText('<img src="' + src + '" border="0" smilieid="' + smilieid + '" alt="" />', false);
} else {
code += ' ';
insertText(code, strlen(code), 0);
}
hideMenu();
}
function discuzcode(cmd, arg) {
if(cmd != 'redo') {
addSnapshot(getEditorContents());
}
checkFocus();
if(in_array(cmd, ['sml', 'url', 'quote', 'code', 'free', 'hide', 'aud', 'vid', 'fls', 'attach', 'image', 'pasteword']) || cmd == 'tbl' || in_array(cmd, ['fontname', 'fontsize', 'forecolor', 'backcolor']) && !arg) {
showEditorMenu(cmd);
return;
} else if(cmd.substr(0, 3) == 'cst') {
showEditorMenu(cmd.substr(5), cmd.substr(3, 1));
return;
} else if(wysiwyg && cmd == 'inserthorizontalrule') {
insertText('<hr class="l">', 14);
} else if(cmd == 'autotypeset') {
autoTypeset();
return;
} else if(!wysiwyg && cmd == 'removeformat') {
var simplestrip = new Array('b', 'i', 'u');
var complexstrip = new Array('font', 'color', 'backcolor', 'size');
var str = getSel();
if(str === false) {
return;
}
for(var tag in simplestrip) {
str = stripSimple(simplestrip[tag], str);
}
for(var tag in complexstrip) {
str = stripComplex(complexstrip[tag], str);
}
insertText(str);
} else if(cmd == 'undo') {
addSnapshot(getEditorContents());
moveCursor(-1);
if((str = getSnapshot()) !== false) {
if(wysiwyg) {
editdoc.body.innerHTML = str;
} else {
editdoc.value = str;
}
}
} else if(cmd == 'redo') {
moveCursor(1);
if((str = getSnapshot()) !== false) {
if(wysiwyg) {
editdoc.body.innerHTML = str;
} else {
editdoc.value = str;
}
}
} else if(!wysiwyg && in_array(cmd, ['insertorderedlist', 'insertunorderedlist'])) {
var listtype = cmd == 'insertorderedlist' ? '1' : '';
var opentag = '[list' + (listtype ? ('=' + listtype) : '') + ']\n';
var closetag = '[/list]';
if(txt = getSel()) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = opentag + trim(txt).replace(regex, '$1[*]') + '\n' + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
while(listvalue = prompt('输入一个列表项目.\r\n留空或者点击取消完成此列表.', '')) {
if(BROWSER.opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertText(listvalue, strlen(listvalue) + 1, 0);
} else {
listvalue = '[*]' + listvalue + '\n';
insertText(listvalue, strlen(listvalue), 0);
}
}
}
} else if(!wysiwyg && cmd == 'unlink') {
var sel = getSel();
sel = stripSimple('url', sel);
sel = stripComplex('url', sel);
insertText(sel);
} else if(cmd == 'floatleft' || cmd == 'floatright') {
var arg = cmd == 'floatleft' ? 'left' : 'right';
if(wysiwyg) {
if(txt = getSel()) {
argm = arg == 'left' ? 'right' : 'left';
insertText('<br style="clear: both"><table class="float" style="float: ' + arg + '; margin-' + argm + ': 5px;"><tbody><tr><td>' + txt + '</td></tr></tbody></table>', true);
}
} else {
var opentag = '[float=' + arg + ']';
var closetag = '[/float]';
if(txt = getSel()) {
txt = opentag + txt + closetag;
insertText(txt, strlen(txt), 0);
} else {
insertText(opentag + closetag, opentag.length, closetag.length);
}
}
} else if(cmd == 'rst') {
loadData();
setEditorTip('数据已恢复');
} else if(cmd == 'svd') {
saveData();
setEditorTip('数据已保存');
} else if(cmd == 'chck') {
checklength(editorform);
} else if(cmd == 'tpr') {
if(confirm('您确认要清除所有内容吗?')) {
clearContent();
}
} else if(cmd == 'downremoteimg') {
showDialog('<div id="remotedowninfo"><p class="mbn">正在下载远程附件,请稍等……</p><p><img src="' + STATICURL + 'image/common/uploading.gif" alt="" /></p></div>', 'notice', '', null, 1);
var message = wysiwyg ? html2bbcode(getEditorContents()) : (!editorform.parseurloff.checked ? parseurl(editorform.message.value) : editorform.message.value);
var oldValidate = editorform.onsubmit;
var oldAction = editorform.action;
editorform.onsubmit = '';
editorform.action = 'forum.php?mod=ajax&action=downremoteimg&wysiwyg='+(wysiwyg ? 1 : 0);
editorform.target = "ajaxpostframe";
editorform.message.value = message;
editorform.submit();
editorform.onsubmit = oldValidate;
editorform.action = oldAction;
editorform.target = "";
} else {
var formatcmd = cmd == 'backcolor' && !BROWSER.ie ? 'hilitecolor' : cmd;
try {
var ret = applyFormat(formatcmd, false, (isUndefined(arg) ? true : arg));
} catch(e) {
var ret = false;
}
}
if(cmd != 'undo') {
addSnapshot(getEditorContents());
}
if(wysiwyg) {
setContext(cmd);
}
if(in_array(cmd, ['bold', 'italic', 'underline', 'strikethrough', 'inserthorizontalrule', 'fontname', 'fontsize', 'forecolor', 'backcolor', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', 'floatleft', 'floatright', 'removeformat', 'unlink', 'undo', 'redo'])) {
hideMenu();
}
doane();
return ret;
}
function setContext(cmd) {
var cmd = !cmd ? '' : cmd;
var contextcontrols = new Array('bold', 'italic', 'underline', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist');
for(var i in contextcontrols) {
var controlid = contextcontrols[i];
var obj = $(editorid + '_' + controlid);
if(obj != null) {
if(cmd == 'clear') {
obj.className = '';
continue;
}
try {
var state = editdoc.queryCommandState(contextcontrols[i]);
} catch(e) {
var state = false;
}
if(isUndefined(obj.state)) {
obj.state = false;
}
if(obj.state != state) {
obj.state = state;
buttonContext(obj, state ? 'mouseover' : 'mouseout');
}
}
}
var fs = editdoc.queryCommandValue('fontname');
if(fs == '' && !BROWSER.ie && window.getComputedStyle) {
fs = editdoc.body.style.fontFamily;
} else if(fs == null) {
fs = '';
}
fs = fs && cmd != 'clear' ? fs : '字体';
if(fs != $(editorid + '_font').fontstate) {
thingy = fs.indexOf(',') > 0 ? fs.substr(0, fs.indexOf(',')) : fs;
$(editorid + '_font').innerHTML = thingy;
$(editorid + '_font').fontstate = fs;
}
try {
var ss = editdoc.queryCommandValue('fontsize');
if(ss == null || ss == '' || cmd == 'clear') {
ss = formatFontsize(editdoc.body.style.fontSize);
} else {
var ssu = ss.substr(-2);
if(ssu == 'px' || ssu == 'pt') {
ss = formatFontsize(ss);
}
}
} catch(e) {}
if(ss != $(editorid + '_size').sizestate) {
if($(editorid + '_size').sizestate == null) {
$(editorid + '_size').sizestate = '';
}
$(editorid + '_size').innerHTML = ss;
$(editorid + '_size').sizestate = ss;
}
}
function buttonContext(obj, state) {
if(state == 'mouseover') {
obj.style.cursor = 'pointer';
var mode = obj.state ? 'down' : 'hover';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = 'hover';
}
} else {
var mode = obj.state ? 'selected' : 'normal';
if(obj.mode != mode) {
obj.mode = mode;
obj.className = mode == 'selected' ? 'hover' : '';
}
}
}
function formatFontsize(csssize) {
switch(csssize) {
case '7.5pt':
case '10px': return 1;
case '13px':
case '10pt': return 2;
case '16px':
case '12pt': return 3;
case '18px':
case '14pt': return 4;
case '24px':
case '18pt': return 5;
case '32px':
case '24pt': return 6;
case '48px':
case '36pt': return 7;
default: return '大小';
}
}
function showEditorMenu(tag, params) {
var sel, selection;
var str = '', strdialog = 0, stitle = '';
var ctrlid = editorid + (params ? '_cst' + params + '_' : '_') + tag;
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
var menu = $(ctrlid + '_menu');
var pos = [0, 0];
var menuwidth = 270;
var menupos = '43!';
var menutype = 'menu';
if(BROWSER.ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
pos = getCaret();
}
selection = sel ? (wysiwyg ? sel.htmlText : sel.text) : getSel();
if(menu) {
if($(ctrlid).getAttribute('menupos') !== null) {
menupos = $(ctrlid).getAttribute('menupos');
}
if($(ctrlid).getAttribute('menuwidth') !== null) {
menu.style.width = $(ctrlid).getAttribute('menuwidth') + 'px';
}
if(menupos == '00') {
menu.className = 'fwinmask';
if($(editorid + '_' + tag + '_menu').style.visibility == 'hidden') {
$(editorid + '_' + tag + '_menu').style.visibility = 'visible';
} else {
showMenu({'ctrlid':ctrlid,'mtype':'win','evt':'click','pos':menupos,'timeout':250,'duration':3,'drag':ctrlid + '_ctrl'});
}
} else {
showMenu({'ctrlid':ctrlid,'evt':'click','pos':menupos,'timeout':250,'duration':in_array(tag, ['fontname', 'fontsize', 'sml']) ? 2 : 3,'drag':1});
}
} else {
switch(tag) {
case 'url':
str = '请输入链接地址:<br /><input type="text" id="' + ctrlid + '_param_1" style="width: 98%" value="" class="px" />'+
(selection ? '' : '<br />请输入链接文字:<br /><input type="text" id="' + ctrlid + '_param_2" style="width: 98%" value="" class="px" />');
break;
case 'forecolor':
showColorBox(ctrlid, 1);
return;
case 'backcolor':
showColorBox(ctrlid, 1, '', 1);
return;
case 'code':
if(wysiwyg) {
opentag = '<div class="blockcode"><blockquote>';
closetag = '</blockquote></div><br />';
}
case 'quote':
if(wysiwyg && tag == 'quote') {
opentag = '<div class="quote"><blockquote>';
closetag = '</blockquote></div><br />';
}
case 'hide':
case 'free':
if(selection) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var lang = {'quote' : '请输入要插入的引用', 'code' : '请输入要插入的代码', 'hide' : '请输入要隐藏的信息内容', 'free' : '如果您设置了帖子售价,请输入购买前免费可见的信息内容'};
str += lang[tag] + ':<br /><textarea id="' + ctrlid + '_param_1" style="width: 98%" cols="50" rows="5" class="txtarea"></textarea>' +
(tag == 'hide' ? '<br /><label><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_1" class="pc" checked="checked" />只有当浏览者回复本帖时才显示</label><br /><label><input type="radio" name="' + ctrlid + '_radio" id="' + ctrlid + '_radio_2" class="pc" />只有当浏览者积分高于</label> <input type="text" size="3" id="' + ctrlid + '_param_2" class="px pxs" /> 时才显示' : '');
break;
case 'tbl':
str = '<p class="pbn">表格行数: <input type="text" id="' + ctrlid + '_param_1" size="2" value="2" class="px" /> 表格列数: <input type="text" id="' + ctrlid + '_param_2" size="2" value="2" class="px" /></p><p class="pbn">表格宽度: <input type="text" id="' + ctrlid + '_param_3" size="2" value="" class="px" /> 背景颜色: <input type="text" id="' + ctrlid + '_param_4" size="2" class="px" onclick="showColorBox(this.id, 2)" /></p><p class="xg2 pbn" style="cursor:pointer" onclick="showDialog($(\'tbltips_msg\').innerHTML, \'notice\', \'小提示\', null, 0)"><img id="tbltips" title="小提示" class="vm" src="' + IMGDIR + '/info_small.gif"> 快速书写表格提示</p>';
str += '<div id="tbltips_msg" style="display: none">“[tr=颜色]” 定义行背景<br />“[td=宽度]” 定义列宽<br />“[td=列跨度,行跨度,宽度]” 定义行列跨度<br /><br />快速书写表格范例:<div class=\'xs0\' style=\'margin:0 5px\'>[table]<br />Name:|Discuz!<br />Version:|X1<br />[/table]</div>用“|”分隔每一列,表格中如有“|”用“\\|”代替,换行用“\\n”代替。</div>';
break;
case 'aud':
str = '<p class="pbn">请输入音乐文件地址:</p><p class="pbn"><input type="text" id="' + ctrlid + '_param_1" class="px" value="" style="width: 220px;" /></p><p class="xg2 pbn">支持 wma mp3 ra rm 等音乐格式<br />示例: http://server/audio.wma</p>';
break;
case 'vid':
str = '<p class="pbn">请输入视频地址:</p><p class="pbn"><input type="text" value="" id="' + ctrlid + '_param_1" style="width: 220px;" class="px" /></p><p class="pbn">宽: <input id="' + ctrlid + '_param_2" size="5" value="500" class="px" /> 高: <input id="' + ctrlid + '_param_3" size="5" value="375" class="px" /></p><p class="xg2 pbn">支持优酷、土豆、56、酷6等视频站的视频网址<br />支持 wmv avi rmvb mov swf flv 等视频格式<br />示例: http://server/movie.wmv</p>';
break;
case 'fls':
str = '<p class="pbn">请输入 Flash 文件地址:</p><p class="pbn"><input type="text" id="' + ctrlid + '_param_1" class="px" value="" style="width: 220px;" /></p><p class="pbn">宽: <input id="' + ctrlid + '_param_2" size="5" value="" class="px" /> 高: <input id="' + ctrlid + '_param_3" size="5" value="" class="px" /></p><p class="xg2 pbn">支持 swf flv 等 Flash 网址<br />示例: http://server/flash.swf</p>';
break;
case 'pasteword':
stitle = '从 Word 粘贴内容';
str = '<p class="px" style="height:300px"><iframe id="' + ctrlid + '_param_1" frameborder="0" style="width:100%;height:100%" onload="this.contentWindow.document.body.style.width=\'550px\';this.contentWindow.document.body.contentEditable=true;this.contentWindow.document.body.focus();this.onload=null"></iframe></p><p class="xg2 pbn">请通过快捷键(Ctrl+V)把 Word 文件中的内容粘贴到上方</p>';
menuwidth = 600;
menupos = '00';
menutype = 'win';
break;
default:
var haveSel = selection == null || selection == false || in_array(trim(selection), ['', 'null', 'undefined', 'false']) ? 0 : 1;
if(params == 1 && haveSel) {
return insertText((opentag + selection + closetag), strlen(opentag), strlen(closetag), true, sel);
}
var promptlang = custombbcodes[tag]['prompt'].split("\t");
for(var i = 1; i <= params; i++) {
if(i != params || !haveSel) {
str += (promptlang[i - 1] ? promptlang[i - 1] : '请输入第 ' + i + ' 个参数:') + '<br /><input type="text" id="' + ctrlid + '_param_' + i + '" style="width: 98%" value="" class="px" />' + (i < params ? '<br />' : '');
}
}
break;
}
var menu = document.createElement('div');
menu.id = ctrlid + '_menu';
menu.style.display = 'none';
menu.className = 'p_pof upf';
menu.style.width = menuwidth + 'px';
if(menupos == '00') {
menu.className = 'fwinmask';
s = '<table width="100%" cellpadding="0" cellspacing="0" class="fwin"><tr><td class="t_l"></td><td class="t_c"></td><td class="t_r"></td></tr><tr><td class="m_l"> </td><td class="m_c">'
+ '<h3 class="flb"><em>' + stitle + '</em><span><a onclick="hideMenu(\'\', \'win\');return false;" class="flbc" href="javascript:;">关闭</a></span></h3><div class="c">' + str + '</div>'
+ '<p class="o pns"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button></p>'
+ '</td><td class="m_r"></td></tr><tr><td class="b_l"></td><td class="b_c"></td><td class="b_r"></td></tr></table>';
} else {
s = '<div class="p_opt cl"><span class="y" style="margin:-10px -10px 0 0"><a onclick="hideMenu();return false;" class="flbc" href="javascript:;">关闭</a></span><div>' + str + '</div><div class="pns mtn"><button type="submit" id="' + ctrlid + '_submit" class="pn pnc"><strong>提交</strong></button></div></div>';
}
menu.innerHTML = s;
$(editorid + '_editortoolbar').appendChild(menu);
showMenu({'ctrlid':ctrlid,'mtype':menutype,'evt':'click','duration':3,'cache':0,'drag':1,'pos':menupos});
}
try {
if($(ctrlid + '_param_1')) {
$(ctrlid + '_param_1').focus();
}
} catch(e) {}
var objs = menu.getElementsByTagName('*');
for(var i = 0; i < objs.length; i++) {
_attachEvent(objs[i], 'keydown', function(e) {
e = e ? e : event;
obj = BROWSER.ie ? event.srcElement : e.target;
if((obj.type == 'text' && e.keyCode == 13) || (obj.type == 'textarea' && e.ctrlKey && e.keyCode == 13)) {
if($(ctrlid + '_submit') && tag != 'image') $(ctrlid + '_submit').click();
doane(e);
} else if(e.keyCode == 27) {
hideMenu();
doane(e);
}
});
}
if($(ctrlid + '_submit')) $(ctrlid + '_submit').onclick = function() {
checkFocus();
if(BROWSER.ie && wysiwyg) {
setCaret(pos[0]);
}
switch(tag) {
case 'url':
var href = $(ctrlid + '_param_1').value;
href = (isEmail(href) ? 'mailto:' : '') + href;
if(href != '') {
var v = selection ? selection : ($(ctrlid + '_param_2').value ? $(ctrlid + '_param_2').value : href);
str = wysiwyg ? ('<a href="' + href + '">' + v + '</a>') : '[url=' + href + ']' + v + '[/url]';
if(wysiwyg) insertText(str, str.length - v.length, 0, (selection ? true : false), sel);
else insertText(str, str.length - v.length - 6, 6, (selection ? true : false), sel);
}
break;
case 'code':
if(wysiwyg) {
opentag = '<div class="blockcode"><blockquote>';
closetag = '</blockquote></div><br />';
if(!BROWSER.ie) {
selection = selection ? selection : '\n';
}
}
case 'quote':
if(wysiwyg && tag == 'quote') {
opentag = '<div class="quote"><blockquote>';
closetag = '</blockquote></div><br />';
if(!BROWSER.ie) {
selection = selection ? selection : '\n';
}
}
case 'hide':
case 'free':
if(tag == 'hide' && $(ctrlid + '_radio_2').checked) {
var mincredits = parseInt($(ctrlid + '_param_2').value);
opentag = mincredits > 0 ? '[hide=' + mincredits + ']' : '[hide]';
}
str = $(ctrlid + '_param_1') && $(ctrlid + '_param_1').value ? $(ctrlid + '_param_1').value : (selection ? selection : '');
if(wysiwyg) {
str = preg_replace(['<', '>'], ['<', '>'], str);
str = str.replace(/\r?\n/g, '<br />');
}
str = opentag + str + closetag;
insertText(str, strlen(opentag), strlen(closetag), false, sel);
break;
case 'tbl':
var rows = $(ctrlid + '_param_1').value;
var columns = $(ctrlid + '_param_2').value;
var width = $(ctrlid + '_param_3').value;
var bgcolor = $(ctrlid + '_param_4').value;
rows = /^[-\+]?\d+$/.test(rows) && rows > 0 && rows <= 30 ? rows : 2;
columns = /^[-\+]?\d+$/.test(columns) && columns > 0 && columns <= 30 ? columns : 2;
width = width.substr(width.length - 1, width.length) == '%' ? (width.substr(0, width.length - 1) <= 98 ? width : '98%') : (width <= 560 ? width : '98%');
bgcolor = /[\(\)%,#\w]+/.test(bgcolor) ? bgcolor : '';
if(wysiwyg) {
str = '<table cellspacing="0" cellpadding="0" width="' + (width ? width : '50%') + '" class="t_table"' + (bgcolor ? ' bgcolor="' + bgcolor + '"' : '') + '>';
for (var row = 0; row < rows; row++) {
str += '<tr>\n';
for (col = 0; col < columns; col++) {
str += '<td> </td>\n';
}
str += '</tr>\n';
}
str += '</table>\n';
} else {
str = '[table=' + (width ? width : '50%') + (bgcolor ? ',' + bgcolor : '') + ']\n';
for (var row = 0; row < rows; row++) {
str += '[tr]';
for (col = 0; col < columns; col++) {
str += '[td] [/td]';
}
str += '[/tr]\n';
}
str += '[/table]\n';
}
insertText(str, str.length, 0, false, sel);
break;
case 'aud':
insertText('[audio]' + $(ctrlid + '_param_1').value + '[/audio]', 7, 8, false, sel);
break;
case 'fls':
if($(ctrlid + '_param_2').value && $(ctrlid + '_param_3').value) {
insertText('[flash=' + parseInt($(ctrlid + '_param_2').value) + ',' + parseInt($(ctrlid + '_param_3').value) + ']' + $(ctrlid + '_param_1').value + '[/flash]', 7, 8, false, sel);
} else {
insertText('[flash]' + $(ctrlid + '_param_1').value + '[/flash]', 7, 8, false, sel);
}
break;
case 'vid':
var mediaUrl = $(ctrlid + '_param_1').value;
var auto = '';
var ext = mediaUrl.lastIndexOf('.') == -1 ? '' : mediaUrl.substr(mediaUrl.lastIndexOf('.') + 1, mb_strlen(mediaUrl)).toLowerCase();
ext = in_array(ext, ['mp3', 'wma', 'ra', 'rm', 'ram', 'mid', 'asx', 'wmv', 'avi', 'mpg', 'mpeg', 'rmvb', 'asf', 'mov', 'flv', 'swf']) ? ext : 'x';
if(ext == 'x') {
if(/^mms:\/\//.test(mediaUrl)) {
ext = 'mms';
} else if(/^(rtsp|pnm):\/\//.test(mediaUrl)) {
ext = 'rtsp';
}
}
var str = '[media=' + ext + ',' + $(ctrlid + '_param_2').value + ',' + $(ctrlid + '_param_3').value + ']' + mediaUrl + '[/media]';
insertText(str, str.length, 0, false, sel);
break;
case 'image':
var width = parseInt($(ctrlid + '_param_2').value);
var height = parseInt($(ctrlid + '_param_3').value);
var src = $(ctrlid + '_param_1').value;
var style = '';
if(wysiwyg) {
style += width ? ' width=' + width : '';
style += height ? ' height=' + height : '';
var str = '<img src=' + src + style + ' border=0 />';
insertText(str, str.length, 0, false, sel);
} else {
style += width || height ? '=' + width + ',' + height : '';
insertText('[img' + style + ']' + src + '[/img]', 0, 0, false, sel);
}
$(ctrlid + '_param_1').value = '';
break;
case 'pasteword':
pasteWord($(ctrlid + '_param_1').contentWindow.document.body.innerHTML);
hideMenu('', 'win');
break;
default:
var first = $(ctrlid + '_param_1').value;
if($(ctrlid + '_param_2')) var second = $(ctrlid + '_param_2').value;
if($(ctrlid + '_param_3')) var third = $(ctrlid + '_param_3').value;
if((params == 1 && first) || (params == 2 && first && (haveSel || second)) || (params == 3 && first && second && (haveSel || third))) {
if(params == 1) {
str = first;
} else if(params == 2) {
str = haveSel ? selection : second;
opentag = '[' + tag + '=' + first + ']';
} else {
str = haveSel ? selection : third;
opentag = '[' + tag + '=' + first + ',' + second + ']';
}
insertText((opentag + str + closetag), strlen(opentag), strlen(closetag), true, sel);
}
break;
}
hideMenu();
};
}
function autoTypeset() {
var sel;
if(BROWSER.ie) {
sel = wysiwyg ? editdoc.selection.createRange() : document.selection.createRange();
}
var selection = sel ? (wysiwyg ? sel.htmlText.replace(/<\/?p>/ig, '<br />') : sel.text) : getSel();
selection = wysiwyg ? selection.replace(/<br[^\>]*>/ig, "\n") : selection.replace(/\r?\n/g, "\n");
selection = trim(selection);
selection = wysiwyg ? selection.replace(/\n+/g, '</p><p style="line-height: 30px; text-indent: 2em;">') : selection.replace(/\n/g, '[/p][p=30, 2, left]');
opentag = wysiwyg ? '<p style="line-height: 30px; text-indent: 2em;">' : '[p=30, 2, left]';
var s = opentag + selection + (wysiwyg ? '</p>' : '[/p]');
insertText(s, strlen(opentag), 4, false, sel);
hideMenu();
}
function getSel() {
if(wysiwyg) {
try {
selection = editwin.getSelection();
checkFocus();
range = selection ? selection.getRangeAt(0) : editdoc.createRange();
return readNodes(range.cloneContents(), false);
} catch(e) {
try {
var range = editdoc.selection.createRange();
if(range.htmlText && range.text) {
return range.htmlText;
} else {
var htmltext = '';
for(var i = 0; i < range.length; i++) {
htmltext += range.item(i).outerHTML;
}
return htmltext;
}
} catch(e) {
return '';
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
return editdoc.value.substr(editdoc.selectionStart, editdoc.selectionEnd - editdoc.selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
}
function insertText(text, movestart, moveend, select, sel) {
checkFocus();
if(wysiwyg) {
try {
editdoc.execCommand('insertHTML', false, text);
} catch(e) {
if(!isUndefined(editdoc.selection) && editdoc.selection.type != 'Text' && editdoc.selection.type != 'None') {
movestart = false;
editdoc.selection.clear();
}
if(isUndefined(sel)) {
sel = editdoc.selection.createRange();
}
sel.pasteHTML(text);
if(text.indexOf('\n') == -1) {
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) + movestart);
sel.moveEnd('character', -moveend);
} else if(movestart != false) {
sel.moveStart('character', -strlen(text));
}
if(!isUndefined(select) && select) {
sel.select();
}
}
}
} else {
if(!isUndefined(editdoc.selectionStart)) {
var opn = editdoc.selectionStart + 0;
editdoc.value = editdoc.value.substr(0, editdoc.selectionStart) + text + editdoc.value.substr(editdoc.selectionEnd);
if(!isUndefined(movestart)) {
editdoc.selectionStart = opn + movestart;
editdoc.selectionEnd = opn + strlen(text) - moveend;
} else if(movestart !== false) {
editdoc.selectionStart = opn;
editdoc.selectionEnd = opn + strlen(text);
}
} else if(document.selection && document.selection.createRange) {
if(isUndefined(sel)) {
sel = document.selection.createRange();
}
if(editbox.sel) {
sel = editbox.sel;
editbox.sel = null;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!isUndefined(movestart)) {
sel.moveStart('character', -strlen(text) +movestart);
sel.moveEnd('character', -moveend);
} else if(movestart !== false) {
sel.moveStart('character', -strlen(text));
}
sel.select();
} else {
editdoc.value += text;
}
}
checkFocus();
}
function stripSimple(tag, str, iterations) {
var opentag = '[' + tag + ']';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var text = str.substr(startindex + opentag.length, stopindex - startindex - opentag.length);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
}
return str;
}
function readNodes(root, toptag) {
var html = "";
var moz_check = /_moz/i;
switch(root.nodeType) {
case Node.ELEMENT_NODE:
case Node.DOCUMENT_FRAGMENT_NODE:
var closed;
if(toptag) {
closed = !root.hasChildNodes();
html = '<' + root.tagName.toLowerCase();
var attr = root.attributes;
for(var i = 0; i < attr.length; ++i) {
var a = attr.item(i);
if(!a.specified || a.name.match(moz_check) || a.value.match(moz_check)) {
continue;
}
html += " " + a.name.toLowerCase() + '="' + a.value + '"';
}
html += closed ? " />" : ">";
}
for(var i = root.firstChild; i; i = i.nextSibling) {
html += readNodes(i, true);
}
if(toptag && !closed) {
html += "</" + root.tagName.toLowerCase() + ">";
}
break;
case Node.TEXT_NODE:
html = htmlspecialchars(root.data);
break;
}
return html;
}
function stripComplex(tag, str, iterations) {
var opentag = '[' + tag + '=';
var closetag = '[/' + tag + ']';
if(isUndefined(iterations)) {
iterations = -1;
}
while((startindex = stripos(str, opentag)) !== false && iterations != 0) {
iterations --;
if((stopindex = stripos(str, closetag)) !== false) {
var openend = stripos(str, ']', startindex);
if(openend !== false && openend > startindex && openend < stopindex) {
var text = str.substr(openend + 1, stopindex - openend - 1);
str = str.substr(0, startindex) + text + str.substr(stopindex + closetag.length);
} else {
break;
}
} else {
break;
}
}
return str;
}
function stripos(haystack, needle, offset) {
if(isUndefined(offset)) {
offset = 0;
}
var index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);
return (index == -1 ? false : index);
}
function switchEditor(mode) {
if(mode == wysiwyg || !allowswitcheditor) {
return;
}
if(!mode) {
var controlbar = $(editorid + '_controls');
var controls = [];
var buttons = controlbar.getElementsByTagName('a');
var buttonslength = buttons.length;
for(var i = 0; i < buttonslength; i++) {
if(buttons[i].id) {
controls[controls.length] = buttons[i].id;
}
}
var controlslength = controls.length;
for(var i = 0; i < controlslength; i++) {
var control = $(controls[i]);
if(control.id.indexOf(editorid + '_') != -1) {
control.state = false;
control.mode = 'normal';
} else if(control.id.indexOf(editorid + '_popup_') != -1) {
control.state = false;
}
}
setContext('clear');
}
cursor = -1;
stack = [];
var parsedtext = getEditorContents();
parsedtext = mode ? bbcode2html(parsedtext) : html2bbcode(parsedtext);
wysiwyg = mode;
$(editorid + '_mode').value = mode;
newEditor(mode, parsedtext);
setEditorStyle();
editwin.focus();
setCaretAtEnd();
}
function setCaretAtEnd() {
if(wysiwyg) {
editdoc.body.innerHTML += '';
} else {
editdoc.value += '';
}
}
function moveCursor(increment) {
var test = cursor + increment;
if(test >= 0 && stack[test] != null && !isUndefined(stack[test])) {
cursor += increment;
}
}
function addSnapshot(str) {
if(stack[cursor] == str) {
return;
} else {
cursor++;
stack[cursor] = str;
if(!isUndefined(stack[cursor + 1])) {
stack[cursor + 1] = null;
}
}
}
function getSnapshot() {
if(!isUndefined(stack[cursor]) && stack[cursor] != null) {
return stack[cursor];
} else {
return false;
}
}
function loadimgsize(imgurl, editor, p) {
var editor = !editor ? editorid : editor;
var s = new Object();
var p = !p ? '_image' : p;
s.img = new Image();
s.img.src = imgurl;
s.loadCheck = function () {
if(s.img.complete) {
$(editor + p + '_param_2').value = s.img.width ? s.img.width : '';
$(editor + p + '_param_3').value = s.img.height ? s.img.height : '';
} else {
setTimeout(function () {s.loadCheck();}, 100);
}
};
s.loadCheck();
}
if(typeof jsloaded == 'function') {
jsloaded('editor');
} | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: space_diy.js 21831 2011-04-13 08:53:11Z maruitao $
*/
var drag = new Drag();
drag.extend({
setDefalutMenu : function () {
this.addMenu('default', '删除', 'drag.removeBlock(event)');
this.addMenu('block', '属性', 'drag.openBlockEdit(event)');
},
removeBlock : function (e) {
if ( typeof e !== 'string') {
e = Util.event(e);
id = e.aim.id.replace('cmd_','');
} else {
id = e;
}
if (!confirm('您确实要删除吗,删除以后将不可恢复')) return false;
$(id).parentNode.removeChild($(id));
var el = $('chk'+id);
if (el != null) el.className = '';
this.initPosition();
this.initChkBlock();
},
initChkBlock : function (data) {
if (typeof name == 'undefined' || data == null ) data = this.data;
if ( data instanceof Frame) {
this.initChkBlock(data['columns']);
} else if (data instanceof Block) {
var el = $('chk'+data.name);
if (el != null) el.className = 'activity';
} else if (typeof data == 'object') {
for (var i in data) {
this.initChkBlock(data[i]);
}
}
},
toggleBlock : function (blockname) {
var el = $('chk'+blockname);
if (el != null) {
if (el.className == '') {
this.getBlockData(blockname);
el.className = 'activity';
} else {
this.removeBlock(blockname);
this.initPosition();
}
this.setClose();
}
},
getBlockData : function (blockname) {
var el = $(blockname);
if (el != null) {
Util.show(blockname);
} else {
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=index&op=getblock&blockname='+blockname+'&inajax=1',function(s) {
if (s) {
el = document.createElement("div");
el.className = drag.blockClass + ' ' + drag.moveableObject;
el.id = blockname;
s = s.replace(/\<script.*\<\/script\>/ig,'<font color="red"> [javascript脚本保存后显示] </font>');
el.innerHTML = s;
var id = drag.data['diypage'][0]['columns']['frame1_left']['children'][0]['name'];
$('frame1_left').insertBefore(el,$(id));
drag.initPosition();
}
});
}
},
openBlockEdit : function (e) {
e = Util.event(e);
var blockname = e.aim.id.replace('cmd_','');
this.removeMenu();
showWindow('showblock', 'home.php?mod=spacecp&ac=index&op=edit&blockname='+blockname,'get',0);
}
});
var spaceDiy = new DIY();
spaceDiy.extend({
save:function () {
drag.clearClose();
document.diyform.spacecss.value = this.getSpacecssStr();
document.diyform.style.value = this.style;
document.diyform.layoutdata.value = drag.getPositionStr();
document.diyform.currentlayout.value = this.currentLayout;
document.diyform.submit();
},
getdiy : function (type) {
var type_ = type == 'image' ? 'diy' : type;
if (type_) {
var nav = $('controlnav').children;
for (var i in nav) {
if (nav[i].className == 'current') {
nav[i].className = '';
}
}
$('nav'+type_).className = 'current';
var para = '&op='+type;
if (arguments.length > 1) {
for (i = 1; i < arguments.length; i++) {
para += '&' + arguments[i] + '=' + arguments[++i];
}
}
var ajaxtarget = type == 'image' ? 'diyimages' : '';
var x = new Ajax();
x.showId = ajaxtarget;
x.get('home.php?mod=spacecp&ac=index'+para+'&inajax=1&ajaxtarget='+ajaxtarget,function(s) {
if (s) {
drag.deleteFrame(['pb', 'bpb', 'tpb', 'lpb']);
if (type == 'image') {
$('diyimages').innerHTML = s;
} else {
$('controlcontent').innerHTML = s;
x.showId = 'controlcontent';
}
if (type_ == 'block') {
drag.initPosition();
drag.initChkBlock();
} else if (type_ == 'layout') {
$('layout'+spaceDiy.currentLayout).className = 'activity';
} else if (type_ == 'diy' && type != 'image') {
spaceDiy.setCurrentDiy(spaceDiy.currentDiy);
if (spaceDiy.styleSheet.rules.length > 0) {
Util.show('recover_button');
}
}
var evaled = false;
if(s.indexOf('ajaxerror') != -1) {
evalscript(s);
evaled = true;
}
if(!evaled && (typeof ajaxerror == 'undefined' || !ajaxerror)) {
if(x.showId) {
ajaxupdateevents($(x.showId));
}
}
if(!evaled) evalscript(s);
}
});
}
},
menuChange : function (tabs, menu) {
var tabobj = $(tabs);
var aobj = tabobj.getElementsByTagName("li");
for(i=0; i<aobj.length; i++) {
aobj[i].className = '';
$(aobj[i].id+'_content').style.display = 'none';
}
$(menu).className = 'a';
$(menu+'_content').style.display="block";
doane(null);
},
delIframe : function (){
drag.deleteFrame(['m_ctc', 'm_bc', 'm_fc']);
},
showEditSpaceInfo : function () {
$('spaceinfoshow').style.display='none';
if (!$('spaceinfoedit')) {
var dom = document.createElement('h2');
dom.id = 'spaceinfoedit';
Util.insertBefore(dom, $('spaceinfoshow'));
}
ajaxget('home.php?mod=spacecp&ac=index&op=getspaceinfo','spaceinfoedit');
},
spaceInfoCancel : function () {
if ($('spaceinfoedit')) $('spaceinfoedit').style.display = 'none';
if ($('spaceinfoshow')) $('spaceinfoshow').style.display = 'inline';
},
spaceInfoSave : function () {
ajaxpost('savespaceinfo','spaceinfoshow');
},
init : function () {
drag.init();
this.style = document.diyform.style.value;
this.currentLayout = typeof document.diyform.currentlayout == 'undefined' ? '' : document.diyform.currentlayout.value;
this.initStyleSheet();
if (this.styleSheet.rules) this.initDiyStyle();
this.initSpaceInfo();
},
initSpaceInfo : function () {
this.spaceInfoCancel();
if ($('spaceinfoshow')) {
if (!$('infoedit')) {
var dom = document.createElement('em');
dom.id = 'infoedit';
dom.innerHTML = '编辑';
$('spacename').appendChild(dom);
}
$('spaceinfoshow').onmousedown = function () {spaceDiy.showEditSpaceInfo();};
}
if ($('nv')) {
if(!$('nv').getElementsByTagName('li').length) {
$('nv').getElementsByTagName('ul')[0].className = 'mininv';
}
$('nv').onmouseover = function () {spaceDiy.showEditNvInfo();};
$('nv').onmouseout = function () {spaceDiy.hideEditNvInfo();};
}
},
showEditNvInfo : function () {
var nv = $('editnvinfo');
if(!nv) {
var dom = document.createElement('div');
dom.innerHTML = '<span id="editnvinfo" class="edit" style="background-color:#336699;" onclick="spaceDiy.opNvEditInfo();">设置</span>';
$('nv').appendChild(dom.childNodes[0]);
} else {
nv.style.display = '';
}
},
hideEditNvInfo : function () {
var nv = $('editnvinfo');
if(nv) {
nv.style.display = 'none';
}
},
opNvEditInfo : function () {
showWindow('showpersonalnv', 'home.php?mod=spacecp&ac=index&op=editnv','get',0);
},
getPersonalNv : function (show) {
var x = new Ajax();
show = !show ? '' : '&show=1';
x.get('home.php?mod=spacecp&ac=index&op=getpersonalnv&inajax=1'+show, function(s) {
if($('nv')) {
$('hd').removeChild($('nv'));
}
var dom = document.createElement('div');
dom.innerHTML = !s ? ' ' : s;
$('hd').appendChild(dom.childNodes[0]);
spaceDiy.initSpaceInfo();
});
}
});
spaceDiy.init(); | JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: google.js 17172 2010-09-25 08:17:48Z zhangguosheng $
*/
document.writeln('<script type="text/javascript">');
document.writeln('function validate_google(theform) {');
document.writeln(' if(theform.site.value == 1) {');
document.writeln(' theform.q.value = \'site:' + google_host + ' \' + theform.q.value;');
document.writeln(' }');
document.writeln('}');
document.writeln('function submitFormWithChannel(channelname) {');
document.writeln(' document.gform.channel.value=channelname;');
document.writeln(' document.gform.submit();');
document.writeln(' return;');
document.writeln('}');
document.writeln('</script>');
document.writeln('<form name="gform" id="gform" method="get" autocomplete="off" action="http://www.google.com/search?" target="_blank" onSubmit="validate_google(this);">');
document.writeln('<input type="hidden" name="client" value="' + (!google_client ? 'aff-discuz' : google_client) + '" />');
document.writeln('<input type="hidden" name="ie" value="' + google_charset + '" />');
document.writeln('<input type="hidden" name="oe" value="UTF-8" />');
document.writeln('<input type="hidden" name="hl" value="' + google_hl + '" />');
document.writeln('<input type="hidden" name="lr" value="' + google_lr + '" />');
document.writeln('<input type="hidden" name="channel" value="search" />');
document.write('<div onclick="javascript:submitFormWithChannel(\'logo\')" style="cursor:pointer;float: left;width:70px;height:23px;background: url(' + STATICURL + 'image/common/Google_small.png) !important;background: none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + STATICURL+ 'image/common/Google_small.png\', sizingMethod=\'scale\')"><img src="' + STATICURL + 'image/common/none.gif" border="0" alt="Google" /></div>');
document.writeln(' <input type="text" class="txt" size="20" name="q" id="q" maxlength="255" value=""></input>');
document.writeln('<select name="site">');
document.writeln('<option value="0"' + google_default_0 + '>网页搜索</option>');
document.writeln('<option value="1"' + google_default_1 + '>站内搜索</option>');
document.writeln('</select>');
document.writeln(' <button type="submit" name="sa" value="true">搜索</button>');
document.writeln('</form>'); | JavaScript |
function uploadEdit(obj) {
mainForm = obj.form;
forms = $('attachbody').getElementsByTagName("FORM");
albumid = $('uploadalbum').value;
edit_save();
upload();
}
function edit_save() {
var p = window.frames['uchome-ifrHtmlEditor'];
var obj = p.window.frames['HtmlEditor'];
var status = p.document.getElementById('uchome-editstatus').value;
if(status == 'code') {
$('uchome-ttHtmlEditor').value = p.document.getElementById('sourceEditor').value;
} else if(status == 'text') {
if(BROWSER.ie) {
obj.document.body.innerText = p.document.getElementById('dvtext').value;
$('uchome-ttHtmlEditor').value = obj.document.body.innerHTML;
} else {
obj.document.body.textContent = p.document.getElementById('dvtext').value;
var sOutText = obj.document.body.innerHTML;
$('uchome-ttHtmlEditor').value = sOutText.replace(/\r\n|\n/g,"<br>");
}
} else {
$('uchome-ttHtmlEditor').value = obj.document.body.innerHTML;
}
backupContent($('uchome-ttHtmlEditor').value);
}
function relatekw() {
edit_save();
var subject = cnCode($('subject').value);
var message = cnCode($('uchome-ttHtmlEditor').value);
if(message) {
message = message.substr(0, 500);
}
var x = new Ajax();
x.get('home.php?mod=spacecp&ac=relatekw&inajax=1&subjectenc=' + subject + '&messageenc=' + message, function(s){
$('tag').value = s;
});
}
function downRemoteFile() {
edit_save();
var formObj = $("articleform");
var oldAction = formObj.action;
formObj.action = "portal.php?mod=portalcp&ac=upload&op=downremotefile";
formObj.onSubmit = "";
formObj.target = "uploadframe";
formObj.submit();
formObj.action = oldAction;
formObj.target = "";
}
function backupContent(sHTML) {
if(sHTML.length > 11) {
var obj = $('uchome-ttHtmlEditor').form;
if(!obj) return;
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject' || el.name == 'title') {
subject = trim(elvalue);
} else if(el.name == 'message' || el.name == 'content') {
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message) {
return;
}
saveUserdata('home', data);
}
}
function edit_insert(html) {
var p = window.frames['uchome-ifrHtmlEditor'];
var obj = p.window.frames['HtmlEditor'];
var status = p.document.getElementById('uchome-editstatus').value;
if(status != 'html') {
alert('本操作只在多媒体编辑模式下才有效');
return;
}
obj.focus();
if(BROWSER.ie){
var f = obj.document.selection.createRange();
f.pasteHTML(html);
f.collapse(false);
f.select();
} else {
obj.document.execCommand('insertHTML', false, html);
}
}
function insertImage(image, url) {
url = typeof url == 'undefined' || url === null ? image : url;
var html = '<p><a href="' + url + '" target="_blank"><img src="'+image+'"></a></p>';
edit_insert(html);
}
function insertFile(file, url) {
url = typeof url == 'undefined' || url === null ? image : url;
var html = '<p><a href="' + url + '" target="_blank" class="attach">' + file + '</a></p>';
edit_insert(html);
} | JavaScript |
var gSetColorType = "";
var gIsIE = document.all;
var gIEVer = fGetIEVer();
var gLoaded = false;
var ev = null;
var gIsHtml = true;
var pos = 0;
var sLength = 0;
function fGetEv(e){
ev = e;
}
function fGetIEVer(){
var iVerNo = 0;
var sVer = navigator.userAgent;
if(sVer.indexOf("MSIE")>-1){
var sVerNo = sVer.split(";")[1];
sVerNo = sVerNo.replace("MSIE","");
iVerNo = parseFloat(sVerNo);
}
return iVerNo;
}
function fSetEditable(){
var f = window.frames["HtmlEditor"];
f.document.designMode="on";
if(!gIsIE)
f.document.execCommand("useCSS",false, true);
}
function renewContent() {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
if(window.confirm('您确定要恢复上次保存?')) {
var data = loadUserdata('home');
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
parent.showDialog('没有可以恢复的数据!');
return;
}
var data = data.split(/\x09\x09/);
if(parent.$('subject')) {
var formObj = parent.$('subject').form;
} else if(parent.$('title')) {
var formObj = parent.$('title').form;
} else {
return;
}
for(var i = 0; i < formObj.elements.length; i++) {
var el = formObj.elements[i];
if(el.name != '' && (el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message' || ele[0] == 'content') {
var f = window.frames["HtmlEditor"];
f.document.body.innerHTML = elvalue;
} else {
el.value = elvalue;
}
}
break
}
}
}
}
}
}
function fSetFrmClick(){
var f = window.frames["HtmlEditor"];
f.document.onclick = function(){
fHideMenu();
}
if(gIsIE) {
f.document.attachEvent("onkeydown", listenKeyDown);
} else {
f.addEventListener('keydown', function(e) {listenKeyDown(e);}, true);
}
}
function listenKeyDown(event) {
parent.gIsEdited = true;
parent.ctrlEnter(event, 'issuance');
}
window.onload = function(){
try{
gLoaded = true;
fSetEditable();
fSetFrmClick();
}catch(e){
}
}
window.onbeforeunload = parent.edit_save;
function fSetColor(){
var dvForeColor =$("dvForeColor");
if(dvForeColor.getElementsByTagName("TABLE").length == 1){
dvForeColor.innerHTML = drawCube() + dvForeColor.innerHTML;
}
}
document.onmousemove = function(e){
if(gIsIE) var el = event.srcElement;
else var el = e.target;
var tdView = $("tdView");
var tdColorCode = $("tdColorCode");
if(el.tagName == "IMG"){
try{
if(fInObj(el, "dvForeColor")){
tdView.bgColor = el.parentNode.bgColor;
tdColorCode.innerHTML = el.parentNode.bgColor
}
}catch(e){}
}
}
function fInObj(el, id){
if(el){
if(el.id == id){
return true;
}else{
if(el.parentNode){
return fInObj(el.parentNode, id);
}else{
return false;
}
}
}
}
function fDisplayObj(id){
var o = $(id);
if(o) o.style.display = "";
}
document.onclick = function(e){
if(gIsIE) var el = event.srcElement;
else var el = e.target;
var dvForeColor =$("dvForeColor");
var dvPortrait =$("dvPortrait");
if(el.tagName == "IMG"){
try{
if(fInObj(el, "dvForeColor")){
format(gSetColorType, el.parentNode.bgColor);
dvForeColor.style.display = "none";
return;
}
}catch(e){}
try{
if(fInObj(el, "dvPortrait")){
format("InsertImage", el.src);
dvPortrait.style.display = "none";
return;
}
}catch(e){}
}
try{
if(fInObj(el, "createUrl") || fInObj(el, "createImg") || fInObj(el, "createSwf") || fInObj(el, "createPage")){
return;
}
}catch(e){}
fHideMenu();
var hideId = "";
if(arrMatch[el.id]){
hideId = arrMatch[el.id];
fDisplayObj(hideId);
}
}
var arrMatch = {
imgFontface:"fontface",
imgFontsize:"fontsize",
imgFontColor:"dvForeColor",
imgBackColor:"dvForeColor",
imgFace:"dvPortrait",
imgAlign:"divAlign",
imgList:"divList",
imgInOut:"divInOut",
faceBox:"editFaceBox",
icoUrl:"createUrl",
icoImg:"createImg",
icoSwf:"createSwf",
icoPage:"createPage"
}
function format(type, para){
var f = window.frames["HtmlEditor"];
var sAlert = "";
if(!gIsIE){
switch(type){
case "Cut":
sAlert = "您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl+X)来完成";
break;
case "Copy":
sAlert = "您的浏览器安全设置不允许编辑器自动执行拷贝操作,请使用键盘快捷键(Ctrl+C)来完成";
break;
case "Paste":
sAlert = "您的浏览器安全设置不允许编辑器自动执行粘贴操作,请使用键盘快捷键(Ctrl+V)来完成";
break;
}
}
if(sAlert != ""){
alert(sAlert);
return;
}
f.focus();
if(!para){
if(gIsIE){
f.document.execCommand(type);
}else{
f.document.execCommand(type,false,false);
}
}else{
if(type == 'insertHTML') {
try{
f.document.execCommand('insertHTML', false, para);
}catch(exp){
var obj = f.document.selection.createRange();
obj.pasteHTML(para);
obj.collapse(false);
obj.select();
}
} else {
try{
f.document.execCommand(type,false,para);
}catch(exp){}
}
}
f.focus();
}
function setMode(bStatus){
var sourceEditor = $("sourceEditor");
var HtmlEditor = $("HtmlEditor");
var divEditor = $("divEditor");
var f = window.frames["HtmlEditor"];
var body = f.document.getElementsByTagName("BODY")[0];
if(bStatus){
sourceEditor.style.display = "block";
divEditor.style.display = "none";
sourceEditor.value = body.innerHTML;
$('uchome-editstatus').value = 'code';
}else{
sourceEditor.style.display = "none";
divEditor.style.display = "";
body.innerHTML = sourceEditor.value;
$('uchome-editstatus').value = 'html';
}
}
function foreColor(e) {
fDisplayColorBoard(e);
gSetColorType = "foreColor";
}
function faceBox(e) {
if(gIsIE){
var e = window.event;
}
var dvFaceBox = $("editFaceBox");
var iX = e.clientX;
var iY = e.clientY;
dvFaceBox.style.display = "";
dvFaceBox.style.left = (iX-140) + "px";
dvFaceBox.style.top = 33 + "px";
dvFaceBox.innerHTML = "";
var faceul = document.createElement("ul");
for(i=1; i<31; i++) {
var faceli = document.createElement("li");
faceli.innerHTML = '<img src="' + parent.STATICURL + 'image/smiley/comcom/'+i+'.gif" onclick="insertImg(this.src);" class="cur1" />';
faceul.appendChild(faceli);
}
dvFaceBox.appendChild(faceul);
return true;
}
function insertImg(src) {
format("insertHTML", '<img src="' + src + '"/>');
}
function doodleBox(event, id) {
if(parent.$('uchome-ttHtmlEditor') != null) {
parent.showWindow(id, 'home.php?mod=magic&mid=doodle&showid=blog_doodle&target=uchome-ttHtmlEditor&from=editor');
} else {
alert("找不到涂鸦板初始化数据");
}
}
function backColor(e){
var sColor = fDisplayColorBoard(e);
if(gIsIE)
gSetColorType = "backcolor";
else
gSetColorType = "backcolor";
}
function fDisplayColorBoard(e){
if(gIsIE){
var e = window.event;
}
if(gIEVer<=5.01 && gIsIE){
var arr = showModalDialog("ColorSelect.htm", "", "font-family:Verdana; font-size:12; status:no; dialogWidth:21em; dialogHeight:21em");
if (arr != null) return arr;
return;
}
var dvForeColor =$("dvForeColor");
var iX = e.clientX;
var iY = e.clientY;
dvForeColor.style.display = "";
dvForeColor.style.left = (iX-30) + "px";
dvForeColor.style.top = 33 + "px";
return true;
}
function createLink(e, show) {
if(typeof show == 'undefined') {
var urlObj = $('insertUrl');
var sURL = urlObj.value;
if ((sURL!=null) && (sURL!="http://")){
setCaret();
format("CreateLink", sURL);
}
fHide($('createUrl'));
urlObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvUrlBox = $("createUrl");
var iX = e.clientX;
var iY = e.clientY;
dvUrlBox.style.display = "";
dvUrlBox.style.left = (iX-300) + "px";
dvUrlBox.style.top = 33 + "px";
}
}
function getCaret() {
if(gIsIE){
window.frames["HtmlEditor"].focus();
var ran = window.frames["HtmlEditor"].document.selection.createRange();
sLength = ran.text.replace(/\r?\n/g, ' ').length;
if(!sLength) {
ran = window.frames["HtmlEditor"].document.body.createTextRange();
}
var rang = document.selection.createRange();
rang.setEndPoint("StartToStart", ran);
pos = rang.text.replace(/\r?\n/g, ' ').length;
}
}
function setCaret() {
if(gIsIE){
window.frames["HtmlEditor"].focus();
var r = window.frames["HtmlEditor"].document.body.createTextRange();
var textLen = r.text.replace(/\r?\n/g, ' ').length;
r.moveStart('character', pos);
if(sLength) {
var eLen = sLength - (textLen - pos);
r.moveEnd('character', eLen);
} else {
r.collapse(true);
}
r.select();
}
}
function clearLink() {
format("Unlink", false);
}
function createImg(e, show) {
if(typeof show == 'undefined') {
var imgObj = $('imgUrl');
var sPhoto = imgObj.value;
if ((sPhoto!=null) && (sPhoto!="http://")){
setCaret();
format("InsertImage", sPhoto);
}
fHide($('createImg'));
imgObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvImgBox = $("createImg");
var iX = e.clientX;
var iY = e.clientY;
dvImgBox.style.display = "";
dvImgBox.style.left = (iX-300) + "px";
dvImgBox.style.top = 33 + "px";
}
}
function createFlash(e, show) {
if(typeof show == 'undefined') {
var flashtag = '';
var vObj = $('videoUrl');
var sFlash = vObj.value;
if ((sFlash!=null) && (sFlash!="http://")){
setCaret();
var sFlashType = $('vtype').value;
if(sFlashType==1) {
flashtag = '[flash=media]';
} else if(sFlashType==2) {
flashtag = '[flash=real]';
} else if(sFlashType==3) {
flashtag = '[flash=mp3]';
} else {
flashtag = '[flash]';
}
format("insertHTML", flashtag + sFlash + '[/flash]');
}
fHide($('createSwf'));
vObj.value = 'http://';
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvSwfBox = $("createSwf");
var iX = e.clientX;
var iY = e.clientY;
dvSwfBox.style.display = "";
dvSwfBox.style.left = (iX-350) + "px";
dvSwfBox.style.top = 33 + "px";
}
}
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
function fSetBorderMouseOver(obj) {
obj.style.borderRight="1px solid #aaa";
obj.style.borderBottom="1px solid #aaa";
obj.style.borderTop="1px solid #fff";
obj.style.borderLeft="1px solid #fff";
}
function fSetBorderMouseOut(obj) {
obj.style.border="none";
}
function fSetBorderMouseDown(obj) {
obj.style.borderRight="1px #F3F8FC solid";
obj.style.borderBottom="1px #F3F8FC solid";
obj.style.borderTop="1px #cccccc solid";
obj.style.borderLeft="1px #cccccc solid";
}
function fDisplayElement(element,displayValue) {
if(gIEVer<=5.01 && gIsIE){
alert('只支持IE 5.01以上版本');
return;
}
fHideMenu();
if ( typeof element == "string" )
element = $(element);
if (element == null) return;
element.style.display = displayValue;
if(gIsIE){
var e = event;
var target = e.srcElement;
}else{
var e = ev;
var target = e.target;
}
var iX = f_GetX(target);
element.style.display = "";
element.style.left = (iX) + "px";
element.style.top = 33 + "px";
return true;
}
function fSetModeTip(obj){
var x = f_GetX(obj);
var y = f_GetY(obj);
var dvModeTip = $("dvModeTip");
if(!dvModeTip){
var dv = document.createElement("DIV");
dv.style.position = "absolute";
dv.style.top = 33 + "px";
dv.style.left = (x-40) + "px";
dv.style.zIndex = "999";
dv.style.fontSize = "12px";
dv.id = "dvModeTip";
dv.style.padding = "2px";
dv.style.border = "1px #000000 solid";
dv.style.backgroundColor = "#FFFFCC";
dv.innerHTML = "编辑源码";
document.body.appendChild(dv);
}else{
dvModeTip.style.display = "";
}
}
function fHideTip(){
$("dvModeTip").style.display = "none";
}
function f_GetX(e)
{
var l=e.offsetLeft;
while(e=e.offsetParent){
l+=e.offsetLeft;
}
return l;
}
function f_GetY(e)
{
var t=e.offsetTop;
while(e=e.offsetParent){
t+=e.offsetTop;
}
return t;
}
function fHideMenu(){
try{
var arr = ["fontface", "fontsize", "dvForeColor", "dvPortrait", "divAlign", "divList" ,"divInOut", "editFaceBox", "createUrl", "createImg", "createSwf", "createPage"];
for(var i=0;i<arr.length;i++){
var obj = $(arr[i]);
if(obj){
obj.style.display = "none";
}
}
try{
parent.LetterPaper.control(window, "hide");
}catch(exp){}
}catch(exp){}
}
function $(id){
return document.getElementById(id);
}
function fHide(obj){
obj.style.display="none";
}
function pageBreak(e, show) {
if(!show) {
var obj = $('pageTitle');
var title = obj ? obj.value : '';
if(obj) {
obj.value = '';
}
var insertText = title ? '[title='+title+']': '';
setCaret();
format("insertHTML", '###NextPage'+insertText+'###');
fHide($('createPage'));
} else {
if(gIsIE){
var e = window.event;
}
getCaret();
var dvSwfBox = $("createPage");
var iX = e.clientX;
var iY = e.clientY;
dvSwfBox.style.display = "";
dvSwfBox.style.left = (iX-300) + "px";
dvSwfBox.style.top = 33 + "px";
}
}
function changeEditType(flag, ev){
gIsHtml = flag;
try{
var mod = parent.MM["compose"];
mod.html = flag;
}catch(exp){}
try{
var dvhtml = $("dvhtml");
var dvtext = $("dvtext");
var HtmlEditor = window.frames["HtmlEditor"];
var ifmHtmlEditor = $("HtmlEditor");
var sourceEditor = $("sourceEditor");
var switchMode = $("switchMode");
var sourceEditor = $("sourceEditor");
var dvHtmlLnk = $("dvHtmlLnk");
if(flag){
dvhtml.style.display = "";
dvtext.style.display = "none";
dvHtmlLnk.style.display = "none";
if(switchMode.checked){
sourceEditor.value = dvtext.value;
$('uchome-editstatus').value = 'code';
}else{
if(document.all){
HtmlEditor.document.body.innerText = dvtext.value;
} else {
HtmlEditor.document.body.innerHTML = dvtext.value.unescapeHTML();
}
$('uchome-editstatus').value = 'html';
}
}else{
function sub1(){
dvhtml.style.display = "none";
dvtext.style.display = "";
dvHtmlLnk.style.display = "";
if(switchMode.checked){
dvtext.value = sourceEditor.value.unescapeHTML();
}else{
if(document.all){
dvtext.value = HtmlEditor.document.body.innerText;
}else{
dvtext.value = HtmlEditor.document.body.innerHTML.unescapeHTML();
}
}
}
ev = ev || event;
if(ev){
if(window.confirm("转换为纯文本时将会遗失某些格式。\n您确定要继续吗?")){
$('uchome-editstatus').value = 'text';
sub1();
}else{
return;
}
}
}
}catch(exp){
}
}
String.prototype.stripTags = function(){
return this.replace(/<\/?[^>]+>/gi, '');
};
String.prototype.unescapeHTML = function(){
var div = document.createElement('div');
div.innerHTML = this.stripTags();
return div.childNodes[0].nodeValue;
};
var s = "";
var hex = new Array(6)
hex[0] = "FF"
hex[1] = "CC"
hex[2] = "99"
hex[3] = "66"
hex[4] = "33"
hex[5] = "00"
function drawCell(red, green, blue) {
var color = '#' + red + green + blue;
if(color == "#000066") color = "#000000";
s += '<TD BGCOLOR="' + color + '" style="height:12px;width:12px;" >';
s += '<IMG '+ ((document.all)?"":"src='editor_none.gif'") +' HEIGHT=12 WIDTH=12>';
s += '</TD>';
}
function drawRow(red, blue) {
s += '<TR>';
for (var i = 0; i < 6; ++i) {
drawCell(red, hex[i], blue)
}
s += '</TR>';
}
function drawTable(blue) {
s += '<TABLE CELLPADDING=0 CELLSPACING=0 BORDER=0>';
for (var i = 0; i < 6; ++i) {
drawRow(hex[i], blue)
}
s += '</TABLE>';
}
function drawCube() {
s += '<TABLE CELLPADDING=0 CELLSPACING=0 style="border:1px #888888 solid"><TR>';
for (var i = 0; i < 2; ++i) {
s += '<TD BGCOLOR="#FFFFFF">';
drawTable(hex[i])
s += '</TD>';
}
s += '</TR><TR>';
for (var i = 2; i < 4; ++i) {
s += '<TD BGCOLOR="#FFFFFF">';
drawTable(hex[i])
s += '</TD>';
}
s += '</TR></TABLE>';
return s;
}
function EV(){}
EV.getTarget = fGetTarget;
EV.getEvent = fGetEvent;
EV.stopEvent = fStopEvent;
EV.stopPropagation = fStopPropagation;
EV.preventDefault = fPreventDefault;
function fGetTarget(ev, resolveTextNode){
if(!ev) ev = this.getEvent();
var t = ev.target || ev.srcElement;
if (resolveTextNode && t && "#text" == t.nodeName) {
return t.parentNode;
} else {
return t;
}
}
function fGetEvent (e) {
var ev = e || window.event;
if (!ev) {
var c = this.getEvent.caller;
while (c) {
ev = c.arguments[0];
if (ev && Event == ev.constructor) {
break;
}
c = c.caller;
}
}
return ev;
}
function fStopEvent(ev) {
if(!ev) ev = this.getEvent();
this.stopPropagation(ev);
this.preventDefault(ev);
}
function fStopPropagation(ev) {
if(!ev) ev = this.getEvent();
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
}
function fPreventDefault(ev) {
if(!ev) ev = this.getEvent();
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
}
function getExt(path) {
return path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase();
}
function checkURL(obj, mod) {
if(mod) {
if(obj.value == 'http://') {
obj.value = '';
}
} else {
if(obj.value == '') {
obj.value = 'http://';
}
}
} | JavaScript |
function submitForm() {
if (dialogHtml == '') {
dialogHtml = $('siteInfo').innerHTML;
$('siteInfo').innerHTML = '';
}
showWindow(null, dialogHtml, 'html');
$('fwin_null').style.top = '80px';
$('cloud_api_ip').value = cloudApiIp;
return false;
}
function dealHandle(msg) {
getMsg = true;
if (msg['status'] == 'error') {
$('loadinginner').innerHTML = '<font color="red">' + msg['content'] + '</font>';
return;
}
$('loading').style.display = 'none';
$('mainArea').style.display = '';
if(cloudStatus == 'upgrade') {
$('title').innerHTML = msg['cloudIntroduction']['upgrade_title'];
$('msg').innerHTML = msg['cloudIntroduction']['upgrade_content'];
} else {
$('title').innerHTML = msg['cloudIntroduction']['open_title'];
$('msg').innerHTML = msg['cloudIntroduction']['open_content'];
}
if (msg['navSteps']) {
$('nav_steps').innerHTML = msg['navSteps'];
}
if (msg['protocalUrl']) {
$('protocal_url').href = msg['protocalUrl'];
}
if (msg['cloudApiIp']) {
cloudApiIp = msg['cloudApiIp'];
}
if (msg['manyouUpdateTips']) {
$('manyou_update_tips').innerHTML = msg['manyouUpdateTips'];
}
}
function expiration() {
if(!getMsg) {
$('loadinginner').innerHTML = '<font color="red">' + expirationText + '</font>';
clearTimeout(expirationTimeout);
}
} | JavaScript |
var j = jQuery.noConflict();
if (typeof disallowfloat == 'undefined' || disallowfloat === null) {
var disallowfloat = '';
}
var currentNormalEditDisplay = 0;
j(document).ready(function() {
ajaxGetSearchResultThreads();
j('#previewForm').submit(function() {
return previewFormSubmit();
});
});
function previewFormSubmit() {
saveAllThread();
if (!selectedTopicId || selectedNormalIds.length < 1) {
alert('请至少推送一条头条主题和一条列表主题');
return false;
}
var i = 1;
for (var k = 1; k <= 5; k++) {
var input_displayorder = j('#normal_thread_' + k).find('.preview_displayorder');
if (input_displayorder.size()) {
input_displayorder.val(i);
i++;
}
}
return true;
}
function initSelect() {
var initTopicObj = j('#search_result .qqqun_op .qqqun_op_topon');
initTopicObj.addClass('qqqun_op_top');
initTopicObj.removeClass('qqqun_op_topon');
var initNormalObj = j('#search_result .qqqun_op .qqqun_op_liston');
initNormalObj.addClass('qqqun_op_list');
initNormalObj.removeClass('qqqun_op_liston');
selectedTopicId = parseInt(selectedTopicId);
if (selectedTopicId) {
j('#thread_addtop_' + selectedTopicId).addClass('qqqun_op_topon');
j('#thread_addtop_' + selectedTopicId).removeClass('qqqun_op_top');
}
j.each(selectedNormalIds, function(k, v) {
v = parseInt(v);
if (v) {
j('#thread_addlist_' + v).addClass('qqqun_op_liston');
j('#thread_addlist_' + v).removeClass('qqqun_op_list');
}
});
}
function ajaxChangeSearch() {
j('#srchtid').val('');
ajaxGetSearchResultThreads();
}
function ajaxGetSearchResultThreads() {
j('#search_result').html('<tr><td colspan="3">加载中...</td></tr>');
ajaxpost('search_form', 'search_result', null, null, null, function() {initSelect(); return false});
return false;
}
function ajaxGetPageResultThreads(page, mpurl) {
j('#search_result').html('<tr><td colspan="3">加载中...</td></tr>');
if (typeof page == 'undefined' || page === null) {
page = 1;
}
if (typeof mpurl == 'undefined' || !mpurl) {
return false;
}
ajaxget(mpurl + '&page=' + page, 'search_result', null, null, null, function() {initSelect();} );
}
function addMiniportalTop(tid) {
tid = parseInt(tid);
if (j.inArray(tid, selectedNormalIds) > -1) {
removeNormalThreadByTid(tid);
}
addMiniportalTopId(tid);
initSelect();
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread&tid=' + tid, 'topicDiv', null, null, null, function() { clickTopicEditor(); });
}
function addMiniportalTopId(tid) {
selectedTopicId = tid;
}
function showPreviewEditor(topic, hideall) {
if (hideall) {
j('.qqqun_list .qqqun_editor').hide();
j('.qqqun_list .qqqun_xl li').removeClass('current');
j('.qqqun_list').removeClass('qqqun_list_editor');
j('.qqqun_top .qqqun_editor').hide();
j('.qqqun_top').removeClass('qqqun_top_editor');
} else {
if (topic) {
j('.qqqun_list .qqqun_editor').hide();
j('.qqqun_list .qqqun_xl li').removeClass('current');
j('.qqqun_list').removeClass('qqqun_list_editor');
j('.qqqun_top .qqqun_editor').show();
j('.qqqun_top').addClass('qqqun_top_editor');
} else {
j('.qqqun_list .qqqun_editor').show();
j('.qqqun_list').addClass('qqqun_list_editor');
j('.qqqun_list .qqqun_xl li').removeClass('current');
j('.qqqun_top .qqqun_editor').hide();
j('.qqqun_top').removeClass('qqqun_top_editor');
}
}
}
function clickTopicEditor(topicFocus) {
if (typeof topicFocus == 'undefined') {
var topicFocus = 'title';
}
showPreviewEditor(true, false);
if (topicFocus == 'title') {
j('#topic-editor-input-title').addClass('pt_focus');
j('#topic-editor-input-title').focus();
} else if (topicFocus == 'content') {
j('#topic-editor-textarea-content').addClass('pt_focus');
j('#topic-editor-textarea-content').focus();
}
currentNormalEditDisplay = 0;
}
function blurTopic(obj) {
var thisobj = j(obj);
thisobj.removeClass('pt_focus');
}
function clickNormalEditor(obj) {
var thisobj = j(obj);
showPreviewEditor(false, false);
thisobj.addClass('pt_focus');
thisobj.focus();
currentNormalEditDisplay = parseInt(thisobj.parent().attr('displayorder'));
}
function blurNormalTextarea(obj) {
var thisobj = j(obj);
liObj = thisobj.parent();
var displayorder = parseInt(liObj.attr('displayorder'));
if (displayorder == currentNormalEditDisplay) {
liObj.addClass('current');
}
j('.qqqun_list .qqqun_xl textarea').removeClass('pt_focus');
}
function addMiniportalList(tid) {
tid = parseInt(tid);
if (j.inArray(tid, selectedNormalIds) > -1) {
return false;
}
if (selectedNormalIds.length >= 5) {
alert('推送帖子已达到5条,请在右侧取消一些再重试。');
return false;
}
if (tid == selectedTopicId) {
selectedTopicId = 0;
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread&tid=0', 'topicDiv');
}
addMiniportalListId(tid);
initSelect();
var insertPos = 'normal_thread_' + selectedNormalIds.length;
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getNormalThread&tid=' + tid, insertPos, null, null, null, function() { clickNormalEditor(j('#' + insertPos).find('textarea')); });
}
function addMiniportalListId(tid) {
selectedNormalIds.push(tid);
}
function editNormalThread() {
var threadLi = j('#normal_thread_' + currentNormalEditDisplay);
clickNormalEditor(threadLi.find('textarea'));
}
function saveAllThread() {
showPreviewEditor(false, true);
currentNormalEditDisplay = 0;
}
function moveNormalThread(up) {
var displayorder = currentNormalEditDisplay;
var threadLi = j('#normal_thread_' + displayorder);
if (!threadLi.attr('id') || !displayorder) {
return false;
}
var newDisplayorder = 0;
if (up) {
newDisplayorder = displayorder - 1;
} else {
newDisplayorder = displayorder + 1;
}
if (newDisplayorder < 1 || newDisplayorder > 5) {
return false;
}
var newLiId = 'normal_thread_' + newDisplayorder;
var newThreadLi = j('#' + newLiId);
if (!newThreadLi.find('textarea').size()) {
return false;
}
var tmpHtml = newThreadLi.html();
newThreadLi.html(threadLi.html());
threadLi.html(tmpHtml);
newThreadLi.addClass('current');
threadLi.removeClass('current');
currentNormalEditDisplay = newDisplayorder;
}
function removeTopicThread(tid) {
tid = parseInt(tid);
selectedTopicId = 0;
initSelect();
ajaxget(adminscript + '?action=cloud&operation=qqgroup&anchor=block&op=getTopicThread', 'topicDiv', null, null, null, function() { showPreviewEditor(false, true)});
}
function removeNormalThread() {
var displayorder = currentNormalEditDisplay;
var removeTid = parseInt(j('#normal_thread_' + displayorder).find('.normal_thread_tid').val());
return removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, true);
}
function removeNormalThreadByTid(tid) {
tid = parseInt(tid);
var threadInput = j('.qqqun_list .qqqun_xl .normal_thread_tid[value="' + tid + '"]');
if (threadInput.size()) {
var displayorder = threadInput.parent().attr('displayorder');
var removeTid = tid;
return removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, false);
}
}
function removeNormalThreadByDisplayorderAndTid(displayorder, removeTid, inNormalEditor) {
displayorder = parseInt(displayorder);
removeTid = parseInt(removeTid);
var threadLi = j('#normal_thread_' + displayorder);
if (!threadLi.attr('id') || !displayorder) {
return false;
}
threadLi.removeClass('current');
var index = j.inArray(removeTid, selectedNormalIds);
if (index != -1) {
selectedNormalIds.splice(index, 1);
}
initSelect();
if (typeof inNormalEditor == 'udefined') {
var inNormalEditor = false;
}
threadLi.slideUp(100, function() { removeNormalThreadRecall(displayorder, inNormalEditor)});
}
function removeNormalThreadRecall(displayorder, inNormalEditor) {
for (var i = displayorder; i <= 5; i++) {
var currentDisplayorder = i;
var nextDisplayorder = i + 1;
var currentLiId = 'normal_thread_' + currentDisplayorder;
var currentThreadLi = j('#' + currentLiId);
var nextLiId = 'normal_thread_' + nextDisplayorder;
var nextThreadLi = j('#' + nextLiId);
if (nextThreadLi.find('textarea').size()) {
currentThreadLi.html(nextThreadLi.html());
currentThreadLi.show();
} else {
currentThreadLi.html('');
currentThreadLi.hide();
break;
}
}
var threadLi = j('#normal_thread_' + displayorder);
var prevDisplayorder = displayorder - 1;
if (threadLi.find('textarea').size()) {
if (inNormalEditor) {
threadLi.addClass('current');
}
currentNormalEditDisplay = displayorder;
} else if (prevDisplayorder) {
var prevThreadLi = j('#normal_thread_' + prevDisplayorder);
if (inNormalEditor) {
prevThreadLi.addClass('current');
}
currentNormalEditDisplay = prevDisplayorder;
} else {
var firstThreadLi = j('#normal_thread_1');
if (inNormalEditor) {
saveAllThread();
}
firstThreadLi.html('<div class="tips">点击左侧 <img src="static/image/admincp/cloud/qun_op_list.png" align="absmiddle" /> 将信息推送到列表</div>');
firstThreadLi.show();
}
}
function ajaxUploadQQGroupImage() {
j('#uploadImageResult').parent().show();
j('#uploadImageResult').text('图片上传中,请稍后...');
ajaxpost('uploadImage', 'uploadImageResult', null, null, null, 'uploadRecall()');
}
function uploadRecall() {
if(j('#uploadImageResult').find('#upload_msg_success').size()) {
j('#uploadImageResult').parent().show();
var debug_rand = Math.random();
var imagePath = j('#uploadImageResult #upload_msg_imgpath').text();
var imageUrl = j('#uploadImageResult #upload_msg_imgurl').text();
j('#topic_image_value').val(imagePath);
j('#topic_editor_thumb').attr('src', imageUrl + '?' + debug_rand);
j('#topic_preview_thumb').attr('src', imageUrl + '?' + debug_rand);
setTimeout(function() {hideWindow('uploadImgWin');}, 2000);
}
} | JavaScript |
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function $(id) {
return document.getElementById(id);
}
Array.prototype.push = function(value) {
this[this.length] = value;
return this.length;
}
function getcookie(name) {
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
seconds = seconds ? seconds : 8400000;
var expires = new Date();
expires.setTime(expires.getTime() + seconds);
document.cookie = escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
function _cancelBubble(e, returnValue) {
if(!e) return ;
if(is_ie) {
if(!returnValue) e.returnValue = false;
e.cancelBubble = true;
} else {
e.stopPropagation();
if(!returnValue) e.preventDefault();
}
}
function checkall(name) {
var e = is_ie ? event : checkall.caller.arguments[0];
obj = is_ie ? e.srcElement : e.target;
var arr = document.getElementsByName(name);
var k = arr.length;
for(var i=0; i<k; i++) {
arr[i].checked = obj.checked;
}
}
function getposition(obj) {
var r = new Array();
r['x'] = obj.offsetLeft;
r['y'] = obj.offsetTop;
while(obj = obj.offsetParent) {
r['x'] += obj.offsetLeft;
r['y'] += obj.offsetTop;
}
return r;
}
function addMouseEvent(obj){
var checkbox,atr,ath,i;
atr=obj.getElementsByTagName("tr");
for(i=0;i<atr.length;i++){
atr[i].onclick=function(){
ath=this.getElementsByTagName("th");
checkbox=this.getElementsByTagName("input")[0];
if(!ath.length && checkbox.getAttribute("type")=="checkbox"){
if(this.className!="currenttr"){
this.className="currenttr";
checkbox.checked=true;
}else{
this.className="";
checkbox.checked=false;
}
}
}
}
}
// editor.js
if(is_ie) document.documentElement.addBehavior("#default#userdata");
function setdata(key, value){
if(is_ie){
document.documentElement.load(key);
document.documentElement.setAttribute("value", value);
document.documentElement.save(key);
return document.documentElement.getAttribute("value");
} else {
sessionStorage.setItem(key,value);
}
}
function getdata(key){
if(is_ie){
document.documentElement.load(key);
return document.documentElement.getAttribute("value");
} else {
return sessionStorage.getItem(key) && sessionStorage.getItem(key).toString().length == 0 ? '' : (sessionStorage.getItem(key) == null ? '' : sessionStorage.getItem(key));
}
}
function form_option_selected(obj, value) {
for(var i=0; i<obj.options.length; i++) {
if(obj.options[i].value == value) {
obj.options[i].selected = true;
}
}
}
function switchcredit(obj, value) {
var creditsettings = credit[value];
var s = '<select name="credit' + obj + '">';
for(var i in creditsettings) {
s += '<option value="' + creditsettings[i][0] + '">' + creditsettings[i][1] + '</option>';
}
s += '</select>';
$(obj).innerHTML = s;
}
function setselect(selectobj, value) {
var len = selectobj.options.length;
for(i = 0;i < len;i++) {
if(selectobj.options[i].value == value) {
selectobj.options[i].selected = true;
}
}
}
function show(id, display) {
if(!$(id)) return false;
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
} | JavaScript |
//Common
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);
function isUndefined(variable) {
return typeof variable == 'undefined' ? true : false;
}
function $(id) {
return document.getElementById(id);
}
function fetchOffset(obj) {
var left_offset = obj.offsetLeft;
var top_offset = obj.offsetTop;
while((obj = obj.offsetParent) != null) {
left_offset += obj.offsetLeft;
top_offset += obj.offsetTop;
}
return { 'left' : left_offset, 'top' : top_offset };
}
function _attachEvent(obj, evt, func) {
if(obj.addEventListener) {
obj.addEventListener(evt, func, false);
} else if(obj.attachEvent) {
obj.attachEvent("on" + evt, func);
}
}
function strlen(str) {
return (is_ie && str.indexOf('\n') != -1) ? str.replace(/\r?\n/g, '_').length : str.length;
}
//Menu
var menus = new menu_handler();
function menu_handler() {
this.menu = Array();
}
function menuitems() {
this.ctrlobj = null,
this.menuobj = null;
this.parentids = Array();
this.allowhide = 1;
this.hidelock = 0;
this.clickstatus = 0;
}
function menuobjpos(id, offset) {
if(!menus.menu[id]) {
return;
}
if(!offset) {
offset = 0;
}
var showobj = menus.menu[id].ctrlobj;
var menuobj = menus.menu[id].menuobj;
showobj.pos = fetchOffset(showobj);
showobj.X = showobj.pos['left'];
showobj.Y = showobj.pos['top'];
showobj.w = showobj.offsetWidth;
showobj.h = showobj.offsetHeight;
menuobj.w = menuobj.offsetWidth;
menuobj.h = menuobj.offsetHeight;
if(offset < 3) {
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + 'px';
menuobj.style.top = offset == 1 ? showobj.Y + 'px' : (offset == 2 || ((showobj.Y + showobj.h + menuobj.h > document.documentElement.scrollTop + document.documentElement.clientHeight) && (showobj.Y - menuobj.h >= 0)) ? (showobj.Y - menuobj.h) + 'px' : showobj.Y + showobj.h + 'px');
} else if(offset == 3) {
menuobj.style.left = (document.body.clientWidth - menuobj.clientWidth) / 2 + document.body.scrollLeft + 'px';
menuobj.style.top = (document.body.clientHeight - menuobj.clientHeight) / 2 + document.body.scrollTop + 'px';
} else if(offset == 4) {
menuobj.style.left = (showobj.X + menuobj.w > document.body.clientWidth) && (showobj.X + showobj.w - menuobj.w >= 0) ? showobj.X + showobj.w - menuobj.w + 'px' : showobj.X + showobj.w + 'px';
menuobj.style.top = showobj.Y + 'px';
}
if(menuobj.style.clip && !is_opera) {
menuobj.style.clip = 'rect(auto, auto, auto, auto)';
}
}
function showmenu(event, id, click, position) {
if(isUndefined(click)) click = false;
if(!menus.menu[id]) {
menus.menu[id] = new menuitems();
menus.menu[id].ctrlobj = $(id);
if(!menus.menu[id].ctrlobj.getAttribute('parentmenu')) {
menus.menu[id].parentids = Array();
} else {
menus.menu[id].parentids = menus.menu[id].ctrlobj.getAttribute('parentmenu').split(',');
}
menus.menu[id].menuobj = $(id + '_menu');
menus.menu[id].menuobj.style.position = 'absolute';
if(event.type == 'mouseover') {
_attachEvent(menus.menu[id].ctrlobj, 'mouseout', function() { setTimeout(function() {hidemenu(id)}, 100); });
_attachEvent(menus.menu[id].menuobj, 'mouseover', function() { lockmenu(id, 0); });
_attachEvent(menus.menu[id].menuobj, 'mouseout', function() { lockmenu(id, 1);setTimeout(function() {hidemenu(id)}, 100); });
} else if(click || event.type == 'click') {
menus.menu[id].clickstatus = 1;
lockmenu(id, 0);
}
} else if(menus.menu[id].clickstatus == 1) {
lockmenu(id, 1);
hidemenu(id);
menus.menu[id].clickstatus = 0;
return;
}
menuobjpos(id, position);
menus.menu[id].menuobj.style.display = '';
}
function hidemenu(id) {
if(!menus.menu[id] || !menus.menu[id].allowhide || menus.menu[id].hidelock) {
return;
}
menus.menu[id].menuobj.style.display = 'none';
}
function lockmenu(id, value) {
if(!menus.menu[id]) {
return;
}
for(i = 0;i < menus.menu[id].parentids.length;i++) {
menus.menu[menus.menu[id].parentids[i]].hidelock = value == 0 ? 1 : 0;
}
menus.menu[id].allowhide = value;
}
//Editor
var lang = new Array();
function insertunit(text, textend, moveend) {
$('pm_textarea').focus();
textend = isUndefined(textend) ? '' : textend;
moveend = isUndefined(textend) ? 0 : moveend;
startlen = strlen(text);
endlen = strlen(textend);
if(!isUndefined($('pm_textarea').selectionStart)) {
var opn = $('pm_textarea').selectionStart + 0;
if(textend != '') {
text = text + $('pm_textarea').value.substring($('pm_textarea').selectionStart, $('pm_textarea').selectionEnd) + textend;
}
$('pm_textarea').value = $('pm_textarea').value.substr(0, $('pm_textarea').selectionStart) + text + $('pm_textarea').value.substr($('pm_textarea').selectionEnd);
if(!moveend) {
$('pm_textarea').selectionStart = opn + strlen(text) - endlen;
$('pm_textarea').selectionEnd = opn + strlen(text) - endlen;
}
} else if(document.selection && document.selection.createRange) {
var sel = document.selection.createRange();
if(textend != '') {
text = text + sel.text + textend;
}
sel.text = text.replace(/\r?\n/g, '\r\n');
if(!moveend) {
sel.moveStart('character', -endlen);
sel.moveEnd('character', -endlen);
}
sel.select();
} else {
$('pm_textarea').value += text;
}
}
function getSel() {
if(!isUndefined($('pm_textarea').selectionStart)) {
return $('pm_textarea').value.substr($('pm_textarea').selectionStart, $('pm_textarea').selectionEnd - $('pm_textarea').selectionStart);
} else if(document.selection && document.selection.createRange) {
return document.selection.createRange().text;
} else if(window.getSelection) {
return window.getSelection() + '';
} else {
return false;
}
}
function insertlist(type) {
txt = getSel();
type = isUndefined(type) ? '' : '=' + type;
if(txt) {
var regex = new RegExp('([\r\n]+|^[\r\n]*)(?!\\[\\*\\]|\\[\\/?list)(?=[^\r\n])', 'gi');
txt = '[list' + type + ']\n' + txt.replace(regex, '$1[*]') + '\n' + '[/list]';
insertunit(txt);
} else {
insertunit('[list' + type + ']\n', '[/list]');
while(listvalue = prompt(lang['pm_prompt_list'], '')) {
if(is_opera > 8) {
listvalue = '\n' + '[*]' + listvalue;
insertunit(listvalue);
} else {
listvalue = '[*]' + listvalue + '\n';
insertunit(listvalue);
}
}
}
}
function inserttag(tag, type) {
txt = getSel();
type = isUndefined(type) ? 0 : type;
if(!type) {
if(!txt) {
txt = prompt(lang['pm_prompt_' + tag], '')
}
if(txt) {
insertunit('[' + tag + ']' + txt + '[/' + tag + ']');
}
} else {
txt1 = prompt(lang['pm_prompt_' + tag], '');
if(!txt) {
txt = txt1;
}
if(txt1) {
insertunit('[' + tag + '=' + txt1 + ']' + txt + '[/' + tag + ']');
}
}
} | JavaScript |
var controlid = null;
var currdate = null;
var startdate = null;
var enddate = null;
var yy = null;
var mm = null;
var hh = null;
var ii = null;
var currday = null;
var addtime = false;
var today = new Date();
var lastcheckedyear = false;
var lastcheckedmonth = false;
function loadcalendar() {
s = '';
s += '<div id="calendar" style="display:none; position:absolute;z-index:100;" onclick="_cancelBubble(event)">';
s += '<iframe id="calendariframe" frameborder="0" style="height:200px; z-index: 110; position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"></iframe>';
s += '<div style="padding:5px; width: 210px; border: 1px solid #B5CFD9; background:#F2F9FD; position: absolute; z-index: 120">';
s += '<table cellspacing="0" cellpadding="0" width="100%" style="text-align: center;" class="table1">';
s += '<thead>';
s += '<tr align="center" id="calendar_week">';
s += '<th><a href="###" onclick="refreshcalendar(yy, mm-1)" title="上一月">《</a></th>';
s += '<th colspan="5" style="text-align: center"><a href="###" onclick="showdiv(\'year\');_cancelBubble(event)" title="点击选择年份" id="year"></a> - <a id="month" title="点击选择月份" href="###" onclick="showdiv(\'month\');_cancelBubble(event)"></a></th>';
s += '<th><A href="###" onclick="refreshcalendar(yy, mm+1)" title="下一月">》</A></th>';
s += '</tr>';
s += '<tr id="calendar_header"><td>日</td><td>一</td><td>二</td><td>三</td><td>四</td><td>五</td><td>六</td></tr>';
s += '</thead>';
s += '<tbody>';
for(var i = 0; i < 6; i++) {
s += '<tr>';
for(var j = 1; j <= 7; j++)
s += "<td id=d" + (i * 7 + j) + " height=\"19\">0</td>";
s += "</tr>";
}
s += '<tr id="hourminute"><td colspan="7" align="center"><input type="text" size="2" value="" id="hour" onKeyUp=\'this.value=this.value > 23 ? 23 : zerofill(this.value);controlid.value=controlid.value.replace(/\\d+(\:\\d+)/ig, this.value+"$1")\'> 点 <input type="text" size="2" value="" id="minute" onKeyUp=\'this.value=this.value > 59 ? 59 : zerofill(this.value);controlid.value=controlid.value.replace(/(\\d+\:)\\d+/ig, "$1"+this.value)\'> 分</td></tr>';
s += '</tbody>';
s += '</table></div></div>';
s += '<div id="calendar_year" onclick="_cancelBubble(event)" style="display: none; z-index: 130;" class="calendarmenu"><div class="col" style="float: left; margin-right: 5px;">';
for(var k = 1930; k <= 2019; k++) {
s += k != 1930 && k % 10 == 0 ? '</div><div style="float: left; margin-right: 5px;">' : '';
s += '<a href="###" onclick="refreshcalendar(' + k + ', mm);$(\'calendar_year\').style.display=\'none\'"><span' + (today.getFullYear() == k ? ' class="bold"' : '') + ' id="calendar_year_' + k + '">' + k + '</span></a><br />';
}
s += '</div></div>';
s += '<div id="calendar_month" onclick="_cancelBubble(event)" style="display: none; padding: 3px; z-index: 140" class="calendarmenu">';
for(var k = 1; k <= 12; k++) {
s += '<a href="###" onclick="refreshcalendar(yy, ' + (k - 1) + ');$(\'calendar_month\').style.display=\'none\'; "><span' + (today.getMonth()+1 == k ? ' class="bold"' : '') + ' id="calendar_month_' + k + '">' + k + ( k < 10 ? ' ' : '') + ' 月</span></a><br />';
}
s += '</div>';
var div = document.createElement('div');
div.innerHTML = s;
$('append').appendChild(div);
_attachEvent(document, 'click', function() {
$('calendar').style.display = 'none';
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
});
$('calendar').onclick = function(e) {
e = is_ie ? event : e;
_cancelBubble(e);
$('calendar_year').style.display = 'none';
$('calendar_month').style.display = 'none';
}
}
function parsedate(s) {
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec(s);
var m1 = (RegExp.$1 && RegExp.$1 > 1899 && RegExp.$1 < 2101) ? parseFloat(RegExp.$1) : today.getFullYear();
var m2 = (RegExp.$2 && (RegExp.$2 > 0 && RegExp.$2 < 13)) ? parseFloat(RegExp.$2) : today.getMonth() + 1;
var m3 = (RegExp.$3 && (RegExp.$3 > 0 && RegExp.$3 < 32)) ? parseFloat(RegExp.$3) : today.getDate();
var m4 = (RegExp.$4 && (RegExp.$4 > -1 && RegExp.$4 < 24)) ? parseFloat(RegExp.$4) : 0;
var m5 = (RegExp.$5 && (RegExp.$5 > -1 && RegExp.$5 < 60)) ? parseFloat(RegExp.$5) : 0;
/(\d+)\-(\d+)\-(\d+)\s*(\d*):?(\d*)/.exec("0000-00-00 00\:00");
return new Date(m1, m2 - 1, m3, m4, m5);
}
function settime(d) {
$('calendar').style.display = 'none';
$('calendar_month').style.display = 'none';
controlid.value = yy + "-" + zerofill(mm + 1) + "-" + zerofill(d) + (addtime ? ' ' + zerofill($('hour').value) + ':' + zerofill($('minute').value) : '');
}
function showcalendar(addtime1, startdate1, enddate1) {
e = is_ie ? event : showcalendar.caller.arguments[0];
controlid1 = is_ie ? e.srcElement : e.target;
controlid = controlid1;
addtime = addtime1;
startdate = startdate1 ? parsedate(startdate1) : false;
enddate = enddate1 ? parsedate(enddate1) : false;
currday = controlid.value ? parsedate(controlid.value) : today;
hh = currday.getHours();
ii = currday.getMinutes();
var p = getposition(controlid);
$('calendar').style.display = 'block';
$('calendar').style.left = p['x']+'px';
$('calendar').style.top = (p['y'] + 20)+'px';
_cancelBubble(e);
refreshcalendar(currday.getFullYear(), currday.getMonth());
if(lastcheckedyear != false) {
$('calendar_year_' + lastcheckedyear).className = '';
$('calendar_year_' + today.getFullYear()).className = 'bold';
}
if(lastcheckedmonth != false) {
$('calendar_month_' + lastcheckedmonth).className = '';
$('calendar_month_' + (today.getMonth() + 1)).className = 'bold';
}
$('calendar_year_' + currday.getFullYear()).className = 'error bold';
$('calendar_month_' + (currday.getMonth() + 1)).className = 'error bold';
$('hourminute').style.display = addtime ? '' : 'none';
lastcheckedyear = currday.getFullYear();
lastcheckedmonth = currday.getMonth() + 1;
}
function refreshcalendar(y, m) {
var x = new Date(y, m, 1);
var mv = x.getDay();
var d = x.getDate();
var dd = null;
yy = x.getFullYear();
mm = x.getMonth();
$("year").innerHTML = yy;
$("month").innerHTML = mm + 1 > 9 ? (mm + 1) : '0' + (mm + 1);
for(var i = 1; i <= mv; i++) {
dd = $("d" + i);
dd.innerHTML = " ";
dd.className = "";
}
while(x.getMonth() == mm) {
dd = $("d" + (d + mv));
dd.innerHTML = '<a href="###" onclick="settime(' + d + ');return false">' + d + '</a>';
if(x.getTime() < today.getTime() || (enddate && x.getTime() > enddate.getTime()) || (startdate && x.getTime() < startdate.getTime())) {
dd.className = 'grey';
} else {
dd.className = '';
}
if(x.getFullYear() == today.getFullYear() && x.getMonth() == today.getMonth() && x.getDate() == today.getDate()) {
dd.className = 'bold';
dd.firstChild.title = '今天';
}
if(x.getFullYear() == currday.getFullYear() && x.getMonth() == currday.getMonth() && x.getDate() == currday.getDate()) {
dd.className = 'error bold';
}
x.setDate(++d);
}
while(d + mv <= 42) {
dd = $("d" + (d + mv));
dd.innerHTML = " ";
d++;
}
if(addtime) {
$('hour').value = zerofill(hh);
$('minute').value = zerofill(ii);
}
}
function showdiv(id) {
var p = getposition($(id));
$('calendar_' + id).style.left = p['x']+'px';
$('calendar_' + id).style.top = (p['y'] + 16)+'px';
$('calendar_' + id).style.display = 'block';
}
function zerofill(s) {
var s = parseFloat(s.toString().replace(/(^[\s0]+)|(\s+$)/g, ''));
s = isNaN(s) ? 0 : s;
return (s < 10 ? '0' : '') + s.toString();
}
window.onload = function() {
loadcalendar();
} | JavaScript |
var Ajaxs = new Array();
function Ajax(waitId) {
var aj = new Object();
aj.waitId = waitId ? $(waitId) : null;
aj.targetUrl = '';
aj.sendString = '';
aj.resultHandle = null;
aj.loading = '<img src="image/common/loading.gif" style="margin: 3px; vertical-align: middle" />Loading... ';
aj.createXMLHttpRequest = function() {
var request = false;
if(window.XMLHttpRequest) {
request = new XMLHttpRequest();
if(request.overrideMimeType) request.overrideMimeType('text/xml');
} else if(window.ActiveXObject) {
var versions = ['Microsoft.XMLHTTP', 'MSXML.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'];
for(var i=0; i<versions.length; i++) {
try {
request = new ActiveXObject(versions[i]);
if(request) return request;
} catch(e) {/*alert(e.message);*/}
}
}
return request;
}
aj.request = aj.createXMLHttpRequest();
if(aj.waitId) {
aj.waitId.orgdisplay = aj.waitId.style.display;
aj.waitId.style.display = '';
aj.waitId.innerHTML = aj.loading;
}
aj.processHandle = function() {
if(aj.request.readyState == 4 && aj.request.status == 200) {
for(k in Ajaxs) {
if(Ajaxs[k] == aj.targetUrl) Ajaxs[k] = null;
}
if(aj.waitId) {
aj.waitId.style.display = 'none';
aj.waitId.style.display = aj.waitId.orgdisplay;
}
aj.resultHandle(aj.request.responseXML.lastChild.firstChild.nodeValue);
}
}
aj.get = function(targetUrl, resultHandle) {
if(in_array(targetUrl, Ajaxs)) {
return false;
} else {
Ajaxs.push(targetUrl);
}
aj.targetUrl = targetUrl;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
if(window.XMLHttpRequest) {
aj.request.open('GET', aj.targetUrl);
aj.request.send(null);
} else {
aj.request.open("GET", targetUrl, true);
aj.request.send();
}
}
/* aj.post = function(targetUrl, sendString, resultHandle) {
aj.targetUrl = targetUrl;
aj.sendString = sendString;
aj.request.onreadystatechange = aj.processHandle;
aj.resultHandle = resultHandle;
aj.request.open('POST', targetUrl);
aj.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
aj.request.send(aj.sendString);
}*/
return aj;
}
function show(id, display) {
if(display == 'auto') {
$(id).style.display = $(id).style.display == '' ? 'none' : '';
} else {
$(id).style.display = display;
}
}
/*
ajaxget('www.baidu.com', 'showid', 'waitid', 'display(\'showid\', 1)');
*/
function ajaxget(url, showId, waitId, display, recall) {
e = is_ie ? event : ajaxget.caller.arguments[0];
ajaxget2(e, url, showId, waitId, display, recall);
_cancelBubble(e);
}
function ajaxget2(e, url, showId, waitId, display, recall) {
target = e ? (is_ie ? e.srcElement : e.target) : null;
display = display ? display : '';
var x = new Ajax(waitId);
x.showId = showId;
x.display = display;
var sep = url.indexOf('?') != -1 ? '&' : '?';
x.target = target;
x.recall = recall;
x.get(url+sep+'inajax=1', function(s) {
if(x.display == 'auto' && x.target) {
x.target.onclick = newfunc('show', x.showId, 'auto');
}
show(x.showId, x.display);
$(x.showId).innerHTML = s;
evalscript(s);
if(x.recall)eval(x.recall);
});
_cancelBubble(e);
}
/*
function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}*/
var evalscripts = new Array();
function evalscript(s) {
if(!s || s.indexOf('<script') == -1) return s;
var p = /<script[^\>]*?src=\"([^\x00]+?)\"[^\>]*( reload=\"1\")?><\/script>/ig;
var arr = new Array();
while(arr = p.exec(s)) appendscript(arr[1], '', arr[2]);
p = /<script[^\>]*?( reload=\"1\")?>([^\x00]+?)<\/script>/ig;
while(arr = p.exec(s)) appendscript('', arr[2], arr[1]);
return s;
}
function appendscript(src, text, reload) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
if(src) {
scriptNode.src = src;
} else if(text){
scriptNode.text = text;
}
$('append').appendChild(scriptNode);
}
// 得到一个定长的 hash 值, 依赖于 stringxor()
function hash(string, length) {
var length = length ? length : 32;
var start = 0;
var i = 0;
var result = '';
filllen = length - string.length % length;
for(i = 0; i < filllen; i++){
string += "0";
}
while(start < string.length) {
result = stringxor(result, string.substr(start, length));
start += length;
}
return result;
}
function stringxor(s1, s2) {
var s = '';
var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var max = Math.max(s1.length, s2.length);
for(var i=0; i<max; i++) {
var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
s += hash.charAt(k % 52);
}
return s;
}
function in_array(needle, haystack) {
for(var i in haystack) {if(haystack[i] == needle) return true;}
return false;
}
function newfunc(func){
var args = new Array();
for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
return function(e){
window[func].apply(window, args);
_cancelBubble(is_ie ? event : e);
}
}
function ajaxmenu(url, position) {
e = is_ie ? event : ajaxmenu.caller.arguments[0];
controlid = is_ie ? e.srcElement : e.target;
var menuid = hash(url);// 使每个 url 对应一个弹出层,避免重复请求
createmenu(menuid);
showmenu2(e, menuid, position, controlid);
if(!$(menuid).innerHTML) {
ajaxget2(e, url, menuid, menuid, '', "setposition('" + menuid + "', '" + position + "', '" + controlid + "')");
} else {
//alert(menuid.innerHTML);
}
_cancelBubble(e);
}
var ajaxpostHandle = null;
function ajaxpost(formid, showid, recall) {
var ajaxframeid = 'ajaxframe';
var ajaxframe = $(ajaxframeid);
if(ajaxframe == null) {
if (is_ie) {
ajaxframe = document.createElement("<iframe name='" + ajaxframeid + "' id='" + ajaxframeid + "'></iframe>");
} else {
ajaxframe = document.createElement("iframe");
ajaxframe.name = ajaxframeid;
ajaxframe.id = ajaxframeid;
}
ajaxframe.style.display = 'none';
$('append').appendChild(ajaxframe);
}
$(formid).target = ajaxframeid;
ajaxpostHandle = [formid, showid, ajaxframeid, recall];
_attachEvent(ajaxframe, 'load', ajaxpost_load);
$(formid).submit();
return false;
}
function ajaxpost_load() {
var s = (is_ie && $(ajaxpostHandle[2])) ? $(ajaxpostHandle[2]).contentWindow.document.XMLDocument.text : $(ajaxpostHandle[2]).contentWindow.document.documentElement.firstChild.nodeValue;
evalscript(s);
if(s) {
// setMenuPosition($(ajaxpostHandle[0]).ctrlid, 0);
$(ajaxpostHandle[1]).innerHTML = s;
if(ajaxpostHandle[3]) {
eval(ajaxpostHandle[3]);
}
// setTimeout("hideMenu()", 3000);
}
// $(ajaxpostHandle[2]).target = ajaxpostHandle[3];
// ajaxpostHandle = null;
}
| JavaScript |
/*
[Discuz!] (C)2001-2009 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: soso_smilies.js 84 2011-02-28 14:15:44Z yexinhao $
*/
var sosojs = document.createElement('script');
sosojs.type = 'text/javascript';
sosojs.charset = "utf-8";
sosojs.src = 'http://bq.soso.com/js/sosoexp_platform.js';
var sosolo = document.getElementsByTagName('script')[0];
sosolo.parentNode.insertBefore(sosojs, sosolo);
function bbcode2html_sososmilies(sososmilieid, getsrc) {
var imgsrc = '';
sososmilieid = String(sososmilieid);
var imgid = 'soso_' + sososmilieid;
if(sososmilieid.indexOf('_') == 0) {
var realsmilieid = sososmilieid.substr(0, sososmilieid.length-2);
var serverid = sososmilieid.substr(sososmilieid.length-1);
imgsrc = "http://piccache"+serverid+".soso.com/face/"+realsmilieid;
} else {
imgsrc = "http://cache.soso.com/img/img/"+sososmilieid+".gif";
}
if(!isUndefined(getsrc)) {
return imgsrc;
}
return '<img src="'+imgsrc+'" smilieid="'+imgid+'" border="0" alt="" />';
}
function html2bbcode_sososmilies(htmlsmilies) {
if(htmlsmilies) {
htmlsmilies = htmlsmilies.replace(/<img[^>]+smilieid=(["']?)soso_(\w+)(\1)[^>]*>/ig, function($1, $2, $3) { return sososmileycode($3);});
}
return htmlsmilies;
}
function sososmileycode(sososmilieid) {
if(sososmilieid) {
return "{:soso_"+sososmilieid+":}";
}
}
function sososmiliesurl2id(sosourl) {
var sososmilieid = '';
if(sosourl && sosourl.length > 30) {
var idindex = sosourl.lastIndexOf('/');
if(sosourl.indexOf('http://piccache') == 0) {
var serverid = sosourl.substr(15,1);
var realsmilieid = sosourl.substr(idindex+1);
sososmilieid = realsmilieid+'_'+serverid;
} else if(sosourl.indexOf('http://cache.soso.com') == 0) {
sososmilieid = sosourl.substring(idindex+1, sosourl.length-4);
}
return sososmilieid;
}
}
function insertsosoSmiley(sosourl) {
var sososmilieid = sososmiliesurl2id(sosourl);
if(sososmilieid) {
var code = sososmileycode(sososmilieid);
var src = bbcode2html_sososmilies(sososmilieid, true);
checkFocus();
if(wysiwyg && allowsmilies && (!$('smileyoff') || $('smileyoff').checked == false)) {
insertText(bbcode2html_sososmilies(sososmilieid), false);
} else {
code += ' ';
insertText(code, strlen(code), 0);
}
hideMenu();
}
}
function insertfastpostSmiley(sosourl, textareaid) {
var sososmilieid = sososmiliesurl2id(sosourl);
if(sososmilieid) {
var code = sososmileycode(sososmilieid);
seditor_insertunit(textareaid, code);
}
}
var TimeCounter = 0;
function SOSO_EXP_CHECK(textareaid) {
TimeCounter++;
if(typeof editorid!='undefined' && textareaid == 'newthread') {
var eExpBtn = $(editorid + '_sml'),
eEditBox = $(editorid + '_textarea');
eExpBtn.setAttribute('init', 1);
fFillEditBox = function(editbox, url) {
insertsosoSmiley(url);
};
} else if(in_array(textareaid, ['post', 'fastpost', 'pm', 'send', 'reply', 'sightml'])) {
var eExpBtn = $(textareaid+"sml"),
eEditBox = $(textareaid+"message"),
fFillEditBox = function(editbox, url) {
insertfastpostSmiley(url, textareaid);
};
} else {
return false;
}
if(typeof SOSO_EXP != "undefined" && typeof SOSO_EXP.Register == "function" && eExpBtn && eEditBox) {
var pos = 'bottom';
if(in_array(textareaid, ['fastpost', 'pm', 'reply'])) {
pos = 'top';
}
eExpBtn.onclick = function() { return null; };
SOSO_EXP.Register(60001, 'discuz', eExpBtn, pos, eEditBox, fFillEditBox);
if(typeof editdoc != "undefined" && editdoc && editdoc.body) {
editdoc.body.onclick = extrafunc_soso_showmenu;
document.body.onclick = extrafunc_soso_showmenu;
}
return true;
} else if(TimeCounter<15) {
setTimeout(function () { SOSO_EXP_CHECK(textareaid) ; }, 2000);
return false;
} else if(typeof SOSO_EXP == "undefined" || typeof SOSO_EXP.Register != "function") {
return false;
} else {
return false;
}
}
if(typeof EXTRAFUNC['bbcode2html'] != "undefined") {
EXTRAFUNC['bbcode2html']['soso'] = 'extrafunc_soso_bbcode2html';
EXTRAFUNC['html2bbcode']['soso'] = 'extrafunc_soso_html2bbcode';
if(typeof editdoc != "undefined") {
EXTRAFUNC['showmenu']['soso'] = 'extrafunc_soso_showmenu';
}
}
function extrafunc_soso_showmenu() {
SOSO_EXP.Platform.hideBox();
}
function extrafunc_soso_bbcode2html() {
if(!fetchCheckbox('smileyoff') && allowsmilies) {
EXTRASTR = EXTRASTR.replace(/\{\:soso_(\w+)\:\}/ig, function($1, $2) { return bbcode2html_sososmilies($2);});
}
return EXTRASTR;
}
function extrafunc_soso_html2bbcode() {
if((allowhtml && fetchCheckbox('htmlon')) || (!fetchCheckbox('bbcodeoff') && allowbbcode)) {
EXTRASTR = html2bbcode_sososmilies(EXTRASTR);
}
return EXTRASTR;
} | JavaScript |
try {
var pageTracker = _gat._getTracker("UA-18761191-1");
pageTracker._trackPageview();
} catch(err) {}
| JavaScript |
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
| JavaScript |
/*
*
* This code is data acquisition code for www.linezing.com web traffic analysis platform.
* www.linezing.com is Taobao's website.
*/
function lz_encode(str)
{
var e = "", i = 0;
for(i=0;i<str.length;i++) {
if(str.charCodeAt(i)>=0&&str.charCodeAt(i)<=255) {
e = e + escape(str.charAt(i));
}
else {
e = e + str.charAt(i);
}
}
return e;
}
function lz_get_screen()
{
var c = "";
if (self.screen) {
c = screen.width+"x"+screen.height;
}
return c;
}
function lz_get_color()
{
var c = "";
if (self.screen) {
c = screen.colorDepth+"-bit";
}
return c;
}
function lz_get_language()
{
var l = "";
var n = navigator;
if (n.language) {
l = n.language.toLowerCase();
}
else
if (n.browserLanguage) {
l = n.browserLanguage.toLowerCase();
}
return l;
}
function lz_get_agent()
{
var a = "";
var n = navigator;
if (n.userAgent) {
a = n.userAgent;
}
return a;
}
function lz_get_jvm_enabled()
{
var j = "";
var n = navigator;
j = n.javaEnabled() ? 1 : 0;
return j;
}
function lz_get_cookie_enabled()
{
var c = "";
var n = navigator;
c = n.cookieEnabled ? 1 : 0;
return c;
}
function lz_get_flash_ver()
{
var f="",n=navigator;
if (n.plugins && n.plugins.length) {
for (var ii=0;ii<n.plugins.length;ii++) {
if (n.plugins[ii].name.indexOf('Shockwave Flash')!=-1) {
f=n.plugins[ii].description.split('Shockwave Flash ')[1];
break;
}
}
}
else
if (window.ActiveXObject) {
for (var ii=10;ii>=2;ii--) {
try {
var fl=eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+ii+"');");
if (fl) {
f=ii + '.0';
break;
}
}
catch(e) {}
}
}
return f;
}
function lz_get_app()
{
var a = "";
var n = navigator;
if (n.appName) {
a = n.appName;
}
return a;
}
function lz_c_ctry_top_domain(str)
{
var pattern = "/^aero$|^cat$|^coop$|^int$|^museum$|^pro$|^travel$|^xxx$|^com$|^net$|^gov$|^org$|^mil$|^edu$|^biz$|^info$|^name$|^ac$|^mil$|^co$|^ed$|^gv$|^nt$|^bj$|^hz$|^sh$|^tj$|^cq$|^he$|^nm$|^ln$|^jl$|^hl$|^js$|^zj$|^ah$|^hb$|^hn$|^gd$|^gx$|^hi$|^sc$|^gz$|^yn$|^xz$|^sn$|^gs$|^qh$|^nx$|^xj$|^tw$|^hk$|^mo$|^fj$|^ha$|^jx$|^sd$|^sx$/i";
if(str.match(pattern)){ return 1; }
return 0;
}
function lz_c_ctry_domain(str)
{
var pattern = "/^ac$|^ad$|^ae$|^af$|^ag$|^ai$|^al$|^am$|^an$|^ao$|^aq$|^ar$|^as$|^at$|^au$|^aw$|^az$|^ba$|^bb$|^bd$|^be$|^bf$|^bg$|^bh$|^bi$|^bj$|^bm$|^bo$|^br$|^bs$|^bt$|^bv$|^bw$|^by$|^bz$|^ca$|^cc$|^cd$|^cf$|^cg$|^ch$|^ci$|^ck$|^cl$|^cm$|^cn$|^co$|^cr$|^cs$|^cu$|^cv$|^cx$|^cy$|^cz$|^de$|^dj$|^dk$|^dm$|^do$|^dz$|^ec$|^ee$|^eg$|^eh$|^er$|^es$|^et$|^eu$|^fi$|^fj$|^fk$|^fm$|^fo$|^fr$|^ly$|^hk$|^hm$|^hn$|^hr$|^ht$|^hu$|^id$|^ie$|^il$|^im$|^in$|^io$|^ir$|^is$|^it$|^je$|^jm$|^jo$|^jp$|^ke$|^kg$|^kh$|^ki$|^km$|^kn$|^kp$|^kr$|^kw$|^ky$|^kz$|^la$|^lb$|^lc$|^li$|^lk$|^lr$|^ls$|^lt$|^lu$|^lv$|^ly$|^ga$|^gb$|^gd$|^ge$|^gf$|^gg$|^gh$|^gi$|^gl$|^gm$|^gn$|^gp$|^gq$|^gr$|^gs$|^gt$|^gu$|^gw$|^gy$|^ma$|^mc$|^md$|^mg$|^mh$|^mk$|^ml$|^mm$|^mn$|^mo$|^mp$|^mq$|^mr$|^ms$|^mt$|^mu$|^mv$|^mw$|^mx$|^my$|^mz$|^na$|^nc$|^ne$|^nf$|^ng$|^ni$|^nl$|^no$|^np$|^nr$|^nu$|^nz$|^om$|^re$|^ro$|^ru$|^rw$|^pa$|^pe$|^pf$|^pg$|^ph$|^pk$|^pl$|^pm$|^pr$|^ps$|^pt$|^pw$|^py$|^qa$|^wf$|^ws$|^sa$|^sb$|^sc$|^sd$|^se$|^sg$|^sh$|^si$|^sj$|^sk$|^sl$|^sm$|^sn$|^so$|^sr$|^st$|^su$|^sv$|^sy$|^sz$|^tc$|^td$|^tf$|^th$|^tg$|^tj$|^tk$|^tm$|^tn$|^to$|^tp$|^tr$|^tt$|^tv$|^tw$|^tz$|^ua$|^ug$|^uk$|^um$|^us$|^uy$|^uz$|^va$|^vc$|^ve$|^vg$|^vi$|^vn$|^vu$|^ye$|^yt$|^yu$|^za$|^zm$|^zr$|^zw$/i";
if(str.match(pattern)){ return 1; }
return 0;
}
function lz_get_domain(host)
{
var d=host.replace(/^www\./, "");
var ss=d.split(".");
var l=ss.length;
if(l == 3){
if(lz_c_ctry_top_domain(ss[1]) && lz_c_ctry_domain(ss[2])){
}
else{
d = ss[1]+"."+ss[2];
}
}
else if(l >= 3){
var ip_pat = "^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$";
if(host.match(ip_pat)){
return d;
}
if(lz_c_ctry_top_domain(ss[l-2]) && lz_c_ctry_domain(ss[l-1])) {
d = ss[l-3]+"."+ss[l-2]+"."+ss[l-1];
}
else{
d = ss[l-2]+"."+ss[l-1];
}
}
return d;
}
function lz_get_cookie(name)
{
var mn=name+"=";
var b,e;
var co=document.cookie;
if (mn=="=") {
return co;
}
b=co.indexOf(mn);
if (b < 0) {
return "";
}
e=co.indexOf(";", b+name.length);
if (e < 0) {
return co.substring(b+name.length + 1);
}
else {
return co.substring(b+name.length + 1, e);
}
}
function lz_set_cookie(name, val, cotp)
{
var date=new Date;
var year=date.getFullYear();
var hour=date.getHours();
var cookie="";
if (cotp == 0) {
cookie=name+"="+val+";";
}
else if (cotp == 1) {
year=year+10;
date.setYear(year);
cookie=name+"="+val+";expires="+date.toGMTString()+";";
}
else if (cotp == 2) {
hour=hour+1;
date.setHours(hour);
cookie=name+"="+val+";expires="+date.toGMTString()+";";
}
var d=lz_get_domain(document.domain);
if(d != ""){
cookie +="domain="+d+";";
}
cookie +="path="+"/;";
document.cookie=cookie;
}
function str_reverse(str) {
var ln = str.length;
var i=0;
var temp="";
for(i=ln-1; i>-1; i--) {
if(str.charAt(i)==".")
temp += "#";
else
temp += str.charAt(i);
}
return temp;
}
function lz_get_ss_id(str)
{
len=str.indexOf("_");
str=str.substring(len+1);
len=str.indexOf("_");
str=str.substring(len+1);
return str;
}
function lz_get_ss_no(str) {
len=str.indexOf("_");
str=str.substring(0,len);
return parseInt(str);
}
function lz_get_stm()
{
var date = new Date();
var yy=date.getFullYear();
var mm=date.getMonth();
var dd=date.getDate();
var hh=date.getHours();
var ii=date.getMinutes();
var ss=date.getSeconds();
var i;
var tm=0;
for(i = 1970; i < yy; i++) {
if ((i % 4 == 0 && i % 100 != 0) || (i % 100 == 0 && i % 400 == 0)) {
tm=tm+31622400;
}
else {
tm=tm+31536000;
}
}
mm=mm+1;
for(i = 1; i < mm; i++) {
if (i == 1 || i == 3 || i == 5 || i == 7 || i == 8 || i == 10 || i == 12) {
tm=tm+2678400;
}
else {
if (i == 2) {
if ((yy % 4 == 0 && yy % 100 != 0) || (yy % 100 == 0 && yy % 400 == 0)) {
tm=tm+2505600;
}
else {
tm=tm+2419200;
}
}
else {
tm=tm+2592000;
}
}
}
tm = tm + (dd-1) * 86400; tm = tm + hh * 3600;
tm = tm + ii * 60;
tm = tm + ss;
return tm;
}
function lz_get_ctm(str) {
len=str.indexOf("_");
str=str.substring(len+1);
len=str.indexOf("_");
str=str.substring(0,len);
return parseInt(str, 10);
}
/* main function */
function lz_main()
{
var unit_id = "2720520";
var client_ip = "119.167.201.162";
var server_time = "1349751245";
var verify_code = "238eb46c";
var type = "0";
var dest_path = "http://dt.tongji.linezing.com/tongji.do?unit_id="+unit_id;
var expire_time = 1800;
var i;
var host=document.location.host;
var domain = lz_get_domain(host.toLocaleLowerCase());
var hashval = 0;
for (i=0; i< domain.length; i++){
hashval += domain.charCodeAt(i);
}
var uv_str = lz_get_cookie("lzstat_uv");
var uv_id = "";
var uv_new = 0;
if (uv_str == ""){
uv_new = 1;
var rand1 = parseInt( Math.random() * 4000000000 );
var rand2 = parseInt( Math.random() * 4000000000 );
uv_id = String(rand1) + String(rand2);
var value = uv_id+"|"+unit_id;
lz_set_cookie("lzstat_uv", value, 1);
}
else{
var arr = uv_str.split("|");
uv_id = arr[0];
var uids_str = arr[1];
var uids = uids_str.split("@");
var uid_num = uids.length;
var bingo = 0;
for(var pos=0,max=uids.length;pos<max;pos++) {
var uid = uids[pos];
if (uid == unit_id){
bingo = 1;
break;
}
}
if (bingo == 0){
uv_new = 1;
if (uid_num >= 100){
var value = uv_id+"|"+unit_id;
}
else{
var value = uv_str+"@"+unit_id;
}
lz_set_cookie("lzstat_uv", value, 1);
}
}
var ss_str = lz_get_cookie("lzstat_ss");
var ss_id = "";
var ss_no = 0;
if (ss_str == ""){
ss_no = 0;
var rand = parseInt(Math.random() * 4000000000);
ss_id = String(rand);
value = ss_id+"_"+"0_"+lz_get_stm()+"_"+unit_id;
lz_set_cookie("lzstat_ss", value, 0);
}
else {
var arr = ss_str.split("|");
var ss_num = arr.length;
var bingo = 0;
for(var pos=0,max=arr.length;pos<max;pos++) {
var ss_info = arr[pos];
var items = ss_info.split("_");
var cookie_ss_id = items[0];
var cookie_ss_no = parseInt(items[1]);
var cookie_ss_stm = items[2];
var cookie_ss_uid = items[3];
if (cookie_ss_uid == unit_id){
bingo = 1;
if (lz_get_stm() - cookie_ss_stm > expire_time) {
ss_no = 0;
var rand = parseInt(Math.random() * 4000000000);
ss_id = String(rand);
}
else{
ss_no = cookie_ss_no + 1;
ss_id = cookie_ss_id;
}
value = ss_id+"_"+ss_no+"_"+lz_get_stm()+"_"+unit_id;
arr[pos] = value;
ss_str = arr.join("|");
lz_set_cookie("lzstat_ss", ss_str, 0);
break;
}
}
if (bingo == 0)
{
ss_no = 0;
var rand = parseInt(Math.random() * 4000000000);
ss_id = String(rand);
value = ss_id+"_"+"0_"+lz_get_stm()+"_"+unit_id;
if (ss_num >= 20){
pos = parseInt(Math.random() * ss_num);
}
else{
pos = ss_num;
}
arr[pos] = value;
ss_str = arr.join("|");
lz_set_cookie("lzstat_ss", ss_str, 0);
}
}
var ref = document.referrer;
ref = lz_encode(String(ref));
var url = document.URL;
url = lz_encode(String(url));
var title = document.title;
title = escape(String(title));
var charset = document.charset;
charset = lz_encode(String(charset));
var screen = lz_get_screen();
screen = lz_encode(String(screen));
var color =lz_get_color();
color =lz_encode(String(color));
var language = lz_get_language();
language = lz_encode(String(language));
var agent =lz_get_agent();
agent =lz_encode(String(agent));
var jvm_enabled =lz_get_jvm_enabled();
jvm_enabled =lz_encode(String(jvm_enabled));
var cookie_enabled =lz_get_cookie_enabled();
cookie_enabled =lz_encode(String(cookie_enabled));
var flash_ver = lz_get_flash_ver();
flash_ver = lz_encode(String(flash_ver));
var app = lz_get_app();
app = lz_encode(String(app));
var filtered = 0;
var domain_filters = new Array();
var ip_filters = new Array();
domain_filters[0] = "gro#tra763";
domain_filters[1] = "moc#olzd";
domain_filters[2] = "moc#tra763";
domain_filters[3] = "moc#df571";
domain_filters[4] = "ten#oog1";
domain_filters[5] = "nc#ppk1";
domain_filters[6] = "nc#osnaknak";
domain_filters[7] = "nc#emocwww";
domain_filters[8] = "nc#psalla";
domain_filters[9] = "moc#oesii";
domain_filters[10] = "moc#kh0083";
domain_filters[11] = "nc#kpwww";
domain_filters[12] = "nc#moc#zw001";
domain_filters[13] = "nc#kpemoc";
domain_filters[14] = "moc#eyiq063";
domain_filters[15] = "moc#qqa4";
domain_filters[16] = "ten#aboakoak";
domain_filters[17] = "moc#ecilliw";
domain_filters[18] = "nc#moc#ibeea";
domain_filters[19] = "moc#ibeea";
domain_filters[20] = "nc#tra763";
domain_filters[21] = "moc#025sns";
domain_filters[22] = "moc#og321oah";
domain_filters[23] = "moc#9zznc";
domain_filters[24] = "nc#9zznc";
domain_filters[25] = "moc#d135";
domain_filters[26] = "moc#ridzoog";
domain_filters[27] = "ten#rqrq";
domain_filters[28] = "moc#195nak";
domain_filters[29] = "moc#uynijtn";
domain_filters[30] = "moc#falwen";
domain_filters[31] = "nc#moc#njyhxj";
var escape_domain = str_reverse(domain);
for (i in domain_filters){
if(domain_filters[i] == escape_domain)
filtered = 1;
}
for (i in ip_filters){
if(ip_filters[i] == client_ip){
filtered = 1;
break;
}
}
var url_id = 0;
var cur_url = location.href;
dest=dest_path+"&uv_id="+uv_id+"&uv_new="+uv_new+"&cna="+""+"&cg="+""+"&mid="+""+"&mmland="+""+"&ade="+""+"&adtm="+""+"&sttm="+""+"&cpa="+""+"&ss_id="+ss_id+"&ss_no="+ss_no+"&ec="+cookie_enabled+"&ref="+ref+"&url="+url+"&title="+title+"&charset="+charset+"&domain="+domain+"&hashval="+hashval+"&filtered="+filtered+"&app="+app+"&agent="+agent+"&color="+color+"&screen="+screen+"&lg="+language+"&je="+jvm_enabled+"&fv="+flash_ver+"&st="+server_time+""+"&vc="+verify_code+""+"&ut=0"+"&url_id="+url_id+"&cnu="+String(Math.random());
document.write("<img src=\""+dest+"\" border=\"0\" width=\"1\" height=\"1\" />");
var icon_link_host="tongji.linezing.com";
if(cur_url.indexOf('#lzclickmap=')>-1) {
var token = cur_url.substr(cur_url.indexOf('#lzclickmap='), 44);
token = token.replace(/([\/'])/g, '\\$1');
document.write('<scr'+'ipt src=\'http://tongji.linezing.com/clickmap/load_clickmap.html?r='+Math.random()+token+'\'></scr'+'ipt>');
return false;
}
if(url_id>0)
document.write('<scr'+'ipt src=\'http://js.tongji.linezing.com/2720520/'+url_id+'/clickcollect.js\'></scr'+'ipt>');
}
lz_main();
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
/****** ON LOAD SET UP STUFF *********/
var navBarIsFixed = false;
$(document).ready(function() {
if (devsite) {
// move the lang selector into the overflow menu
$("#moremenu .mid div.header:last").after($("#language").detach());
}
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
// set search's onkeyup handler here so we can show suggestions
// even while search results are visible
$("#search_autocomplete").keyup(function() {return search_changed(event, false, toRoot)});
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false); // see search_autocomplete.js
hideResults(); // see search_autocomplete.js
});
$('.search').click(function() {
if (!$('#search_autocomplete').is(":focused")) {
$('#search_autocomplete').focus();
}
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePath.substring(1,pagePath.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
}
// select current page in sidenav and header, and set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var training = $(".next-class-link").length; // decides whether to provide "next class" link
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide").append($nextLink.html());
$('.next-class-link').find('.new').empty();
} else {
$('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
// If this is a training 'article', there should be no prev/next nav
// ... if the grandparent is the "nav" ... and it has no child list items...
if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
!$selListItem.find('li').length) {
$('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
var $classDescriptions = $classLinks.attr('description');
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
$('#nav li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me */
// if (section.hasClass('selected') || section.find('li').hasClass('selected')) {
// /* but not if myself or my descendents are selected */
// return;
// }
section.children('ul').slideUp(250, function() {
section.closest('li').removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul'));
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (navBarIsFixed) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
// Set up fixed navbar
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
$(window).scroll(function(event) {
if ($('#side-nav').length == 0) return;
if (event.target.nodeName == "DIV") {
// Dump scroll event if the target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
return;
}
var scrollTop = $(window).scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var searchResultHeight = $('#searchResults').is(":visible") ?
$('#searchResults').outerHeight() : 0;
var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
navBarShouldBeFixed = false;
}
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (navBarIsFixed && navBarShouldBeFixed) {
return;
}
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
// make it fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// add neato "back to top" button
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else {
// make it static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
$('#devdoc-nav a.totop').hide();
}
navBarIsFixed = navBarShouldBeFixed;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-section-header').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
resizeNav();
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
});
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) return;
var selectedOffset = $selected.position().top;
if (selectedOffset + 90 > $nav.height()) { // add 90 so that we scroll up even
// if the current item is close to the bottom
api.scrollTo(0, selectedOffset - ($nav.height() / 4), false); // scroll the item into view
// to be 1/4 of the way from the top
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; expires=" + expiration+"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
/*
REMEMBER THE PREVIOUS PAGE FOR EACH TAB
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if ((path.indexOf("/resources/") != -1) || (path.indexOf("/training/") != -1)) {
writeCookie("lastpage", path, "resources", null);
}
});
*/
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
// keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj.parentNode.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text", obj).toggle();
div.removeClass("open").addClass("closed");
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function sync_selection_table(toroot)
{
var $list = $("#search_filtered");
var $li; //list item jquery object
var i; //list item iterator
gSelectedID = -1;
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('#search_filtered li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedIndex = $('#search_filtered li').index(this);
});
$li.append('<a></a>');
}
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
$('#search_filtered_div').removeClass('no-display');
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','show-item');
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','no-display');
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
li = list.rows[ROW_COUNT];
li.className = "show-item";
c1 = li.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
list.rows[ROW_COUNT].className = "hide-item";
}*/
//if we have no results, hide the table
} else {
$('#search_filtered_div').addClass('no-display');
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 13 = enter
if (e.keyCode == 13) {
$('#search_filtered_div').addClass('no-display');
if (!$('#search_filtered_div').hasClass('no-display') || (gSelectedIndex < 0)) {
if ($("#searchResults").is(":hidden")) {
// if results aren't showing, return true to allow search to execute
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex--;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex++;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
else if (!kd && (e.keyCode != 40) && (e.keyCode != 38)) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow');
return false;
}
function hideResults() {
$("#searchResults").slideUp();
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
google.load('search', '1');
var searchControl;
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
// create search control
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow');
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Exit if the hash isn't a search query or there's an error in the query
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow');
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference")) {
if(!location.pathname.indexOf("/reference-gms/packages.html")
&& !location.pathname.indexOf("/reference-gcm/packages.html")
&& !location.pathname.indexOf("/reference/com/google") == 0) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
resizeNav();
}
function init_default_google_navtree(toroot) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
}
function init_default_gcm_navtree(toroot) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
/****** ON LOAD SET UP STUFF *********/
var navBarIsFixed = false;
$(document).ready(function() {
if (devsite) {
// move the lang selector into the overflow menu
$("#moremenu .mid div.header:last").after($("#language").detach());
}
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
// set search's onkeyup handler here so we can show suggestions
// even while search results are visible
$("#search_autocomplete").keyup(function() {return search_changed(event, false, toRoot)});
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false); // see search_autocomplete.js
hideResults(); // see search_autocomplete.js
});
$('.search').click(function() {
if (!$('#search_autocomplete').is(":focused")) {
$('#search_autocomplete').focus();
}
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePath.substring(1,pagePath.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
}
// select current page in sidenav and header, and set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var training = $(".next-class-link").length; // decides whether to provide "next class" link
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide").append($nextLink.html());
$('.next-class-link').find('.new').empty();
} else {
$('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
// If this is a training 'article', there should be no prev/next nav
// ... if the grandparent is the "nav" ... and it has no child list items...
if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
!$selListItem.find('li').length) {
$('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
var $classDescriptions = $classLinks.attr('description');
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
$('#nav li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me */
// if (section.hasClass('selected') || section.find('li').hasClass('selected')) {
// /* but not if myself or my descendents are selected */
// return;
// }
section.children('ul').slideUp(250, function() {
section.closest('li').removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul'));
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (navBarIsFixed) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
// Set up fixed navbar
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
$(window).scroll(function(event) {
if ($('#side-nav').length == 0) return;
if (event.target.nodeName == "DIV") {
// Dump scroll event if the target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
return;
}
var scrollTop = $(window).scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var searchResultHeight = $('#searchResults').is(":visible") ?
$('#searchResults').outerHeight() : 0;
var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
navBarShouldBeFixed = false;
}
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (navBarIsFixed && navBarShouldBeFixed) {
return;
}
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
// make it fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// add neato "back to top" button
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else {
// make it static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
$('#devdoc-nav a.totop').hide();
}
navBarIsFixed = navBarShouldBeFixed;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-section-header').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
resizeNav();
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
});
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) return;
var selectedOffset = $selected.position().top;
if (selectedOffset + 90 > $nav.height()) { // add 90 so that we scroll up even
// if the current item is close to the bottom
api.scrollTo(0, selectedOffset - ($nav.height() / 4), false); // scroll the item into view
// to be 1/4 of the way from the top
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; expires=" + expiration+"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
/*
REMEMBER THE PREVIOUS PAGE FOR EACH TAB
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if ((path.indexOf("/resources/") != -1) || (path.indexOf("/training/") != -1)) {
writeCookie("lastpage", path, "resources", null);
}
});
*/
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
// keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj.parentNode.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text", obj).toggle();
div.removeClass("open").addClass("closed");
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function sync_selection_table(toroot)
{
var $list = $("#search_filtered");
var $li; //list item jquery object
var i; //list item iterator
gSelectedID = -1;
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('#search_filtered li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedIndex = $('#search_filtered li').index(this);
});
$li.append('<a></a>');
}
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
$('#search_filtered_div').removeClass('no-display');
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','show-item');
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','no-display');
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
li = list.rows[ROW_COUNT];
li.className = "show-item";
c1 = li.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
list.rows[ROW_COUNT].className = "hide-item";
}*/
//if we have no results, hide the table
} else {
$('#search_filtered_div').addClass('no-display');
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 13 = enter
if (e.keyCode == 13) {
$('#search_filtered_div').addClass('no-display');
if (!$('#search_filtered_div').hasClass('no-display') || (gSelectedIndex < 0)) {
if ($("#searchResults").is(":hidden")) {
// if results aren't showing, return true to allow search to execute
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex--;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex++;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
else if (!kd && (e.keyCode != 40) && (e.keyCode != 38)) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow');
return false;
}
function hideResults() {
$("#searchResults").slideUp();
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
google.load('search', '1');
var searchControl;
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
// create search control
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow');
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Exit if the hash isn't a search query or there's an error in the query
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow');
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference")) {
if(!location.pathname.indexOf("/reference-gms/packages.html")
&& !location.pathname.indexOf("/reference-gcm/packages.html")
&& !location.pathname.indexOf("/reference/com/google") == 0) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
resizeNav();
}
function init_default_google_navtree(toroot) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
}
function init_default_gcm_navtree(toroot) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
/****** ON LOAD SET UP STUFF *********/
var navBarIsFixed = false;
$(document).ready(function() {
if (devsite) {
// move the lang selector into the overflow menu
$("#moremenu .mid div.header:last").after($("#language").detach());
}
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
// set search's onkeyup handler here so we can show suggestions
// even while search results are visible
$("#search_autocomplete").keyup(function() {return search_changed(event, false, toRoot)});
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false); // see search_autocomplete.js
hideResults(); // see search_autocomplete.js
});
$('.search').click(function() {
if (!$('#search_autocomplete').is(":focused")) {
$('#search_autocomplete').focus();
}
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePath.substring(1,pagePath.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
}
// select current page in sidenav and header, and set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var training = $(".next-class-link").length; // decides whether to provide "next class" link
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide").append($nextLink.html());
$('.next-class-link').find('.new').empty();
} else {
$('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
// If this is a training 'article', there should be no prev/next nav
// ... if the grandparent is the "nav" ... and it has no child list items...
if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
!$selListItem.find('li').length) {
$('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
var $classDescriptions = $classLinks.attr('description');
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
$('#nav li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me */
// if (section.hasClass('selected') || section.find('li').hasClass('selected')) {
// /* but not if myself or my descendents are selected */
// return;
// }
section.children('ul').slideUp(250, function() {
section.closest('li').removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul'));
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (navBarIsFixed) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
// Set up fixed navbar
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
$(window).scroll(function(event) {
if ($('#side-nav').length == 0) return;
if (event.target.nodeName == "DIV") {
// Dump scroll event if the target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
return;
}
var scrollTop = $(window).scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var searchResultHeight = $('#searchResults').is(":visible") ?
$('#searchResults').outerHeight() : 0;
var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
navBarShouldBeFixed = false;
}
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (navBarIsFixed && navBarShouldBeFixed) {
return;
}
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
// make it fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// add neato "back to top" button
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else {
// make it static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
$('#devdoc-nav a.totop').hide();
}
navBarIsFixed = navBarShouldBeFixed;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-section-header').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
resizeNav();
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
});
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) return;
var selectedOffset = $selected.position().top;
if (selectedOffset + 90 > $nav.height()) { // add 90 so that we scroll up even
// if the current item is close to the bottom
api.scrollTo(0, selectedOffset - ($nav.height() / 4), false); // scroll the item into view
// to be 1/4 of the way from the top
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; expires=" + expiration+"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
/*
REMEMBER THE PREVIOUS PAGE FOR EACH TAB
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if ((path.indexOf("/resources/") != -1) || (path.indexOf("/training/") != -1)) {
writeCookie("lastpage", path, "resources", null);
}
});
*/
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
// keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj.parentNode.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text", obj).toggle();
div.removeClass("open").addClass("closed");
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function sync_selection_table(toroot)
{
var $list = $("#search_filtered");
var $li; //list item jquery object
var i; //list item iterator
gSelectedID = -1;
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('#search_filtered li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedIndex = $('#search_filtered li').index(this);
});
$li.append('<a></a>');
}
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
$('#search_filtered_div').removeClass('no-display');
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','show-item');
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','no-display');
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
li = list.rows[ROW_COUNT];
li.className = "show-item";
c1 = li.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
list.rows[ROW_COUNT].className = "hide-item";
}*/
//if we have no results, hide the table
} else {
$('#search_filtered_div').addClass('no-display');
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 13 = enter
if (e.keyCode == 13) {
$('#search_filtered_div').addClass('no-display');
if (!$('#search_filtered_div').hasClass('no-display') || (gSelectedIndex < 0)) {
if ($("#searchResults").is(":hidden")) {
// if results aren't showing, return true to allow search to execute
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex--;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex++;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
else if (!kd && (e.keyCode != 40) && (e.keyCode != 38)) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow');
return false;
}
function hideResults() {
$("#searchResults").slideUp();
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
google.load('search', '1');
var searchControl;
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
// create search control
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow');
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Exit if the hash isn't a search query or there's an error in the query
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow');
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference")) {
if(!location.pathname.indexOf("/reference-gms/packages.html")
&& !location.pathname.indexOf("/reference-gcm/packages.html")
&& !location.pathname.indexOf("/reference/com/google") == 0) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
resizeNav();
}
function init_default_google_navtree(toroot) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
}
function init_default_gcm_navtree(toroot) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
| JavaScript |
var classesNav;
var devdocNav;
var sidenav;
var cookie_namespace = 'android_developer';
var NAV_PREF_TREE = "tree";
var NAV_PREF_PANELS = "panels";
var nav_pref;
var isMobile = false; // true if mobile, so we can adjust some layout
var basePath = getBaseUri(location.pathname);
var SITE_ROOT = toRoot + basePath.substring(1,basePath.indexOf("/",1));
/****** ON LOAD SET UP STUFF *********/
var navBarIsFixed = false;
$(document).ready(function() {
if (devsite) {
// move the lang selector into the overflow menu
$("#moremenu .mid div.header:last").after($("#language").detach());
}
// init the fullscreen toggle click event
$('#nav-swap .fullscreen').click(function(){
if ($(this).hasClass('disabled')) {
toggleFullscreen(true);
} else {
toggleFullscreen(false);
}
});
// initialize the divs with custom scrollbars
$('.scroll-pane').jScrollPane( {verticalGutter:0} );
// add HRs below all H2s (except for a few other h2 variants)
$('h2').not('#qv h2').not('#tb h2').not('.sidebox h2').not('#devdoc-nav h2').not('h2.norule').css({marginBottom:0}).after('<hr/>');
// set search's onkeyup handler here so we can show suggestions
// even while search results are visible
$("#search_autocomplete").keyup(function() {return search_changed(event, false, toRoot)});
// set up the search close button
$('.search .close').click(function() {
$searchInput = $('#search_autocomplete');
$searchInput.attr('value', '');
$(this).addClass("hide");
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
search_focus_changed($searchInput.get(), false); // see search_autocomplete.js
hideResults(); // see search_autocomplete.js
});
$('.search').click(function() {
if (!$('#search_autocomplete').is(":focused")) {
$('#search_autocomplete').focus();
}
});
// Set up quicknav
var quicknav_open = false;
$("#btn-quicknav").click(function() {
if (quicknav_open) {
$(this).removeClass('active');
quicknav_open = false;
collapse();
} else {
$(this).addClass('active');
quicknav_open = true;
expand();
}
})
var expand = function() {
$('#header-wrap').addClass('quicknav');
$('#quicknav').stop().show().animate({opacity:'1'});
}
var collapse = function() {
$('#quicknav').stop().animate({opacity:'0'}, 100, function() {
$(this).hide();
$('#header-wrap').removeClass('quicknav');
});
}
//Set up search
$("#search_autocomplete").focus(function() {
$("#search-container").addClass('active');
})
$("#search-container").mouseover(function() {
$("#search-container").addClass('active');
$("#search_autocomplete").focus();
})
$("#search-container").mouseout(function() {
if ($("#search_autocomplete").is(":focus")) return;
if ($("#search_autocomplete").val() == '') {
setTimeout(function(){
$("#search-container").removeClass('active');
$("#search_autocomplete").blur();
},250);
}
})
$("#search_autocomplete").blur(function() {
if ($("#search_autocomplete").val() == '') {
$("#search-container").removeClass('active');
}
})
// prep nav expandos
var pagePath = document.location.pathname;
// account for intl docs by removing the intl/*/ path
if (pagePath.indexOf("/intl/") == 0) {
pagePath = pagePath.substr(pagePath.indexOf("/",6)); // start after intl/ to get last /
}
if (pagePath.indexOf(SITE_ROOT) == 0) {
if (pagePath == '' || pagePath.charAt(pagePath.length - 1) == '/') {
pagePath += 'index.html';
}
}
if (SITE_ROOT.match(/\.\.\//) || SITE_ROOT == '') {
// If running locally, SITE_ROOT will be a relative path, so account for that by
// finding the relative URL to this page. This will allow us to find links on the page
// leading back to this page.
var pathParts = pagePath.split('/');
var relativePagePathParts = [];
var upDirs = (SITE_ROOT.match(/(\.\.\/)+/) || [''])[0].length / 3;
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push('..');
}
for (var i = 0; i < upDirs; i++) {
relativePagePathParts.push(pathParts[pathParts.length - (upDirs - i) - 1]);
}
relativePagePathParts.push(pathParts[pathParts.length - 1]);
pagePath = relativePagePathParts.join('/');
} else {
// Otherwise the page path is already an absolute URL
}
// Highlight the header tabs...
// highlight Design tab
if ($("body").hasClass("design")) {
$("#header li.design a").addClass("selected");
// highlight Develop tab
} else if ($("body").hasClass("develop") || $("body").hasClass("google")) {
$("#header li.develop a").addClass("selected");
// In Develop docs, also highlight appropriate sub-tab
var rootDir = pagePath.substring(1,pagePath.indexOf('/', 1));
if (rootDir == "training") {
$("#nav-x li.training a").addClass("selected");
} else if (rootDir == "guide") {
$("#nav-x li.guide a").addClass("selected");
} else if (rootDir == "reference") {
// If the root is reference, but page is also part of Google Services, select Google
if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
} else {
$("#nav-x li.reference a").addClass("selected");
}
} else if ((rootDir == "tools") || (rootDir == "sdk")) {
$("#nav-x li.tools a").addClass("selected");
} else if ($("body").hasClass("google")) {
$("#nav-x li.google a").addClass("selected");
}
// highlight Distribute tab
} else if ($("body").hasClass("distribute")) {
$("#header li.distribute a").addClass("selected");
}
// select current page in sidenav and header, and set up prev/next links if they exist
var $selNavLink = $('#nav').find('a[href="' + pagePath + '"]');
var $selListItem;
if ($selNavLink.length) {
// Find this page's <li> in sidenav and set selected
$selListItem = $selNavLink.closest('li');
$selListItem.addClass('selected');
// Traverse up the tree and expand all parent nav-sections
$selNavLink.parents('li.nav-section').each(function() {
$(this).addClass('expanded');
$(this).children('ul').show();
});
// set up prev links
var $prevLink = [];
var $prevListItem = $selListItem.prev('li');
var crossBoundaries = ($("body.design").length > 0) || ($("body.guide").length > 0) ? true :
false; // navigate across topic boundaries only in design docs
if ($prevListItem.length) {
if ($prevListItem.hasClass('nav-section')) {
// jump to last topic of previous section
$prevLink = $prevListItem.find('a:last');
} else if (!$selListItem.hasClass('nav-section')) {
// jump to previous topic in this section
$prevLink = $prevListItem.find('a:eq(0)');
}
} else {
// jump to this section's index page (if it exists)
var $parentListItem = $selListItem.parents('li');
$prevLink = $selListItem.parents('li').find('a');
// except if cross boundaries aren't allowed, and we're at the top of a section already
// (and there's another parent)
if (!crossBoundaries && $parentListItem.hasClass('nav-section')
&& $selListItem.hasClass('nav-section')) {
$prevLink = [];
}
}
// set up next links
var $nextLink = [];
var startClass = false;
var training = $(".next-class-link").length; // decides whether to provide "next class" link
var isCrossingBoundary = false;
if ($selListItem.hasClass('nav-section')) {
// we're on an index page, jump to the first topic
$nextLink = $selListItem.find('ul:eq(0)').find('a:eq(0)');
// if there aren't any children, go to the next section (required for About pages)
if($nextLink.length == 0) {
$nextLink = $selListItem.next('li').find('a');
} else if ($('.topic-start-link').length) {
// as long as there's a child link and there is a "topic start link" (we're on a landing)
// then set the landing page "start link" text to be the first doc title
$('.topic-start-link').text($nextLink.text().toUpperCase());
}
// If the selected page has a description, then it's a class or article homepage
if ($selListItem.find('a[description]').length) {
// this means we're on a class landing page
startClass = true;
}
} else {
// jump to the next topic in this section (if it exists)
$nextLink = $selListItem.next('li').find('a:eq(0)');
if (!$nextLink.length) {
isCrossingBoundary = true;
// no more topics in this section, jump to the first topic in the next section
$nextLink = $selListItem.parents('li:eq(0)').next('li.nav-section').find('a:eq(0)');
if (!$nextLink.length) { // Go up another layer to look for next page (lesson > class > course)
$nextLink = $selListItem.parents('li:eq(1)').next('li.nav-section').find('a:eq(0)');
}
}
}
if (startClass) {
$('.start-class-link').attr('href', $nextLink.attr('href')).removeClass("hide");
// if there's no training bar (below the start button),
// then we need to add a bottom border to button
if (!$("#tb").length) {
$('.start-class-link').css({'border-bottom':'1px solid #DADADA'});
}
} else if (isCrossingBoundary && !$('body.design').length) { // Design always crosses boundaries
$('.content-footer.next-class').show();
$('.next-page-link').attr('href','')
.removeClass("hide").addClass("disabled")
.click(function() { return false; });
$('.next-class-link').attr('href',$nextLink.attr('href'))
.removeClass("hide").append($nextLink.html());
$('.next-class-link').find('.new').empty();
} else {
$('.next-page-link').attr('href', $nextLink.attr('href')).removeClass("hide");
}
if (!startClass && $prevLink.length) {
var prevHref = $prevLink.attr('href');
if (prevHref == SITE_ROOT + 'index.html') {
// Don't show Previous when it leads to the homepage
} else {
$('.prev-page-link').attr('href', $prevLink.attr('href')).removeClass("hide");
}
}
// If this is a training 'article', there should be no prev/next nav
// ... if the grandparent is the "nav" ... and it has no child list items...
if (training && $selListItem.parents('ul').eq(1).is('[id="nav"]') &&
!$selListItem.find('li').length) {
$('.next-page-link,.prev-page-link').attr('href','').addClass("disabled")
.click(function() { return false; });
}
}
// Set up the course landing pages for Training with class names and descriptions
if ($('body.trainingcourse').length) {
var $classLinks = $selListItem.find('ul li a').not('#nav .nav-section .nav-section ul a');
var $classDescriptions = $classLinks.attr('description');
var $olClasses = $('<ol class="class-list"></ol>');
var $liClass;
var $imgIcon;
var $h2Title;
var $pSummary;
var $olLessons;
var $liLesson;
$classLinks.each(function(index) {
$liClass = $('<li></li>');
$h2Title = $('<a class="title" href="'+$(this).attr('href')+'"><h2>' + $(this).html()+'</h2><span></span></a>');
$pSummary = $('<p class="description">' + $(this).attr('description') + '</p>');
$olLessons = $('<ol class="lesson-list"></ol>');
$lessons = $(this).closest('li').find('ul li a');
if ($lessons.length) {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-tutorial.png" alt=""/>');
$lessons.each(function(index) {
$olLessons.append('<li><a href="'+$(this).attr('href')+'">' + $(this).html()+'</a></li>');
});
} else {
$imgIcon = $('<img src="'+toRoot+'assets/images/resource-article.png" alt=""/>');
$pSummary.addClass('article');
}
$liClass.append($h2Title).append($imgIcon).append($pSummary).append($olLessons);
$olClasses.append($liClass);
});
$('.jd-descr').append($olClasses);
}
// Set up expand/collapse behavior
$('#nav li.nav-section .nav-section-header').click(function() {
var section = $(this).closest('li.nav-section');
if (section.hasClass('expanded')) {
/* hide me */
// if (section.hasClass('selected') || section.find('li').hasClass('selected')) {
// /* but not if myself or my descendents are selected */
// return;
// }
section.children('ul').slideUp(250, function() {
section.closest('li').removeClass('expanded');
resizeNav();
});
} else {
/* show me */
// first hide all other siblings
var $others = $('li.nav-section.expanded', $(this).closest('ul'));
$others.removeClass('expanded').children('ul').slideUp(250);
// now expand me
section.closest('li').addClass('expanded');
section.children('ul').slideDown(250, function() {
resizeNav();
});
}
});
$(".scroll-pane").scroll(function(event) {
event.preventDefault();
return false;
});
/* Resize nav height when window height changes */
$(window).resize(function() {
if ($('#side-nav').length == 0) return;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
setNavBarLeftPos(); // do this even if sidenav isn't fixed because it could become fixed
// make sidenav behave when resizing the window and side-scolling is a concern
if (navBarIsFixed) {
if ((stylesheet.attr("disabled") == "disabled") || stylesheet.length == 0) {
updateSideNavPosition();
} else {
updateSidenavFullscreenWidth();
}
}
resizeNav();
});
// Set up fixed navbar
var prevScrollLeft = 0; // used to compare current position to previous position of horiz scroll
$(window).scroll(function(event) {
if ($('#side-nav').length == 0) return;
if (event.target.nodeName == "DIV") {
// Dump scroll event if the target is a DIV, because that means the event is coming
// from a scrollable div and so there's no need to make adjustments to our layout
return;
}
var scrollTop = $(window).scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var searchResultHeight = $('#searchResults').is(":visible") ?
$('#searchResults').outerHeight() : 0;
var totalHeaderHeight = headerHeight + subheaderHeight + searchResultHeight;
// we set the navbar fixed when the scroll position is beyond the height of the site header...
var navBarShouldBeFixed = scrollTop > totalHeaderHeight;
// ... except if the document content is shorter than the sidenav height.
// (this is necessary to avoid crazy behavior on OSX Lion due to overscroll bouncing)
if ($("#doc-col").height() < $("#side-nav").height()) {
navBarShouldBeFixed = false;
}
var scrollLeft = $(window).scrollLeft();
// When the sidenav is fixed and user scrolls horizontally, reposition the sidenav to match
if (navBarIsFixed && (scrollLeft != prevScrollLeft)) {
updateSideNavPosition();
prevScrollLeft = scrollLeft;
}
// Don't continue if the header is sufficently far away
// (to avoid intensive resizing that slows scrolling)
if (navBarIsFixed && navBarShouldBeFixed) {
return;
}
if (navBarIsFixed != navBarShouldBeFixed) {
if (navBarShouldBeFixed) {
// make it fixed
var width = $('#devdoc-nav').width();
$('#devdoc-nav')
.addClass('fixed')
.css({'width':width+'px'})
.prependTo('#body-content');
// add neato "back to top" button
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
// update the sidenaav position for side scrolling
updateSideNavPosition();
} else {
// make it static again
$('#devdoc-nav')
.removeClass('fixed')
.css({'width':'auto','margin':''})
.prependTo('#side-nav');
$('#devdoc-nav a.totop').hide();
}
navBarIsFixed = navBarShouldBeFixed;
}
resizeNav(250); // pass true in order to delay the scrollbar re-initialization for performance
});
var navBarLeftPos;
if ($('#devdoc-nav').length) {
setNavBarLeftPos();
}
// Stop expand/collapse behavior when clicking on nav section links (since we're navigating away
// from the page)
$('.nav-section-header').find('a:eq(0)').click(function(evt) {
window.location.href = $(this).attr('href');
return false;
});
// Set up play-on-hover <video> tags.
$('video.play-on-hover').bind('click', function(){
$(this).get(0).load(); // in case the video isn't seekable
$(this).get(0).play();
});
// Set up tooltips
var TOOLTIP_MARGIN = 10;
$('acronym,.tooltip-link').each(function() {
var $target = $(this);
var $tooltip = $('<div>')
.addClass('tooltip-box')
.append($target.attr('title'))
.hide()
.appendTo('body');
$target.removeAttr('title');
$target.hover(function() {
// in
var targetRect = $target.offset();
targetRect.width = $target.width();
targetRect.height = $target.height();
$tooltip.css({
left: targetRect.left,
top: targetRect.top + targetRect.height + TOOLTIP_MARGIN
});
$tooltip.addClass('below');
$tooltip.show();
}, function() {
// out
$tooltip.hide();
});
});
// Set up <h2> deeplinks
$('h2').click(function() {
var id = $(this).attr('id');
if (id) {
document.location.hash = id;
}
});
//Loads the +1 button
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
// Revise the sidenav widths to make room for the scrollbar
// which avoids the visible width from changing each time the bar appears
var $sidenav = $("#side-nav");
var sidenav_width = parseInt($sidenav.innerWidth());
$("#devdoc-nav #nav").css("width", sidenav_width - 4 + "px"); // 4px is scrollbar width
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
if ($(".scroll-pane").length > 1) {
// Check if there's a user preference for the panel heights
var cookieHeight = readCookie("reference_height");
if (cookieHeight) {
restoreHeight(cookieHeight);
}
}
resizeNav();
/* init the language selector based on user cookie for lang */
loadLangPref();
changeNavLang(getLangPref());
/* setup event handlers to ensure the overflow menu is visible while picking lang */
$("#language select")
.mousedown(function() {
$("div.morehover").addClass("hover"); })
.blur(function() {
$("div.morehover").removeClass("hover"); });
/* some global variable setup */
resizePackagesNav = $("#resize-packages-nav");
classesNav = $("#classes-nav");
devdocNav = $("#devdoc-nav");
var cookiePath = "";
if (location.href.indexOf("/reference/") != -1) {
cookiePath = "reference_";
} else if (location.href.indexOf("/guide/") != -1) {
cookiePath = "guide_";
} else if (location.href.indexOf("/tools/") != -1) {
cookiePath = "tools_";
} else if (location.href.indexOf("/training/") != -1) {
cookiePath = "training_";
} else if (location.href.indexOf("/design/") != -1) {
cookiePath = "design_";
} else if (location.href.indexOf("/distribute/") != -1) {
cookiePath = "distribute_";
}
});
function toggleFullscreen(enable) {
var delay = 20;
var enabled = true;
var stylesheet = $('link[rel="stylesheet"][class="fullscreen"]');
if (enable) {
// Currently NOT USING fullscreen; enable fullscreen
stylesheet.removeAttr('disabled');
$('#nav-swap .fullscreen').removeClass('disabled');
$('#devdoc-nav').css({left:''});
setTimeout(updateSidenavFullscreenWidth,delay); // need to wait a moment for css to switch
enabled = true;
} else {
// Currently USING fullscreen; disable fullscreen
stylesheet.attr('disabled', 'disabled');
$('#nav-swap .fullscreen').addClass('disabled');
setTimeout(updateSidenavFixedWidth,delay); // need to wait a moment for css to switch
enabled = false;
}
writeCookie("fullscreen", enabled, null, null);
setNavBarLeftPos();
resizeNav(delay);
updateSideNavPosition();
setTimeout(initSidenavHeightResize,delay);
}
function setNavBarLeftPos() {
navBarLeftPos = $('#body-content').offset().left;
}
function updateSideNavPosition() {
var newLeft = $(window).scrollLeft() - navBarLeftPos;
$('#devdoc-nav').css({left: -newLeft});
$('#devdoc-nav .totop').css({left: -(newLeft - parseInt($('#side-nav').css('margin-left')))});
}
// TODO: use $(document).ready instead
function addLoadEvent(newfun) {
var current = window.onload;
if (typeof window.onload != 'function') {
window.onload = newfun;
} else {
window.onload = function() {
current();
newfun();
}
}
}
var agent = navigator['userAgent'].toLowerCase();
// If a mobile phone, set flag and do mobile setup
if ((agent.indexOf("mobile") != -1) || // android, iphone, ipod
(agent.indexOf("blackberry") != -1) ||
(agent.indexOf("webos") != -1) ||
(agent.indexOf("mini") != -1)) { // opera mini browsers
isMobile = true;
}
/* loads the lists.js file to the page.
Loading this in the head was slowing page load time */
addLoadEvent( function() {
var lists = document.createElement("script");
lists.setAttribute("type","text/javascript");
lists.setAttribute("src", toRoot+"reference/lists.js");
document.getElementsByTagName("head")[0].appendChild(lists);
} );
addLoadEvent( function() {
$("pre:not(.no-pretty-print)").addClass("prettyprint");
prettyPrint();
} );
/* ######### RESIZE THE SIDENAV HEIGHT ########## */
function resizeNav(delay) {
var $nav = $("#devdoc-nav");
var $window = $(window);
var navHeight;
// Get the height of entire window and the total header height.
// Then figure out based on scroll position whether the header is visible
var windowHeight = $window.height();
var scrollTop = $window.scrollTop();
var headerHeight = $('#header').outerHeight();
var subheaderHeight = $('#nav-x').outerHeight();
var headerVisible = (scrollTop < (headerHeight + subheaderHeight));
// get the height of space between nav and top of window.
// Could be either margin or top position, depending on whether the nav is fixed.
var topMargin = (parseInt($nav.css('margin-top')) || parseInt($nav.css('top'))) + 1;
// add 1 for the #side-nav bottom margin
// Depending on whether the header is visible, set the side nav's height.
if (headerVisible) {
// The sidenav height grows as the header goes off screen
navHeight = windowHeight - (headerHeight + subheaderHeight - scrollTop) - topMargin;
} else {
// Once header is off screen, the nav height is almost full window height
navHeight = windowHeight - topMargin;
}
$scrollPanes = $(".scroll-pane");
if ($scrollPanes.length > 1) {
// subtract the height of the api level widget and nav swapper from the available nav height
navHeight -= ($('#api-nav-header').outerHeight(true) + $('#nav-swap').outerHeight(true));
$("#swapper").css({height:navHeight + "px"});
if ($("#nav-tree").is(":visible")) {
$("#nav-tree").css({height:navHeight});
}
var classesHeight = navHeight - parseInt($("#resize-packages-nav").css("height")) - 10 + "px";
//subtract 10px to account for drag bar
// if the window becomes small enough to make the class panel height 0,
// then the package panel should begin to shrink
if (parseInt(classesHeight) <= 0) {
$("#resize-packages-nav").css({height:navHeight - 10}); //subtract 10px for drag bar
$("#packages-nav").css({height:navHeight - 10});
}
$("#classes-nav").css({'height':classesHeight, 'margin-top':'10px'});
$("#classes-nav .jspContainer").css({height:classesHeight});
} else {
$nav.height(navHeight);
}
if (delay) {
updateFromResize = true;
delayedReInitScrollbars(delay);
} else {
reInitScrollbars();
}
}
var updateScrollbars = false;
var updateFromResize = false;
/* Re-initialize the scrollbars to account for changed nav size.
* This method postpones the actual update by a 1/4 second in order to optimize the
* scroll performance while the header is still visible, because re-initializing the
* scroll panes is an intensive process.
*/
function delayedReInitScrollbars(delay) {
// If we're scheduled for an update, but have received another resize request
// before the scheduled resize has occured, just ignore the new request
// (and wait for the scheduled one).
if (updateScrollbars && updateFromResize) {
updateFromResize = false;
return;
}
// We're scheduled for an update and the update request came from this method's setTimeout
if (updateScrollbars && !updateFromResize) {
reInitScrollbars();
updateScrollbars = false;
} else {
updateScrollbars = true;
updateFromResize = false;
setTimeout('delayedReInitScrollbars()',delay);
}
}
/* Re-initialize the scrollbars to account for changed nav size. */
function reInitScrollbars() {
var pane = $(".scroll-pane").each(function(){
var api = $(this).data('jsp');
if (!api) { setTimeout(reInitScrollbars,300); return;}
api.reinitialise( {verticalGutter:0} );
});
$(".scroll-pane").removeAttr("tabindex"); // get rid of tabindex added by jscroller
}
/* Resize the height of the nav panels in the reference,
* and save the new size to a cookie */
function saveNavPanels() {
var basePath = getBaseUri(location.pathname);
var section = basePath.substring(1,basePath.indexOf("/",1));
writeCookie("height", resizePackagesNav.css("height"), section, null);
}
function restoreHeight(packageHeight) {
$("#resize-packages-nav").height(packageHeight);
$("#packages-nav").height(packageHeight);
// var classesHeight = navHeight - packageHeight;
// $("#classes-nav").css({height:classesHeight});
// $("#classes-nav .jspContainer").css({height:classesHeight});
}
/* ######### END RESIZE THE SIDENAV HEIGHT ########## */
/** Scroll the jScrollPane to make the currently selected item visible
This is called when the page finished loading. */
function scrollIntoView(nav) {
var $nav = $("#"+nav);
var element = $nav.jScrollPane({/* ...settings... */});
var api = element.data('jsp');
if ($nav.is(':visible')) {
var $selected = $(".selected", $nav);
if ($selected.length == 0) return;
var selectedOffset = $selected.position().top;
if (selectedOffset + 90 > $nav.height()) { // add 90 so that we scroll up even
// if the current item is close to the bottom
api.scrollTo(0, selectedOffset - ($nav.height() / 4), false); // scroll the item into view
// to be 1/4 of the way from the top
}
}
}
/* Show popup dialogs */
function showDialog(id) {
$dialog = $("#"+id);
$dialog.prepend('<div class="box-border"><div class="top"> <div class="left"></div> <div class="right"></div></div><div class="bottom"> <div class="left"></div> <div class="right"></div> </div> </div>');
$dialog.wrapInner('<div/>');
$dialog.removeClass("hide");
}
/* ######### COOKIES! ########## */
function readCookie(cookie) {
var myCookie = cookie_namespace+"_"+cookie+"=";
if (document.cookie) {
var index = document.cookie.indexOf(myCookie);
if (index != -1) {
var valStart = index + myCookie.length;
var valEnd = document.cookie.indexOf(";", valStart);
if (valEnd == -1) {
valEnd = document.cookie.length;
}
var val = document.cookie.substring(valStart, valEnd);
return val;
}
}
return 0;
}
function writeCookie(cookie, val, section, expiration) {
if (val==undefined) return;
section = section == null ? "_" : "_"+section+"_";
if (expiration == null) {
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // default expiration is one week
expiration = date.toGMTString();
}
var cookieValue = cookie_namespace + section + cookie + "=" + val
+ "; expires=" + expiration+"; path=/";
document.cookie = cookieValue;
}
/* ######### END COOKIES! ########## */
/*
REMEMBER THE PREVIOUS PAGE FOR EACH TAB
function loadLast(cookiePath) {
var location = window.location.href;
if (location.indexOf("/"+cookiePath+"/") != -1) {
return true;
}
var lastPage = readCookie(cookiePath + "_lastpage");
if (lastPage) {
window.location = lastPage;
return false;
}
return true;
}
$(window).unload(function(){
var path = getBaseUri(location.pathname);
if (path.indexOf("/reference/") != -1) {
writeCookie("lastpage", path, "reference", null);
} else if (path.indexOf("/guide/") != -1) {
writeCookie("lastpage", path, "guide", null);
} else if ((path.indexOf("/resources/") != -1) || (path.indexOf("/training/") != -1)) {
writeCookie("lastpage", path, "resources", null);
}
});
*/
function toggle(obj, slide) {
var ul = $("ul:first", obj);
var li = ul.parent();
if (li.hasClass("closed")) {
if (slide) {
ul.slideDown("fast");
} else {
ul.show();
}
li.removeClass("closed");
li.addClass("open");
$(".toggle-img", li).attr("title", "hide pages");
} else {
ul.slideUp("fast");
li.removeClass("open");
li.addClass("closed");
$(".toggle-img", li).attr("title", "show pages");
}
}
function buildToggleLists() {
$(".toggle-list").each(
function(i) {
$("div:first", this).append("<a class='toggle-img' href='#' title='show pages' onClick='toggle(this.parentNode.parentNode, true); return false;'></a>");
$(this).addClass("closed");
});
}
/* REFERENCE NAV SWAP */
function getNavPref() {
var v = readCookie('reference_nav');
if (v != NAV_PREF_TREE) {
v = NAV_PREF_PANELS;
}
return v;
}
function chooseDefaultNav() {
nav_pref = getNavPref();
if (nav_pref == NAV_PREF_TREE) {
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
}
}
function swapNav() {
if (nav_pref == NAV_PREF_TREE) {
nav_pref = NAV_PREF_PANELS;
} else {
nav_pref = NAV_PREF_TREE;
init_default_navtree(toRoot);
}
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
writeCookie("nav", nav_pref, "reference", date.toGMTString());
$("#nav-panels").toggle();
$("#panel-link").toggle();
$("#nav-tree").toggle();
$("#tree-link").toggle();
resizeNav();
// Gross nasty hack to make tree view show up upon first swap by setting height manually
$("#nav-tree .jspContainer:visible")
.css({'height':$("#nav-tree .jspContainer .jspPane").height() +'px'});
// Another nasty hack to make the scrollbar appear now that we have height
resizeNav();
if ($("#nav-tree").is(':visible')) {
scrollIntoView("nav-tree");
} else {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
}
}
/* ############################################ */
/* ########## LOCALIZATION ############ */
/* ############################################ */
function getBaseUri(uri) {
var intlUrl = (uri.substring(0,6) == "/intl/");
if (intlUrl) {
base = uri.substring(uri.indexOf('intl/')+5,uri.length);
base = base.substring(base.indexOf('/')+1, base.length);
//alert("intl, returning base url: /" + base);
return ("/" + base);
} else {
//alert("not intl, returning uri as found.");
return uri;
}
}
function requestAppendHL(uri) {
//append "?hl=<lang> to an outgoing request (such as to blog)
var lang = getLangPref();
if (lang) {
var q = 'hl=' + lang;
uri += '?' + q;
window.location = uri;
return false;
} else {
return true;
}
}
function changeNavLang(lang) {
var $links = $("#devdoc-nav,#header,#nav-x,.training-nav-top,.content-footer").find("a["+lang+"-lang]");
$links.each(function(i){ // for each link with a translation
var $link = $(this);
if (lang != "en") { // No need to worry about English, because a language change invokes new request
// put the desired language from the attribute as the text
$link.text($link.attr(lang+"-lang"))
}
});
}
function changeLangPref(lang, submit) {
var date = new Date();
expires = date.toGMTString(date.setTime(date.getTime()+(10*365*24*60*60*1000)));
// keep this for 50 years
//alert("expires: " + expires)
writeCookie("pref_lang", lang, null, expires);
// ####### TODO: Remove this condition once we're stable on devsite #######
// This condition is only needed if we still need to support legacy GAE server
if (devsite) {
// Switch language when on Devsite server
if (submit) {
$("#setlang").submit();
}
} else {
// Switch language when on legacy GAE server
if (submit) {
window.location = getBaseUri(location.pathname);
}
}
}
function loadLangPref() {
var lang = readCookie("pref_lang");
if (lang != 0) {
$("#language").find("option[value='"+lang+"']").attr("selected",true);
}
}
function getLangPref() {
var lang = $("#language").find(":selected").attr("value");
if (!lang) {
lang = readCookie("pref_lang");
}
return (lang != 0) ? lang : 'en';
}
/* ########## END LOCALIZATION ############ */
/* Used to hide and reveal supplemental content, such as long code samples.
See the companion CSS in android-developer-docs.css */
function toggleContent(obj) {
var div = $(obj.parentNode.parentNode);
var toggleMe = $(".toggle-content-toggleme",div);
if (div.hasClass("closed")) { // if it's closed, open it
toggleMe.slideDown();
$(".toggle-content-text", obj).toggle();
div.removeClass("closed").addClass("open");
$(".toggle-content-img", div).attr("title", "hide").attr("src", toRoot
+ "assets/images/triangle-opened.png");
} else { // if it's open, close it
toggleMe.slideUp('fast', function() { // Wait until the animation is done before closing arrow
$(".toggle-content-text", obj).toggle();
div.removeClass("open").addClass("closed");
$(".toggle-content-img", div).attr("title", "show").attr("src", toRoot
+ "assets/images/triangle-closed.png");
});
}
return false;
}
/* New version of expandable content */
function toggleExpandable(link,id) {
if($(id).is(':visible')) {
$(id).slideUp();
$(link).removeClass('expanded');
} else {
$(id).slideDown();
$(link).addClass('expanded');
}
}
function hideExpandable(ids) {
$(ids).slideUp();
$(ids).prev('h4').find('a.expandable').removeClass('expanded');
}
/*
* Slideshow 1.0
* Used on /index.html and /develop/index.html for carousel
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* btnPause: optional identifier for pause button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacSlideshow = function(o) {
//Options - see above
o = $.extend({
btnPrev: null,
btnNext: null,
btnPause: null,
auto: true,
speed: 500,
autoTime: 12000,
easing: null,
start: 0,
scroll: 1,
pagination: true
}, o || {});
//Set up a carousel for each
return this.each(function() {
var running = false;
var animCss = o.vertical ? "top" : "left";
var sizeCss = o.vertical ? "height" : "width";
var div = $(this);
var ul = $("ul", div);
var tLi = $("li", ul);
var tl = tLi.size();
var timer = null;
var li = $("li", ul);
var itemLength = li.size();
var curr = o.start;
li.css({float: o.vertical ? "none" : "left"});
ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"});
div.css({position: "relative", "z-index": "2", left: "0px"});
var liSize = o.vertical ? height(li) : width(li);
var ulSize = liSize * itemLength;
var divSize = liSize;
li.css({width: li.width(), height: li.height()});
ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize));
div.css(sizeCss, divSize+"px");
//Pagination
if (o.pagination) {
var pagination = $("<div class='pagination'></div>");
var pag_ul = $("<ul></ul>");
if (tl > 1) {
for (var i=0;i<tl;i++) {
var li = $("<li>"+i+"</li>");
pag_ul.append(li);
if (i==o.start) li.addClass('active');
li.click(function() {
go(parseInt($(this).text()));
})
}
pagination.append(pag_ul);
div.append(pagination);
}
}
//Previous button
if(o.btnPrev)
$(o.btnPrev).click(function(e) {
e.preventDefault();
return go(curr-o.scroll);
});
//Next button
if(o.btnNext)
$(o.btnNext).click(function(e) {
e.preventDefault();
return go(curr+o.scroll);
});
//Pause button
if(o.btnPause)
$(o.btnPause).click(function(e) {
e.preventDefault();
if ($(this).hasClass('paused')) {
startRotateTimer();
} else {
pauseRotateTimer();
}
});
//Auto rotation
if(o.auto) startRotateTimer();
function startRotateTimer() {
clearInterval(timer);
timer = setInterval(function() {
if (curr == tl-1) {
go(0);
} else {
go(curr+o.scroll);
}
}, o.autoTime);
$(o.btnPause).removeClass('paused');
}
function pauseRotateTimer() {
clearInterval(timer);
$(o.btnPause).addClass('paused');
}
//Go to an item
function go(to) {
if(!running) {
if(to<0) {
to = itemLength-1;
} else if (to>itemLength-1) {
to = 0;
}
curr = to;
running = true;
ul.animate(
animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing,
function() {
running = false;
}
);
$(o.btnPrev + "," + o.btnNext).removeClass("disabled");
$( (curr-o.scroll<0 && o.btnPrev)
||
(curr+o.scroll > itemLength && o.btnNext)
||
[]
).addClass("disabled");
var nav_items = $('li', pagination);
nav_items.removeClass('active');
nav_items.eq(to).addClass('active');
}
if(o.auto) startRotateTimer();
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/*
* dacSlideshow 1.0
* Used on develop/index.html for side-sliding tabs
*
* Sample usage:
* HTML -
* <div class="slideshow-container">
* <a href="" class="slideshow-prev">Prev</a>
* <a href="" class="slideshow-next">Next</a>
* <ul>
* <li class="item"><img src="images/marquee1.jpg"></li>
* <li class="item"><img src="images/marquee2.jpg"></li>
* <li class="item"><img src="images/marquee3.jpg"></li>
* <li class="item"><img src="images/marquee4.jpg"></li>
* </ul>
* </div>
*
* <script type="text/javascript">
* $('.slideshow-container').dacSlideshow({
* auto: true,
* btnPrev: '.slideshow-prev',
* btnNext: '.slideshow-next'
* });
* </script>
*
* Options:
* btnPrev: optional identifier for previous button
* btnNext: optional identifier for next button
* auto: whether or not to auto-proceed
* speed: animation speed
* autoTime: time between auto-rotation
* easing: easing function for transition
* start: item to select by default
* scroll: direction to scroll in
* pagination: whether or not to include dotted pagination
*
*/
(function($) {
$.fn.dacTabbedList = function(o) {
//Options - see above
o = $.extend({
speed : 250,
easing: null,
nav_id: null,
frame_id: null
}, o || {});
//Set up a carousel for each
return this.each(function() {
var curr = 0;
var running = false;
var animCss = "margin-left";
var sizeCss = "width";
var div = $(this);
var nav = $(o.nav_id, div);
var nav_li = $("li", nav);
var nav_size = nav_li.size();
var frame = div.find(o.frame_id);
var content_width = $(frame).find('ul').width();
//Buttons
$(nav_li).click(function(e) {
go($(nav_li).index($(this)));
})
//Go to an item
function go(to) {
if(!running) {
curr = to;
running = true;
frame.animate({ 'margin-left' : -(curr*content_width) }, o.speed, o.easing,
function() {
running = false;
}
);
nav_li.removeClass('active');
nav_li.eq(to).addClass('active');
}
return false;
};
});
};
function css(el, prop) {
return parseInt($.css(el[0], prop)) || 0;
};
function width(el) {
return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
};
function height(el) {
return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
};
})(jQuery);
/* ######################################################## */
/* ################ SEARCH SUGGESTIONS ################## */
/* ######################################################## */
var gSelectedIndex = -1;
var gSelectedID = -1;
var gMatches = new Array();
var gLastText = "";
var ROW_COUNT = 20;
var gInitialized = false;
function set_item_selected($li, selected)
{
if (selected) {
$li.attr('class','jd-autocomplete jd-selected');
} else {
$li.attr('class','jd-autocomplete');
}
}
function set_item_values(toroot, $li, match)
{
var $link = $('a',$li);
$link.html(match.__hilabel || match.label);
$link.attr('href',toroot + match.link);
}
function sync_selection_table(toroot)
{
var $list = $("#search_filtered");
var $li; //list item jquery object
var i; //list item iterator
gSelectedID = -1;
//initialize the table; draw it for the first time (but not visible).
if (!gInitialized) {
for (i=0; i<ROW_COUNT; i++) {
var $li = $("<li class='jd-autocomplete'></li>");
$list.append($li);
$li.mousedown(function() {
window.location = this.firstChild.getAttribute("href");
});
$li.mouseover(function() {
$('#search_filtered li').removeClass('jd-selected');
$(this).addClass('jd-selected');
gSelectedIndex = $('#search_filtered li').index(this);
});
$li.append('<a></a>');
}
gInitialized = true;
}
//if we have results, make the table visible and initialize result info
if (gMatches.length > 0) {
$('#search_filtered_div').removeClass('no-display');
var N = gMatches.length < ROW_COUNT ? gMatches.length : ROW_COUNT;
for (i=0; i<N; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','show-item');
set_item_values(toroot, $li, gMatches[i]);
set_item_selected($li, i == gSelectedIndex);
if (i == gSelectedIndex) {
gSelectedID = gMatches[i].id;
}
}
//start hiding rows that are no longer matches
for (; i<ROW_COUNT; i++) {
$li = $('#search_filtered li:nth-child('+(i+1)+')');
$li.attr('class','no-display');
}
//if there are more results we're not showing, so say so.
/* if (gMatches.length > ROW_COUNT) {
li = list.rows[ROW_COUNT];
li.className = "show-item";
c1 = li.cells[0];
c1.innerHTML = "plus " + (gMatches.length-ROW_COUNT) + " more";
} else {
list.rows[ROW_COUNT].className = "hide-item";
}*/
//if we have no results, hide the table
} else {
$('#search_filtered_div').addClass('no-display');
}
}
function search_changed(e, kd, toroot)
{
var search = document.getElementById("search_autocomplete");
var text = search.value.replace(/(^ +)|( +$)/g, '');
// show/hide the close button
if (text != '') {
$(".search .close").removeClass("hide");
} else {
$(".search .close").addClass("hide");
}
// 13 = enter
if (e.keyCode == 13) {
$('#search_filtered_div').addClass('no-display');
if (!$('#search_filtered_div').hasClass('no-display') || (gSelectedIndex < 0)) {
if ($("#searchResults").is(":hidden")) {
// if results aren't showing, return true to allow search to execute
return true;
} else {
// otherwise, results are already showing, so allow ajax to auto refresh the results
// and ignore this Enter press to avoid the reload.
return false;
}
} else if (kd && gSelectedIndex >= 0) {
window.location = toroot + gMatches[gSelectedIndex].link;
return false;
}
}
// 38 -- arrow up
else if (kd && (e.keyCode == 38)) {
if (gSelectedIndex >= 0) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex--;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
// 40 -- arrow down
else if (kd && (e.keyCode == 40)) {
if (gSelectedIndex < gMatches.length-1
&& gSelectedIndex < ROW_COUNT-1) {
$('#search_filtered li').removeClass('jd-selected');
gSelectedIndex++;
$('#search_filtered li:nth-child('+(gSelectedIndex+1)+')').addClass('jd-selected');
}
return false;
}
else if (!kd && (e.keyCode != 40) && (e.keyCode != 38)) {
gMatches = new Array();
matchedCount = 0;
gSelectedIndex = -1;
for (var i=0; i<DATA.length; i++) {
var s = DATA[i];
if (text.length != 0 &&
s.label.toLowerCase().indexOf(text.toLowerCase()) != -1) {
gMatches[matchedCount] = s;
matchedCount++;
}
}
rank_autocomplete_results(text);
for (var i=0; i<gMatches.length; i++) {
var s = gMatches[i];
if (gSelectedID == s.id) {
gSelectedIndex = i;
}
}
highlight_autocomplete_result_labels(text);
sync_selection_table(toroot);
return true; // allow the event to bubble up to the search api
}
}
function rank_autocomplete_results(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
// helper function that gets the last occurence index of the given regex
// in the given string, or -1 if not found
var _lastSearch = function(s, re) {
if (s == '')
return -1;
var l = -1;
var tmp;
while ((tmp = s.search(re)) >= 0) {
if (l < 0) l = 0;
l += tmp;
s = s.substr(tmp + 1);
}
return l;
};
// helper function that counts the occurrences of a given character in
// a given string
var _countChar = function(s, c) {
var n = 0;
for (var i=0; i<s.length; i++)
if (s.charAt(i) == c) ++n;
return n;
};
var queryLower = query.toLowerCase();
var queryAlnum = (queryLower.match(/\w+/) || [''])[0];
var partPrefixAlnumRE = new RegExp('\\b' + queryAlnum);
var partExactAlnumRE = new RegExp('\\b' + queryAlnum + '\\b');
var _resultScoreFn = function(result) {
// scores are calculated based on exact and prefix matches,
// and then number of path separators (dots) from the last
// match (i.e. favoring classes and deep package names)
var score = 1.0;
var labelLower = result.label.toLowerCase();
var t;
t = _lastSearch(labelLower, partExactAlnumRE);
if (t >= 0) {
// exact part match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 200 / (partsAfter + 1);
} else {
t = _lastSearch(labelLower, partPrefixAlnumRE);
if (t >= 0) {
// part prefix match
var partsAfter = _countChar(labelLower.substr(t + 1), '.');
score *= 20 / (partsAfter + 1);
}
}
return score;
};
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__resultScore = _resultScoreFn(gMatches[i]);
}
gMatches.sort(function(a,b){
var n = b.__resultScore - a.__resultScore;
if (n == 0) // lexicographical sort if scores are the same
n = (a.label < b.label) ? -1 : 1;
return n;
});
}
function highlight_autocomplete_result_labels(query) {
query = query || '';
if (!gMatches || !gMatches.length)
return;
var queryLower = query.toLowerCase();
var queryAlnumDot = (queryLower.match(/[\w\.]+/) || [''])[0];
var queryRE = new RegExp(
'(' + queryAlnumDot.replace(/\./g, '\\.') + ')', 'ig');
for (var i=0; i<gMatches.length; i++) {
gMatches[i].__hilabel = gMatches[i].label.replace(
queryRE, '<b>$1</b>');
}
}
function search_focus_changed(obj, focused)
{
if (!focused) {
if(obj.value == ""){
$(".search .close").addClass("hide");
}
document.getElementById("search_filtered_div").className = "no-display";
}
}
function submit_search() {
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
loadSearchResults();
$("#searchResults").slideDown('slow');
return false;
}
function hideResults() {
$("#searchResults").slideUp();
$(".search .close").addClass("hide");
location.hash = '';
$("#search_autocomplete").val("").blur();
// reset the ajax search callback to nothing, so results don't appear unless ENTER
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {});
return false;
}
/* ########################################################## */
/* ################ CUSTOM SEARCH ENGINE ################## */
/* ########################################################## */
google.load('search', '1');
var searchControl;
function loadSearchResults() {
document.getElementById("search_autocomplete").style.color = "#000";
// create search control
searchControl = new google.search.SearchControl();
// use our existing search form and use tabs when multiple searchers are used
drawOptions = new google.search.DrawOptions();
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
drawOptions.setInput(document.getElementById("search_autocomplete"));
// configure search result options
searchOptions = new google.search.SearcherOptions();
searchOptions.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
// configure each of the searchers, for each tab
devSiteSearcher = new google.search.WebSearch();
devSiteSearcher.setUserDefinedLabel("All");
devSiteSearcher.setSiteRestriction("001482626316274216503:zu90b7s047u");
designSearcher = new google.search.WebSearch();
designSearcher.setUserDefinedLabel("Design");
designSearcher.setSiteRestriction("http://developer.android.com/design/");
trainingSearcher = new google.search.WebSearch();
trainingSearcher.setUserDefinedLabel("Training");
trainingSearcher.setSiteRestriction("http://developer.android.com/training/");
guidesSearcher = new google.search.WebSearch();
guidesSearcher.setUserDefinedLabel("Guides");
guidesSearcher.setSiteRestriction("http://developer.android.com/guide/");
referenceSearcher = new google.search.WebSearch();
referenceSearcher.setUserDefinedLabel("Reference");
referenceSearcher.setSiteRestriction("http://developer.android.com/reference/");
googleSearcher = new google.search.WebSearch();
googleSearcher.setUserDefinedLabel("Google Services");
googleSearcher.setSiteRestriction("http://developer.android.com/google/");
blogSearcher = new google.search.WebSearch();
blogSearcher.setUserDefinedLabel("Blog");
blogSearcher.setSiteRestriction("http://android-developers.blogspot.com");
// add each searcher to the search control
searchControl.addSearcher(devSiteSearcher, searchOptions);
searchControl.addSearcher(designSearcher, searchOptions);
searchControl.addSearcher(trainingSearcher, searchOptions);
searchControl.addSearcher(guidesSearcher, searchOptions);
searchControl.addSearcher(referenceSearcher, searchOptions);
searchControl.addSearcher(googleSearcher, searchOptions);
searchControl.addSearcher(blogSearcher, searchOptions);
// configure result options
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
searchControl.setTimeoutInterval(google.search.SearchControl.TIMEOUT_SHORT);
searchControl.setNoResultsString(google.search.SearchControl.NO_RESULTS_DEFAULT_STRING);
// upon ajax search, refresh the url and search title
searchControl.setSearchStartingCallback(this, function(control, searcher, query) {
updateResultTitle(query);
var query = document.getElementById('search_autocomplete').value;
location.hash = 'q=' + query;
});
// draw the search results box
searchControl.draw(document.getElementById("leftSearchControl"), drawOptions);
// get query and execute the search
searchControl.execute(decodeURI(getQuery(location.hash)));
document.getElementById("search_autocomplete").focus();
addTabListeners();
}
// End of loadSearchResults
google.setOnLoadCallback(function(){
if (location.hash.indexOf("q=") == -1) {
// if there's no query in the url, don't search and make sure results are hidden
$('#searchResults').hide();
return;
} else {
// first time loading search results for this page
$('#searchResults').slideDown('slow');
$(".search .close").removeClass("hide");
loadSearchResults();
}
}, true);
// when an event on the browser history occurs (back, forward, load) requery hash and do search
$(window).hashchange( function(){
// Exit if the hash isn't a search query or there's an error in the query
if ((location.hash.indexOf("q=") == -1) || (query == "undefined")) {
// If the results pane is open, close it.
if (!$("#searchResults").is(":hidden")) {
hideResults();
}
return;
}
// Otherwise, we have a search to do
var query = decodeURI(getQuery(location.hash));
searchControl.execute(query);
$('#searchResults').slideDown('slow');
$("#search_autocomplete").focus();
$(".search .close").removeClass("hide");
updateResultTitle(query);
});
function updateResultTitle(query) {
$("#searchTitle").html("Results for <em>" + escapeHTML(query) + "</em>");
}
// forcefully regain key-up event control (previously jacked by search api)
$("#search_autocomplete").keyup(function(event) {
return search_changed(event, false, toRoot);
});
// add event listeners to each tab so we can track the browser history
function addTabListeners() {
var tabHeaders = $(".gsc-tabHeader");
for (var i = 0; i < tabHeaders.length; i++) {
$(tabHeaders[i]).attr("id",i).click(function() {
/*
// make a copy of the page numbers for the search left pane
setTimeout(function() {
// remove any residual page numbers
$('#searchResults .gsc-tabsArea .gsc-cursor-box.gs-bidi-start-align').remove();
// move the page numbers to the left position; make a clone,
// because the element is drawn to the DOM only once
// and because we're going to remove it (previous line),
// we need it to be available to move again as the user navigates
$('#searchResults .gsc-webResult .gsc-cursor-box.gs-bidi-start-align:visible')
.clone().appendTo('#searchResults .gsc-tabsArea');
}, 200);
*/
});
}
setTimeout(function(){$(tabHeaders[0]).click()},200);
}
function getQuery(hash) {
var queryParts = hash.split('=');
return queryParts[1];
}
/* returns the given string with all HTML brackets converted to entities
TODO: move this to the site's JS library */
function escapeHTML(string) {
return string.replace(/</g,"<")
.replace(/>/g,">");
}
/* ######################################################## */
/* ################# JAVADOC REFERENCE ################### */
/* ######################################################## */
/* Initialize some droiddoc stuff, but only if we're in the reference */
if (location.pathname.indexOf("/reference")) {
if(!location.pathname.indexOf("/reference-gms/packages.html")
&& !location.pathname.indexOf("/reference-gcm/packages.html")
&& !location.pathname.indexOf("/reference/com/google") == 0) {
$(document).ready(function() {
// init available apis based on user pref
changeApiLevel();
initSidenavHeightResize()
});
}
}
var API_LEVEL_COOKIE = "api_level";
var minLevel = 1;
var maxLevel = 1;
/******* SIDENAV DIMENSIONS ************/
function initSidenavHeightResize() {
// Change the drag bar size to nicely fit the scrollbar positions
var $dragBar = $(".ui-resizable-s");
$dragBar.css({'width': $dragBar.parent().width() - 5 + "px"});
$( "#resize-packages-nav" ).resizable({
containment: "#nav-panels",
handles: "s",
alsoResize: "#packages-nav",
resize: function(event, ui) { resizeNav(); }, /* resize the nav while dragging */
stop: function(event, ui) { saveNavPanels(); } /* once stopped, save the sizes to cookie */
});
}
function updateSidenavFixedWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav a.totop').css({'display':'block','width':$("#nav").innerWidth()+'px'});
initSidenavHeightResize();
}
function updateSidenavFullscreenWidth() {
if (!navBarIsFixed) return;
$('#devdoc-nav').css({
'width' : $('#side-nav').css('width'),
'margin' : $('#side-nav').css('margin')
});
$('#devdoc-nav .totop').css({'left': 'inherit'});
initSidenavHeightResize();
}
function buildApiLevelSelector() {
maxLevel = SINCE_DATA.length;
var userApiLevel = parseInt(readCookie(API_LEVEL_COOKIE));
userApiLevel = userApiLevel == 0 ? maxLevel : userApiLevel; // If there's no cookie (zero), use the max by default
minLevel = parseInt($("#doc-api-level").attr("class"));
// Handle provisional api levels; the provisional level will always be the highest possible level
// Provisional api levels will also have a length; other stuff that's just missing a level won't,
// so leave those kinds of entities at the default level of 1 (for example, the R.styleable class)
if (isNaN(minLevel) && minLevel.length) {
minLevel = maxLevel;
}
var select = $("#apiLevelSelector").html("").change(changeApiLevel);
for (var i = maxLevel-1; i >= 0; i--) {
var option = $("<option />").attr("value",""+SINCE_DATA[i]).append(""+SINCE_DATA[i]);
// if (SINCE_DATA[i] < minLevel) option.addClass("absent"); // always false for strings (codenames)
select.append(option);
}
// get the DOM element and use setAttribute cuz IE6 fails when using jquery .attr('selected',true)
var selectedLevelItem = $("#apiLevelSelector option[value='"+userApiLevel+"']").get(0);
selectedLevelItem.setAttribute('selected',true);
}
function changeApiLevel() {
maxLevel = SINCE_DATA.length;
var selectedLevel = maxLevel;
selectedLevel = parseInt($("#apiLevelSelector option:selected").val());
toggleVisisbleApis(selectedLevel, "body");
var date = new Date();
date.setTime(date.getTime()+(10*365*24*60*60*1000)); // keep this for 10 years
var expiration = date.toGMTString();
writeCookie(API_LEVEL_COOKIE, selectedLevel, null, expiration);
if (selectedLevel < minLevel) {
var thing = ($("#jd-header").html().indexOf("package") != -1) ? "package" : "class";
$("#naMessage").show().html("<div><p><strong>This " + thing
+ " requires API level " + minLevel + " or higher.</strong></p>"
+ "<p>This document is hidden because your selected API level for the documentation is "
+ selectedLevel + ". You can change the documentation API level with the selector "
+ "above the left navigation.</p>"
+ "<p>For more information about specifying the API level your app requires, "
+ "read <a href='" + toRoot + "training/basics/supporting-devices/platforms.html'"
+ ">Supporting Different Platform Versions</a>.</p>"
+ "<input type='button' value='OK, make this page visible' "
+ "title='Change the API level to " + minLevel + "' "
+ "onclick='$(\"#apiLevelSelector\").val(\"" + minLevel + "\");changeApiLevel();' />"
+ "</div>");
} else {
$("#naMessage").hide();
}
}
function toggleVisisbleApis(selectedLevel, context) {
var apis = $(".api",context);
apis.each(function(i) {
var obj = $(this);
var className = obj.attr("class");
var apiLevelIndex = className.lastIndexOf("-")+1;
var apiLevelEndIndex = className.indexOf(" ", apiLevelIndex);
apiLevelEndIndex = apiLevelEndIndex != -1 ? apiLevelEndIndex : className.length;
var apiLevel = className.substring(apiLevelIndex, apiLevelEndIndex);
if (apiLevel.length == 0) { // for odd cases when the since data is actually missing, just bail
return;
}
apiLevel = parseInt(apiLevel);
// Handle provisional api levels; if this item's level is the provisional one, set it to the max
var selectedLevelNum = parseInt(selectedLevel)
var apiLevelNum = parseInt(apiLevel);
if (isNaN(apiLevelNum)) {
apiLevelNum = maxLevel;
}
// Grey things out that aren't available and give a tooltip title
if (apiLevelNum > selectedLevelNum) {
obj.addClass("absent").attr("title","Requires API Level \""
+ apiLevel + "\" or higher");
}
else obj.removeClass("absent").removeAttr("title");
});
}
/* ################# SIDENAV TREE VIEW ################### */
function new_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
node.label_div = document.createElement("div");
node.label_div.className = "label";
if (api_level != null) {
$(node.label_div).addClass("api");
$(node.label_div).addClass("api-level-"+api_level);
}
node.li.appendChild(node.label_div);
if (children_data != null) {
node.expand_toggle = document.createElement("a");
node.expand_toggle.href = "javascript:void(0)";
node.expand_toggle.onclick = function() {
if (node.expanded) {
$(node.get_children_ul()).slideUp("fast");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.expanded = false;
} else {
expand_node(me, node);
}
};
node.label_div.appendChild(node.expand_toggle);
node.plus_img = document.createElement("img");
node.plus_img.src = me.toroot + "assets/images/triangle-closed-small.png";
node.plus_img.className = "plus";
node.plus_img.width = "8";
node.plus_img.border = "0";
node.expand_toggle.appendChild(node.plus_img);
node.expanded = false;
}
var a = document.createElement("a");
node.label_div.appendChild(a);
node.label = document.createTextNode(text);
a.appendChild(node.label);
if (link) {
a.href = me.toroot + link;
} else {
if (children_data != null) {
a.className = "nolink";
a.href = "javascript:void(0)";
a.onclick = node.expand_toggle.onclick;
// This next line shouldn't be necessary. I'll buy a beer for the first
// person who figures out how to remove this line and have the link
// toggle shut on the first try. --joeo@android.com
node.expanded = false;
}
}
node.children_ul = null;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "children_ul";
node.children_ul.style.display = "none";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
return node;
}
function expand_node(me, node)
{
if (node.children_data && !node.expanded) {
if (node.children_visited) {
$(node.get_children_ul()).slideDown("fast");
} else {
get_node(me, node);
if ($(node.label_div).hasClass("absent")) {
$(node.get_children_ul()).addClass("absent");
}
$(node.get_children_ul()).slideDown("fast");
}
node.plus_img.src = me.toroot + "assets/images/triangle-opened-small.png";
node.expanded = true;
// perform api level toggling because new nodes are new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
}
function get_node(me, mom)
{
mom.children_visited = true;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
mom.children[i] = new_node(me, mom, node_data[0], node_data[1],
node_data[2], node_data[3]);
}
}
function this_page_relative(toroot)
{
var full = document.location.pathname;
var file = "";
if (toroot.substr(0, 1) == "/") {
if (full.substr(0, toroot.length) == toroot) {
return full.substr(toroot.length);
} else {
// the file isn't under toroot. Fail.
return null;
}
} else {
if (toroot != "./") {
toroot = "./" + toroot;
}
do {
if (toroot.substr(toroot.length-3, 3) == "../" || toroot == "./") {
var pos = full.lastIndexOf("/");
file = full.substr(pos) + file;
full = full.substr(0, pos);
toroot = toroot.substr(0, toroot.length-3);
}
} while (toroot != "" && toroot != "/");
return file.substr(1);
}
}
function find_page(url, data)
{
var nodes = data;
var result = null;
for (var i in nodes) {
var d = nodes[i];
if (d[1] == url) {
return new Array(i);
}
else if (d[2] != null) {
result = find_page(url, d[2]);
if (result != null) {
return (new Array(i).concat(result));
}
}
}
return null;
}
function init_default_navtree(toroot) {
init_navtree("tree-list", toroot, NAVTREE_DATA);
// perform api level toggling because because the whole tree is new to the DOM
var selectedLevel = $("#apiLevelSelector option:selected").val();
toggleVisisbleApis(selectedLevel, "#side-nav");
}
function init_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_node(me, me.node);
me.this_page = this_page_relative(toroot);
me.breadcrumbs = find_page(me.this_page, root_nodes);
if (me.breadcrumbs != null && me.breadcrumbs.length != 0) {
var mom = me.node;
for (var i in me.breadcrumbs) {
var j = me.breadcrumbs[i];
mom = mom.children[j];
expand_node(me, mom);
}
mom.label_div.className = mom.label_div.className + " selected";
addLoadEvent(function() {
scrollIntoView("nav-tree");
});
}
}
/* TODO: eliminate redundancy with non-google functions */
function init_google_navtree(navtree_id, toroot, root_nodes)
{
var me = new Object();
me.toroot = toroot;
me.node = new Object();
me.node.li = document.getElementById(navtree_id);
me.node.children_data = root_nodes;
me.node.children = new Array();
me.node.children_ul = document.createElement("ul");
me.node.get_children_ul = function() { return me.node.children_ul; };
//me.node.children_ul.className = "children_ul";
me.node.li.appendChild(me.node.children_ul);
me.node.depth = 0;
get_google_node(me, me.node);
}
function new_google_node(me, mom, text, link, children_data, api_level)
{
var node = new Object();
var child;
node.children = Array();
node.children_data = children_data;
node.depth = mom.depth + 1;
node.get_children_ul = function() {
if (!node.children_ul) {
node.children_ul = document.createElement("ul");
node.children_ul.className = "tree-list-children";
node.li.appendChild(node.children_ul);
}
return node.children_ul;
};
node.li = document.createElement("li");
mom.get_children_ul().appendChild(node.li);
if(link) {
child = document.createElement("a");
}
else {
child = document.createElement("span");
child.className = "tree-list-subtitle";
}
if (children_data != null) {
node.li.className="nav-section";
node.label_div = document.createElement("div");
node.label_div.className = "nav-section-header-ref";
node.li.appendChild(node.label_div);
get_google_node(me, node);
node.label_div.appendChild(child);
}
else {
node.li.appendChild(child);
}
if(link) {
child.href = me.toroot + link;
}
node.label = document.createTextNode(text);
child.appendChild(node.label);
node.children_ul = null;
return node;
}
function get_google_node(me, mom)
{
mom.children_visited = true;
var linkText;
for (var i in mom.children_data) {
var node_data = mom.children_data[i];
linkText = node_data[0];
if(linkText.match("^"+"com.google.android")=="com.google.android"){
linkText = linkText.substr(19, linkText.length);
}
mom.children[i] = new_google_node(me, mom, linkText, node_data[1],
node_data[2], node_data[3]);
}
}
function showGoogleRefTree() {
init_default_google_navtree(toRoot);
init_default_gcm_navtree(toRoot);
resizeNav();
}
function init_default_google_navtree(toroot) {
init_google_navtree("gms-tree-list", toroot, GMS_NAVTREE_DATA);
}
function init_default_gcm_navtree(toroot) {
init_google_navtree("gcm-tree-list", toroot, GCM_NAVTREE_DATA);
}
/* TOGGLE INHERITED MEMBERS */
/* Toggle an inherited class (arrow toggle)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleInherited(linkObj, expand) {
var base = linkObj.getAttribute("id");
var list = document.getElementById(base + "-list");
var summary = document.getElementById(base + "-summary");
var trigger = document.getElementById(base + "-trigger");
var a = $(linkObj);
if ( (expand == null && a.hasClass("closed")) || expand ) {
list.style.display = "none";
summary.style.display = "block";
trigger.src = toRoot + "assets/images/triangle-opened.png";
a.removeClass("closed");
a.addClass("opened");
} else if ( (expand == null && a.hasClass("opened")) || (expand == false) ) {
list.style.display = "block";
summary.style.display = "none";
trigger.src = toRoot + "assets/images/triangle-closed.png";
a.removeClass("opened");
a.addClass("closed");
}
return false;
}
/* Toggle all inherited classes in a single table (e.g. all inherited methods)
* @param linkObj The link that was clicked.
* @param expand 'true' to ensure it's expanded. 'false' to ensure it's closed.
* 'null' to simply toggle.
*/
function toggleAllInherited(linkObj, expand) {
var a = $(linkObj);
var table = $(a.parent().parent().parent()); // ugly way to get table/tbody
var expandos = $(".jd-expando-trigger", table);
if ( (expand == null && a.text() == "[Expand]") || expand ) {
expandos.each(function(i) {
toggleInherited(this, true);
});
a.text("[Collapse]");
} else if ( (expand == null && a.text() == "[Collapse]") || (expand == false) ) {
expandos.each(function(i) {
toggleInherited(this, false);
});
a.text("[Expand]");
}
return false;
}
/* Toggle all inherited members in the class (link in the class title)
*/
function toggleAllClassInherited() {
var a = $("#toggleAllClassInherited"); // get toggle link from class title
var toggles = $(".toggle-all", $("#body-content"));
if (a.text() == "[Expand All]") {
toggles.each(function(i) {
toggleAllInherited(this, true);
});
a.text("[Collapse All]");
} else {
toggles.each(function(i) {
toggleAllInherited(this, false);
});
a.text("[Expand All]");
}
return false;
}
/* Expand all inherited members in the class. Used when initiating page search */
function ensureAllInheritedExpanded() {
var toggles = $(".toggle-all", $("#body-content"));
toggles.each(function(i) {
toggleAllInherited(this, true);
});
$("#toggleAllClassInherited").text("[Collapse All]");
}
/* HANDLE KEY EVENTS
* - Listen for Ctrl+F (Cmd on Mac) and expand all inherited members (to aid page search)
*/
var agent = navigator['userAgent'].toLowerCase();
var mac = agent.indexOf("macintosh") != -1;
$(document).keydown( function(e) {
var control = mac ? e.metaKey && !e.ctrlKey : e.ctrlKey; // get ctrl key
if (control && e.which == 70) { // 70 is "F"
ensureAllInheritedExpanded();
}
});
| JavaScript |
var BUILD_TIMESTAMP = "25 Feb 2013 20:11";
| JavaScript |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.