code
stringlengths
1
2.08M
language
stringclasses
1 value
(function ($) { $.scroller.i18n.es = $.extend($.scroller.i18n.es, { setText: 'Aceptar', cancelText: 'Cancelar' }); })(jQuery);
JavaScript
(function ($) { $.scroller.themes.jqm = { defaults: { jqmBody: 'c', jqmHeader:'b', jqmWheel: 'd', jqmClickPick: 'c', jqmSet: 'b', jqmCancel: 'c' }, init: function(elm, inst) { var s = inst.settings; $('.dw', elm).removeClass('dwbg').addClass('ui-overlay-shadow ui-corner-all ui-body-a'); $('.dwb-s span', elm).attr('data-role', 'button').attr('data-theme', s.jqmSet); $('.dwb-n span', elm).attr('data-role', 'button').attr('data-theme', s.jqmCancel); $('.dwb-c span', elm).attr('data-role', 'button').attr('data-theme', s.jqmCancel); $('.dwwb', elm).attr('data-role', 'button').attr('data-theme', s.jqmClickPick); $('.dwv', elm).addClass('ui-header ui-bar-' + s.jqmHeader); $('.dwwr', elm).addClass('ui-body-' + s.jqmBody); $('.dwpm .dww', elm).addClass('ui-body-' + s.jqmWheel); if (s.display != 'inline') $('.dw', elm).addClass('pop in'); elm.trigger('create'); // Hide on overlay click $('.dwo', elm).click(function() { inst.hide(); }); } } })(jQuery);
JavaScript
function schatting_koper() { var koopsom = document.hypotheek_form.koopsom.value; var schatting = Math.round(0.02 * koopsom); document.hypotheek_form.inschatting.value = schatting; } function bereken_totaal() { var koopsom = parseInt(document.hypotheek_form.koopsom.value); var inschatting = parseInt(document.hypotheek_form.inschatting.value); var bouwdepot = document.hypotheek_form.bouwdepot.value; var som = parseInt(koopsom + inschatting); if(bouwdepot != "") { som = som + parseInt(bouwdepot); } document.hypotheek_form.totaal.value = som; } function bereken_maandkosten() { var jaarinkomen = parseInt(document.hypotheek_form.jaarinkomen.value); var jaarinkomen_partner = parseInt(document.hypotheek_form.jaarinkomen_partner.value); var overwaarde = parseInt(document.hypotheek_form.overwaarde.value); var inkomen = jaarinkomen + jaarinkomen_partner + overwaarde; var inkomen_maand = inkomen / 12; var kosten_maand = (parseInt(document.hypotheek_form.totaal.value) / 30) / 12; var result = "<h3>De maandelijkse lasten bedragen " + Math.round(kosten_maand) + " euro. <br>" result = result + "Uw maandelijkse inkomen is " + Math.round(inkomen_maand) + " euro.</h3>"; document.getElementById("result").innerHTML = result; }
JavaScript
function schatting_koper() { var koopsom = document.hypotheek_form.koopsom.value; var schatting = Math.round(0.02 * koopsom); document.hypotheek_form.inschatting.value = schatting; } function bereken_totaal() { var koopsom = parseInt(document.hypotheek_form.koopsom.value); var inschatting = parseInt(document.hypotheek_form.inschatting.value); var bouwdepot = document.hypotheek_form.bouwdepot.value; var som = parseInt(koopsom + inschatting); if(bouwdepot != "") { som = som + parseInt(bouwdepot); } document.hypotheek_form.totaal.value = som; } function bereken_maandkosten() { var jaarinkomen = parseInt(document.hypotheek_form.jaarinkomen.value); var jaarinkomen_partner = parseInt(document.hypotheek_form.jaarinkomen_partner.value); var overwaarde = parseInt(document.hypotheek_form.overwaarde.value); var inkomen = jaarinkomen + jaarinkomen_partner + overwaarde; var inkomen_maand = inkomen / 12; var kosten_maand = (parseInt(document.hypotheek_form.totaal.value) / 30) / 12; var result = "<h3>De maandelijkse lasten bedragen " + Math.round(kosten_maand) + " euro. <br>" result = result + "Uw maandelijkse inkomen is " + Math.round(inkomen_maand) + " euro.</h3>"; document.getElementById("result").innerHTML = result; }
JavaScript
var nid=0; var tid=431; var mid=947; var full=1; var popDialogOptions = "dialogWidth:950px; dialogHeight:700px; dialogTop:0px; dialogLeft:0px; edge:Raised; center:0; help:0; resizable:1; scroll:1; status:0"; var popWindowOptions = "scrollbars=1,menubar=0,toolbar=0,location=0,personalbar=0,status=0,resizable=1"; var doexit = true; var usePopDialog = true; var isUsingSpecial = false; function loadpopups(){ if(doexit && !isUsingSpecial) { doexit = false; window.open(popURL1,"",popWindowOptions); } }
JavaScript
var nid=0; var tid=431; var mid=947; var full=1; var popDialogOptions = "dialogWidth:950px; dialogHeight:700px; dialogTop:0px; dialogLeft:0px; edge:Raised; center:0; help:0; resizable:1; scroll:1; status:0"; var popWindowOptions = "scrollbars=1,menubar=0,toolbar=0,location=0,personalbar=0,status=0,resizable=1"; var doexit = true; var usePopDialog = true; var isUsingSpecial = false; function loadpopups(){ if(doexit && !isUsingSpecial) { doexit = false; window.open(popURL1,"",popWindowOptions); } }
JavaScript
var nid=0; var tid=431; var mid=947; var full=1; var popDialogOptions = "dialogWidth:950px; dialogHeight:700px; dialogTop:0px; dialogLeft:0px; edge:Raised; center:0; help:0; resizable:1; scroll:1; status:0"; var popWindowOptions = "scrollbars=1,menubar=0,toolbar=0,location=0,personalbar=0,status=0,resizable=1"; var doexit = true; var usePopDialog = true; var isUsingSpecial = false; function loadpopups(){ if(doexit && !isUsingSpecial) { doexit = false; window.open(popURL1,"",popWindowOptions); } }
JavaScript
/** FROM: http://www.nsftools.com/misc/SearchAndHighlight.htm **/ /** Adapted by vikuit **/ /* * This is the function that actually highlights a text string by * adding HTML tags before and after all occurrences of the search * term. You can pass your own tags if you'd like, or if the * highlightStartTag or highlightEndTag parameters are omitted or * are empty strings then the default <font> tags will be used. */ function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) { if (searchTerm == "" || searchTerm.length < 3){ return bodyText; } // the highlightStartTag and highlightEndTag parameters are optional if ((!highlightStartTag) || (!highlightEndTag)) { highlightStartTag = "<span style='color:blue; background-color:yellow;'>"; highlightEndTag = "</span>"; } // find all occurences of the search term in the given text, // and add some "highlight" tags to them (we're not using a // regular expression search, because we want to filter out // matches that occur within HTML tags and script blocks, so // we have to do a little extra validation) var newText = ""; var i = -1; var lcSearchTerm = searchTerm.toLowerCase(); var lcBodyText = bodyText.toLowerCase(); while (bodyText.length > 0) { i = lcBodyText.indexOf(lcSearchTerm, i+1); if (i < 0) { newText += bodyText; bodyText = ""; } else { // skip anything inside an HTML tag if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) { // skip anything inside a <script> block if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) { newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag; bodyText = bodyText.substr(i + searchTerm.length); lcBodyText = bodyText.toLowerCase(); i = -1; } } } } return newText; } /* * This is sort of a wrapper function to the doHighlight function. * It takes the searchText that you pass, optionally splits it into * separate words, and transforms the text on the current web page. * Only the "searchText" parameter is required; all other parameters * are optional and can be omitted. */ function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag) { // if the treatAsPhrase parameter is true, then we should search for // the entire phrase that was entered; otherwise, we will split the // search string so that each word is searched for and highlighted // individually if (treatAsPhrase) { searchArray = [searchText]; } else { searchArray = searchText.split(" "); } if (!document.body || typeof(document.body.innerHTML) == "undefined") { if (warnOnFailure) { alert("Sorry, for some reason the text of this page is unavailable. Searching will not work."); } return false; } var bodyText = document.body.innerHTML; for (var i = 0; i < searchArray.length; i++) { bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag); } document.body.innerHTML = bodyText; return true; } /* * This displays a dialog box that allows a user to enter their own * search terms to highlight on the page, and then passes the search * text or phrase to the highlightSearchTerms function. All parameters * are optional. */ function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor) { // This function prompts the user for any words that should // be highlighted on this web page if (!defaultText) { defaultText = ""; } // we can optionally use our own highlight tag values if ((!textColor) || (!bgColor)) { highlightStartTag = ""; highlightEndTag = ""; } else { highlightStartTag = "<span style='color:" + textColor + "; background-color:" + bgColor + ";'>"; highlightEndTag = "</span>"; } if (treatAsPhrase) { promptText = "Please enter the phrase you'd like to search for:"; } else { promptText = "Please enter the words you'd like to search for, separated by spaces:"; } searchText = prompt(promptText, defaultText); if (!searchText) { alert("No search terms were entered. Exiting function."); return false; } return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag); } /* * This function takes a referer/referrer string and parses it * to determine if it contains any search terms. If it does, the * search terms are passed to the highlightSearchTerms function * so they can be highlighted on the current page. */ function highlightGoogleSearchTerms(referrer) { // This function has only been very lightly tested against // typical Google search URLs. If you wanted the Google search // terms to be automatically highlighted on a page, you could // call the function in the onload event of your <body> tag, // like this: // <body onload='highlightGoogleSearchTerms(document.referrer);'> //var referrer = document.referrer; if (!referrer) { return false; } var queryPrefix = "q="; var startPos = referrer.toLowerCase().indexOf(queryPrefix); if ((startPos < 0) || (startPos + queryPrefix.length == referrer.length)) { return false; } var endPos = referrer.indexOf("&", startPos); if (endPos < 0) { endPos = referrer.length; } var queryString = referrer.substring(startPos + queryPrefix.length, endPos); // fix the space characters queryString = queryString.replace(/%20/gi, " "); queryString = queryString.replace(/\+/gi, " "); // remove the quotes (if you're really creative, you could search for the // terms within the quotes as phrases, and everything else as single terms) queryString = queryString.replace(/%22/gi, ""); queryString = queryString.replace(/\"/gi, ""); return highlightSearchTerms(queryString, false); } /* * This function is just an easy way to test the highlightGoogleSearchTerms * function. */ function testHighlightGoogleSearchTerms() { var referrerString = "http://www.google.com/search?q=javascript%20highlight&start=0"; referrerString = prompt("Test the following referrer string:", referrerString); return highlightGoogleSearchTerms(referrerString); }
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('placeholder','en',{placeholder:{title:'Placeholder Properties',toolbar:'Create Placeholder',text:'Placeholder Text',edit:'Edit Placeholder',textMissing:'The placeholder must contain text.'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/* (C) Copyright 2011 Jose Carrasco <jose.carrasco at vikuit dot com> This file is part of "vikuit". "vikuit" is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. "vikuit" is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with "vikuit". If not, see <http://www.gnu.org/licenses/>. */ // Register the related command. CKEDITOR.plugins.add('gadget', { init: function(editor) { var pluginName = 'gadget'; CKEDITOR.dialog.add(pluginName, this.path + 'dialogs/gadget.js'); editor.addCommand(pluginName, new CKEDITOR.dialogCommand(pluginName)); editor.ui.addButton('Gadget', { label: 'Google Gadget', command: pluginName, icon: CKEDITOR.plugins.getPath(pluginName ) + 'images/gadget.png' }); } });
JavaScript
/* (C) Copyright 2011 Jose Carrasco <jose.carrasco at vikuit dot com> This file is part of "vikuit". "vikuit" is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. "vikuit" is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with "vikuit". If not, see <http://www.gnu.org/licenses/>. */ CKEDITOR.plugins.setLang('gadget','en',{gadget:{ GadgetBtn : 'Insert Google Gadget', GadgetDlgTitle : 'Gadget Properties', GadgetDlgUrl : 'Gadget URL', GadgetDlgHeight : 'Gadget Height', GadgetDlgWidth : 'Gadget Width', GadgetErrNoUrl : 'Please provide a URL', GadgetErrNoHeight : 'Please provide a height', GadgetErrNoWidth : 'Please provide a width' }});
JavaScript
( function(){ var gadgetDialog = function(editor){ return { title : 'Google Gadget Properties', minWidth : 400, minHeight : 300, contents : [ { id : 'dialog', label : 'Google Gadget Properties', expand : true, elements : [ { type : 'text', id : 'url', label : 'url', style : 'width:100%' }, { type : 'text', id : 'width', label : 'width', style : 'width:100%' }, { type : 'text', id : 'height', label : 'height', style : 'width:100%' } ] } ] } } CKEDITOR.dialog.add('gadget', function(editor) { return gadgetDialog(editor); }); })();
JavaScript
/* (C) Copyright 2011 Jose Carrasco <jose.carrasco at vikuit dot com> (C) Copyright 2011 Jose Blanco <jose.blanco at vikuit dot com> This file is part of "vikuit". "vikuit" is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. "vikuit" is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with "vikuit". If not, see <http://www.gnu.org/licenses/>. */ CKEDITOR.editorConfig = function( config ) { config.extraPlugins = 'gadget'; config.toolbar_Full = [ ['Source','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], '/', ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['BidiLtr', 'BidiRtl'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe'], '/', ['Styles','Format','Font','FontSize'], ['TextColor','BGColor'], ['Maximize', 'ShowBlocks','-','About'] ]; config.toolbar_Article = [ ['Styles','Undo','Redo','-','Find','Replace'], ['Bold','Italic','Underline','StrikeThrough'], ['OrderedList','UnorderedList','-','Outdent','Indent'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'], ['Link','Unlink'], ['Gadget', 'Image','Flash','SpecialChar'] ]; config.toolbar_Basic = [ ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'] ]; };
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Compressed version of core/ckeditor_base.js. See original for instructions. /*jsl:ignore*/ if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.5.1',revision:'6398',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})(); /*jsl:end*/ // Uncomment the following line to have a new timestamp generated for each // request, having clear cache load of the editor code. // CKEDITOR.timestamp = ( new Date() ).valueOf(); if ( CKEDITOR.loader ) CKEDITOR.loader.load( 'core/ckeditor' ); else { // Set the script name to be loaded by the loader. CKEDITOR._autoLoad = 'core/ckeditor'; // Include the loader script. document.write( '<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' ); }
JavaScript
/* * jQuery history plugin * * sample page: http://www.mikage.to/jquery/jquery_history.html * * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari) * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization * for msie when no initial hash supplied. */ jQuery.extend({ historyCurrentHash: undefined, historyCallback: undefined, historyIframeSrc: undefined, historyInit: function(callback, src){ jQuery.historyCallback = callback; if (src) jQuery.historyIframeSrc = src; var current_hash = location.hash.replace(/\?.*$/, ''); jQuery.historyCurrentHash = current_hash; // if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) { if (jQuery.browser.msie) { // To stop the callback firing twice during initilization if no hash present if (jQuery.historyCurrentHash == '') { jQuery.historyCurrentHash = '#'; } // add hidden iframe for IE jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"'+ (jQuery.historyIframeSrc ? ' src="'+jQuery.historyIframeSrc+'"' : '') +'></iframe>' ); var ihistory = jQuery("#jQuery_history")[0]; var iframe = ihistory.contentWindow.document; iframe.open(); iframe.close(); iframe.location.hash = current_hash; } else if (jQuery.browser.safari) { // etablish back/forward stacks jQuery.historyBackStack = []; jQuery.historyBackStack.length = history.length; jQuery.historyForwardStack = []; jQuery.lastHistoryLength = history.length; jQuery.isFirst = true; } if(current_hash) jQuery.historyCallback(current_hash.replace(/^#/, '')); setInterval(jQuery.historyCheck, 100); }, historyAddHistory: function(hash) { // This makes the looping function do something jQuery.historyBackStack.push(hash); jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured) this.isFirst = true; }, historyCheck: function(){ // if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) { if (jQuery.browser.msie) { // On IE, check for location.hash of iframe var ihistory = jQuery("#jQuery_history")[0]; var iframe = ihistory.contentDocument || ihistory.contentWindow.document; var current_hash = iframe.location.hash.replace(/\?.*$/, ''); if(current_hash != jQuery.historyCurrentHash) { location.hash = current_hash; jQuery.historyCurrentHash = current_hash; jQuery.historyCallback(current_hash.replace(/^#/, '')); } } else if (jQuery.browser.safari) { if(jQuery.lastHistoryLength == history.length && jQuery.historyBackStack.length > jQuery.lastHistoryLength) { jQuery.historyBackStack.shift(); } if (!jQuery.dontCheck) { var historyDelta = history.length - jQuery.historyBackStack.length; jQuery.lastHistoryLength = history.length; if (historyDelta) { // back or forward button has been pushed jQuery.isFirst = false; if (historyDelta < 0) { // back button has been pushed // move items to forward stack for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop()); } else { // forward button has been pushed // move items to back stack for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift()); } var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1]; if (cachedHash != undefined) { jQuery.historyCurrentHash = location.hash.replace(/\?.*$/, ''); jQuery.historyCallback(cachedHash); } } else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) { // back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark) // document.URL doesn't change in Safari if (location.hash) { var current_hash = location.hash; jQuery.historyCallback(location.hash.replace(/^#/, '')); } else { var current_hash = ''; jQuery.historyCallback(''); } jQuery.isFirst = true; } } } else { // otherwise, check for location.hash var current_hash = location.hash.replace(/\?.*$/, ''); if(current_hash != jQuery.historyCurrentHash) { jQuery.historyCurrentHash = current_hash; jQuery.historyCallback(current_hash.replace(/^#/, '')); } } }, historyLoad: function(hash){ var newhash; hash = decodeURIComponent(hash.replace(/\?.*$/, '')); if (jQuery.browser.safari) { newhash = hash; } else { newhash = '#' + hash; location.hash = newhash; } jQuery.historyCurrentHash = newhash; // if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) { if (jQuery.browser.msie) { var ihistory = jQuery("#jQuery_history")[0]; var iframe = ihistory.contentWindow.document; iframe.open(); iframe.close(); iframe.location.hash = newhash; jQuery.lastHistoryLength = history.length; jQuery.historyCallback(hash); } else if (jQuery.browser.safari) { jQuery.dontCheck = true; // Manually keep track of the history values for Safari this.historyAddHistory(hash); // Wait a while before allowing checking so that Safari has time to update the "history" object // correctly (otherwise the check loop would detect a false change in hash). var fn = function() {jQuery.dontCheck = false;}; window.setTimeout(fn, 200); jQuery.historyCallback(hash); // N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards. // By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the // URL in the browser and the "history" object are both updated correctly. location.hash = newhash; } else { jQuery.historyCallback(hash); } } });
JavaScript
/** * jQuery Opacity Rollover plugin * * Copyright (c) 2009 Trent Foley (http://trentacular.com) * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php */ ;(function($) { var defaults = { mouseOutOpacity: 0.67, mouseOverOpacity: 1.0, fadeSpeed: 'fast', exemptionSelector: '.selected' }; $.fn.opacityrollover = function(settings) { // Initialize the effect $.extend(this, defaults, settings); var config = this; function fadeTo(element, opacity) { var $target = $(element); if (config.exemptionSelector) $target = $target.not(config.exemptionSelector); $target.fadeTo(config.fadeSpeed, opacity); } this.css('opacity', this.mouseOutOpacity) .hover( function () { fadeTo(this, config.mouseOverOpacity); }, function () { fadeTo(this, config.mouseOutOpacity); }); return this; }; })(jQuery);
JavaScript
/** * jQuery Galleriffic plugin * * Copyright (c) 2008 Trent Foley (http://trentacular.com) * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * Much thanks to primary contributer Ponticlaro (http://www.ponticlaro.com) */ ;(function($) { // Globally keep track of all images by their unique hash. Each item is an image data object. var allImages = {}; var imageCounter = 0; // Galleriffic static class $.galleriffic = { version: '2.0.1', // Strips invalid characters and any leading # characters normalizeHash: function(hash) { return hash.replace(/^.*#/, '').replace(/\?.*$/, ''); }, getImage: function(hash) { if (!hash) return undefined; hash = $.galleriffic.normalizeHash(hash); return allImages[hash]; }, // Global function that looks up an image by its hash and displays the image. // Returns false when an image is not found for the specified hash. // @param {String} hash This is the unique hash value assigned to an image. gotoImage: function(hash) { var imageData = $.galleriffic.getImage(hash); if (!imageData) return false; var gallery = imageData.gallery; gallery.gotoImage(imageData); return true; }, // Removes an image from its respective gallery by its hash. // Returns false when an image is not found for the specified hash or the // specified owner gallery does match the located images gallery. // @param {String} hash This is the unique hash value assigned to an image. // @param {Object} ownerGallery (Optional) When supplied, the located images // gallery is verified to be the same as the specified owning gallery before // performing the remove operation. removeImageByHash: function(hash, ownerGallery) { var imageData = $.galleriffic.getImage(hash); if (!imageData) return false; var gallery = imageData.gallery; if (ownerGallery && ownerGallery != gallery) return false; return gallery.removeImageByIndex(imageData.index); } }; var defaults = { delay: 3000, numThumbs: 20, preloadAhead: 40, // Set to -1 to preload all images enableTopPager: false, enableBottomPager: true, maxPagesToShow: 7, imageContainerSel: '', captionContainerSel: '', controlsContainerSel: '', loadingContainerSel: '', renderSSControls: true, renderNavControls: true, playLinkText: 'Play', pauseLinkText: 'Pause', prevLinkText: 'Previous', nextLinkText: 'Next', nextPageLinkText: 'Next &rsaquo;', prevPageLinkText: '&lsaquo; Prev', enableHistory: false, enableKeyboardNavigation: true, autoStart: false, syncTransitions: false, defaultTransitionDuration: 1000, onSlideChange: undefined, // accepts a delegate like such: function(prevIndex, nextIndex) { ... } onTransitionOut: undefined, // accepts a delegate like such: function(slide, caption, isSync, callback) { ... } onTransitionIn: undefined, // accepts a delegate like such: function(slide, caption, isSync) { ... } onPageTransitionOut: undefined, // accepts a delegate like such: function(callback) { ... } onPageTransitionIn: undefined, // accepts a delegate like such: function() { ... } onImageAdded: undefined, // accepts a delegate like such: function(imageData, $li) { ... } onImageRemoved: undefined // accepts a delegate like such: function(imageData, $li) { ... } }; // Primary Galleriffic initialization function that should be called on the thumbnail container. $.fn.galleriffic = function(settings) { // Extend Gallery Object $.extend(this, { // Returns the version of the script version: $.galleriffic.version, // Current state of the slideshow isSlideshowRunning: false, slideshowTimeout: undefined, // This function is attached to the click event of generated hyperlinks within the gallery clickHandler: function(e, link) { this.pause(); if (!this.enableHistory) { // The href attribute holds the unique hash for an image var hash = $.galleriffic.normalizeHash($(link).attr('href')); $.galleriffic.gotoImage(hash); e.preventDefault(); } }, // Appends an image to the end of the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html. // @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery. appendImage: function(listItem) { this.addImage(listItem, false, false); return this; }, // Inserts an image into the set of images. Argument listItem can be either a jQuery DOM element or arbitrary html. // @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery. // @param {Integer} position The index within the gallery where the item shouold be added. insertImage: function(listItem, position) { this.addImage(listItem, false, true, position); return this; }, // Adds an image to the gallery and optionally inserts/appends it to the DOM (thumbExists) // @param listItem Either a jQuery object or a string of html of the list item that is to be added to the gallery. // @param {Boolean} thumbExists Specifies whether the thumbnail already exists in the DOM or if it needs to be added. // @param {Boolean} insert Specifies whether the the image is appended to the end or inserted into the gallery. // @param {Integer} position The index within the gallery where the item shouold be added. addImage: function(listItem, thumbExists, insert, position) { var $li = ( typeof listItem === "string" ) ? $(listItem) : listItem; var $aThumb = $li.find('a.thumb'); var slideUrl = $aThumb.attr('href'); var title = $aThumb.attr('title'); var $caption = $li.find('.caption').remove(); var hash = $aThumb.attr('name'); // Increment the image counter imageCounter++; // Autogenerate a hash value if none is present or if it is a duplicate if (!hash || allImages[''+hash]) { hash = imageCounter; } // Set position to end when not specified if (!insert) position = this.data.length; var imageData = { title:title, slideUrl:slideUrl, caption:$caption, hash:hash, gallery:this, index:position }; // Add the imageData to this gallery's array of images if (insert) { this.data.splice(position, 0, imageData); // Reset index value on all imageData objects this.updateIndices(position); } else { this.data.push(imageData); } var gallery = this; // Add the element to the DOM if (!thumbExists) { // Update thumbs passing in addition post transition out handler this.updateThumbs(function() { var $thumbsUl = gallery.find('ul.thumbs'); if (insert) $thumbsUl.children(':eq('+position+')').before($li); else $thumbsUl.append($li); if (gallery.onImageAdded) gallery.onImageAdded(imageData, $li); }); } // Register the image globally allImages[''+hash] = imageData; // Setup attributes and click handler $aThumb.attr('rel', 'history') .attr('href', '#'+hash) .removeAttr('name') .click(function(e) { gallery.clickHandler(e, this); }); return this; }, // Removes an image from the gallery based on its index. // Returns false when the index is out of range. removeImageByIndex: function(index) { if (index < 0 || index >= this.data.length) return false; var imageData = this.data[index]; if (!imageData) return false; this.removeImage(imageData); return true; }, // Convenience method that simply calls the global removeImageByHash method. removeImageByHash: function(hash) { return $.galleriffic.removeImageByHash(hash, this); }, // Removes an image from the gallery. removeImage: function(imageData) { var index = imageData.index; // Remove the image from the gallery data array this.data.splice(index, 1); // Remove the global registration delete allImages[''+imageData.hash]; // Remove the image's list item from the DOM this.updateThumbs(function() { var $li = gallery.find('ul.thumbs') .children(':eq('+index+')') .remove(); if (gallery.onImageRemoved) gallery.onImageRemoved(imageData, $li); }); // Update each image objects index value this.updateIndices(index); return this; }, // Updates the index values of the each of the images in the gallery after the specified index updateIndices: function(startIndex) { for (i = startIndex; i < this.data.length; i++) { this.data[i].index = i; } return this; }, // Scraped the thumbnail container for thumbs and adds each to the gallery initializeThumbs: function() { this.data = []; var gallery = this; this.find('ul.thumbs > li').each(function(i) { gallery.addImage($(this), true, false); }); return this; }, isPreloadComplete: false, // Initalizes the image preloader preloadInit: function() { if (this.preloadAhead == 0) return this; this.preloadStartIndex = this.currentImage.index; var nextIndex = this.getNextIndex(this.preloadStartIndex); return this.preloadRecursive(this.preloadStartIndex, nextIndex); }, // Changes the location in the gallery the preloader should work // @param {Integer} index The index of the image where the preloader should restart at. preloadRelocate: function(index) { // By changing this startIndex, the current preload script will restart this.preloadStartIndex = index; return this; }, // Recursive function that performs the image preloading // @param {Integer} startIndex The index of the first image the current preloader started on. // @param {Integer} currentIndex The index of the current image to preload. preloadRecursive: function(startIndex, currentIndex) { // Check if startIndex has been relocated if (startIndex != this.preloadStartIndex) { var nextIndex = this.getNextIndex(this.preloadStartIndex); return this.preloadRecursive(this.preloadStartIndex, nextIndex); } var gallery = this; // Now check for preloadAhead count var preloadCount = currentIndex - startIndex; if (preloadCount < 0) preloadCount = this.data.length-1-startIndex+currentIndex; if (this.preloadAhead >= 0 && preloadCount > this.preloadAhead) { // Do this in order to keep checking for relocated start index setTimeout(function() { gallery.preloadRecursive(startIndex, currentIndex); }, 500); return this; } var imageData = this.data[currentIndex]; if (!imageData) return this; // If already loaded, continue if (imageData.image) return this.preloadNext(startIndex, currentIndex); // Preload the image var image = new Image(); image.onload = function() { imageData.image = this; gallery.preloadNext(startIndex, currentIndex); }; image.alt = imageData.title; image.src = imageData.slideUrl; return this; }, // Called by preloadRecursive in order to preload the next image after the previous has loaded. // @param {Integer} startIndex The index of the first image the current preloader started on. // @param {Integer} currentIndex The index of the current image to preload. preloadNext: function(startIndex, currentIndex) { var nextIndex = this.getNextIndex(currentIndex); if (nextIndex == startIndex) { this.isPreloadComplete = true; } else { // Use setTimeout to free up thread var gallery = this; setTimeout(function() { gallery.preloadRecursive(startIndex, nextIndex); }, 100); } return this; }, // Safe way to get the next image index relative to the current image. // If the current image is the last, returns 0 getNextIndex: function(index) { var nextIndex = index+1; if (nextIndex >= this.data.length) nextIndex = 0; return nextIndex; }, // Safe way to get the previous image index relative to the current image. // If the current image is the first, return the index of the last image in the gallery. getPrevIndex: function(index) { var prevIndex = index-1; if (prevIndex < 0) prevIndex = this.data.length-1; return prevIndex; }, // Pauses the slideshow pause: function() { this.isSlideshowRunning = false; if (this.slideshowTimeout) { clearTimeout(this.slideshowTimeout); this.slideshowTimeout = undefined; } if (this.$controlsContainer) { this.$controlsContainer .find('div.ss-controls a').removeClass().addClass('play') .attr('title', this.playLinkText) .attr('href', '#play') .html(this.playLinkText); } return this; }, // Plays the slideshow play: function() { this.isSlideshowRunning = true; if (this.$controlsContainer) { this.$controlsContainer .find('div.ss-controls a').removeClass().addClass('pause') .attr('title', this.pauseLinkText) .attr('href', '#pause') .html(this.pauseLinkText); } if (!this.slideshowTimeout) { var gallery = this; this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay); } return this; }, // Toggles the state of the slideshow (playing/paused) toggleSlideshow: function() { if (this.isSlideshowRunning) this.pause(); else this.play(); return this; }, // Advances the slideshow to the next image and delegates navigation to the // history plugin when history is enabled // enableHistory is true ssAdvance: function() { if (this.isSlideshowRunning) this.next(true); return this; }, // Advances the gallery to the next image. // @param {Boolean} dontPause Specifies whether to pause the slideshow. // @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled. next: function(dontPause, bypassHistory) { this.gotoIndex(this.getNextIndex(this.currentImage.index), dontPause, bypassHistory); return this; }, // Navigates to the previous image in the gallery. // @param {Boolean} dontPause Specifies whether to pause the slideshow. // @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled. previous: function(dontPause, bypassHistory) { this.gotoIndex(this.getPrevIndex(this.currentImage.index), dontPause, bypassHistory); return this; }, // Navigates to the next page in the gallery. // @param {Boolean} dontPause Specifies whether to pause the slideshow. // @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled. nextPage: function(dontPause, bypassHistory) { var page = this.getCurrentPage(); var lastPage = this.getNumPages() - 1; if (page < lastPage) { var startIndex = page * this.numThumbs; var nextPage = startIndex + this.numThumbs; this.gotoIndex(nextPage, dontPause, bypassHistory); } return this; }, // Navigates to the previous page in the gallery. // @param {Boolean} dontPause Specifies whether to pause the slideshow. // @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled. previousPage: function(dontPause, bypassHistory) { var page = this.getCurrentPage(); if (page > 0) { var startIndex = page * this.numThumbs; var prevPage = startIndex - this.numThumbs; this.gotoIndex(prevPage, dontPause, bypassHistory); } return this; }, // Navigates to the image at the specified index in the gallery // @param {Integer} index The index of the image in the gallery to display. // @param {Boolean} dontPause Specifies whether to pause the slideshow. // @param {Boolean} bypassHistory Specifies whether to delegate navigation to the history plugin when history is enabled. gotoIndex: function(index, dontPause, bypassHistory) { if (!dontPause) this.pause(); if (index < 0) index = 0; else if (index >= this.data.length) index = this.data.length-1; var imageData = this.data[index]; if (!bypassHistory && this.enableHistory) $.historyLoad(String(imageData.hash)); // At the moment, historyLoad only accepts string arguments else this.gotoImage(imageData); return this; }, // This function is garaunteed to be called anytime a gallery slide changes. // @param {Object} imageData An object holding the image metadata of the image to navigate to. gotoImage: function(imageData) { var index = imageData.index; if (this.onSlideChange) this.onSlideChange(this.currentImage.index, index); this.currentImage = imageData; this.preloadRelocate(index); this.refresh(); return this; }, // Returns the default transition duration value. The value is halved when not // performing a synchronized transition. // @param {Boolean} isSync Specifies whether the transitions are synchronized. getDefaultTransitionDuration: function(isSync) { if (isSync) return this.defaultTransitionDuration; return this.defaultTransitionDuration / 2; }, // Rebuilds the slideshow image and controls and performs transitions refresh: function() { var imageData = this.currentImage; if (!imageData) return this; var index = imageData.index; // Update Controls if (this.$controlsContainer) { this.$controlsContainer .find('div.nav-controls a.prev').attr('href', '#'+this.data[this.getPrevIndex(index)].hash).end() .find('div.nav-controls a.next').attr('href', '#'+this.data[this.getNextIndex(index)].hash); } var previousSlide = this.$imageContainer.find('span.current').addClass('previous').removeClass('current'); var previousCaption = 0; if (this.$captionContainer) { previousCaption = this.$captionContainer.find('span.current').addClass('previous').removeClass('current'); } // Perform transitions simultaneously if syncTransitions is true and the next image is already preloaded var isSync = this.syncTransitions && imageData.image; // Flag we are transitioning var isTransitioning = true; var gallery = this; var transitionOutCallback = function() { // Flag that the transition has completed isTransitioning = false; // Remove the old slide previousSlide.remove(); // Remove old caption if (previousCaption) previousCaption.remove(); if (!isSync) { if (imageData.image && imageData.hash == gallery.data[gallery.currentImage.index].hash) { gallery.buildImage(imageData, isSync); } else { // Show loading container if (gallery.$loadingContainer) { gallery.$loadingContainer.show(); } } } }; if (previousSlide.length == 0) { // For the first slide, the previous slide will be empty, so we will call the callback immediately transitionOutCallback(); } else { if (this.onTransitionOut) { this.onTransitionOut(previousSlide, previousCaption, isSync, transitionOutCallback); } else { previousSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0, transitionOutCallback); if (previousCaption) previousCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 0.0); } } // Go ahead and begin transitioning in of next image if (isSync) this.buildImage(imageData, isSync); if (!imageData.image) { var image = new Image(); // Wire up mainImage onload event image.onload = function() { imageData.image = this; // Only build image if the out transition has completed and we are still on the same image hash if (!isTransitioning && imageData.hash == gallery.data[gallery.currentImage.index].hash) { gallery.buildImage(imageData, isSync); } }; // set alt and src image.alt = imageData.title; image.src = imageData.slideUrl; } // This causes the preloader (if still running) to relocate out from the currentIndex this.relocatePreload = true; return this.syncThumbs(); }, // Called by the refresh method after the previous image has been transitioned out or at the same time // as the out transition when performing a synchronous transition. // @param {Object} imageData An object holding the image metadata of the image to build. // @param {Boolean} isSync Specifies whether the transitions are synchronized. buildImage: function(imageData, isSync) { var gallery = this; var nextIndex = this.getNextIndex(imageData.index); // Construct new hidden span for the image var newSlide = this.$imageContainer .append('<span class="image-wrapper current"><a class="advance-link" rel="history" href="#'+this.data[nextIndex].hash+'" title="'+imageData.title+'">&nbsp;</a></span>') .find('span.current').css('opacity', '0'); newSlide.find('a') .append(imageData.image) .click(function(e) { gallery.clickHandler(e, this); }); var newCaption = 0; if (this.$captionContainer) { // Construct new hidden caption for the image newCaption = this.$captionContainer .append('<span class="image-caption current"></span>') .find('span.current').css('opacity', '0') .append(imageData.caption); } // Hide the loading conatiner if (this.$loadingContainer) { this.$loadingContainer.hide(); } // Transition in the new image if (this.onTransitionIn) { this.onTransitionIn(newSlide, newCaption, isSync); } else { newSlide.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0); if (newCaption) newCaption.fadeTo(this.getDefaultTransitionDuration(isSync), 1.0); } if (this.isSlideshowRunning) { if (this.slideshowTimeout) clearTimeout(this.slideshowTimeout); this.slideshowTimeout = setTimeout(function() { gallery.ssAdvance(); }, this.delay); } return this; }, // Returns the current page index that should be shown for the currentImage getCurrentPage: function() { return Math.floor(this.currentImage.index / this.numThumbs); }, // Applies the selected class to the current image's corresponding thumbnail. // Also checks if the current page has changed and updates the displayed page of thumbnails if necessary. syncThumbs: function() { var page = this.getCurrentPage(); if (page != this.displayedPage) this.updateThumbs(); // Remove existing selected class and add selected class to new thumb var $thumbs = this.find('ul.thumbs').children(); $thumbs.filter('.selected').removeClass('selected'); $thumbs.eq(this.currentImage.index).addClass('selected'); return this; }, // Performs transitions on the thumbnails container and updates the set of // thumbnails that are to be displayed and the navigation controls. // @param {Delegate} postTransitionOutHandler An optional delegate that is called after // the thumbnails container has transitioned out and before the thumbnails are rebuilt. updateThumbs: function(postTransitionOutHandler) { var gallery = this; var transitionOutCallback = function() { // Call the Post-transition Out Handler if (postTransitionOutHandler) postTransitionOutHandler(); gallery.rebuildThumbs(); // Transition In the thumbsContainer if (gallery.onPageTransitionIn) gallery.onPageTransitionIn(); else gallery.show(); }; // Transition Out the thumbsContainer if (this.onPageTransitionOut) { this.onPageTransitionOut(transitionOutCallback); } else { this.hide(); transitionOutCallback(); } return this; }, // Updates the set of thumbnails that are to be displayed and the navigation controls. rebuildThumbs: function() { var needsPagination = this.data.length > this.numThumbs; // Rebuild top pager if (this.enableTopPager) { var $topPager = this.find('div.top'); if ($topPager.length == 0) $topPager = this.prepend('<div class="top pagination"></div>').find('div.top'); else $topPager.empty(); if (needsPagination) this.buildPager($topPager); } // Rebuild bottom pager if (this.enableBottomPager) { var $bottomPager = this.find('div.bottom'); if ($bottomPager.length == 0) $bottomPager = this.append('<div class="bottom pagination"></div>').find('div.bottom'); else $bottomPager.empty(); if (needsPagination) this.buildPager($bottomPager); } var page = this.getCurrentPage(); var startIndex = page*this.numThumbs; var stopIndex = startIndex+this.numThumbs-1; if (stopIndex >= this.data.length) stopIndex = this.data.length-1; // Show/Hide thumbs var $thumbsUl = this.find('ul.thumbs'); $thumbsUl.find('li').each(function(i) { var $li = $(this); if (i >= startIndex && i <= stopIndex) { $li.show(); } else { $li.hide(); } }); this.displayedPage = page; // Remove the noscript class from the thumbs container ul $thumbsUl.removeClass('noscript'); return this; }, // Returns the total number of pages required to display all the thumbnails. getNumPages: function() { return Math.ceil(this.data.length/this.numThumbs); }, // Rebuilds the pager control in the specified matched element. // @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt. buildPager: function(pager) { var gallery = this; var numPages = this.getNumPages(); var page = this.getCurrentPage(); var startIndex = page * this.numThumbs; var pagesRemaining = this.maxPagesToShow - 1; var pageNum = page - Math.floor((this.maxPagesToShow - 1) / 2) + 1; if (pageNum > 0) { var remainingPageCount = numPages - pageNum; if (remainingPageCount < pagesRemaining) { pageNum = pageNum - (pagesRemaining - remainingPageCount); } } if (pageNum < 0) { pageNum = 0; } // Prev Page Link if (page > 0) { var prevPage = startIndex - this.numThumbs; pager.append('<a rel="history" href="#'+this.data[prevPage].hash+'" title="'+this.prevPageLinkText+'">'+this.prevPageLinkText+'</a>'); } // Create First Page link if needed if (pageNum > 0) { this.buildPageLink(pager, 0, numPages); if (pageNum > 1) pager.append('<span class="ellipsis">&hellip;</span>'); pagesRemaining--; } // Page Index Links while (pagesRemaining > 0) { this.buildPageLink(pager, pageNum, numPages); pagesRemaining--; pageNum++; } // Create Last Page link if needed if (pageNum < numPages) { var lastPageNum = numPages - 1; if (pageNum < lastPageNum) pager.append('<span class="ellipsis">&hellip;</span>'); this.buildPageLink(pager, lastPageNum, numPages); } // Next Page Link var nextPage = startIndex + this.numThumbs; if (nextPage < this.data.length) { pager.append('<a rel="history" href="#'+this.data[nextPage].hash+'" title="'+this.nextPageLinkText+'">'+this.nextPageLinkText+'</a>'); } pager.find('a').click(function(e) { gallery.clickHandler(e, this); }); return this; }, // Builds a single page link within a pager. This function is called by buildPager // @param {jQuery} pager A jQuery element set matching the particular pager to be rebuilt. // @param {Integer} pageNum The page number of the page link to build. // @param {Integer} numPages The total number of pages required to display all thumbnails. buildPageLink: function(pager, pageNum, numPages) { var pageLabel = pageNum + 1; var currentPage = this.getCurrentPage(); if (pageNum == currentPage) pager.append('<span class="current">'+pageLabel+'</span>'); else if (pageNum < numPages) { var imageIndex = pageNum*this.numThumbs; pager.append('<a rel="history" href="#'+this.data[imageIndex].hash+'" title="'+pageLabel+'">'+pageLabel+'</a>'); } return this; } }); // Now initialize the gallery $.extend(this, defaults, settings); // Verify the history plugin is available if (this.enableHistory && !$.historyInit) this.enableHistory = false; // Select containers if (this.imageContainerSel) this.$imageContainer = $(this.imageContainerSel); if (this.captionContainerSel) this.$captionContainer = $(this.captionContainerSel); if (this.loadingContainerSel) this.$loadingContainer = $(this.loadingContainerSel); // Initialize the thumbails this.initializeThumbs(); if (this.maxPagesToShow < 3) this.maxPagesToShow = 3; this.displayedPage = -1; this.currentImage = this.data[0]; var gallery = this; // Hide the loadingContainer if (this.$loadingContainer) this.$loadingContainer.hide(); // Setup controls if (this.controlsContainerSel) { this.$controlsContainer = $(this.controlsContainerSel).empty(); if (this.renderSSControls) { if (this.autoStart) { this.$controlsContainer .append('<div class="ss-controls"><a href="#pause" class="pause" title="'+this.pauseLinkText+'">'+this.pauseLinkText+'</a></div>'); } else { this.$controlsContainer .append('<div class="ss-controls"><a href="#play" class="play" title="'+this.playLinkText+'">'+this.playLinkText+'</a></div>'); } this.$controlsContainer.find('div.ss-controls a') .click(function(e) { gallery.toggleSlideshow(); e.preventDefault(); return false; }); } if (this.renderNavControls) { this.$controlsContainer .append('<div class="nav-controls"><a class="prev" rel="history" title="'+this.prevLinkText+'">'+this.prevLinkText+'</a><a class="next" rel="history" title="'+this.nextLinkText+'">'+this.nextLinkText+'</a></div>') .find('div.nav-controls a') .click(function(e) { gallery.clickHandler(e, this); }); } } var initFirstImage = !this.enableHistory || !location.hash; if (this.enableHistory && location.hash) { var hash = $.galleriffic.normalizeHash(location.hash); var imageData = allImages[hash]; if (!imageData) initFirstImage = true; } // Setup gallery to show the first image if (initFirstImage) this.gotoIndex(0, false, true); // Setup Keyboard Navigation if (this.enableKeyboardNavigation) { $(document).keydown(function(e) { var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; switch(key) { case 32: // space gallery.next(); e.preventDefault(); break; case 33: // Page Up gallery.previousPage(); e.preventDefault(); break; case 34: // Page Down gallery.nextPage(); e.preventDefault(); break; case 35: // End gallery.gotoIndex(gallery.data.length-1); e.preventDefault(); break; case 36: // Home gallery.gotoIndex(0); e.preventDefault(); break; case 37: // left arrow gallery.previous(); e.preventDefault(); break; case 39: // right arrow gallery.next(); e.preventDefault(); break; } }); } // Auto start the slideshow if (this.autoStart) this.play(); // Kickoff Image Preloader after 1 second setTimeout(function() { gallery.preloadInit(); }, 1000); return this; }; })(jQuery);
JavaScript
/** * Modified by jose.blanco at vikuit dot com * This file is part of vikuit, please check vikuit license. **/ (function($){ var maxItems=0; var style = 'mblog'; var labelBy = 'By'; var labelRead = 'Read more'; var current = ""; var standard = true; $.fn.microblogging = function(j){ var k=$.extend({ targeturl:"http://www.vikuit.com/", loadingImg:'/static/images/throbber.gif', maxItems:1, standard:true, current:"", style:'mblog', labelBy:'By', labelRead:'Read more'},j); if(!j.targeturl) return false; var l=$.extend(k,j); var n="xml"; var divid=guid(); this.append('<div id="'+divid+'newsfeed"><div class="atomloader" style="position:absolute;text-align:center;z-index:99;"><img src="'+l.loadingImg+'"/></div></div>'); $('#'+divid+'newsfeed .atomloader').width(this.width()); $('#'+divid+'newsfeed .atomloader').height(this.height()); $('#'+divid+'newsfeed .atomloader img').height(this.height()/4); var toplocal=(this.height()/2)-($('#'+divid+'newsfeed .atomloader img').height()/2) $('#'+divid+'newsfeed .atomloader img').css('margin-top',toplocal+'px'); var path=l.targeturl; maxItems=l.maxItems; standard = l.standard; style = l.style; labelBy = l.labelBy; labelRead = l.labelRead; current = l.current; requestRSS(path,function(results){ $('#'+divid+'newsfeed').append(results); $('#'+divid+'newsfeed .atomloader').remove(); }); }; function S4(){ return(((1+Math.random())*0x10000)|0).toString(16).substring(1); } function guid(){ return(S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); } function requestRSS(site,callback){ if(!site){ alert('No site was passed.'); return false; } $.ajax({ type: 'get', url: site, async: true, error: function(){ document.getElementById("mssger" ).innerHTML = "Oops!! :("; $( "#mssger" ).dialog( "open" ); }, success: function(data){cbFunc(data)} }); function cbFunc(data){ var items = data.getElementsByTagName("item"); if(items[0]){ var datalength=items.length; if(datalength>maxItems){ datalength=maxItems }; var i; var feedHTML=""; for(i=0;i<datalength;i++) { var author = items[i].getElementsByTagName("author")[0].childNodes[0].nodeValue; feedHTML += "<div class='"+style+"'><blockquote>"; feedHTML+="<cite>"+(standard?labelBy+": ":"")+"<strong>"+author +"</strong>" try { if (standard && (author == current || current == 'admin' )){ try { var key = -1; var tokens = items[i].getElementsByTagName("link")[0].textContent.split("/"); if (tokens.length > 0){ key = tokens[tokens.length-1]; } feedHTML+=" <a href='javascript:removeBloggingPost(\""+key+"\");'><img src='/static/images/cross.png' /></a> "; } catch(e){} } } catch(e) {} try { var pub = new Date(items[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue); feedHTML+=" | "+ pub.toLocaleDateString()+" "+pub.toLocaleTimeString()+"" } catch(e) {} feedHTML += "</cite>"; feedHTML+="<p>"+items[i].getElementsByTagName("title")[0].childNodes[0].nodeValue+"</p>"; feedHTML+="</blockquote></div>"; } if(typeof callback==='function'){ callback(feedHTML); } } else throw new Error('Nothing returned from getJSON.'); } }//Cross })(jQuery); function sendBloggingPost(user, content) { var params = "auth="+auth+"&content="+content; var href = "/module/mblog.edit?" ajaxPost(href, params); } function removeBloggingPost(key) { var params = "act=del&auth="+auth+"&key="+key; var href = "/module/mblog.edit?" ajaxPost(href, params); } function ajaxPost(href, params){ $.ajax({ type: 'post', url: href, data: params, dataType: 'json', async: true, cache: false, error: function(){ document.getElementById("mssger" ).innerHTML = 'OOops!!'; $( "#mssger" ).dialog( "open" ); }, success: function(json){ var saved = json.saved; if (saved == true){ document.getElementById("mssger").innerHTML = "OK"; $( "#mssger" ).dialog( "open" ); } else { document.getElementById("mssger" ).innerHTML = json.msg; $( "#mssger" ).dialog( "open" ); } } }); }
JavaScript
function selectTR(trname,trcount,url) { for (i=1;i<=trcount;i++) { document.all["tr"+i].style.backgroundColor=""; } trname.style.backgroundColor="#C8D7E3"; parent.main.location.href=url; } var isSelected = false ; function select_all_checkbox(form,chk_name) { if(!isSelected) { // select_all_checkbox_handler(form, chk_name, true); isSelected = true ; } else { if(isSelected) { // select_all_checkbox_handler(form, chk_name, false); isSelected =false ; } } } function select_all_checkbox_handler(form,chk_name,isSelected) { for(var i=0; i<form.elements.length; i++) { if(form.elements[i].name == chk_name) { form.elements[i].checked = isSelected ; } } } function selectCheckedID(form,chk_name) { var itemIDs = ""; for(var i=0; i<form.elements.length; i++) { if(form.elements[i].name == chk_name && form.elements[i].checked == true) { if (itemIDs == "") itemIDs = itemIDs + form.elements[i].value; else itemIDs = itemIDs + "," + form.elements[i].value; } } return itemIDs; } function selectCheckedIDString(form,chk_name) { var itemIDs = ""; for(var i=0; i<form.elements.length; i++) { if(form.elements[i].name == chk_name && form.elements[i].checked == true) { if (itemIDs == "") itemIDs = itemIDs + "'" + form.elements[i].value + "'"; else itemIDs = itemIDs + "," + "'" + form.elements[i].value + "'"; } } return itemIDs; } function selectDoubleCheckedID(form,chk_name) { var itemIDs = ""; var iCount = 0; for(var i=0; i<form.elements.length; i++) { if(form.elements[i].name == chk_name && form.elements[i].checked == true) { if (itemIDs == "") { itemIDs = itemIDs + form.elements[i].value; } else { itemIDs = itemIDs + "," + form.elements[i].value; } iCount ++; } } if (iCount!=2) return ""; return itemIDs; }
JavaScript
function postvalue(id,value){ $("#" + id).val(value); } function posttip(value){ alert(value); }
JavaScript
function calendar() { calendar.prototype.pt = 'div1'; calendar.prototype.id = 'calendar1'; calendar.prototype.month = 0; calendar.prototype.year = 2000; calendar.prototype.boxid = 'foundtime'; calendar.prototype.exec = function() { var obj = document.getElementById(this.pt); this.createCalendar(obj); } calendar.prototype.Monthday = function(year, month) { var theDate=new Date(year + "/"+ month + "/01"); var theDayNumOfThisMonth=(new Date(theDate.getFullYear(),theDate.getMonth()+1,0)).getDate(); return theDayNumOfThisMonth; } calendar.prototype.createCalendar = function(obj) { var id = this.id; var oldObj = document.getElementById(id); if (oldObj) { oldObj.parentNode.removeChild(oldObj);} var doc = document.createElement("div"); doc.setAttribute('id',id); doc.style.cssText = "border:1px solid #ccc;width:200;height:100;position:absolute;background-color:#fff"; obj.appendChild(doc); var newObj = document.getElementById(id); //initialization var nowDate = new Date(); var yyyy = nowDate.getFullYear() + ""; var mm = nowDate.getMonth()+1; var thisMonthday = this.Monthday(yyyy,mm); var firstday = this.getFirstday(yyyy,mm); this.month = mm; this.year = yyyy; newObj.innerHTML = this.html(thisMonthday,firstday); } calendar.prototype.getFirstday = function(yyyy,mm) { var initDay = new Date(yyyy+"/"+mm+"/1"); var firstday = initDay.getDay(); return firstday; } calendar.prototype.next = function(yyyy,mm) { mm++; if (mm > 12) { mm = 1; yyyy++;} var thisMonthday = this.Monthday(yyyy,mm); var firstday = this.getFirstday(yyyy,mm); var newObj = document.getElementById(this.id); this.month = mm; this.year = yyyy; newObj.innerHTML = this.html(thisMonthday,firstday); } calendar.prototype.prev = function(yyyy,mm) { mm--; if (mm < 1) { mm = 12; yyyy--;} var thisMonthday = this.Monthday(yyyy,mm); var firstday = this.getFirstday(yyyy,mm); var newObj = document.getElementById(this.id); this.month = mm; this.year = yyyy; newObj.innerHTML = this.html(thisMonthday,firstday); } calendar.prototype.html = function(daycount,firstday) { var tday = new Date(); var tDay = tday.getDate(); var tMin = tday.getMinutes(); var tHour = tday.getHours(); var tSec = tday.getSeconds(); var strhtml = ""; var id = this.id; strhtml += "<table width='210' height='150' cellpadding='0' border='0' style='border-collapse: collapse'>"; strhtml += "<tr><td valign='top'><div align='center'>"; strhtml += "<table width='210' style='font-size:10px;text-align:center;font-family:verdana' border='0' cellpadding='0' bordercolor='#C0C0C0' style='border-collapse: collapse'>"; strhtml += "<tr>"; strhtml += "<td bgcolor='#cccccc'>" strhtml += "<a href='javascript:var o = new calendar();o.id=\""+ this.id +"\";o.pt=\""+this.pt+"\";o.prev(\""+this.year+"\",\""+ this.month +"\");'><<</a>"; strhtml += "</td>"; strhtml += "<td height='20' colspan='5' bgcolor='#cccccc'>"+ this.year; strhtml += " - "+this.month+"</td><td bgcolor='#cccccc'>"; strhtml += "<a href='javascript:var o = new calendar();o.id=\""+ this.id +"\";o.pt=\""+this.pt+"\";o.next(\""+this.year+"\",\""+ this.month +"\");'>>></a>"; strhtml += "</td></tr></table>"; strhtml += "<table width='210' style='font-size:10px;text-align:center;font-family:verdana' border='0' cellpadding='0' bordercolor='#C0C0C0' style='border-collapse: collapse'>"; strhtml += "<tr>"; strhtml += "<td height='20'>Mon</td>"; strhtml += "<td height='20'>Tue</td>"; strhtml += "<td height='20'>Wed</td>"; strhtml += "<td height='20'>Thu</td>"; strhtml += "<td height='20'>Fri</td>"; strhtml += "<td height='20'>Sat</td>"; strhtml += "<td height='20'>Sun</td>"; strhtml += "</tr>"; var m = 1-firstday; for (j=0;j<this.trCount(daycount,firstday);j++) { strhtml += "<tr>"; for (n=0;n<7;n++) { var fulltime = this.year + "-" + this.month + "-" + m; if (m>daycount || m<1) { strhtml += "<td height='30' width='30'>&nbsp;</td>"; } else{ if (m==tDay) { strhtml += "<td height='30' width='30' style='border:1px solid #ff0000' style='cursor:hand' onmouseover='this.bgColor=\"#cadef7\"' onmouseout='this.bgColor=\"\";' onclick='var o = new calendar();o.id=\""+ this.id +"\";o.pt=\""+this.pt+"\";o.boxid=\""+ this.boxid +"\";o.choose(\""+fulltime +"\");'>"+m+"</td>"; }else{ strhtml += "<td height='30' width='30' onclick='var o = new calendar();o.id=\""+ this.id +"\";o.pt=\""+this.pt+"\";o.boxid=\""+ this.boxid +"\";o.choose(\""+fulltime +"\");' onmouseover='this.bgColor=\"#cadef7\"' style='cursor:hand' onmouseout='this.bgColor=\"\";'>"+m+"</td>"; } } m++; } strhtml += "<tr>"; } strhtml += "</table>"; //Time strhtml += "<table width='210' style='font-size:10px;font-family:verdana' cellpadding='0' border='0' style='border-collapse: collapse'><tr><td height='20' align='center'>"; strhtml += "<select id='"+ id +"_hour' style='height:16;width:36;font-size:10px'>"; for (j=0;j<24;j++){ var hours = ""; if ((j+"").length == 1){ hours = "0"+j;}else{ hours = j;} var selected = ""; if (tHour == j){ selected = " selected "; } strhtml += "<option value='"+hours+"' "+ selected +">"+hours+"</option>"; } strhtml += "</select>"; strhtml += ":<select id='"+id+"_minute' style='height:16;width:36;font-size:10px'>"; for (j=0;j<60;j++){ var min = ""; if ((j+"").length == 1){ min = "0"+j;}else{ min = j;} var selected = ""; if (tMin == j){ selected = " selected "; } strhtml += "<option value='"+min+"' "+selected+">"+min+"</option>"; } strhtml += "</select>"; strhtml += ":<select id='"+id+"_second' style='height:16;width:36;font-size:10px'>"; for (j=0;j<60;j++){ var sec = ""; var selected = ""; if (tSec == j){ selected = " selected "; } if ((j+"").length == 1){ sec = "0"+j;}else{ sec = j;} strhtml += "<option value='"+sec +"' "+ selected +">"+sec +"</option>"; } strhtml += "</select>"; strhtml += " - <a href='javascript:;' onclick='closeit(\""+ this.id +"\")'>Close</a> - </td></tr></table>"; strhtml += "</div>"; strhtml += "</td></tr>"; strhtml += "</table>"; strhtml += "<iframe width='100%' style='position:absolute; top:0px; z-index:-1;border-style:none' frameborder='0' border='0' marginwidth='1' marginheight='1' scrolling='no' height='99%'></iframe>"; return strhtml; } calendar.prototype.choose = function(v) { var id = this.id; var full = v + " " + document.getElementById(id + '_hour').value + ":" + document.getElementById(id+'_minute').value + ":" + document.getElementById(id+'_second').value; document.getElementById(this.boxid).value = full; var oldObj = document.getElementById(id); if (oldObj) { oldObj.parentNode.removeChild(oldObj);} } calendar.prototype.trCount = function(daycount,firstday) { var remain = daycount - (7-firstday); var tr = this.computing(remain,7) + 1; return tr; } calendar.prototype.computing = function(a,b) { if (a % b == 0){ return a / b;} else { return Math.floor(a/b)+1;} } } function closeit(id) { var obj = document.getElementById(id); if (obj) { obj.parentNode.removeChild(obj); } }
JavaScript
/* http://www.JSON.org/json2.js 2008-03-24 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This file creates a global JSON object containing three methods: stringify, parse, and quote. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects without a toJSON method. It can be a function or an array. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the object holding the key. This is the toJSON method added to Dates: function toJSON(key) { return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; } You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If no replacer parameter is provided, then a default replacer will be used: function replacer(key, value) { return Object.hasOwnProperty.call(this, key) ? value : undefined; } The default replacer is passed the key and value for each item in the structure. It excludes inherited members. If the replacer parameter is an array, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representaions, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then then indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); JSON.quote(text) This method wraps a string in quotes, escaping some characters as needed. This is a reference implementation. You are free to copy, modify, or redistribute. USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD THIRD PARTY CODE INTO YOUR PAGES. */ /*jslint regexp: true, forin: true, evil: true */ /*global JSON */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, floor, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, length, parse, propertyIsEnumerable, prototype, push, quote, replace, stringify, test, toJSON, toString */ if (!this.JSON) { // Create a JSON object only if one does not already exist. We create the // object in a closure to avoid global variables. JSON = function () { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } Date.prototype.toJSON = function () { // Eventually, this method will be based on the date.toISOString method. return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. return escapeable.test(string) ? '"' + string.replace(escapeable, function (a) { var c = meta[a]; if (typeof c === 'string') { return c; } c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // If the object has a dontEnum length property, we'll treat it as an array. if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length'))) { // The object is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value, rep); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { v = str(k, value, rep); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // Return the JSON object containing the stringify, parse, and quote methods. return { stringify: function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; if (space) { // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } } // If there is no replacer parameter, use the default replacer. if (!replacer) { rep = function (key, value) { if (!Object.hasOwnProperty.call(this, key)) { return undefined; } return value; }; // The replacer can be a function or an array. Otherwise, throw an error. } else if (typeof replacer === 'function' || (typeof replacer === 'object' && typeof replacer.length === 'number')) { rep = replacer; } else { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }, parse: function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in three stages. In the first stage, we run the text against // regular expressions that look for non-JSON patterns. We are especially // concerned with '()' and 'new' because they can cause invocation, and '=' // because it can cause mutation. But just to be safe, we want to reject all // unexpected forms. // We split the first stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace all backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'). replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the second stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional third stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }, quote: quote }; }(); }
JavaScript
$(function(){ $("img").LoadImage(true,800,600,"images/imgloading.gif"); });
JavaScript
function cdiv() { cdiv.prototype.h = 360; cdiv.prototype.w = 500; cdiv.prototype.id = 'div1'; cdiv.prototype.bordercolor = '#99B6DB'; cdiv.prototype.bgcolor = '#ffffff'; cdiv.prototype.offsetX = 0; cdiv.prototype.offsetY = 0; cdiv.prototype.exec = function() { var hh = this.h; var ww = this.w; var cid = this.id var bordercolor = this.bordercolor; var bgcolor = this.bgcolor; var oX = this.offsetX; var oY = this.offsetY; var obj = document.getElementById(cid); if (!obj) {}else { document.body.removeChild(obj); } var doc = document.createElement("div"); doc.style.cssText = 'position:absolute;width:'+ww+';height:'+hh+';border:1px solid '+ bordercolor +';background-color:'+ bgcolor; doc.setAttribute('id',cid); document.body.appendChild(doc); var obj2 = document.getElementById(cid); var pos = oPos(); var size = getSize(obj2); obj2.style.left = pos.x - parseInt(size.w) /2 - oX; obj2.style.top = pos.y - parseInt(size.h) /2 - oY; obj2.innerHTML = "<iframe width='99%' style='position:absolute; top:0px; z-index:-1;border-style:none' frameborder='0' border='0' id='iframe0' marginwidth='1' marginheight='1' scrolling='no' height='99%'></iframe>"; } function getSize(obj) { var width = 0; var height = 0; width = obj.style.width; height = obj.style.height; return {w:width,h:height} } function oPos() { return {x: parseInt(document.body.clientWidth)/2, y: parseInt(document.body.clientHeight)/2} } } function dialog() { dialog.prototype.width = 200; dialog.prototype.height = 200; dialog.prototype.url = ''; dialog.prototype.rv = ''; dialog.prototype.exec = function() { var url = this.url; url = url.toLowerCase(); var arr = showModalDialog(url, window, "dialogWidth:"+ this.width +"px;dialogHeight:"+ this.height +"px;help:no;scroll:no;status:no;help:no"); this.rv = arr; } }
JavaScript
/* **************图片预加载插件****************** ///作者:没剑(2008-06-23) ///http://regedit.cnblogs.com ///说明:在图片加载前显示一个加载标志,当图片下载完毕后显示图片出来 可对图片进行是否自动缩放功能 此插件使用时可让页面先加载,而图片后加载的方式, 解决了平时使用时要在图片显示出来后才能进行缩放时撑大布局的问题 ///参数设置: scaling 是否等比例自动缩放 width 图片最大高 height 图片最大宽 loadpic 加载中的图片路径 ///范例 使用说明: $("div img").LoadImage(true,120,90); 效果如下: 测试地址http://img.jb51.net/online/jqueryLoadImage/demo.htm */ jQuery.fn.LoadImage=function(scaling,width,height,loadpic){ if(loadpic==null)loadpic="load3.gif"; return this.each(function(){ var t=$(this); var src=$(this).attr("src") var img=new Image(); //alert("Loading") img.src=src; //自动缩放图片 var autoScaling=function(){ if(scaling){ if(img.width>0 && img.height>0){ if(img.width/img.height>=width/height){ if(img.width>width){ t.width(width); t.height((img.height*width)/img.width); }else{ t.width(img.width); t.height(img.height); } } else{ if(img.height>height){ t.height(height); t.width((img.width*height)/img.height); }else{ t.width(img.width); t.height(img.height); } } } } } //处理ff下会自动读取缓存图片 if(img.complete){ //alert("getToCache!"); autoScaling(); return; } $(this).attr("src",""); var loading=$("<img alt=\"加载中\" title=\"图片加载中\" src=\""+loadpic+"\" />"); t.hide(); t.after(loading); $(img).load(function(){ autoScaling(); loading.remove(); t.attr("src",this.src); t.show(); //alert("finally!") }); }); }
JavaScript
function doSzBorder(){ var polyline = new GPolyline([ new GLatLng(22.726,113.758), new GLatLng(22.737,113.764), new GLatLng(22.743,113.771), new GLatLng(22.752,113.787), new GLatLng(22.757,113.794), new GLatLng(22.764,113.794), new GLatLng(22.770,113.790), new GLatLng(22.775,113.801), new GLatLng(22.778,113.803), new GLatLng(22.783,113.802), new GLatLng(22.789,113.813), new GLatLng(22.793,113.818), new GLatLng(22.801,113.836), new GLatLng(22.812,113.840), new GLatLng(22.820,113.840), new GLatLng(22.823,113.838), new GLatLng(22.828,113.838), new GLatLng(22.834,113.847), new GLatLng(22.842,113.870), new GLatLng(22.850,113.879), new GLatLng(22.842,113.901), new GLatLng(22.833,113.911), new GLatLng(22.827,113.943), new GLatLng(22.817,113.955), new GLatLng(22.810,113.972), new GLatLng(22.798,113.980), new GLatLng(22.801,113.991), new GLatLng(22.775,113.998), new GLatLng(22.762,114.006), new GLatLng(22.765,114.033), new GLatLng(22.771,114.049), new GLatLng(22.775,114.056), new GLatLng(22.748,114.068), new GLatLng(22.751,114.088), new GLatLng(22.742,114.100), new GLatLng(22.733,114.102), new GLatLng(22.724,114.107), new GLatLng(22.717,114.125), new GLatLng(22.710,114.145), new GLatLng(22.700,114.149), new GLatLng(22.688,114.156), new GLatLng(22.677,114.168), new GLatLng(22.666,114.155), new GLatLng(22.655,114.175), new GLatLng(22.667,114.190), new GLatLng(22.686,114.195), new GLatLng(22.700,114.199), new GLatLng(22.713,114.207), new GLatLng(22.725,114.209), new GLatLng(22.737,114.216), new GLatLng(22.764,114.202), new GLatLng(22.769,114.184), new GLatLng(22.779,114.183), new GLatLng(22.790,114.202), new GLatLng(22.800,114.212), new GLatLng(22.812,114.226), new GLatLng(22.783,114.258), new GLatLng(22.810,114.289), new GLatLng(22.804,114.311), new GLatLng(22.809,114.346), new GLatLng(22.792,114.348), new GLatLng(22.777,114.349), new GLatLng(22.765,114.356), new GLatLng(22.759,114.388), new GLatLng(22.763,114.396), new GLatLng(22.777,114.398), new GLatLng(22.785,114.409), new GLatLng(22.769,114.416), new GLatLng(22.751,114.415), new GLatLng(22.724,114.405), new GLatLng(22.710,114.411), new GLatLng(22.700,114.427), new GLatLng(22.677,114.429), new GLatLng(22.662,114.433), new GLatLng(22.667,114.460), new GLatLng(22.669,114.496), new GLatLng(22.661,114.510) ],"#f33f00",6,0.5,0.3); map.addOverlay(polyline); }
JavaScript
//拖拽模块 ;(function($){ $.fn.jndrag = function(settings){ var obj = this; var isIE = (document.all) ? true : false; var params = $.extend({ handle:$(this) },settings || {}); var _x,_y; var handle; if (params.handle != "#this"){ handle = $(obj.find(params.handle)); } else{ handle = $(obj); } obj.mousedown(function(){ $("div[name!='calendar']").each(function(){ $(this).css("z-Index",0); }); obj.css("z-Index",100); }); $(handle).css("cursor","move"); handle.mousedown(function(event){ $("div[name!='calendar']").each(function(){ $(this).css("z-Index",0); }); _x = event.clientX - obj.offset().left; _y = event.clientY - obj.offset().top; obj.bind("mousemove",move).bind("mouseup",stop).bind("blur",stop); obj.css("z-Index",100); }); function move(){ var top = event.clientY - _y; var left = event.clientX - _x; if (top < 0) { top = 0;} if (left < 0) { left = 0;} obj.css({position:'absolute', left:left + 'px', top : top + 'px'}); if (isIE){ obj.get(0).setCapture(); }else{ event.preventDefault(); } } function stop(){ obj.unbind("mousemove").unbind("mouseup"); if (isIE){ obj.get(0).releaseCapture();} } } })(jQuery);
JavaScript
/*** * SHOP++ Header JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ shopxx.base=''; $().ready( function() { // 刷新header登录、注册信息 $.flushHeaderInfo = function () { var $headerShowLoginWindow = $("#headerShowLoginWindow"); var $headerShowRegisterWindow = $("#headerShowRegisterWindow"); var $headerLoginMemberUsername = $("#headerLoginMemberUsername"); var $headerMemberCenter = $("#headerMemberCenter"); var $headerLogout = $("#headerLogout"); if($.cookie("loginMemberUsername") != null) { $headerLoginMemberUsername.text($.cookie("loginMemberUsername")); $headerMemberCenter.show(); $headerLogout.show(); $headerShowLoginWindow.hide(); $headerShowRegisterWindow.hide(); } else { $headerLoginMemberUsername.text(""); $headerShowLoginWindow.show(); $headerShowRegisterWindow.show(); $headerMemberCenter.hide(); $headerLogout.hide(); } } $.flushHeaderInfo(); // 知识产权拍卖品搜索 $productSearchKeyword = $("#productSearchKeyword"); productSearchKeywordDefaultValue = $("#productSearchKeyword").val(); $productSearchKeyword.focus( function() { if ($productSearchKeyword.val() == productSearchKeywordDefaultValue) { $productSearchKeyword.val(""); } }); $productSearchKeyword.blur( function() { if ($productSearchKeyword.val() == "") { $productSearchKeyword.val(productSearchKeywordDefaultValue); } }); $("#productSearchForm").submit( function() { if ($.trim($productSearchKeyword.val()) == "" || $.trim($productSearchKeyword.val()) == productSearchKeywordDefaultValue) { return false; } }); // 显示购物车信息 var maxShowCartItemListCount = 30; // 最大购物车项数,为null则不限制 var isAjaxDate = true; $(".showCartItemList").hover( function() { $("#cartItemListDetail").stop(true, true); $("#cartItemListDetail").fadeIn(); if (isAjaxDate) { $.ajax({ url: shopxx.base + "/shop/cart_item!ajaxList.action", dataType: "json", beforeSend: function() { $("#cartItemListDetail").html('<li><span class="loadingIcon">&nbsp;</span>正在加载...</li>'); }, success: function(data) { isAjaxDate = false; var cartItemInfoHtml = ""; var cartItemListHtml = ""; $.each(data, function(index, object) { if (index == 0) { if (object.totalQuantity == 0) { cartItemInfoHtml = '<li>您的购物车中暂无知识产权拍卖品!</li>'; } else { cartItemInfoHtml = '<li><span class="rightArea">共 ' + object.totalQuantity + ' 件 总计:<strong>' + object.totalPrice + '</strong></span></li>'; } } else { cartItemListHtml = '<li><a class="leftArea" href="' + shopxx.base + object.htmlFilePath + '" title="' + object.name + '">' + object.name.substring(0, 12) + '</a><span class="rightArea"><strong>' + object.price + ' × ' + object.quantity + '</strong></span></li>' + cartItemListHtml; } if (maxShowCartItemListCount != null && index >= maxShowCartItemListCount) { return false; } }); $("#cartItemListDetail").html(cartItemListHtml + cartItemInfoHtml); } }) } }, function() { $("#cartItemListDetail").fadeOut(); } ); $("#cartItemListDetail").hover( function() { $("#cartItemListDetail").stop(true, true); $("#cartItemListDetail").show(); }, function() { $("#cartItemListDetail").fadeOut(); } ) // 刷新购物车信息 $.flushCartItemList = function() { isAjaxDate = true; } });
JavaScript
/*** * SHOP++ Friend Link JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ $().ready( function() { $(".pictureFriendLink .scrollable").scrollable({ loop: true, speed: 1000 }); $(".pictureFriendLink .scrollable a").hover( function() { $(this).stop().animate({"opacity": 1}); }, function() { $(this).stop().animate({"opacity": 0.5}); } ).animate({"opacity": 0.5 }); });
JavaScript
/*** * SHOP++ Base JavaScript * * http://www.shopxx.net * * Copyright © 2010 shopxx.net All Rights Reserved. **/ // 解决IE6不缓存背景图片问题 if(!window.XMLHttpRequest) { document.execCommand("BackgroundImageCache", false, true); } // 添加收藏夹 function addFavorite(url, title) { if (document.all) { window.external.addFavorite(url, title); } else if (window.sidebar) { window.sidebar.addPanel(title, url, ""); } } // html字符串转义 function htmlEscape(htmlString) { htmlString = htmlString.replace(/&/g, '&amp;'); htmlString = htmlString.replace(/</g, '&lt;'); htmlString = htmlString.replace(/>/g, '&gt;'); htmlString = htmlString.replace(/'/g, '&acute;'); htmlString = htmlString.replace(/"/g, '&quot;'); htmlString = htmlString.replace(/\|/g, '&brvbar;'); return htmlString; } // 设置Cookie function setCookie(name, value) { var expires = (arguments.length > 2) ? arguments[2] : null; document.cookie = name + "=" + encodeURIComponent(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ";path=" + shopxx.base; } // 获取Cookie function getCookie(name) { var value = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (value != null) { return decodeURIComponent(value[2]); } else { return null; } } // 删除cookie function deleteCookie(name) { var expires = new Date(); expires.setTime(expires.getTime() - 1000 * 60); setCookie(name, "", expires); } // 浮点数加法运算 function floatAdd(arg1, arg2) { var r1, r2, m; try{ r1 = arg1.toString().split(".")[1].length; } catch(e) { r1 = 0; } try { r2 = arg2.toString().split(".")[1].length; } catch(e) { r2 = 0; } m = Math.pow(10, Math.max(r1, r2)); return (arg1 * m + arg2 * m) / m; } // 浮点数减法运算 function floatSub(arg1, arg2) { var r1, r2, m, n; try { r1 = arg1.toString().split(".")[1].length; } catch(e) { r1 = 0 } try { r2 = arg2.toString().split(".")[1].length; } catch(e) { r2 = 0 } m = Math.pow(10, Math.max(r1, r2)); n = (r1 >= r2) ? r1 : r2; return ((arg1 * m - arg2 * m) / m).toFixed(n); } // 浮点数乘法运算 function floatMul(arg1, arg2) { var m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length; } catch(e) {} try { m += s2.split(".")[1].length; } catch(e) {} return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m); } // 浮点数除法运算 function floatDiv(arg1, arg2) { var t1 = 0, t2 = 0, r1, r2; try { t1 = arg1.toString().split(".")[1].length; } catch(e) {} try { t2 = arg2.toString().split(".")[1].length; } catch(e) {} with(Math) { r1 = Number(arg1.toString().replace(".", "")); r2 = Number(arg2.toString().replace(".", "")); return (r1 / r2) * pow(10, t2 - t1); } } // 设置数值精度 function setScale(value, scale, roundingMode) { if (roundingMode.toLowerCase() == "roundhalfup") { return (Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale)).toFixed(scale); } else if (roundingMode.toLowerCase() == "roundup") { return (Math.ceil(value * Math.pow(10, scale)) / Math.pow(10, scale)).toFixed(scale); } else { return (Math.floor(value * Math.pow(10, scale)) / Math.pow(10, scale)).toFixed(scale); } } // 格式化商品价格货币 function priceCurrencyFormat(price) { price = setScale(price, shopxx.priceScale, shopxx.priceRoundType); return shopxx.currencySign + price; } // 格式化商品价格货币(包含货币单位) function priceUnitCurrencyFormat(price) { price = setScale(price, shopxx.priceScale, shopxx.priceRoundType); return shopxx.currencySign + price + shopxx.currencyUnit; } // 格式化订单金额货币 function orderCurrencyFormat(price) { price = setScale(price, shopxx.orderScale, shopxx.orderRoundType); return shopxx.currencySign + price; } // 格式化订单金额货币(包含货币单位) function orderUnitCurrencyFormat(price) { price = setScale(price, shopxx.orderScale, shopxx.orderRoundType); return shopxx.currencySign + price + shopxx.currencyUnit; } $().ready( function() { var $body; var $select; var dialogIdNumber = 0; var dialogZIndex = 100; var messageIdNumber = 0; $.dialog = function (settings) { var dialogId; if (settings.id != null) { dialogId = settings.id; } else { dialogId = "dialog" + dialogIdNumber; dialogIdNumber ++; } if (settings.content == null) { settings.content = ""; } if (settings.width == null || settings.width == "auto") { settings.width = 320; } if (settings.height == null) { settings.height = "auto"; } if ($body == null) { $body = $("body"); } if(!window.XMLHttpRequest && $select == null) { $select = $("select"); } if ($select != null) { $select.css("visibility", "hidden"); } var dialogHtml = ""; if (settings.modal == true) { dialogHtml += '<div id="dialogOverlay' + dialogId + '" class="dialogOverlay"></div>'; } if (settings.className != null) { dialogHtml += '<div id="' + dialogId + '" class="baseDialog ' + settings.className + '"><div class="dialogWrap"></div><div class="dialogMain">'; } else { dialogHtml += '<div id="' + dialogId + '" class="baseDialog"><div class="dialogWrap"></div><div class="dialogMain">'; } if (settings.title != null) { dialogHtml += '<div id="dialogTitle' + dialogId + '" class="dialogTitle">' + settings.title + '</div><div id="dialogClose' + dialogId + '" class="dialogClose"></div>'; } else { dialogHtml += '<div id="dialogClose' + dialogId + '" class="dialogClose"></div>'; } if (settings.type != null) { dialogHtml += '<div id="dialogContent' + dialogId + '" class="dialogContent dialog' + settings.type + 'Icon">' + settings.content + '</div>'; } else { dialogHtml += '<div id="dialogContent' + dialogId + '" class="dialogContent">' + settings.content + '</div>'; } if (settings.ok != null || settings.cancel != null) { dialogHtml += '<div id="dialogButtonArea' + dialogId + '" class="dialogButtonArea">'; } if (settings.ok != null) { dialogHtml += '<input type="button" id="dialogOk' + dialogId + '" class="formButton" value="' + settings.ok + '" hidefocus="true" />'; } if (settings.cancel != null) { dialogHtml += '<input type="button" id="dialogCancel' + dialogId + '" class="formButton" value="' + settings.cancel + '" hidefocus="true" />'; } if (settings.ok != null || settings.cancel != null) { dialogHtml += '</div>'; } dialogHtml += '</div></div>'; $body.append(dialogHtml); var isDialogTitleDown = false; var dialogX; var dialogY; var $dialogOverlay = $("#dialogOverlay" + dialogId); var $dialog = $("#" + dialogId); var $dialogTitle = $("#dialogTitle" + dialogId); var $dialogClose = $("#dialogClose" + dialogId); var $dialogOk = $("#dialogOk" + dialogId); var $dialogCancel = $("#dialogCancel" + dialogId); $dialog.css({"width": settings.width, "height": settings.height, "margin-left": - parseInt(settings.width / 2), "z-index": dialogZIndex ++}); function dialogClose() { if ($select != null) { $select.css("visibility", "visible"); } $dialogOverlay.remove(); $dialog.remove(); } if (settings.autoCloseTime != null) { setTimeout(dialogClose, settings.autoCloseTime); } $dialogClose.click( function() { if ($.isFunction(settings.cancelCallback)) { if (settings.cancelCallback.apply() != false) { dialogClose(); } } else { dialogClose(); } }); $dialogOk.click( function() { if ($.isFunction(settings.okCallback)) { if (settings.okCallback.apply() != false) { dialogClose(); } } else { dialogClose(); } }); $dialogCancel.click( function() { if ($.isFunction(settings.cancelCallback)) { if (settings.cancelCallback.apply() != false) { dialogClose(); } } else { dialogClose(); } }); $dialogTitle.mousedown(function (event) { $dialog.css({"z-index": dialogZIndex ++}); var offset = $(this).offset(); if(!window.XMLHttpRequest) { dialogX = event.clientX - offset.left + 6; dialogY = event.clientY - offset.top + 6; } else { dialogX = event.pageX - offset.left + 6; dialogY = event.pageY - offset.top + 6; } isDialogTitleDown = true; return false; }); $(document).mousemove(function (event) { if (!isDialogTitleDown) { return false; } $dialog.css({"top": event.clientY - dialogY, "left": event.clientX - dialogX, "margin": 0}); }).mouseup(function () { isDialogTitleDown = false; }); $dialog.keypress(function(event) { if(event.keyCode == 13) { if ($.isFunction(settings.okCallback)) { if (settings.okCallback.apply() != false) { dialogClose(); } } else { dialogClose(); } } }); $dialogOverlay.show(); $dialog.show(); $dialog.focus(); return dialogId; } $.closeDialog = function (dialogId) { if ($select != null) { $select.css("visibility", "visible"); } var $dialogOverlay = $("#dialogOverlay" + dialogId); var $dialog = $("#" + dialogId); $dialogOverlay.remove(); $dialog.remove(); } $.message = function (settings) { if (settings.content == null) { settings.content = ""; } if ($body == null) { $body = $("body"); } if(!window.XMLHttpRequest && $select == null) { $select = $("select"); } if ($select != null) { $select.css("visibility", "hidden"); } var messageId = "message" + messageIdNumber; messageIdNumber ++; var messageHtml; if (settings.type != null) { messageHtml = '<div id="' + messageId + '" class="baseMessage"><div class="messageContent message' + settings.type + 'Icon">' + settings.content + '</div></div>'; } else { messageHtml = '<div id="' + messageId + '" class="baseMessage"><div class="messageContent">' + settings.content + '</div></div>'; } $body.append(messageHtml); var $message = $("#" + messageId); $message.css({"margin-left": "-" + parseInt($message.width() / 2) + "px"}).show(); setTimeout(function() { $message.animate({left: 0, opacity: "hide"}, "slow", function() { $message.remove(); if ($select != null) { $select.css("visibility", "visible"); } }); }, 2000); return messageId; } });
JavaScript
/*** * SHOP++ Article JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ $().ready( function() { // 改变文章内容字体大小 $articleContent = $("#articleContent"); $("#changeBigFontSize").click(function () { $articleContent.css({"font-size": "16px"}); }); $("#changeNormalFontSize").click(function () { $articleContent.css({"font-size": "14px"}); }); $("#changeSmallFontSize").click(function () { $articleContent.css({"font-size": "12px"}); }); // 文章搜索 $articleSearchKeyword = $("#articleSearchKeyword"); articleSearchKeywordDefaultValue = $("#articleSearchKeyword").val(); $articleSearchKeyword.focus( function() { if ($articleSearchKeyword.val() == articleSearchKeywordDefaultValue) { $articleSearchKeyword.val(""); } }); $articleSearchKeyword.blur( function() { if ($articleSearchKeyword.val() == "") { $articleSearchKeyword.val(articleSearchKeywordDefaultValue); } }); $("#articleSearchForm").submit( function() { if ($.trim($articleSearchKeyword.val()) == "" || $.trim($articleSearchKeyword.val()) == articleSearchKeywordDefaultValue) { return false; } }); });
JavaScript
/*** * SHOP++ Register JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ $().ready( function() { // 注册窗口显示 $.registerWindowShow = function () { $("#registerWindow").jqmShow(); } // 协议窗口显示 $.agreementWindowShow = function () { $("#agreementWindow").jqmShow(); } // 注册窗口 var registerWindowHtml = '<div id="registerWindow" class="registerWindow"><div class="windowTop"><div class="windowTitle">会员注册</div><a class="windowClose registerWindowClose" href="#" hidefocus="true"></a></div><div class="windowMiddle"><form id="registerWindowForm" action="' + shopxx.base + '/shop/member!ajaxRegister.action" method="post"><table><tr><th>用户名: </th><td><input type="text" name="member.username" class="formText {required: true, username: true, remote: \'' + shopxx.base + '/shop/member!checkUsername.action\', minlength: 2, maxlength: 20, messages: {required: \'请输入用户名!\', username: \'不允许包含特殊字符!\', remote: \'用户名已存在,请重新输入!\'}}" title="用户名只允许包含中文、英文、数字和下划线!" /></td></tr><tr><th>密&nbsp;&nbsp;&nbsp;码: </th><td><input type="password" id="registerWindowPassword" name="member.password" class="formText {required: true, minlength: 4, maxlength: 20, messages: {required: \'请输入密码!\', minlength: \'密码长度不能小于4\', maxlength: \'密码长度不能大于20\'}}" /></td></tr><tr><th>重复密码: </th><td><input type="password" name="rePassword" class="formText {equalTo: \'#registerWindowPassword\', messages: {equalTo: \'两次密码输入不一致!\'}}" title="密码长度只允许在4-20之间!" /></td></tr><tr><th>E-mail: </th><td><input type="text" name="member.email" class="formText {required: true, email: true, messages: {required: \'请输入E-mail!\', email: \'E-mail格式错误!\'}}" /></td></tr><tr><th>验证码: </th><td><input type="text" id="registerWindowCaptcha" name="j_captcha" class="formTextS {required: true, messages: {required: \'请输入验证码!\'}}" messagePosition="#registerWindowCaptchaMessagePosition" /><img id="registerWindowCaptchaImage" src="" alt="换一张" /><span id="registerWindowCaptchaMessagePosition"></span></td></tr><tr><th>&nbsp;</th><td><label><input type="checkbox" id="isAgreeAgreement" name="isAgreeAgreement" class="{required: true, messages: {required: \'必须同意注册协议,才可进行注册操作!\'}}" value="true" checked messagePosition="#isAgreeAgreementMessagePosition" /><a id="showAgreementWindow" class="showAgreementWindow" href="#">已阅读并同意《注册协议》</a></label><span id="isAgreeAgreementMessagePosition"></span></td></tr><tr><th>&nbsp;</th><td><input type="submit" id="registerWindowSubmit" class="registerWindowSubmit" value="" hidefocus="true" /></td></tr></table></form></div><div class="windowBottom"></div></div>'; // 协议窗口 var agreementWindowHtml = '<div id="agreementWindow" class="agreementWindow"><div class="windowTop"><div class="windowTitle">注册协议</div><a class="windowClose agreementWindowClose" href="#" hidefocus="true"></a></div><div class="windowMiddle"><div id="agreementContent"></div><input type="button" id="agreementButton" class="agreementButton agreementWindowClose" value="" hidefocus="true" /></div><div class="windowBottom"></div></div>'; $("body").prepend(registerWindowHtml).append(agreementWindowHtml); // 注册悬浮窗口 $("#registerWindow").jqm({ modal: true,// 是否开启模态窗口 overlay: 30,// 屏蔽层透明度 trigger: ".showRegisterWindow",// 激活元素 closeClass: "registerWindowClose",// 关闭按钮 onHide: function(hash) { $("#registerWindowForm").resetForm(); hash.o.remove(); hash.w.fadeOut(); }, onShow: function(hash){ hash.w.fadeIn(); registerWindowCaptchaImageRefresh(); } }).jqDrag(".windowTop"); // 协议悬浮窗口 $("#agreementWindow").jqm({ modal: true,// 是否开启模态窗口 overlay: 0,// 屏蔽层透明度 trigger: ".showAgreementWindow",// 激活元素 closeClass: "agreementWindowClose",// 关闭按钮 onShow: function(hash){ if ($.trim($("#agreementContent").html()) == "") { $.ajax({ beforeSend: function(data) { $("#agreementContent").html('<span class="loadingIcon">&nbsp;</span> 加载中...'); }, url: shopxx.base + "/shop/member!getAgreement.action", success: function(data){ $("#agreementContent").html(data); } }); } hash.w.fadeIn(); } }).jqDrag(".windowTop"); $("#agreementButton").click( function() { $("#isAgreeAgreement").attr("checked", true); }); // 表单验证 $("#registerWindowForm").validate({ invalidHandler: function(form, validator) { $.each(validator.invalid, function(key, value){ $.tip(value); return false; }); }, errorPlacement:function(error, element) {}, submitHandler: function(form) { $("#registerWindowSubmit").attr("disabled", true); $("#registerWindowForm").ajaxSubmit({ dataType: "json", success: function(data) { if (data.status == "success") { $.tip(data.status, data.message); $.flushHeaderInfo(); $("#registerWindow").jqmHide(); } else { registerWindowCaptchaImageRefresh(); $("#registerWindowCaptcha").val(""); $.tip(data.status, data.message); } $("#registerWindowSubmit").attr("disabled", false); } }); } }); // 刷新验证码图片 function registerWindowCaptchaImageRefresh() { $("#registerWindowCaptchaImage").attr("src", shopxx.base + "/captcha.jpg?timestamp" + (new Date()).valueOf()); } // 点击刷新验证码图片 $("#registerWindowCaptchaImage").click( function() { registerWindowCaptchaImageRefresh(); }); });
JavaScript
/*** * SHOP++ Login JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ $().ready( function() { // 登录窗口显示 $.loginWindowShow = function () { $("#loginWindow").jqmShow(); } // 必须会员登录才允许的操作,若未登录则显示登录窗口 $("a.mustMemberLogin").click( function(event) { if ($.cookie("loginMemberUsername") == null) { $.cookie("redirectionUrl", $(this).attr("href"), {path: "/"}); $("#loginWindow").jqmShow(); return false; } }); // 登录窗口 var loginWindowHtml = '<div id="loginWindow" class="loginWindow"><div class="windowTop"><div class="windowTitle">会员登录</div><a class="windowClose loginWindowClose" href="#" hidefocus="true"></a></div><div class="windowMiddle"><form id="loginWindowForm" action="' + shopxx.base + '/shop/member!ajaxLogin.action" method="post"><table><tr><th>用户名: </th><td><input type="text" name="member.username" class="formText {required: true, messages: {required: \'请填写用户名!\'}}" /></td></tr><tr><th>密&nbsp;&nbsp;&nbsp;码: </th><td><input type="password" name="member.password" class="formText {required: true, messages: {required: \'请填写密码!\'}}" /></td></tr><tr><th>验证码: </th><td><input type="text" id="loginWindowCaptcha" name="j_captcha" class="formTextS {required: true, messages: {required: \'请填写验证码!\'}}" /><img id="loginWindowCaptchaImage" src="" alt="换一张" /></td></tr><tr><th>&nbsp;</th><td><span class="warnIcon">&nbsp;</span><a href="' + shopxx.base + '/shop/member!passwordRecover.action">忘记了密码? 点击找回!</a></td></tr><tr><th>&nbsp;</th><td><input type="submit" id="loginWindowSubmit" class="loginSubmit" value="登 录" hidefocus="true" /></td></tr></table></form></div><div class="windowBottom"></div></div>'; $("body").prepend(loginWindowHtml); // 登录悬浮窗口 $("#loginWindow").jqm({ modal: true,// 是否开启模态窗口 overlay: 30,// 屏蔽层透明度 trigger: ".showLoginWindow",// 激活元素 closeClass: "loginWindowClose",// 关闭按钮 onHide: function(hash) { $("#loginWindowForm").resetForm(); $.cookie("redirectionUrl", null, {path: "/"}); hash.o.remove(); hash.w.fadeOut(); }, onShow: function(hash){ hash.w.fadeIn(); loginWindowCaptchaImageRefresh(); } }).jqDrag(".windowTop"); // 表单验证 $("#loginWindowForm").validate({ invalidHandler: function(form, validator) { $.each(validator.invalid, function(key, value){ $.tip(value); return false; }); }, errorPlacement:function(error, element) {}, submitHandler: function(form) { $("#loginWindowSubmit").attr("disabled", true); $("#loginWindowForm").ajaxSubmit({ dataType: "json", success: function(data) { if (data.status == "success") { $.tip(data.status, data.message); $.flushHeaderInfo(); $.flushCartItemList(); var redirectionUrl = $.cookie("redirectionUrl"); $("#loginWindow").jqmHide(); if(redirectionUrl != null && redirectionUrl != "") { location.href = redirectionUrl; } } else { loginWindowCaptchaImageRefresh(); $("#loginWindowCaptcha").val(""); $.tip(data.status, data.message); } $("#loginWindowSubmit").attr("disabled", false); } }); } }); // 刷新验证码图片 function loginWindowCaptchaImageRefresh() { $("#loginWindowCaptchaImage").attr("src", shopxx.base + "/captcha.jpg?timestamp" + (new Date()).valueOf()); } // 点击刷新验证码图片 $("#loginWindowCaptchaImage").click( function() { loginWindowCaptchaImageRefresh(); }); // 刷新验证码图片 function loginCaptchaImageRefresh() { $("#loginCaptchaImage").attr("src", shopxx.base + "/captcha.jpg?timestamp" + (new Date()).valueOf()); } // 点击刷新验证码图片 $("#loginCaptchaImage").click( function() { loginCaptchaImageRefresh(); }); // 表单验证 $("#loginForm").submit(function() { if ($("#loginUsername").val() == "") { $.message("请输入您的用户名!"); return false; } if ($("#loginPassword").val() == "") { $.message("请输入您的密码!"); return false; } if ($("#loginCaptcha").val() == "") { $.message("请输入您的验证码!"); return false; } }) });
JavaScript
/*** * SHOP++ Product JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ $().ready( function() { $productListForm = $("#productListForm"); $pageNumber = $("#pageNumber"); $pageSize = $("#pageSize"); $orderType = $("#orderType"); $viewType = $("#viewType"); $tableType = $("#tableType"); $pictureType = $("#pictureType"); $addFavorite = $(".addFavorite"); $addCartItem = $(".addCartItem"); $addCartItemTip = $("#addCartItemTip"); $tipClose = $("#addCartItemTip .tipClose"); $addCartItemTipMessageIcon = $("#addCartItemTipMessageIcon"); $addCartItemTipMessage = $("#addCartItemTipMessage"); $addCartItemTipInfo = $("#addCartItemTipInfo"); // 知识产权拍卖品分类菜单 $(".productCategory ul.menu").superfish({ delay: 100 }); // 缩略图滚动栏 $(".productContent .scrollable").scrollable({ speed: 600 }); // Tab效果 $(".productContent ul.productImageTab").tabs(".productImage .tabContent", { event: "mouseover"// 触发tab切换的事件 }); // Tab效果 $(".productContent ul.productAttributeTab").tabs(".productBottom .tabContent", { effect: "fade",// 逐渐显示动画 fadeInSpeed: 500,// 动画显示速度 event: "mouseover"// 触发tab切换的事件 }); // Tab效果 $(".productContent ul.productAuctionTab").tabs(".productMiddle .tabContent", { effect: "fade",// 逐渐显示动画 fadeInSpeed: 500,// 动画显示速度 event: "mouseover"// 触发tab切换的事件 }); // 知识产权拍卖品图片放大镜效果 $("a.zoom").zoomimage({ opacity: 0.6, controlsTrigger: "mouseover", controls: true, centered: true, hideSource: true }); // 更多知识产权拍卖品参数 var productAttributeTab = $(".productContent ul.productAttributeTab").tabs(); $("#moreProductAttribute").click( function() { var index = productAttributeTab.getIndex(); if (index == 0) { productAttributeTab.next(); } }); // 每页显示数 $pageSize.change( function() { $pageNumber.val("1"); $productListForm.submit(); }); // 知识产权拍卖品排序 $orderType.change( function() { $pageNumber.val("1"); $productListForm.submit(); }); // 列表方式查看 $tableType.click( function() { $viewType.val("tableType"); $productListForm.submit(); return false; }); // 图片方式查看 $pictureType.click( function() { $viewType.val("pictureType"); $productListForm.submit(); return false; }); // 添加知识产权拍卖品至购物车 /* $addCartItem.click( function() { var $this = $(this); var id = $this.metadata().id; var x = $this.offset().left - 50; var y = $this.offset().top + $this.height() + 6; $addCartItemTip.css({"left" :x, "top" :y}); var quantity = $("#quantity").val(); if (quantity == null) { quantity = 1; } var reg = /^[0-9]*[1-9][0-9]*$/; if (!reg.test(quantity)) { $addCartItemTipMessageIcon.removeClass("successIcon").addClass("errorIcon"); $addCartItemTipMessage.text("加入购物车失败!"); $addCartItemTipInfo.text("知识产权拍卖品数量必须为正整数!"); $addCartItemTip.fadeIn(); return false; } $.ajax({ url: shopxx.base + "/shop/cart_item!ajaxAdd.action", data: {"id": id, "quantity": quantity}, dataType: "json", beforeSend: function() { $this.attr("disabled", true); }, success: function(data) { $.flushCartItemList(); if (data.status == "success") { $addCartItemTipMessageIcon.removeClass("errorIcon").addClass("successIcon"); $addCartItemTipMessage.text(data.message); $addCartItemTipInfo.text("共计知识产权拍卖品:" + data.totalQuantity + "件,总计金额:" + data.totalPrice); } else if (data.status == "error") { $addCartItemTipMessageIcon.removeClass("successIcon").addClass("errorIcon"); $addCartItemTipMessage.text(data.message); $addCartItemTipInfo.empty(); } $addCartItemTip.fadeIn(); $this.attr("disabled", false); } }); }); */ //====================参加竞拍开始======================== $addCartItem.click( function() { var $this = $(this); if ($.cookie("loginMemberUsername") == null) { $.flushHeaderInfo(); $.loginWindowShow(); return false; } else { var $this = $(this); var id = $this.metadata().id; var x = $this.offset().left - 50; var y = $this.offset().top + $this.height() + 6; $addCartItemTip.css({"left" :x, "top" :y}); var quantity = $("#quantity").val(); if (quantity == null) { quantity = 1; } var reg = /^[0-9]*[1-9][0-9]*$/; if (!reg.test(quantity)) { $addCartItemTipMessageIcon.removeClass("successIcon").addClass("errorIcon"); $addCartItemTipMessage.text("竞价失败!"); $addCartItemTipInfo.text("竞价必须为正整数!"); $addCartItemTip.fadeIn(); return false; } $.ajax({ url: shopxx.base + "/shop/cart_item!ajaxAddAuction.action", data: {"id": id, "quantity": quantity}, dataType: "json", beforeSend: function() { $this.attr("disabled", true); }, success: function(data) { $.flushCartItemList(); if (data.status == "success") { $addCartItemTipMessageIcon.removeClass("errorIcon").addClass("successIcon"); $addCartItemTipMessage.text(data.message); $addCartItemTipInfo.text("当前最高竞价为:" + data.totalPrice); } else if (data.status == "error") { $addCartItemTipMessageIcon.removeClass("successIcon").addClass("errorIcon"); $addCartItemTipMessage.text(data.message); $addCartItemTipInfo.empty(); } $addCartItemTip.fadeIn(); $this.attr("disabled", false); } }); } }); //====================参加竞拍结束======================== // 添加购物车提示框隐藏 $tipClose.click( function() { $addCartItemTip.fadeOut(); return false; }); // 产品收藏 $addFavorite.click( function() { var $this = $(this); if ($.cookie("loginMemberUsername") == null) { $.flushHeaderInfo(); $.loginWindowShow(); return false; } else { var id = $(this).metadata().id; $.ajax({ url: shopxx.base + "/shop/favorite!ajaxAdd.action", data: {"id": id}, dataType: "json", beforeSend: function() { $this.attr("disabled", true); }, success: function(data) { $.tip(data.status, data.message); $this.attr("disabled", false); }, error: function(data) { if ($.cookie("loginMemberUsername") == null) { $.flushHeaderInfo(); $.loginWindowShow(); return false; } $this.attr("disabled", false); } }); } }); // 添加知识产权拍卖品浏览记录 var maxProductHistoryListCount = 5; // 最大知识产权拍卖品浏览记录数 $.addProductHistory = function(name, htmlFilePath) { var productHistory = { name: name, htmlFilePath: htmlFilePath }; var productHistoryArray = new Array(); var productHistoryListCookie = $.cookie("productHistoryList"); if(productHistoryListCookie) { productHistoryArray = eval(productHistoryListCookie); } var productHistoryListHtml = ""; for (var i in productHistoryArray) { productHistoryListHtml += '<li><a href="' + productHistoryArray[i].htmlFilePath + '">' + productHistoryArray[i].name + '</a></li>'; } for (var i in productHistoryArray) { if(productHistoryArray[i].htmlFilePath == htmlFilePath) { return; } } if(productHistoryArray.length >= maxProductHistoryListCount) { productHistoryArray.shift(); } productHistoryArray.push(productHistory); var newProductHistoryCookieString = ""; for (var i in productHistoryArray) { newProductHistoryCookieString += ',{name: "' + productHistoryArray[i].name + '", htmlFilePath: "' + productHistoryArray[i].htmlFilePath + '"}' } newProductHistoryCookieString = "[" + newProductHistoryCookieString.substring(1, newProductHistoryCookieString.length) + "]"; $.cookie("productHistoryList", newProductHistoryCookieString, {path: "/"}); } // 知识产权拍卖品浏览记录列表 var productHistoryArray = new Array(); var productHistoryListCookie = $.cookie("productHistoryList"); if(productHistoryListCookie) { productHistoryArray = eval(productHistoryListCookie); } var productHistoryListHtml = ""; for (var i in productHistoryArray) { productHistoryListHtml += '<li><span class="icon">&nbsp;</span><a href="' + productHistoryArray[i].htmlFilePath + '">' + productHistoryArray[i].name + '</a></li>'; } $("#productHistoryListDetail").html(productHistoryListHtml); }); //获取最新报价 function getNewPrice(id){ //alert(id); $.ajax({ url: shopxx.base + "/shop/cart_item!ajaxGetAuctionPrice.action", data: {"id": id}, dataType: "json", beforeSend: function() { }, success: function(data) { if (data.status == "success") { $("#cur_price").html(data.message); } else if (data.status == "error") { $("#cur_price").html("获取最新报价失败!"); } } }); }
JavaScript
/*** * SHOP++ Register JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ $().ready( function() { var $allCheck = $(".list input.allCheck");// 全选复选框 var $idsCheck = $(".list input[name='ids']");// ID复选框 var $deleteButton = $(".list input.deleteButton");// 删除按钮 var $approvePassButton = $(".list input.approvePassButton");// 通过审核按钮 var $approveCalcelButton = $(".list input.approveCalcelButton");// 取消审核按钮 var $listForm = $(".list form");// 列表表单 var $searchButton = $("#searchButton");// 查询按钮 var $pageNumber = $("#pageNumber");// 当前页码 var $pageSize = $("#pageSize");// 每页显示数 var $sort = $(".list .sort");// 排序 var $orderBy = $("#orderBy");// 排序方式 var $order = $("#order");// 排序字段 // 全选 $allCheck.click( function() { if ($(this).attr("checked") == true) { $idsCheck.attr("checked", true); $deleteButton.attr("disabled", false); $approvePassButton.attr("disabled", false); $approveCalcelButton.attr("disabled", false); } else { $idsCheck.attr("checked", false); $deleteButton.attr("disabled", true); $approvePassButton.attr("disabled", true); $approveCalcelButton.attr("disabled", true); } }); // 无复选框被选中时,删除按钮不可用 $idsCheck.click( function() { var $idsChecked = $(".list input[name='ids']:checked"); if ($idsChecked.size() > 0) { $deleteButton.attr("disabled", false); $approvePassButton.attr("disabled", false); $approveCalcelButton.attr("disabled", false); } else { $deleteButton.attr("disabled", true); $approvePassButton.attr("disabled", true); $approveCalcelButton.attr("disabled", true); } }); // 批量删除 $deleteButton.click( function() { var url = $(this).attr("url"); var $idsCheckedCheck = $(".list input[name='ids']:checked"); if (confirm("您确定要删除吗?") == true) { $.ajax({ url: url, data: $idsCheckedCheck.serialize(), dataType: "json", async: false, beforeSend: function(data) { $deleteButton.attr("disabled", true) }, success: function(data) { $deleteButton.attr("disabled", false) if (data.status == "success") { $idsCheckedCheck.parent().parent().remove(); } $.message(data.status, data.message); } }); } }); // 批量通过审核 $approvePassButton.click( function() { var url = $(this).attr("url"); var $idsCheckedCheck = $(".list input[name='ids']:checked"); if (confirm("您确定要对所选会员通过审核吗?") == true) { $.ajax({ url: url, data: $idsCheckedCheck.serialize(), dataType: "json", async: false, beforeSend: function(data) { $approvePassButton.attr("disabled", true) }, success: function(data) { $approvePassButton.attr("disabled", false) if (data.status == "success") { //$idsCheckedCheck.parent().parent().remove(); } $.message(data.status, data.message); $listForm.submit(); } }); } }); // 批量取消审核 $approveCalcelButton.click( function() { var url = $(this).attr("url"); var $idsCheckedCheck = $(".list input[name='ids']:checked"); if (confirm("您确定要对所选会员取消审核吗?") == true) { $.ajax({ url: url, data: $idsCheckedCheck.serialize(), dataType: "json", async: false, beforeSend: function(data) { $approveCalcelButton.attr("disabled", true) }, success: function(data) { $approveCalcelButton.attr("disabled", false) if (data.status == "success") { //$idsCheckedCheck.parent().parent().remove(); } //$.message(data.status, data.message); $listForm.submit(); } }); } }); // 查找 $searchButton.click( function() { $pageNumber.val("1"); $listForm.submit(); }); // 每页显示数 $pageSize.change( function() { $pageNumber.val("1"); $listForm.submit(); }); // 排序 $sort.click( function() { var $currentOrderBy = $(this).attr("name"); if ($orderBy.val() == $currentOrderBy) { if ($order.val() == "") { $order.val("asc") } else if ($order.val() == "desc") { $order.val("asc"); } else if ($order.val() == "asc") { $order.val("desc"); } } else { $orderBy.val($currentOrderBy); $order.val("asc"); } $pageNumber.val("1"); $listForm.submit(); }); // 排序图标效果 sortStyle(); function sortStyle() { var orderByValue = $orderBy.val(); var orderValue = $order.val(); if (orderByValue != "" && orderValue != "") { $(".sort[name='" + orderByValue + "']").after('<span class="' + orderValue + 'Sort">&nbsp;</span>'); } } // 页码跳转 $.gotoPage = function(id) { $pageNumber.val(id); $listForm.submit(); } });
JavaScript
/*** * SHOP++ Install JavaScript * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ if(!window.XMLHttpRequest) { // 解决IE6透明PNG图片BUG DD_belatedPNG.fix(".png"); // 解决IE6不缓存背景图片问题 document.execCommand("BackgroundImageCache", false, true); } $().ready( function() { // 消息提示窗口 $("body").prepend('<div id="messageWindow" class="messageWindow"><div class="windowTop"><div class="windowTitle">提示信息&nbsp;</div><a class="messageClose windowClose" href="#" hidefocus="true"></a></div><div class="windowMiddle"><div class="messageContent"><span class="icon">&nbsp;</span><span class="messageText"></span></div><input type="button" class="formButton messageButton windowClose" value="确 定" hidefocus="true"/></div><div class="windowBottom"></div></div>'); // 消息提示窗口 $("#messageWindow").jqm({ overlay: 60, closeClass: "windowClose", modal: true, trigger: false, onHide: function(object) { object.o.remove(); object.w.fadeOut(); } }).jqDrag(".windowTop"); // 警告信息 $.message = function () { var $messageWindow = $("#messageWindow"); var $icon = $("#messageWindow .icon"); var $messageText = $("#messageWindow .messageText"); var $messageButton = $("#messageWindow .messageButton"); var messageType; var messageText; if (arguments.length == 1) { messageType = "warn"; messageText = arguments[0]; } else { messageType = arguments[0]; messageText = arguments[1]; } if (messageType == "success") { $icon.removeClass("warn").removeClass("error").addClass("success"); } else if (messageType == "error") { $icon.removeClass("warn").removeClass("success").addClass("error"); } else { $icon.removeClass("success").removeClass("error").addClass("warn"); } $messageText.html(messageText); $messageWindow.jqmShow(); $messageButton.focus(); } });
JavaScript
/* * jQuery pager plugin * Version 1.0 (12/22/2008) * @requires jQuery v1.2.6 or later * * Example at: http://jonpauldavies.github.com/JQuery/Pager/PagerDemo.html * * Copyright (c) 2008-2009 Jon Paul Davies * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Read the related blog post and contact the author at http://www.j-dee.com/2008/12/22/jquery-pager-plugin/ * * This version is far from perfect and doesn't manage it's own state, therefore contributions are more than welcome! * * Usage: .pager({ pagenumber: 1, pagecount: 15, buttonClickCallback: PagerClickTest }); * * Where pagenumber is the visible page number * pagecount is the total number of pages to display * buttonClickCallback is the method to fire when a pager button is clicked. * * buttonClickCallback signiture is PagerClickTest = function(pageclickednumber) * Where pageclickednumber is the number of the page clicked in the control. * * The included Pager.CSS file is a dependancy but can obviously tweaked to your wishes * Tested in IE6 IE7 Firefox & Safari. Any browser strangeness, please report. */ (function($) { $.fn.pager = function(options) { var opts = $.extend({}, $.fn.pager.defaults, options); return this.each(function() { // empty out the destination element and then render out the pager with the supplied options $(this).empty().append(renderpager(parseInt(options.pagenumber), parseInt(options.pagecount), options.buttonClickCallback)); }); }; // render and return the pager with the supplied options function renderpager(pagenumber, pagecount, buttonClickCallback) { // setup $pager to hold render var $pager = $('<ul class="pages"></ul>'); // add in the previous and next buttons $pager.append(renderButton('首页', pagenumber, pagecount, buttonClickCallback)).append(renderButton('上一页', pagenumber, pagecount, buttonClickCallback)); // pager currently only handles 10 viewable pages ( could be easily parameterized, maybe in next version ) so handle edge cases var startPoint = 1; var endPoint = 9; if (pagenumber > 4) { startPoint = pagenumber - 4; endPoint = pagenumber + 4; } if (endPoint > pagecount) { startPoint = pagecount - 8; endPoint = pagecount; } if (startPoint < 1) { startPoint = 1; } // loop thru visible pages and render buttons for (var page = startPoint; page <= endPoint; page++) { var currentButton = $('<li class="page-number">' + (page) + '</li>'); page == pagenumber ? currentButton.addClass('pgCurrent') : currentButton.click(function() { buttonClickCallback(this.firstChild.data); }); currentButton.appendTo($pager); } // render in the next and last buttons before returning the whole rendered control back. $pager.append(renderButton('下一页', pagenumber, pagecount, buttonClickCallback)).append(renderButton('末页', pagenumber, pagecount, buttonClickCallback)); return $pager; } // renders and returns a 'specialized' button, ie 'next', 'previous' etc. rather than a page number button function renderButton(buttonLabel, pagenumber, pagecount, buttonClickCallback) { var $Button = $('<li class="pgNext">' + buttonLabel + '</li>'); var destPage = 1; // work out destination page for required button type switch (buttonLabel) { case "首页": destPage = 1; break; case "上一页": destPage = pagenumber - 1; break; case "下一页": destPage = pagenumber + 1; break; case "末页": destPage = pagecount; break; } // disable and 'grey' out buttons if not needed. if (buttonLabel == "首页" || buttonLabel == "上一页") { pagenumber <= 1 ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); }); } else { pagenumber >= pagecount ? $Button.addClass('pgEmpty') : $Button.click(function() { buttonClickCallback(destPage); }); } return $Button; } // pager defaults. hardly worth bothering with in this case but used as placeholder for expansion in the next version $.fn.pager.defaults = { pagenumber: 1, pagecount: 1 }; })(jQuery);
JavaScript
(function() { function stripHtml(value) { // remove html tags and space chars return value.replace(/<.[^<>]*?>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ') // remove numbers and punctuation .replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g,''); } jQuery.validator.addMethod("maxWords", function(value, element, params) { return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length < params; }, jQuery.validator.format("Please enter {0} words or less.")); jQuery.validator.addMethod("minWords", function(value, element, params) { return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params; }, jQuery.validator.format("Please enter at least {0} words.")); jQuery.validator.addMethod("rangeWords", function(value, element, params) { return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params[0] && value.match(/bw+b/g).length < params[1]; }, jQuery.validator.format("Please enter between {0} and {1} words.")); })(); jQuery.validator.addMethod("letterswithbasicpunc", function(value, element) { return this.optional(element) || /^[a-z-.,()'\"\s]+$/i.test(value); }, "Letters or punctuation only please"); jQuery.validator.addMethod("alphanumeric", function(value, element) { return this.optional(element) || /^\w+$/i.test(value); }, "Letters, numbers, spaces or underscores only please"); jQuery.validator.addMethod("lettersonly", function(value, element) { return this.optional(element) || /^[a-z]+$/i.test(value); }, "Letters only please"); jQuery.validator.addMethod("nowhitespace", function(value, element) { return this.optional(element) || /^\S+$/i.test(value); }, "No white space please"); jQuery.validator.addMethod("ziprange", function(value, element) { return this.optional(element) || /^90[2-5]\d\{2}-\d{4}$/.test(value); }, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx"); jQuery.validator.addMethod("integer", function(value, element) { return this.optional(element) || /^-?\d+$/.test(value); }, "A positive or negative non-decimal number please"); // 正数验证 jQuery.validator.addMethod("positive", function(value, element) { if (value > 0) { return true; } else { return false; } }, "请输入合法的正数!"); // 正整数验证 jQuery.validator.addMethod("positiveInteger", function(value, element) { var tel = /^[1-9]\d*$/; return this.optional(element) || (tel.test(value)); }, "请输入合法的正整数!"); // 手机号码验证 jQuery.validator.addMethod("mobile", function(value, element) { var length = value.length; return this.optional(element) || (/^[1][0-9]{10}$/.test(value)); }, "手机号码格式错误,请重新输入!"); // 电话号码验证 jQuery.validator.addMethod("phone", function(value, element) { var phone = /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/; return this.optional(element) || (phone.test(value)); }, "电话号码格式错误,请重新输入!"); // 邮政编码验证 jQuery.validator.addMethod("zipCode", function(value, element) { var zip = /^[0-9]{6}$/; return this.optional(element) || (zip.test(value)); }, "邮政编码格式错误,请重新输入!"); // 若指定元素为不为空则此元素也为必填 jQuery.validator.addMethod("requiredTo", function(value, element, param) { var requiredTo = $(param).val(); if(requiredTo != "") { return value != ""; } else { return true; } }, "此内容为必填项,请输入!"); // 指定元素与此元素必须填写其中一项 jQuery.validator.addMethod("requiredOne", function(value, element, param) { var requiredOne = $(param).val(); if(requiredOne == "") { return value != ""; } else { return true; } }, $.validator.format("两项必须填写一项!")); // 用户名字符串验证 jQuery.validator.addMethod("username", function(value, element) { return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value); }, "只允许包含中文、英文、数字和下划线!"); // 字符串前缀验证 jQuery.validator.addMethod("prefix", function(value, element, param) { var prefix = new RegExp("^" + param); return this.optional(element) || (prefix.test(value)); }, $.validator.format("请输入以 {0} 开头的字符串!")); // 验证值不允许与特定值等于 jQuery.validator.addMethod("notEqual", function(value, element, param) { return value != param; }, $.validator.format("输入值不允许为{0}!")); /** * Return true, if the value is a valid vehicle identification number (VIN). * * Works with all kind of text inputs. * * @example <input type="text" size="20" name="VehicleID" class="{required:true,vinUS:true}" /> * @desc Declares a required input element whose value must be a valid vehicle identification number. * * @name jQuery.validator.methods.vinUS * @type Boolean * @cat Plugins/Validate/Methods */ jQuery.validator.addMethod( "vinUS", function(v){ if (v.length != 17) return false; var i, n, d, f, cd, cdv; var LL = ["A","B","C","D","E","F","G","H","J","K","L","M","N","P","R","S","T","U","V","W","X","Y","Z"]; var VL = [1,2,3,4,5,6,7,8,1,2,3,4,5,7,9,2,3,4,5,6,7,8,9]; var FL = [8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2]; var rs = 0; for(i = 0; i < 17; i++){ f = FL[i]; d = v.slice(i,i+1); if(i == 8){ cdv = d; } if(!isNaN(d)){ d *= f; } else{ for(n = 0; n < LL.length; n++){ if(d.toUpperCase() === LL[n]){ d = VL[n]; d *= f; if(isNaN(cdv) && n == 8){ cdv = LL[n]; } break; } } } rs += d; } cd = rs % 11; if(cd == 10){cd = "X";} if(cd == cdv){return true;} return false; }, "The specified vehicle identification number (VIN) is invalid." ); /** * Return true, if the value is a valid date, also making this formal check dd/mm/yyyy. * * @example jQuery.validator.methods.date("01/01/1900") * @result true * * @example jQuery.validator.methods.date("01/13/1990") * @result false * * @example jQuery.validator.methods.date("01.01.1900") * @result false * * @example <input name="pippo" class="{dateITA:true}" /> * @desc Declares an optional input element whose value must be a valid date. * * @name jQuery.validator.methods.dateITA * @type Boolean * @cat Plugins/Validate/Methods */ jQuery.validator.addMethod( "dateITA", function(value, element) { var check = false; var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/; if( re.test(value)){ var adata = value.split('/'); var gg = parseInt(adata[0],10); var mm = parseInt(adata[1],10); var aaaa = parseInt(adata[2],10); var xdata = new Date(aaaa,mm-1,gg); if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) ) check = true; else check = false; } else check = false; return this.optional(element) || check; }, "Please enter a correct date" ); jQuery.validator.addMethod("dateNL", function(value, element) { return this.optional(element) || /^\d\d?[\.\/-]\d\d?[\.\/-]\d\d\d?\d?$/.test(value); }, "Vul hier een geldige datum in." ); jQuery.validator.addMethod("time", function(value, element) { return this.optional(element) || /^([01][0-9])|(2[0123]):([0-5])([0-9])$/.test(value); }, "Please enter a valid time, between 00:00 and 23:59" ); /** * matches US phone number format * * where the area code may not start with 1 and the prefix may not start with 1 * allows '-' or ' ' as a separator and allows parens around area code * some people may want to put a '1' in front of their number * * 1(212)-999-2345 * or * 212 999 2344 * or * 212-999-0983 * * but not * 111-123-5434 * and not * 212 123 4567 */ jQuery.validator.addMethod("phoneUS", function(phone_number, element) { phone_number = phone_number.replace(/\s+/g, ""); return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, "Please specify a valid phone number"); jQuery.validator.addMethod('phoneUK', function(phone_number, element) { return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(\(?(0|\+44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/); }, 'Please specify a valid phone number'); jQuery.validator.addMethod('mobileUK', function(phone_number, element) { return this.optional(element) || phone_number.length > 9 && phone_number.match(/^((0|\+44)7(5|6|7|8|9){1}\d{2}\s?\d{6})$/); }, 'Please specify a valid mobile number'); // TODO check if value starts with <, otherwise don't try stripping anything jQuery.validator.addMethod("strippedminlength", function(value, element, param) { return jQuery(value).text().length >= param; }, jQuery.validator.format("Please enter at least {0} characters")); // same as email, but TLD is optional jQuery.validator.addMethod("email2", function(value, element, param) { return this.optional(element) || /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value); }, jQuery.validator.messages.email); // same as url, but TLD is optional jQuery.validator.addMethod("url2", function(value, element, param) { return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value); }, jQuery.validator.messages.url); // NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator // Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0 // Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings) jQuery.validator.addMethod("creditcardtypes", function(value, element, param) { if (/[^0-9-]+/.test(value)) return false; value = value.replace(/\D/g, ""); var validTypes = 0x0000; if (param.mastercard) validTypes |= 0x0001; if (param.visa) validTypes |= 0x0002; if (param.amex) validTypes |= 0x0004; if (param.dinersclub) validTypes |= 0x0008; if (param.enroute) validTypes |= 0x0010; if (param.discover) validTypes |= 0x0020; if (param.jcb) validTypes |= 0x0040; if (param.unknown) validTypes |= 0x0080; if (param.all) validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080; if (validTypes & 0x0001 && /^(51|52|53|54|55)/.test(value)) { //mastercard return value.length == 16; } if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa return value.length == 16; } if (validTypes & 0x0004 && /^(34|37)/.test(value)) { //amex return value.length == 15; } if (validTypes & 0x0008 && /^(300|301|302|303|304|305|36|38)/.test(value)) { //dinersclub return value.length == 14; } if (validTypes & 0x0010 && /^(2014|2149)/.test(value)) { //enroute return value.length == 15; } if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover return value.length == 16; } if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb return value.length == 16; } if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb return value.length == 15; } if (validTypes & 0x0080) { //unknown return true; } return false; }, "Please enter a valid credit card number.");
JavaScript
/* * jqDnR - Minimalistic Drag'n'Resize for jQuery. * * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net * Licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * $Version: 2007.08.19 +r2 */ (function($){ $.fn.jqDrag=function(h){return i(this,h,'d');}; $.fn.jqResize=function(h){return i(this,h,'r');}; $.jqDnR={dnr:{},e:0, drag:function(v){ if(M.k == 'd')E.css({left:M.X+v.pageX-M.pX,top:M.Y+v.pageY-M.pY}); else E.css({width:Math.max(v.pageX-M.pX+M.W,0),height:Math.max(v.pageY-M.pY+M.H,0)}); return false;}, stop:function(){E.css('opacity',M.o);$().unbind('mousemove',J.drag).unbind('mouseup',J.stop);} }; var J=$.jqDnR,M=J.dnr,E=J.e, i=function(e,h,k){return e.each(function(){h=(h)?$(h,e):e; h.bind('mousedown',{e:e,k:k},function(v){var d=v.data,p={};E=d.e; // attempt utilization of dimensions plugin to fix IE issues if(E.css('position') != 'relative'){try{E.position(p);}catch(e){}} M={X:p.left||f('left')||0,Y:p.top||f('top')||0,W:f('width')||E[0].scrollWidth||0,H:f('height')||E[0].scrollHeight||0,pX:v.pageX,pY:v.pageY,k:d.k,o:E.css('opacity')}; E.css({opacity:0.8});$().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop); return false; }); });}, f=function(k){return parseInt(E.css(k))||false;}; })(jQuery);
JavaScript
jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io }, createUploadForm: function(id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = $('#' + fileElementId); var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId); $(oldElement).before(newElement); $(oldElement).appendTo(form); //set attributes $(form).css('position', 'absolute'); $(form).css('top', '-1200px'); $(form).css('left', '-1200px'); $(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {} if ( s.global ) jQuery.event.trigger("ajaxSend", [xml, s]); // Wait for a response to come back var uploadCallback = function(isTimeout) { var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if ( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if ( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); // If a local callback was specified, fire it and pass it the data if ( s.success ) s.success( data, status ); // Fire the global callback if( s.global ) jQuery.event.trigger( "ajaxSuccess", [xml, s] ); } else jQuery.handleError(s, xml, status); } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); } // The request was completed if( s.global ) jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) jQuery.event.trigger( "ajaxStop" ); // Process result if ( s.complete ) s.complete(xml, status); jQuery(io).unbind() setTimeout(function() { try { $(io).remove(); $(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null } } // Timeout checker if ( s.timeout > 0 ) { setTimeout(function(){ // Check to see if the request is still happening if( !requestDone ) uploadCallback( "timeout" ); }, s.timeout); } try { // var io = $('#' + frameId); var form = $('#' + formId); $(form).attr('action', s.url); $(form).attr('method', 'POST'); $(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } $(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global context if ( type == "script" ) jQuery.globalEval( data ); // Get the JavaScript object, if JSON is used. if ( type == "json" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); //alert($('param', data).each(function(){alert($(this).attr('value'));})); return data; } })
JavaScript
(function($){ /* hoverIntent by Brian Cherne */ $.fn.hoverIntent = function(f,g) { // default configuration options var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; // override configuration options with user supplied object cfg = $.extend(cfg, g ? { over: f, out: g } : f ); // instantiate variables // cX, cY = current X and Y position of mouse, updated by mousemove event // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval var cX, cY, pX, pY; // A private function for getting mouse position var track = function(ev) { cX = ev.pageX; cY = ev.pageY; }; // A private function for comparing current and previous mouse position var compare = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); // compare mouse positions to see if they've crossed the threshold if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { $(ob).unbind("mousemove",track); // set hoverIntent state to true (so mouseOut can be called) ob.hoverIntent_s = 1; return cfg.over.apply(ob,[ev]); } else { // set previous coordinates for next time pX = cX; pY = cY; // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); } }; // A private function for delaying the mouseOut function var delay = function(ev,ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob,[ev]); }; // A private function for handling mouse 'hovering' var handleHover = function(e) { // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } if ( p == this ) { return false; } // copy objects to be passed into t (required for event object to be passed in IE) var ev = jQuery.extend({},e); var ob = this; // cancel hoverIntent timer if it exists if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } // else e.type == "onmouseover" if (e.type == "mouseover") { // set "previous" X and Y position based on initial entry point pX = ev.pageX; pY = ev.pageY; // update "current" X and Y position based on mousemove $(ob).bind("mousemove",track); // start polling interval (self-calling timeout) to compare mouse coordinates over time if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} // else e.type == "onmouseout" } else { // unbind expensive mousemove event $(ob).unbind("mousemove",track); // if hoverIntent state is true, then call the mouseOut function after the specified delay if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} } }; // bind the function to the two event listeners return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);
JavaScript
/** * * Zoomimage * Author: Stefan Petre www.eyecon.ro * */ (function($){ var EYE = window.EYE = function() { var _registered = { init: [] }; return { init: function() { $.each(_registered.init, function(nr, fn){ fn.call(); }); }, extend: function(prop) { for (var i in prop) { if (prop[i] != undefined) { this[i] = prop[i]; } } }, register: function(fn, type) { if (!_registered[type]) { _registered[type] = []; } _registered[type].push(fn); } }; }(); $(EYE.init); })(jQuery); (function($) { EYE.extend({ getPosition : function(e, forceIt) { var x = 0; var y = 0; var es = e.style; var restoreStyles = false; if (forceIt && jQuery.curCSS(e,'display') == 'none') { var oldVisibility = es.visibility; var oldPosition = es.position; restoreStyles = true; es.visibility = 'hidden'; es.display = 'block'; es.position = 'absolute'; } var el = e; if (el.getBoundingClientRect) { // IE var box = el.getBoundingClientRect(); x = box.left + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) - 2; y = box.top + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - 2; } else { x = el.offsetLeft; y = el.offsetTop; el = el.offsetParent; if (e != el) { while (el) { x += el.offsetLeft; y += el.offsetTop; el = el.offsetParent; } } if (jQuery.browser.safari && jQuery.curCSS(e, 'position') == 'absolute' ) { x -= document.body.offsetLeft; y -= document.body.offsetTop; } el = e.parentNode; while (el && el.tagName.toUpperCase() != 'BODY' && el.tagName.toUpperCase() != 'HTML') { if (jQuery.curCSS(el, 'display') != 'inline') { x -= el.scrollLeft; y -= el.scrollTop; } el = el.parentNode; } } if (restoreStyles == true) { es.display = 'none'; es.position = oldPosition; es.visibility = oldVisibility; } return {x:x, y:y}; }, getSize : function(e) { var w = parseInt(jQuery.curCSS(e,'width'), 10); var h = parseInt(jQuery.curCSS(e,'height'), 10); var wb = 0; var hb = 0; if (jQuery.curCSS(e, 'display') != 'none') { wb = e.offsetWidth; hb = e.offsetHeight; } else { var es = e.style; var oldVisibility = es.visibility; var oldPosition = es.position; es.visibility = 'hidden'; es.display = 'block'; es.position = 'absolute'; wb = e.offsetWidth; hb = e.offsetHeight; es.display = 'none'; es.position = oldPosition; es.visibility = oldVisibility; } return {w:w, h:h, wb:wb, hb:hb}; }, getClient : function(e) { var h, w; if (e) { w = e.clientWidth; h = e.clientHeight; } else { var de = document.documentElement; w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; } return {w:w,h:h}; }, getScroll : function (e) { var t=0, l=0, w=0, h=0, iw=0, ih=0; if (e && e.nodeName.toLowerCase() != 'body') { t = e.scrollTop; l = e.scrollLeft; w = e.scrollWidth; h = e.scrollHeight; } else { if (document.documentElement) { 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; } if (typeof pageYOffset != 'undefined') { t = pageYOffset; l = pageXOffset; } iw = self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0; ih = self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0; } return { t: t, l: l, w: w, h: h, iw: iw, ih: ih }; }, getMargins : function(e, toInteger) { var t = jQuery.curCSS(e,'marginTop') || ''; var r = jQuery.curCSS(e,'marginRight') || ''; var b = jQuery.curCSS(e,'marginBottom') || ''; var l = jQuery.curCSS(e,'marginLeft') || ''; if (toInteger) return { t: parseInt(t, 10)||0, r: parseInt(r, 10)||0, b: parseInt(b, 10)||0, l: parseInt(l, 10) }; else return {t: t, r: r, b: b, l: l}; }, getPadding : function(e, toInteger) { var t = jQuery.curCSS(e,'paddingTop') || ''; var r = jQuery.curCSS(e,'paddingRight') || ''; var b = jQuery.curCSS(e,'paddingBottom') || ''; var l = jQuery.curCSS(e,'paddingLeft') || ''; if (toInteger) return { t: parseInt(t, 10)||0, r: parseInt(r, 10)||0, b: parseInt(b, 10)||0, l: parseInt(l, 10) }; else return {t: t, r: r, b: b, l: l}; }, getBorder : function(e, toInteger) { var t = jQuery.curCSS(e,'borderTopWidth') || ''; var r = jQuery.curCSS(e,'borderRightWidth') || ''; var b = jQuery.curCSS(e,'borderBottomWidth') || ''; var l = jQuery.curCSS(e,'borderLeftWidth') || ''; if (toInteger) return { t: parseInt(t, 10)||0, r: parseInt(r, 10)||0, b: parseInt(b, 10)||0, l: parseInt(l, 10)||0 }; else return {t: t, r: r, b: b, l: l}; }, traverseDOM : function(nodeEl, func) { func(nodeEl); nodeEl = nodeEl.firstChild; while(nodeEl){ EYE.traverseDOM(nodeEl, func); nodeEl = nodeEl.nextSibling; } }, getInnerWidth : function(el, scroll) { var offsetW = el.offsetWidth; return scroll ? Math.max(el.scrollWidth,offsetW) - offsetW + el.clientWidth:el.clientWidth; }, getInnerHeight : function(el, scroll) { var offsetH = el.offsetHeight; return scroll ? Math.max(el.scrollHeight,offsetH) - offsetH + el.clientHeight:el.clientHeight; }, getExtraWidth : function(el) { if($.boxModel) return (parseInt($.curCSS(el, 'paddingLeft'))||0) + (parseInt($.curCSS(el, 'paddingRight'))||0) + (parseInt($.curCSS(el, 'borderLeftWidth'))||0) + (parseInt($.curCSS(el, 'borderRightWidth'))||0); return 0; }, getExtraHeight : function(el) { if($.boxModel) return (parseInt($.curCSS(el, 'paddingTop'))||0) + (parseInt($.curCSS(el, 'paddingBottom'))||0) + (parseInt($.curCSS(el, 'borderTopWidth'))||0) + (parseInt($.curCSS(el, 'borderBottomWidth'))||0); return 0; }, isChildOf: function(parentEl, el, container) { if (parentEl == el) { return true; } if (!el || !el.nodeType || el.nodeType != 1) { return false; } if (parentEl.contains && !$.browser.safari) { return parentEl.contains(el); } if ( parentEl.compareDocumentPosition ) { return !!(parentEl.compareDocumentPosition(el) & 16); } var prEl = el.parentNode; while(prEl && prEl != container) { if (prEl == parentEl) return true; prEl = prEl.parentNode; } return false; }, centerEl : function(el, axis) { var clientScroll = EYE.getScroll(); var size = EYE.getSize(el); if (!axis || axis == 'vertically') $(el).css( { top: clientScroll.t + ((Math.min(clientScroll.h,clientScroll.ih) - size.hb)/2) + 'px' } ); if (!axis || axis == 'horizontally') $(el).css( { left: clientScroll.l + ((Math.min(clientScroll.w,clientScroll.iw) - size.wb)/2) + 'px' } ); } }); if (!$.easing.easeout) { $.easing.easeout = function(p, n, firstNum, delta, duration) { return -delta * ((n=n/duration-1)*n*n*n - 1) + firstNum; }; } })(jQuery); (function($){ EYE.extend({ zoomimage: { libs: {}, types: /\.jpg|\.jpeg|\.png|\.gif|\.bmp/g, current: null, moved: false, pointer: {x:0,y:0}, diff: {x:0, y:0}, trackKey: false, //default options (many options are controled via CSS) defaults: { opacity: 0.3, //caption opacity border: 0, // border arround the image shadow: 6, // shadow size duration: 300, // animation duration prevent: 14, // pixels to move the mouse before the image is dragged controls: true, // display controls caption: true, // display caption hideSource: false, centered: false, className: false, onLoad: function(){return false}, beforeZoomIn: function(){return false}, onZoomIn: function(){return false}, beforeZoomOut: function(){return false}, onZoomOut: function(){return false}, onFocus: function(){return false}, controlsTrigger: 'focus', easing: 'linear', preload: 'click' }, // the template for the image's box template: [ '<div class="zoomimage">', '<div class="zoomimage_s">', '<div class="zoomimage_st">', '<div class="zoomimage_stl png"></div>', '<div class="zoomimage_stc png"></div>', '<div class="zoomimage_str png"></div>', '</div>', '<div class="zoomimage_sc">', '<div class="zoomimage_scl png"></div>', '<div class="zoomimage_scc png"></div>', '<div class="zoomimage_scr png"></div>', '</div>', '<div class="zoomimage_sb">', '<div class="zoomimage_sbl png"></div>', '<div class="zoomimage_sbc png"></div>', '<div class="zoomimage_sbr png"></div>', '</div>', '</div>', '<img src="" />', '<div class="zoomimage_controls">', '<a href="#" class="zoomimage_prev png"></a>', '<a href="#" class="zoomimage_next png"></a>', '</div>', '<div class="zoomimage_caption"></div>', '<div class="zoomimage_loading"></div>', '</div>' ], // handle click on the trigger click: function(e) { var el = this; el.blur(); // if the image was not preloaded yet then wait if (el.zoomimageCfg.loading === true) { return false; } //zoom it in if not zoomed already if (el.zoomimageCfg.zoomed == false) { EYE.zoomimage.zoomIn(el); //else zoom it out } else { EYE.zoomimage.zoomOut(el, false); } return false; }, // zoom in the image zoomIn: function(el) { //if the image was not loaded yet then wait if (el.zoomimageCfg.loaded === false) { //if the image is not preloading then start preloading if (el.zoomimageCfg.loading != true) { el.zoomimageCfg.loading = true; EYE.zoomimage.preload(el); } return; } //if the image is zoomed in then just focus it if (el.zoomimageCfg.zoomed == true) { EYE.zoomimage.focus(el); return; } el.zoomimageCfg.beforeZoomIn.apply(el,[el.zoomimageCfg.box]); var elPos = EYE.getPosition(el, true); var elHeight = el.offsetHeight; var elWidth = el.offsetWidth; var pos = EYE.getScroll(); var borderAndShadow = el.zoomimageCfg.border + el.zoomimageCfg.shadow; var width = el.zoomimageCfg.width + borderAndShadow * 2; var height = el.zoomimageCfg.height + borderAndShadow * 2; var screenRatio = pos.iw/pos.ih; var imageRatio = el.zoomimageCfg.width/el.zoomimageCfg.height; // if the image is bigger then the viewport then resize the image to fit if (screenRatio > imageRatio) { if (height > pos.ih) { height = pos.ih; width = parseInt(height * imageRatio,10); } } else if (width > pos.iw) { width = pos.iw; height = parseInt(width / imageRatio, 10); } //if the image should be centered then do that, else center to trigger's position but do not leave the viewport var top = el.zoomimageCfg.centered ? pos.t + parseInt((pos.ih - height)/2, 10) : Math.min( Math.max( pos.t, elPos.y + (elHeight - height)/2 - borderAndShadow ), pos.t + pos.ih - height ); var left = el.zoomimageCfg.centered ? pos.l + parseInt((pos.iw - width)/2, 10) : Math.min( Math.max( pos.l, elPos.x + (elWidth - width)/2 - borderAndShadow ), pos.l + pos.iw - width ); var imgWidth = width - borderAndShadow * 2; var imgHeight = height - borderAndShadow * 2; if(el.zoomimageCfg.hideSource === true) { el.style.visibility = 'hidden'; } //move the image's box and animated it $('#' + el.zoomimageCfg.box) .css({ top: elPos.y + 'px', left: elPos.x + 'px', width: elWidth + 'px', height: elHeight + 'px' }) .find('>div') .hide() .end() .find('img') .attr('src', el.zoomimageCfg.src) .css({ top: 0, left: 0, width: '100%', height: '100%', display: 'block', borderWidth: '0px' }) .end() .animate({ width: imgWidth, height: imgHeight, top: top + borderAndShadow, left: left + borderAndShadow }, el.zoomimageCfg.duration, el.zoomimageCfg.easing, function(){ $(this) .css({ top: top + 'px', left: left + 'px', width: width + 'px', height: height + 'px' }) .find('img') .css({ top: el.zoomimageCfg.shadow + 'px', left: el.zoomimageCfg.shadow + 'px', width: imgWidth + 'px', height: imgHeight + 'px', borderWidth: el.zoomimageCfg.border + 'px' }) .end() .find('>div:first') .find('div.zoomimage_sc') .css('height', height - el.zoomimageCfg.shadow*2 + 'px') .end() .show(); el.zoomimageCfg.zoomed = true; EYE.zoomimage.focus(el); el.zoomimageCfg.onZoomIn.apply(el,[el.zoomimageCfg.box]); }); }, //focus image and show gallery controls if it is part of a gallery showControls: function(el) { if(el == undefined) return; if (el.zoomimageCfg == undefined) { el = $('#' + $(el).attr('zoomimage')).get(0); } var height, imgWidth, borderAndShadow = el.zoomimageCfg.border + el.zoomimageCfg.shadow; $('#' + el.zoomimageCfg.box) .find('img') .each(function(){ imgWidth = parseInt($.curCSS(this, 'width'),10); }) .end() .get(0).zoomimageControls = true; // if it has caption then display it if(el.zoomimageCfg.caption) { $('#' + el.zoomimageCfg.box) .find('>div:eq(2)') .stop() .css({ bottom: borderAndShadow + 'px', left: borderAndShadow + 'px', width: imgWidth + 'px' }) .show() .each(function() { this.style.height = 'auto'; height = this.offsetHeight; this.style.height = '0'; }) .animate({height: height}, el.zoomimageCfg.duration); } //if it has controls then show them if(el.zoomimageCfg.controls) { // show controls only if it is part of a gallery if (EYE.zoomimage.libs[el.zoomimageCfg.lib] > 1) { $('#' + el.zoomimageCfg.box) .find('>div:eq(1)') .show() .each(function(){ if (!el.zoomimageCfg.controlsHeight) { el.zoomimageCfg.controlsHeight = this.offsetHeight; } this.style.height = '0'; }) .css({ top: borderAndShadow + 'px', left: borderAndShadow + 'px', width: imgWidth + 'px' }) .animate({height: el.zoomimageCfg.controlsHeight}, el.zoomimageCfg.duration); } } }, //zoom out the image and go to the next/previous if any zoomOut: function(el, goToNext) { var boxEl, elPos, borderAndShadow, elSize; // if the action was started by the trigger if (el.zoomimageCfg) { if (el.zoomimageCfg.zoomed === false) { return; } el.zoomimageCfg.beforeZoomOut.apply(el,[el.zoomimageCfg.box]); boxEl = document.getElementById(el.zoomimageCfg.box); // else try to find a link that has the same href as the image src } else { boxEl = el; el = $('a[href=' + $('img',boxEl).attr('src') + ']').get(0); } // the trigger was found so scale to image to trigger's size if (el) { elPos = EYE.getPosition(el, true); el.zoomimageCfg.zoomed = false; borderAndShadow = el.zoomimageCfg.border + el.zoomimageCfg.shadow; elSize = { width: el.offsetWidth, height: el.offsetHeight }; // the trigger was not found so scale the image to its center } else { borderAndShadow = EYE.zoomimage.defaults.border + EYE.zoomimage.defaults.shadow; elSize = { width: 0, height: 0 }; elPos = EYE.getPosition(boxEl, true); elPos.y += parseInt(boxEl.offsetHeight/2, 10); elPos.x += parseInt(boxEl.offsetWidth/2, 10); } $(boxEl) .css({ top: boxEl.offsetTop + borderAndShadow + 'px', left: boxEl.offsetLeft + borderAndShadow + 'px', width: boxEl.offsetWidth - borderAndShadow*2 + 'px', height: boxEl.offsetHeight - borderAndShadow*2 + 'px' }) .find('>div') .stop() .hide() .end() .find('img') .css({ top: 0, left: 0, width: '100%', height: '100%', borderWidth: '0px' }) .end() .animate( { top: elPos.y + 'px', left: elPos.x + 'px', width: elSize.width + 'px', height: elSize.height + 'px' }, // if the trigger was not found the use the default duration el ? el.zoomimageCfg.duration : EYE.zoomimage.defaults.duration, el.zoomimageCfg.easing, function() { //hide image and remove focus EYE.zoomimage.blur(); $(this).hide(); // if the trigger was found then aply callback and try to focus the next one zoomed if (el) { if(el.zoomimageCfg.hideSource === true) { el.style.visibility = 'visible'; } el.zoomimageCfg.onZoomOut.apply(el,[el.zoomimageCfg.box]); if (!goToNext) { EYE.zoomimage.focus($('div.zoomimage:visible:last').not(':animated').get(0)); } //the trigger was not found so remove the image since no trigger is present in the page } else { $(boxEl).stop().remove(); } } ); }, mouseOver: function(e) { var triggerEl = document.getElementById($(this).attr('zoomimage')); if (triggerEl.zoomimageCfg.zoomed === true && this.zoomimageControls == false) { EYE.zoomimage.showControls(triggerEl); } return false; }, mouseOut: function(e) { if ( !EYE.isChildOf(this, e.relatedTarget, this) ) { $(this) .find('>div:not(:first)') .stop() .hide(); this.zoomimageControls = false; } return false; }, // prepare for possible drag mouseDown: function(e) { // find the trigger var triggerEl = document.getElementById($(this).attr('zoomimage')); //if the trigger was found then prepare informations for drag if (triggerEl) { $.extend(EYE.zoomimage,{ current: this, prevent: triggerEl.zoomimageCfg.prevent, moved: false, diff: { x: e.pageX - this.offsetLeft, y: e.pageY - this.offsetTop }, pointer: { x: e.pageX , y: e.pageY } }); $(document) .bind('mousemove', EYE.zoomimage.mouseMove) .bind('mouseup', EYE.zoomimage.mouseUp); // if the trigger was not found then it is an orphan and zoom it out } else { $(this).zoomimageClear(); } return false; }, //do the drag if prevent distance was overtake mouseMove: function(e) { var diffX = Math.abs(EYE.zoomimage.pointer.x - e.pageX); var diffY = Math.abs(EYE.zoomimage.pointer.y - e.pageY); //the prevent distance was not reached yet so we check if it is reached already if (EYE.zoomimage.moved === false) { if ( diffX > EYE.zoomimage.prevent|| diffY > EYE.zoomimage.prevent) { EYE.zoomimage.moved = true; $(EYE.zoomimage.current).addClass('zoomimage_move'); if (!$(EYE.zoomimage.current).is('.zoomimage_focused')) { EYE.zoomimage.focus(EYE.zoomimage.current); } } // the prevent distance was overtake so the element can be moved } else { EYE.zoomimage.current.style.top = e.pageY - EYE.zoomimage.diff.y + 'px'; EYE.zoomimage.current.style.left = e.pageX - EYE.zoomimage.diff.x + 'px'; } return false; }, //the drag stops mouseUp: function (e) { $(EYE.zoomimage.current).removeClass('zoomimage_move'); EYE.zoomimage.current = null; $(document) .unbind('mousemove', EYE.zoomimage.mouseMove) .unbind('mouseup', EYE.zoomimage.mouseUp); return false; }, // click on image imageClick: function(e) { $(document) .unbind('mousemove', EYE.zoomimage.mouseMove) .unbind('mouseup', EYE.zoomimage.mouseUp); var el = document.getElementById($(this).attr('zoomimage')); // if the trigger was found if (el) { //if the image was not moved but was focused if (EYE.zoomimage.moved === false && $(this).is('.zoomimage_focused')) { // if the event target is a link then it was a click on one of the controls and go to the next image if ($(e.target).is('a')) { EYE.zoomimage.zoomNext(el, e.target.className == 'zoomimage_next' ? 1 : -1); var goToNext = true; // else just zoom it out } else { EYE.zoomimage.zoomOut(el, goToNext||false); } // just focus the image } else if(!$(this).is('.zoomimage_focused')) { EYE.zoomimage.focus(this); } //the trigger was not found so the image is orphan and zoom it out } else { $(this).zoomimageClear(); } return false; }, //zoom out any opened image and clear orphan images clear: function() { var subject = this; if (subject.size() == 0) { subject = $('div.zoomimage'); } return subject.each(function(){ var triggerEl = document.getElementById($(this).attr('zoomimage')); if (triggerEl) { EYE.zoomimage.zoomOut(triggerEl, false); } else { EYE.zoomimage.zoomOut(this, false); } }); }, // zoom the next image in gallery zoomNext: function(el, dir) { if(el.zoomimageCfg.zoomed === false) { return; } EYE.zoomimage.zoomOut(el, true); var nextImg = el.zoomimageCfg.iteration + dir; var lib = $(el).attr('zoomimage'); var maxImg = EYE.zoomimage.libs[lib]; if (nextImg < 0) { nextImg = maxImg - 1; } else if (nextImg >= maxImg) { nextImg = 0; } EYE.zoomimage.zoomIn($('a[zoomimage="' + lib + '"]').get(nextImg)); }, //hande any key pressed keyPressed: function(e) { var el = $('div.zoomimage_focused'); if (el.size() == 1) { var pressedKey = e.charCode || e.keyCode || -1; el = $('#' + $(el).attr('zoomimage')).get(0); var lib = $(el).attr('zoomimage'); switch (pressedKey) { //end case 35: // go to the last image in the gallery if (EYE.zoomimage.libs[lib] > 1 && EYE.zoomimage.libs[lib] - 1 != el.zoomimageCfg.iteration) { EYE.zoomimage.zoomNext(el, EYE.zoomimage.libs[lib] - el.zoomimageCfg.iteration - 1); return false; } break; //home case 36: // go to the first image in the gallery if (EYE.zoomimage.libs[lib] > 1 && el.zoomimageCfg.iteration != 0) { EYE.zoomimage.zoomNext(el, - el.zoomimageCfg.iteration); return false; } break; //down; case 40: //left case 37: //backspace case 8: //page up case 33: //p case 80: case 112: // go to the previous image in the gallery if (EYE.zoomimage.libs[lib] > 1) { EYE.zoomimage.zoomNext(el, -1); return false; } break; //up case 38: //right case 39: //page down case 34: //space case 32: //n case 110: case 78: // go to the next image in the gallery if (EYE.zoomimage.libs[lib] > 1) { EYE.zoomimage.zoomNext(el, 1); return false; } break; //escape case 27: // well zoome out the curent image EYE.zoomimage.zoomOut(el, false); return false; break; } } }, // focus on image focus: function(el) { if(el == undefined) return; if (el.zoomimageCfg == undefined) { el = $('#' + $(el).attr('zoomimage')).get(0); } else { var showControls = true; } // if another image is focused then remove focus EYE.zoomimage.blur(el); $('#' + el.zoomimageCfg.box) .not('.zoomimage_focused') .addClass('zoomimage_focused'); el.zoomimageCfg.onFocus.apply(el,[el.zoomimageCfg.box]); if (el.zoomimageCfg.controlsTrigger == 'focus' || showControls) { EYE.zoomimage.showControls(el); } }, //blur image blur: function(el) { $('div.zoomimage_focused') .not('#' + (el == undefined ? 'fakezoomimage' : el.zoomimageCfg.box)) .removeClass('zoomimage_focused') .each(function(){ this.zoomimageControls = false; }) .find('>div:not(:first)') .stop() .hide(); }, preload: function(el) { // place the loading aimation on top var boxEl = $('#' + el.zoomimageCfg.box).show(); boxEl.find('>div, img').hide(); var elPos = EYE.getPosition(el, true); boxEl .find('>div:last') .show() .end() .css({ top: elPos.y + 'px', left: elPos.x + 'px', width: el.offsetWidth + 'px', height: el.offsetHeight + 'px' }); // preload the image var preld= new Image(); preld.src = el.href; //if the image was laoded already if (preld.complete) { EYE.zoomimage.markPreloaded(preld, el); // else place a callback } else { preld.onload = function() { EYE.zoomimage.markPreloaded(preld, el); }; } }, markPreloaded: function(preld, el) { //mark image as loaded and remember the size and source $.extend(el.zoomimageCfg,{ loaded: true, width: preld.width, height: preld.height, src: preld.src }); // hide loading animation $('#' + el.zoomimageCfg.box) .find('div.zoomimage_loading') .hide(); //if the image waits to be enlarged then zoom in if (el.zoomimageCfg.loading) { el.zoomimageCfg.loading = false; EYE.zoomimage.zoomIn(el); } el.zoomimageCfg.onLoad.apply(el,[el.zoomimageCfg.box]); }, //constructor init: function(opt) { //generate a library key var libKey = parseInt(Math.random()*2000,10); //store the number of images in the library EYE.zoomimage.libs[libKey] = 0; opt = $.extend({lib:libKey}, EYE.zoomimage.defaults, opt||{}); return this.each(function(){ var jQEl = $(this); var el = this; //consider only the links pointing to an image if (el.href && el.href.toLowerCase().match(EYE.zoomimage.types) != null) { //store library options el.zoomimageCfg = $.extend({}, opt, { zoomed: false, loading: false, loaded: false, animated: false, src: el.href, iteration: EYE.zoomimage.libs[libKey], box: 'zoomimage_' + parseInt(Math.random() * 2000, 10) + '' }); //increment the number of images in the library EYE.zoomimage.libs[libKey]++; jQEl .bind('click', EYE.zoomimage.click) .attr('zoomimage', libKey) .attr('zoomimageBox', el.zoomimageCfg.box); var currId = jQEl.attr('id'); if (!currId) { currId = el.zoomimageCfg.box + '_trigger'; jQEl.attr('id', currId); } var titleAttr = $(el).attr('title'); if (titleAttr == '' || titleAttr == false) { el.zoomimageCfg.caption = false; } // generate the HTML for the image's box $(EYE.zoomimage.template.join('')) .attr('id', el.zoomimageCfg.box) .attr('zoomimage', currId) .addClass(el.zoomimageCfg.className) .appendTo(document.body) .bind('mousedown', EYE.zoomimage.mouseDown) .bind('click', EYE.zoomimage.imageClick) .each(function(){ this.zoomimageControls = false; if (el.zoomimageCfg.controlsTrigger != 'focus') { $(this) .bind('mouseover', EYE.zoomimage.mouseOver) .bind('mouseout', EYE.zoomimage.mouseOut); } }) .find('>div') .not(':first') .css('opacity', el.zoomimageCfg.opacity) .end() .filter('div:eq(2)') .html('<p>' + titleAttr + '</p>'); if (el.zoomimageCfg.preload == 'load') { EYE.zoomimage.preload(el); } if (EYE.zoomimage.trackKey === false) { EYE.zoomimage.trackKey = true; $(document).bind('keydown', EYE.zoomimage.keyPressed); } } }); } } }); $.fn.extend({ /** * Open all images found in 'href' attribute from each element specified in the selection. The images are grouped in galleries. The images are preloaded before any user interation. * @name zoomimage * @description Open all images found in 'href' attribute from each element specified in the selection. The images are grouped in galleries * @param Hash options A hash of parameters. All parameters are optional. * @option float opacity The opacity for the caption and controls. Default: 0.3 * @option int border Image's border. Default: 0 * @option int duration Animation duration. Default 300 * @option int prevent Pixes to move the mouse before the images is dragged (prevents accidental dragging). Default: 14 * @option boolean controls Whatever if the controls are displayed (if the image is not part of an libriry then the controls are not displayed) * @option boolean caption Whatever if the caption is displayed (the caption text is the text from 'title' atribute. Default: true * @option boolean centered Whatever if the image should be centered in the viewport or to the trigger. Default: false * @option string easing Animation easing. Default: linear * @option boolean hideSource Whatever to hide source when the image is opened. Default: false * @option string className CSS class to add to image's box. Default: false * @option string controlsTrigger 'focus' to show caption and controls when the box is focused or 'mouseover' to show controls and caption on mouse over. Default: 'focus' * @option string preload 'click' to preload the image when the trigger is clicked or 'load' to preload the image on document load. Default: 'click' * @option function onLoad Callback function triggered when the image was loaded * @option function beforeZoomIn Callback function triggered before the image is zoomed in * @option function onZoomIn Callback function triggered when the image is zooms in * @option function beforeZoomOut Callback function triggered before the image is zoomed out * @option function onZoomOut Callback function triggered when the image is zooms out * @option function onFocus Callback function triggered when the image is focused */ zoomimage: EYE.zoomimage.init, /** * Zooms out all opened images and removes orphans (when the trigger was not found) * To clear specific images use for slector 'div.zooimage[whatever]', else all the images are processed */ zoomimageClear: EYE.zoomimage.clear }); })(jQuery);
JavaScript
/** * * Date picker * Author: Stefan Petre www.eyecon.ro * * Dual licensed under the MIT and GPL licenses * */ (function ($) { var DatePicker = function () { var ids = {}, views = { years: 'datepickerViewYears', moths: 'datepickerViewMonths', days: 'datepickerViewDays' }, tpl = { wrapper: '<div class="datepicker"><div class="datepickerBorderT" /><div class="datepickerBorderB" /><div class="datepickerBorderL" /><div class="datepickerBorderR" /><div class="datepickerBorderTL" /><div class="datepickerBorderTR" /><div class="datepickerBorderBL" /><div class="datepickerBorderBR" /><div class="datepickerContainer"><table cellspacing="0" cellpadding="0"><tbody><tr></tr></tbody></table></div></div>', head: [ '<td>', '<table cellspacing="0" cellpadding="0">', '<thead>', '<tr>', '<th class="datepickerGoPrev"><a href="#"><span><%=prev%></span></a></th>', '<th colspan="6" class="datepickerMonth"><a href="#"><span></span></a></th>', '<th class="datepickerGoNext"><a href="#"><span><%=next%></span></a></th>', '</tr>', '<tr class="datepickerDoW">', '<th><span><%=week%></span></th>', '<th><span><%=day1%></span></th>', '<th><span><%=day2%></span></th>', '<th><span><%=day3%></span></th>', '<th><span><%=day4%></span></th>', '<th><span><%=day5%></span></th>', '<th><span><%=day6%></span></th>', '<th><span><%=day7%></span></th>', '</tr>', '</thead>', '</table></td>' ], space : '<td class="datepickerSpace"><div></div></td>', days: [ '<tbody class="datepickerDays">', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[0].week%></span></a></th>', '<td class="<%=weeks[0].days[0].classname%>"><a href="#"><span><%=weeks[0].days[0].text%></span></a></td>', '<td class="<%=weeks[0].days[1].classname%>"><a href="#"><span><%=weeks[0].days[1].text%></span></a></td>', '<td class="<%=weeks[0].days[2].classname%>"><a href="#"><span><%=weeks[0].days[2].text%></span></a></td>', '<td class="<%=weeks[0].days[3].classname%>"><a href="#"><span><%=weeks[0].days[3].text%></span></a></td>', '<td class="<%=weeks[0].days[4].classname%>"><a href="#"><span><%=weeks[0].days[4].text%></span></a></td>', '<td class="<%=weeks[0].days[5].classname%>"><a href="#"><span><%=weeks[0].days[5].text%></span></a></td>', '<td class="<%=weeks[0].days[6].classname%>"><a href="#"><span><%=weeks[0].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[1].week%></span></a></th>', '<td class="<%=weeks[1].days[0].classname%>"><a href="#"><span><%=weeks[1].days[0].text%></span></a></td>', '<td class="<%=weeks[1].days[1].classname%>"><a href="#"><span><%=weeks[1].days[1].text%></span></a></td>', '<td class="<%=weeks[1].days[2].classname%>"><a href="#"><span><%=weeks[1].days[2].text%></span></a></td>', '<td class="<%=weeks[1].days[3].classname%>"><a href="#"><span><%=weeks[1].days[3].text%></span></a></td>', '<td class="<%=weeks[1].days[4].classname%>"><a href="#"><span><%=weeks[1].days[4].text%></span></a></td>', '<td class="<%=weeks[1].days[5].classname%>"><a href="#"><span><%=weeks[1].days[5].text%></span></a></td>', '<td class="<%=weeks[1].days[6].classname%>"><a href="#"><span><%=weeks[1].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[2].week%></span></a></th>', '<td class="<%=weeks[2].days[0].classname%>"><a href="#"><span><%=weeks[2].days[0].text%></span></a></td>', '<td class="<%=weeks[2].days[1].classname%>"><a href="#"><span><%=weeks[2].days[1].text%></span></a></td>', '<td class="<%=weeks[2].days[2].classname%>"><a href="#"><span><%=weeks[2].days[2].text%></span></a></td>', '<td class="<%=weeks[2].days[3].classname%>"><a href="#"><span><%=weeks[2].days[3].text%></span></a></td>', '<td class="<%=weeks[2].days[4].classname%>"><a href="#"><span><%=weeks[2].days[4].text%></span></a></td>', '<td class="<%=weeks[2].days[5].classname%>"><a href="#"><span><%=weeks[2].days[5].text%></span></a></td>', '<td class="<%=weeks[2].days[6].classname%>"><a href="#"><span><%=weeks[2].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[3].week%></span></a></th>', '<td class="<%=weeks[3].days[0].classname%>"><a href="#"><span><%=weeks[3].days[0].text%></span></a></td>', '<td class="<%=weeks[3].days[1].classname%>"><a href="#"><span><%=weeks[3].days[1].text%></span></a></td>', '<td class="<%=weeks[3].days[2].classname%>"><a href="#"><span><%=weeks[3].days[2].text%></span></a></td>', '<td class="<%=weeks[3].days[3].classname%>"><a href="#"><span><%=weeks[3].days[3].text%></span></a></td>', '<td class="<%=weeks[3].days[4].classname%>"><a href="#"><span><%=weeks[3].days[4].text%></span></a></td>', '<td class="<%=weeks[3].days[5].classname%>"><a href="#"><span><%=weeks[3].days[5].text%></span></a></td>', '<td class="<%=weeks[3].days[6].classname%>"><a href="#"><span><%=weeks[3].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[4].week%></span></a></th>', '<td class="<%=weeks[4].days[0].classname%>"><a href="#"><span><%=weeks[4].days[0].text%></span></a></td>', '<td class="<%=weeks[4].days[1].classname%>"><a href="#"><span><%=weeks[4].days[1].text%></span></a></td>', '<td class="<%=weeks[4].days[2].classname%>"><a href="#"><span><%=weeks[4].days[2].text%></span></a></td>', '<td class="<%=weeks[4].days[3].classname%>"><a href="#"><span><%=weeks[4].days[3].text%></span></a></td>', '<td class="<%=weeks[4].days[4].classname%>"><a href="#"><span><%=weeks[4].days[4].text%></span></a></td>', '<td class="<%=weeks[4].days[5].classname%>"><a href="#"><span><%=weeks[4].days[5].text%></span></a></td>', '<td class="<%=weeks[4].days[6].classname%>"><a href="#"><span><%=weeks[4].days[6].text%></span></a></td>', '</tr>', '<tr>', '<th class="datepickerWeek"><a href="#"><span><%=weeks[5].week%></span></a></th>', '<td class="<%=weeks[5].days[0].classname%>"><a href="#"><span><%=weeks[5].days[0].text%></span></a></td>', '<td class="<%=weeks[5].days[1].classname%>"><a href="#"><span><%=weeks[5].days[1].text%></span></a></td>', '<td class="<%=weeks[5].days[2].classname%>"><a href="#"><span><%=weeks[5].days[2].text%></span></a></td>', '<td class="<%=weeks[5].days[3].classname%>"><a href="#"><span><%=weeks[5].days[3].text%></span></a></td>', '<td class="<%=weeks[5].days[4].classname%>"><a href="#"><span><%=weeks[5].days[4].text%></span></a></td>', '<td class="<%=weeks[5].days[5].classname%>"><a href="#"><span><%=weeks[5].days[5].text%></span></a></td>', '<td class="<%=weeks[5].days[6].classname%>"><a href="#"><span><%=weeks[5].days[6].text%></span></a></td>', '</tr>', '</tbody>' ], months: [ '<tbody class="<%=className%>">', '<tr>', '<td colspan="2"><a href="#"><span><%=data[0]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[1]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[2]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[3]%></span></a></td>', '</tr>', '<tr>', '<td colspan="2"><a href="#"><span><%=data[4]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[5]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[6]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[7]%></span></a></td>', '</tr>', '<tr>', '<td colspan="2"><a href="#"><span><%=data[8]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[9]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[10]%></span></a></td>', '<td colspan="2"><a href="#"><span><%=data[11]%></span></a></td>', '</tr>', '</tbody>' ] }, defaults = { flat: false, starts: 1, prev: '&#9664;', next: '&#9654;', lastSel: false, mode: 'single', view: 'days', calendars: 1, format: 'Y-m-d', position: 'bottom', eventName: 'click', onRender: function(){return {};}, onChange: function(){return true;}, onShow: function(){return true;}, onBeforeShow: function(){return true;}, onHide: function(){return true;}, locale: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], weekMin: 'wk' } }, fill = function(el) { var options = $(el).data('datepicker'); var cal = $(el); var currentCal = Math.floor(options.calendars/2), date, data, dow, month, cnt = 0, week, days, indic, indic2, html, tblCal; cal.find('td>table tbody').remove(); for (var i = 0; i < options.calendars; i++) { date = new Date(options.current); date.addMonths(-currentCal + i); tblCal = cal.find('table').eq(i+1); switch (tblCal[0].className) { case 'datepickerViewDays': dow = formatDate(date, 'B, Y'); break; case 'datepickerViewMonths': dow = date.getFullYear(); break; case 'datepickerViewYears': dow = (date.getFullYear()-6) + ' - ' + (date.getFullYear()+5); break; } tblCal.find('thead tr:first th:eq(1) span').text(dow); dow = date.getFullYear()-6; data = { data: [], className: 'datepickerYears' } for ( var j = 0; j < 12; j++) { data.data.push(dow + j); } html = tmpl(tpl.months.join(''), data); date.setDate(1); data = {weeks:[], test: 10}; month = date.getMonth(); var dow = (date.getDay() - options.starts) % 7; date.addDays(-(dow + (dow < 0 ? 7 : 0))); week = -1; cnt = 0; while (cnt < 42) { indic = parseInt(cnt/7,10); indic2 = cnt%7; if (!data.weeks[indic]) { week = date.getWeekNumber(); data.weeks[indic] = { week: week, days: [] }; } data.weeks[indic].days[indic2] = { text: date.getDate(), classname: [] }; if (month != date.getMonth()) { data.weeks[indic].days[indic2].classname.push('datepickerNotInMonth'); } if (date.getDay() == 0) { data.weeks[indic].days[indic2].classname.push('datepickerSunday'); } if (date.getDay() == 6) { data.weeks[indic].days[indic2].classname.push('datepickerSaturday'); } var fromUser = options.onRender(date); var val = date.valueOf(); if (fromUser.selected || options.date == val || $.inArray(val, options.date) > -1 || (options.mode == 'range' && val >= options.date[0] && val <= options.date[1])) { data.weeks[indic].days[indic2].classname.push('datepickerSelected'); } if (fromUser.disabled) { data.weeks[indic].days[indic2].classname.push('datepickerDisabled'); } if (fromUser.className) { data.weeks[indic].days[indic2].classname.push(fromUser.className); } data.weeks[indic].days[indic2].classname = data.weeks[indic].days[indic2].classname.join(' '); cnt++; date.addDays(1); } html = tmpl(tpl.days.join(''), data) + html; data = { data: options.locale.monthsShort, className: 'datepickerMonths' }; html = tmpl(tpl.months.join(''), data) + html; tblCal.append(html); } }, parseDate = function (date, format) { if (date.constructor == Date) { return new Date(date); } var parts = date.split(/\W+/); var against = format.split(/\W+/), d, m, y, h, min, now = new Date(); for (var i = 0; i < parts.length; i++) { switch (against[i]) { case 'd': case 'e': d = parseInt(parts[i],10); break; case 'm': m = parseInt(parts[i], 10)-1; break; case 'Y': case 'y': y = parseInt(parts[i], 10); y += y > 100 ? 0 : (y < 29 ? 2000 : 1900); break; case 'H': case 'I': case 'k': case 'l': h = parseInt(parts[i], 10); break; case 'P': case 'p': if (/pm/i.test(parts[i]) && h < 12) { h += 12; } else if (/am/i.test(parts[i]) && h >= 12) { h -= 12; } break; case 'M': min = parseInt(parts[i], 10); break; } } return new Date( y === undefined ? now.getFullYear() : y, m === undefined ? now.getMonth() : m, d === undefined ? now.getDate() : d, h === undefined ? now.getHours() : h, min === undefined ? now.getMinutes() : min, 0 ); }, formatDate = function(date, format) { var m = date.getMonth(); var d = date.getDate(); var y = date.getFullYear(); var wn = date.getWeekNumber(); var w = date.getDay(); var s = {}; var hr = date.getHours(); var pm = (hr >= 12); var ir = (pm) ? (hr - 12) : hr; var dy = date.getDayOfYear(); if (ir == 0) { ir = 12; } var min = date.getMinutes(); var sec = date.getSeconds(); var parts = format.split(''), part; for ( var i = 0; i < parts.length; i++ ) { part = parts[i]; switch (parts[i]) { case 'a': part = date.getDayName(); break; case 'A': part = date.getDayName(true); break; case 'b': part = date.getMonthName(); break; case 'B': part = date.getMonthName(true); break; case 'C': part = 1 + Math.floor(y / 100); break; case 'd': part = (d < 10) ? ("0" + d) : d; break; case 'e': part = d; break; case 'H': part = (hr < 10) ? ("0" + hr) : hr; break; case 'I': part = (ir < 10) ? ("0" + ir) : ir; break; case 'j': part = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; break; case 'k': part = hr; break; case 'l': part = ir; break; case 'm': part = (m < 9) ? ("0" + (1+m)) : (1+m); break; case 'M': part = (min < 10) ? ("0" + min) : min; break; case 'p': case 'P': part = pm ? "PM" : "AM"; break; case 's': part = Math.floor(date.getTime() / 1000); break; case 'S': part = (sec < 10) ? ("0" + sec) : sec; break; case 'u': part = w + 1; break; case 'w': part = w; break; case 'y': part = ('' + y).substr(2, 2); break; case 'Y': part = y; break; } parts[i] = part; } return parts.join(''); }, extendDate = function(options) { if (Date.prototype.tempDate) { return; } Date.prototype.tempDate = null; Date.prototype.months = options.months; Date.prototype.monthsShort = options.monthsShort; Date.prototype.days = options.days; Date.prototype.daysShort = options.daysShort; Date.prototype.getMonthName = function(fullName) { return this[fullName ? 'months' : 'monthsShort'][this.getMonth()]; }; Date.prototype.getDayName = function(fullName) { return this[fullName ? 'days' : 'daysShort'][this.getDay()]; }; Date.prototype.addDays = function (n) { this.setDate(this.getDate() + n); this.tempDate = this.getDate(); }; Date.prototype.addMonths = function (n) { if (this.tempDate == null) { this.tempDate = this.getDate(); } this.setDate(1); this.setMonth(this.getMonth() + n); this.setDate(Math.min(this.tempDate, this.getMaxDays())); }; Date.prototype.addYears = function (n) { if (this.tempDate == null) { this.tempDate = this.getDate(); } this.setDate(1); this.setFullYear(this.getFullYear() + n); this.setDate(Math.min(this.tempDate, this.getMaxDays())); }; Date.prototype.getMaxDays = function() { var tmpDate = new Date(Date.parse(this)), d = 28, m; m = tmpDate.getMonth(); d = 28; while (tmpDate.getMonth() == m) { d ++; tmpDate.setDate(d); } return d - 1; }; Date.prototype.getFirstDay = function() { var tmpDate = new Date(Date.parse(this)); tmpDate.setDate(1); return tmpDate.getDay(); }; Date.prototype.getWeekNumber = function() { var tempDate = new Date(this); tempDate.setDate(tempDate.getDate() - (tempDate.getDay() + 6) % 7 + 3); var dms = tempDate.valueOf(); tempDate.setMonth(0); tempDate.setDate(4); return Math.round((dms - tempDate.valueOf()) / (604800000)) + 1; }; Date.prototype.getDayOfYear = function() { var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0); var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0); var time = now - then; return Math.floor(time / 24*60*60*1000); }; }, layout = function (el) { var options = $(el).data('datepicker'); var cal = $('#' + options.id); if (!options.extraHeight) { var divs = $(el).find('div'); options.extraHeight = divs.get(0).offsetHeight + divs.get(1).offsetHeight; options.extraWidth = divs.get(2).offsetWidth + divs.get(3).offsetWidth; } var tbl = cal.find('table:first').get(0); var width = tbl.offsetWidth; var height = tbl.offsetHeight; cal.css({ width: width + options.extraWidth + 'px', height: height + options.extraHeight + 'px' }).find('div.datepickerContainer').css({ width: width + 'px', height: height + 'px' }); }, click = function(ev) { if ($(ev.target).is('span')) { ev.target = ev.target.parentNode; } var el = $(ev.target); if (el.is('a')) { ev.target.blur(); if (el.hasClass('datepickerDisabled')) { return false; } var options = $(this).data('datepicker'); var parentEl = el.parent(); var tblEl = parentEl.parent().parent().parent(); var tblIndex = $('table', this).index(tblEl.get(0)) - 1; var tmp = new Date(options.current); var changed = false; var fillIt = false; if (parentEl.is('th')) { if (parentEl.hasClass('datepickerWeek') && options.mode == 'range' && !parentEl.next().hasClass('datepickerDisabled')) { var val = parseInt(parentEl.next().text(), 10); tmp.addMonths(tblIndex - Math.floor(options.calendars/2)); if (parentEl.next().hasClass('datepickerNotInMonth')) { tmp.addMonths(val > 15 ? -1 : 1); } tmp.setDate(val); options.date[0] = (tmp.setHours(0,0,0,0)).valueOf(); tmp.setHours(23,59,59,0); tmp.addDays(6); options.date[1] = tmp.valueOf(); fillIt = true; changed = true; options.lastSel = false; } else if (parentEl.hasClass('datepickerMonth')) { tmp.addMonths(tblIndex - Math.floor(options.calendars/2)); switch (tblEl.get(0).className) { case 'datepickerViewDays': tblEl.get(0).className = 'datepickerViewMonths'; el.find('span').text(tmp.getFullYear()); break; case 'datepickerViewMonths': tblEl.get(0).className = 'datepickerViewYears'; el.find('span').text((tmp.getFullYear()-6) + ' - ' + (tmp.getFullYear()+5)); break; case 'datepickerViewYears': tblEl.get(0).className = 'datepickerViewDays'; el.find('span').text(formatDate(tmp, 'B, Y')); break; } } else if (parentEl.parent().parent().is('thead')) { switch (tblEl.get(0).className) { case 'datepickerViewDays': options.current.addMonths(parentEl.hasClass('datepickerGoPrev') ? -1 : 1); break; case 'datepickerViewMonths': options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -1 : 1); break; case 'datepickerViewYears': options.current.addYears(parentEl.hasClass('datepickerGoPrev') ? -12 : 12); break; } fillIt = true; } } else if (parentEl.is('td') && !parentEl.hasClass('datepickerDisabled')) { switch (tblEl.get(0).className) { case 'datepickerViewMonths': options.current.setMonth(tblEl.find('tbody.datepickerMonths td').index(parentEl)); options.current.setFullYear(parseInt(tblEl.find('thead th.datepickerMonth span').text(), 10)); options.current.addMonths(Math.floor(options.calendars/2) - tblIndex); tblEl.get(0).className = 'datepickerViewDays'; break; case 'datepickerViewYears': options.current.setFullYear(parseInt(el.text(), 10)); tblEl.get(0).className = 'datepickerViewMonths'; break; default: var val = parseInt(el.text(), 10); tmp.addMonths(tblIndex - Math.floor(options.calendars/2)); if (parentEl.hasClass('datepickerNotInMonth')) { tmp.addMonths(val > 15 ? -1 : 1); } tmp.setDate(val); switch (options.mode) { case 'multiple': val = (tmp.setHours(0,0,0,0)).valueOf(); if ($.inArray(val, options.date) > -1) { $.each(options.date, function(nr, dat){ if (dat == val) { options.date.splice(nr,1); return false; } }); } else { options.date.push(val); } break; case 'range': if (!options.lastSel) { options.date[0] = (tmp.setHours(0,0,0,0)).valueOf(); } val = (tmp.setHours(23,59,59,0)).valueOf(); if (val < options.date[0]) { options.date[1] = options.date[0] + 86399000; options.date[0] = val - 86399000; } else { options.date[1] = val; } options.lastSel = !options.lastSel; break; default: options.date = tmp.valueOf(); break; } break; } fillIt = true; changed = true; } if (fillIt) { fill(this); } if (changed) { options.onChange.apply(this, prepareDate(options)); } } return false; }, prepareDate = function (options) { var tmp; if (options.mode == 'single') { tmp = new Date(options.date); return [formatDate(tmp, options.format), tmp, options.el]; } else { tmp = [[],[], options.el]; $.each(options.date, function(nr, val){ var date = new Date(val); tmp[0].push(formatDate(date, options.format)); tmp[1].push(date); }); return tmp; } }, getViewport = function () { var m = document.compatMode == 'CSS1Compat'; return { l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft), t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop), w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth), h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight) }; }, isChildOf = function(parentEl, el, container) { if (parentEl == el) { return true; } if (parentEl.contains) { return parentEl.contains(el); } if ( parentEl.compareDocumentPosition ) { return !!(parentEl.compareDocumentPosition(el) & 16); } var prEl = el.parentNode; while(prEl && prEl != container) { if (prEl == parentEl) return true; prEl = prEl.parentNode; } return false; }, show = function (ev) { var cal = $('#' + $(this).data('datepickerId')); if (!cal.is(':visible')) { var calEl = cal.get(0); fill(calEl); var options = cal.data('datepicker'); options.onBeforeShow.apply(this, [cal.get(0)]); var pos = $(this).offset(); var viewPort = getViewport(); var top = pos.top; var left = pos.left; var oldDisplay = $.curCSS(calEl, 'display'); cal.css({ visibility: 'hidden', display: 'block' }); layout(calEl); switch (options.position){ case 'top': top -= calEl.offsetHeight; break; case 'left': left -= calEl.offsetWidth; break; case 'right': left += this.offsetWidth; break; case 'bottom': top += this.offsetHeight; break; } if (top + calEl.offsetHeight > viewPort.t + viewPort.h) { top = pos.top - calEl.offsetHeight; } if (top < viewPort.t) { top = pos.top + this.offsetHeight + calEl.offsetHeight; } if (left + calEl.offsetWidth > viewPort.l + viewPort.w) { left = pos.left - calEl.offsetWidth; } if (left < viewPort.l) { left = pos.left + this.offsetWidth } cal.css({ visibility: 'visible', display: 'block', top: top + 'px', left: left + 'px' }); if (options.onShow.apply(this, [cal.get(0)]) != false) { cal.show(); } $(document).bind('mousedown', {cal: cal, trigger: this}, hide); } return false; }, hide = function (ev) { if (ev.target != ev.data.trigger && !isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) { if (ev.data.cal.data('datepicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) { ev.data.cal.hide(); } $(document).unbind('mousedown', hide); } }; return { init: function(options){ options = $.extend({}, defaults, options||{}); extendDate(options.locale); options.calendars = Math.max(1, parseInt(options.calendars,10)||1); options.mode = /single|multiple|range/.test(options.mode) ? options.mode : 'single'; return this.each(function(){ if (!$(this).data('datepicker')) { options.el = this; if (options.date.constructor == String) { options.date = parseDate(options.date, options.format); options.date.setHours(0,0,0,0); } if (options.mode != 'single') { if (options.date.constructor != Array) { options.date = [options.date.valueOf()]; if (options.mode == 'range') { options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf()); } } else { for (var i = 0; i < options.date.length; i++) { options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf(); } if (options.mode == 'range') { options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf(); } } } else { options.date = options.date.valueOf(); } if (!options.current) { options.current = new Date(); } else { options.current = parseDate(options.current, options.format); } options.current.setDate(1); options.current.setHours(0,0,0,0); var id = 'datepicker_' + parseInt(Math.random() * 1000), cnt; options.id = id; $(this).data('datepickerId', options.id); var cal = $(tpl.wrapper).attr('id', id).bind('click', click).data('datepicker', options); if (options.className) { cal.addClass(options.className); } var html = ''; for (var i = 0; i < options.calendars; i++) { cnt = options.starts; if (i > 0) { html += tpl.space; } html += tmpl(tpl.head.join(''), { week: options.locale.weekMin, prev: options.prev, next: options.next, day1: options.locale.daysMin[(cnt++)%7], day2: options.locale.daysMin[(cnt++)%7], day3: options.locale.daysMin[(cnt++)%7], day4: options.locale.daysMin[(cnt++)%7], day5: options.locale.daysMin[(cnt++)%7], day6: options.locale.daysMin[(cnt++)%7], day7: options.locale.daysMin[(cnt++)%7] }); } cal .find('tr:first').append(html) .find('table').addClass(views[options.view]); fill(cal.get(0)); if (options.flat) { cal.appendTo(this).show().css('position', 'relative'); layout(cal.get(0)); } else { cal.appendTo(document.body); $(this).bind(options.eventName, show); } } }); }, showPicker: function() { return this.each( function () { if ($(this).data('datepickerId')) { show.apply(this); } }); }, hidePicker: function() { return this.each( function () { if ($(this).data('datepickerId')) { $('#' + $(this).data('datepickerId')).hide(); } }); }, setDate: function(date, shiftTo){ return this.each(function(){ if ($(this).data('datepickerId')) { var cal = $('#' + $(this).data('datepickerId')); var options = cal.data('datepicker'); options.date = date; if (options.date.constructor == String) { options.date = parseDate(options.date, options.format); options.date.setHours(0,0,0,0); } if (options.mode != 'single') { if (options.date.constructor != Array) { options.date = [options.date.valueOf()]; if (options.mode == 'range') { options.date.push(((new Date(options.date[0])).setHours(23,59,59,0)).valueOf()); } } else { for (var i = 0; i < options.date.length; i++) { options.date[i] = (parseDate(options.date[i], options.format).setHours(0,0,0,0)).valueOf(); } if (options.mode == 'range') { options.date[1] = ((new Date(options.date[1])).setHours(23,59,59,0)).valueOf(); } } } else { options.date = options.date.valueOf(); } if (shiftTo) { options.current = new Date (options.mode != 'single' ? options.date[0] : options.date); } fill(cal.get(0)); } }); }, getDate: function(formated) { if (this.size() > 0) { return prepareDate($('#' + $(this).data('datepickerId')).data('datepicker'))[formated ? 0 : 1]; } }, clear: function(){ return this.each(function(){ if ($(this).data('datepickerId')) { var cal = $('#' + $(this).data('datepickerId')); var options = cal.data('datepicker'); if (options.mode != 'single') { options.date = []; fill(cal.get(0)); } } }); }, fixLayout: function(){ return this.each(function(){ if ($(this).data('datepickerId')) { var cal = $('#' + $(this).data('datepickerId')); var options = cal.data('datepicker'); if (options.flat) { layout(cal.get(0)); } } }); } }; }(); $.fn.extend({ DatePicker: DatePicker.init, DatePickerHide: DatePicker.hidePicker, DatePickerShow: DatePicker.showPicker, DatePickerSetDate: DatePicker.setDate, DatePickerGetDate: DatePicker.getDate, DatePickerClear: DatePicker.clear, DatePickerLayout: DatePicker.fixLayout }); })(jQuery); (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();
JavaScript
/*! * jQuery Form Plugin * version: 2.43 (12-MAR-2010) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ target: '#output' }); return false; // <-- important! }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') options = { success: options }; var url = $.trim(this.attr('action')); if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } url = url || window.location.href || ''; options = $.extend({ url: url, type: this.attr('method') || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options || {}); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (var n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) a.push( { name: n, value: options.data[n][k] } ); } else a.push( { name: n, value: options.data[n] } ); } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else options.data = q; // data is the query string for 'post' var $form = this, callbacks = []; if (options.resetForm) callbacks.push(function() { $form.resetForm(); }); if (options.clearForm) callbacks.push(function() { $form.clearForm(); }); // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) callbacks.push(options.success); options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg for (var i=0, max=callbacks.length; i < max; i++) callbacks[i].apply(options, [data, status, xhr || $form, $form]); }; // are there files to upload? var files = $('input:file', this).fieldValue(); var found = false; for (var j=0; j < files.length; j++) if (files[j]) found = true; var multipart = false; // var mp = 'multipart/form-data'; // multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if ((files.length && options.iframe !== false) || options.iframe || found || multipart) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) $.get(options.closeKeepAlive, fileUpload); else fileUpload(); } else $.ajax(options); // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit]', form).length) { alert('Error: Form elements must not be named "submit".'); return; } var opts = $.extend({}, $.ajaxSettings, options); var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts); var id = 'jqFormIO' + (new Date().getTime()); var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" onload="(jQuery(this).data(\'form-plugin-onload\'))()" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function() { this.aborted = 1; $io.attr('src', opts.iframeSrc); // abort op in progress } }; var g = opts.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) $.event.trigger("ajaxStart"); if (g) $.event.trigger("ajaxSend", [xhr, opts]); if (s.beforeSend && s.beforeSend(xhr, s) === false) { s.global && $.active--; return; } if (xhr.aborted) return; var cbInvoked = false; var timedOut = 0; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { opts.extraData = opts.extraData || {}; opts.extraData[n] = sub.value; if (sub.type == "image") { opts.extraData[n+'.x'] = form.clk_x; opts.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') form.setAttribute('method', 'POST'); if (form.getAttribute('action') != opts.url) form.setAttribute('action', opts.url); // ie borks in some cases when setting encoding if (! opts.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (opts.timeout) setTimeout(function() { timedOut = true; cb(); }, opts.timeout); // add "extra" data to form if provided in options var extraInputs = []; try { if (opts.extraData) for (var n in opts.extraData) extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+opts.extraData[n]+'" />') .appendTo(form)[0]); // add iframe to doc and submit the form $io.appendTo('body'); $io.data('form-plugin-onload', cb); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); t ? form.setAttribute('target', t) : $form.removeAttr('target'); $(extraInputs).remove(); } }; if (opts.forceSync) doSubmit(); else setTimeout(doSubmit, 10); // this lets dom updates render var domCheckCount = 100; function cb() { if (cbInvoked) return; var ok = true; try { if (timedOut) throw 'timeout'; // extract the server response from the iframe var data, doc; doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } log('Could not access iframe DOM after 100 tries.'); return; } log('response detected'); cbInvoked = true; xhr.responseText = doc.body ? doc.body.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; xhr.getResponseHeader = function(header){ var headers = {'content-type': opts.dataType}; return headers[header]; }; if (opts.dataType == 'json' || opts.dataType == 'script') { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) xhr.responseText = ta.value; else { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; if (pre) xhr.responseText = pre.innerHTML; } } else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = $.httpData(xhr, opts.dataType); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; $.handleError(opts, xhr, 'error', e); } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { opts.success(data, 'success'); if (g) $.event.trigger("ajaxSuccess", [xhr, opts]); } if (g) $.event.trigger("ajaxComplete", [xhr, opts]); if (g && ! --$.active) $.event.trigger("ajaxStop"); if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error'); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); }; function toXml(s, doc) { if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else doc = (new DOMParser()).parseFromString(s, 'text/xml'); return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null; }; }; }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { e.preventDefault(); $(this).ajaxSubmit(options); }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) return; target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length == 0) return a; var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) return a; for(var i=0, max=els.length; i < max; i++) { var el = els[i]; var n = el.name; if (!n) continue; if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } var v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(var j=0, jmax=v.length; j < jmax; j++) a.push({name: n, value: v[j]}); } else if (v !== null && typeof v != 'undefined') a.push({name: n, value: v}); } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0], n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) return; var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) a.push({name: n, value: v[i]}); } else if (v !== null && typeof v != 'undefined') a.push({name: this.name, value: v}); }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) continue; v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (typeof successful == 'undefined') successful = true; if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) return null; if (tag == 'select') { var index = el.selectedIndex; if (index < 0) return null; var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; if (one) return v; a.push(v); } } return a; } return el.value; }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') this.value = ''; else if (t == 'checkbox' || t == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) this.reset(); }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b == undefined) b = true; return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select == undefined) select = true; return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') this.checked = select; else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) window.console.log(msg); else if (window.opera && window.opera.postError) window.opera.postError(msg); } }; })(jQuery);
JavaScript
/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version: 1.0.3 * Requires jQuery 1.1.3+ * Docs: http://docs.jquery.com/Plugins/livequery */ (function($) { $.extend($.fn, { livequery: function(type, fn, fn2) { var self = this, q; // Handle different call patterns if ($.isFunction(type)) fn2 = fn, fn = type, type = undefined; // See if Live Query already exists $.each( $.livequery.queries, function(i, query) { if ( self.selector == query.selector && self.context == query.context && type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) ) // Found the query, exit the each loop return (q = query) && false; }); // Create new Live Query if it wasn't found q = q || new $.livequery(this.selector, this.context, type, fn, fn2); // Make sure it is running q.stopped = false; // Run it immediately for the first time q.run(); // Contnue the chain return this; }, expire: function(type, fn, fn2) { var self = this; // Handle different call patterns if ($.isFunction(type)) fn2 = fn, fn = type, type = undefined; // Find the Live Query based on arguments and stop it $.each( $.livequery.queries, function(i, query) { if ( self.selector == query.selector && self.context == query.context && (!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped ) $.livequery.stop(query.id); }); // Continue the chain return this; } }); $.livequery = function(selector, context, type, fn, fn2) { this.selector = selector; this.context = context || document; this.type = type; this.fn = fn; this.fn2 = fn2; this.elements = []; this.stopped = false; // The id is the index of the Live Query in $.livequery.queries this.id = $.livequery.queries.push(this)-1; // Mark the functions for matching later on fn.$lqguid = fn.$lqguid || $.livequery.guid++; if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++; // Return the Live Query return this; }; $.livequery.prototype = { stop: function() { var query = this; if ( this.type ) // Unbind all bound events this.elements.unbind(this.type, this.fn); else if (this.fn2) // Call the second function for all matched elements this.elements.each(function(i, el) { query.fn2.apply(el); }); // Clear out matched elements this.elements = []; // Stop the Live Query from running until restarted this.stopped = true; }, run: function() { // Short-circuit if stopped if ( this.stopped ) return; var query = this; var oEls = this.elements, els = $(this.selector, this.context), nEls = els.not(oEls); // Set elements to the latest set of matched elements this.elements = els; if (this.type) { // Bind events to newly matched elements nEls.bind(this.type, this.fn); // Unbind events to elements no longer matched if (oEls.length > 0) $.each(oEls, function(i, el) { if ( $.inArray(el, els) < 0 ) $.event.remove(el, query.type, query.fn); }); } else { // Call the first function for newly matched elements nEls.each(function() { query.fn.apply(this); }); // Call the second function for elements no longer matched if ( this.fn2 && oEls.length > 0 ) $.each(oEls, function(i, el) { if ( $.inArray(el, els) < 0 ) query.fn2.apply(el); }); } } }; $.extend($.livequery, { guid: 0, queries: [], queue: [], running: false, timeout: null, checkQueue: function() { if ( $.livequery.running && $.livequery.queue.length ) { var length = $.livequery.queue.length; // Run each Live Query currently in the queue while ( length-- ) $.livequery.queries[ $.livequery.queue.shift() ].run(); } }, pause: function() { // Don't run anymore Live Queries until restarted $.livequery.running = false; }, play: function() { // Restart Live Queries $.livequery.running = true; // Request a run of the Live Queries $.livequery.run(); }, registerPlugin: function() { $.each( arguments, function(i,n) { // Short-circuit if the method doesn't exist if (!$.fn[n]) return; // Save a reference to the original method var old = $.fn[n]; // Create a new method $.fn[n] = function() { // Call the original method var r = old.apply(this, arguments); // Request a run of the Live Queries $.livequery.run(); // Return the original methods result return r; } }); }, run: function(id) { if (id != undefined) { // Put the particular Live Query in the queue if it doesn't already exist if ( $.inArray(id, $.livequery.queue) < 0 ) $.livequery.queue.push( id ); } else // Put each Live Query in the queue if it doesn't already exist $.each( $.livequery.queries, function(id) { if ( $.inArray(id, $.livequery.queue) < 0 ) $.livequery.queue.push( id ); }); // Clear timeout if it already exists if ($.livequery.timeout) clearTimeout($.livequery.timeout); // Create a timeout to check the queue and actually run the Live Queries $.livequery.timeout = setTimeout($.livequery.checkQueue, 20); }, stop: function(id) { if (id != undefined) // Stop are particular Live Query $.livequery.queries[ id ].stop(); else // Stop all Live Queries $.each( $.livequery.queries, function(id) { $.livequery.queries[ id ].stop(); }); } }); // Register core DOM manipulation methods $.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove'); // Run Live Queries when the Document is ready $(function() { $.livequery.play(); }); // Save a reference to the original init method var init = $.prototype.init; // Create a new init method that exposes two new properties: selector and context $.prototype.init = function(a,c) { // Call the original init and save the result var r = init.apply(this, arguments); // Copy over properties if they exist already if (a && a.selector) r.context = a.context, r.selector = a.selector; // Set properties if ( typeof a == 'string' ) r.context = c || document, r.selector = a; // Return the result return r; }; // Give the init function the jQuery prototype for later instantiation (needed after Rev 4091) $.prototype.init.prototype = $.prototype; })(jQuery);
JavaScript
/* * Metadata - jQuery plugin for parsing metadata from elements * * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $ * */ /** * Sets the type of metadata to use. Metadata is encoded in JSON, and each property * in the JSON will become a property of the element itself. * * There are three supported types of metadata storage: * * attr: Inside an attribute. The name parameter indicates *which* attribute. * * class: Inside the class attribute, wrapped in curly braces: { } * * elem: Inside a child element (e.g. a script tag). The * name parameter indicates *which* element. * * The metadata for an element is loaded the first time the element is accessed via jQuery. * * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements * matched by expr, then redefine the metadata type and run another $(expr) for other elements. * * @name $.metadata.setType * * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p> * @before $.metadata.setType("class") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from the class attribute * * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p> * @before $.metadata.setType("attr", "data") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a "data" attribute * * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p> * @before $.metadata.setType("elem", "script") * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label" * @desc Reads metadata from a nested script element * * @param String type The encoding type * @param String name The name of the attribute to be used to get metadata (optional) * @cat Plugins/Metadata * @descr Sets the type of encoding to be used when loading metadata for the first time * @type undefined * @see metadata() */ (function($) { $.extend({ metadata : { defaults : { type: 'class', name: 'metadata', cre: /({.*})/, single: 'metadata' }, setType: function( type, name ){ this.defaults.type = type; this.defaults.name = name; }, get: function( elem, opts ){ var settings = $.extend({},this.defaults,opts); // check for empty string in single property if ( !settings.single.length ) settings.single = 'metadata'; var data = $.data(elem, settings.single); // returned cached data if it already exists if ( data ) return data; data = "{}"; if ( settings.type == "class" ) { var m = settings.cre.exec( elem.className ); if ( m ) data = m[1]; } else if ( settings.type == "elem" ) { if( !elem.getElementsByTagName ) return undefined; var e = elem.getElementsByTagName(settings.name); if ( e.length ) data = $.trim(e[0].innerHTML); } else if ( elem.getAttribute != undefined ) { var attr = elem.getAttribute( settings.name ); if ( attr ) data = attr; } if ( data.indexOf( '{' ) <0 ) data = "{" + data + "}"; data = eval("(" + data + ")"); $.data( elem, settings.single, data ); return data; } } }); /** * Returns the metadata object for the first member of the jQuery object. * * @name metadata * @descr Returns element's metadata object * @param Object opts An object contianing settings to override the defaults * @type jQuery * @cat Plugins/Metadata */ $.fn.metadata = function( opts ){ return $.metadata.get( this[0], opts ); }; })(jQuery);
JavaScript
/* * jqModal - Minimalist Modaling with jQuery * (http://dev.iceburg.net/jquery/jqModal/) * * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net> * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * $Version: 03/01/2009 +r14 */ (function($) { $.fn.jqm=function(o){ var p={ overlay: 50, overlayClass: 'jqmOverlay', closeClass: 'jqmClose', trigger: '.jqModal', ajax: F, ajaxText: '', target: F, modal: F, toTop: F, onShow: F, onHide: F, onLoad: F }; return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s; H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s}; if(p.trigger)$(this).jqmAddTrigger(p.trigger); });}; $.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');}; $.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');}; $.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});}; $.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});}; $.jqm = { hash:{}, open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z); if(c.modal) {if(!A[0])L('bind');A.push(s);} else if(c.overlay > 0)h.w.jqmAddClose(o); else o=F; h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F; if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}} if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u; r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});} else if(cc)h.w.jqmAddClose($(cc,h.w)); if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o); (c.onShow)?c.onShow(h):h.w.show();e(h);return F; }, close:function(s){var h=H[s];if(!h.a)return F;h.a=F; if(A[0]){A.pop();if(!A[0])L('unbind');} if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove(); if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F; }, params:{}}; var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false, i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}), e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);}, f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}}, L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);}, m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;}, hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() { if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});}; })(jQuery);
JavaScript
/* * Translated default messages for the jQuery validation plugin. * Locale: CN */ jQuery.extend(jQuery.validator.messages, { required: "此内容为必填项,请输入!", remote: "内容输入错误!", email: "E-mail格式错误,请重新输入!", url: "网址格式错误,请重新输入!", date: "日期格式错误,请重新输入!", dateISO: "日期格式错误,请重新输入!", number: "请输入合法的数字!", digits: "请输入零或正整数!", creditcard: "信用卡号格式错误,请重新输入!", equalTo: "两次输入不一致,请重新输入!", accept: "请输入拥有合法后缀名的字符串!", maxlength: jQuery.validator.format("字符串长度不能大于{0}!"), minlength: jQuery.validator.format("字符串长度不能小于{0}!"), rangelength: jQuery.validator.format("字符串长度只允许在{0}-{1}之间!"), range: jQuery.validator.format("输入的数值只允许在{0}-{1}之间!"), max: jQuery.validator.format("输入的数值不允许大于{0}!"), min: jQuery.validator.format("输入的数值不允许小于{0}!"), integer: "请输入合法的整数!", positive: "请输入合法的正数!", positiveInteger: "请输入合法的正整数!", mobile: "手机号码格式错误,请重新输入!", phone: "电话号码格式错误,请重新输入!", zipCode: "邮政编码格式错误,请重新输入!", requiredTo: "此内容为必填项,请输入!", username: "只允许包含中文、英文、数字和下划线!", prefix: "请输入以 {0} 开头的字符串!", lettersonly: "只允许包含字母!" });
JavaScript
/* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { var menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 800, animation : {opacity:'show'}, speed : 'normal', autoArrows : true, dropShadows : true, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow: function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);
JavaScript
/** * Cookie plugin * * Copyright (c) 2006 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * Create a cookie with the given name and value and other optional parameters. * * @example $.cookie('the_cookie', 'the_value'); * @desc Set the value of a cookie. * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); * @desc Create a cookie with all available options. * @example $.cookie('the_cookie', 'the_value'); * @desc Create a session cookie. * @example $.cookie('the_cookie', null); * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain * used when the cookie was set. * * @param String name The name of the cookie. * @param String value The value of the cookie. * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. * If set to null or omitted, the cookie will be a session cookie and will not be retained * when the the browser exits. * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will * require a secure protocol (like HTTPS). * @type undefined * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ /** * Get the value of a cookie with the given name. * * @example $.cookie('the_cookie'); * @desc Get the value of a cookie. * * @param String name The name of the cookie. * @return The value of the cookie. * @type String * * @name $.cookie * @cat Plugins/Cookie * @author Klaus Hartl/klaus.hartl@stilbuero.de */ jQuery.cookie = function(name, value, options) { if (typeof value != 'undefined') { // name and value given, set cookie options = options || {}; if (value === null) { value = ''; options.expires = -1; } var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; } expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE } // CAUTION: Needed to parenthesize options.path and options.domain // in the following expressions, otherwise they evaluate to undefined // in the packed version for some reason... var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); } else { // only name given, get cookie var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } };
JavaScript
/*** * lSelect(Link Select) 无限级联动下拉菜单插件 * * JSON数据格式示例:[{"title": "北京", "value": "beijing"},{"title": "湖南", "value": "hunan"},{"title": "湖北", "value": "hubei"}] * * http://www.shopxx.net * * Copyright (c) 2008 SHOP++. All rights reserved. **/ (function($){ $.extend($.fn, { lSelect: function(options){ // 默认参数 var settings = { url: "",// 数据获取url parameter: "path",// 数据获取参数名称 title: "title",// 定义JSON数据格式:选择名称 value: "value",// 定义JSON数据格式:选择值 emptyOption: "请选择",// 选择提示,null表示无提示 cssClass: "lSelect",// 下拉框css名称 cssStyle: {"margin-right": "10px"},// 下拉框左右css样式 isFadeIn: true// 是否渐显 }; $.extend(settings, options); return this.each(function(){ var $this = $(this); $this.hide(); var selectGroupClass = "lSelect" + Math.round(Math.random() * 1000000); var items = {}; var selectName = $this.attr("name"); var defaultSelectedValue = $this.val(); if (defaultSelectedValue == "") { addSelect($this); } else { var $select = $this; var defaultSelectedValueArray = defaultSelectedValue.split(","); for (var i = 0; i < defaultSelectedValueArray.length; i++) { var $nextSelect = addSelect($select, defaultSelectedValueArray[i]); if($nextSelect) { $select = $nextSelect; } } } // 绑定Select元素 function bindSelect(element) { element.bind("change", function(){ addSelect(element); $this.val(element.val()); }); } // 获取Json数据 function getJson(key) { if(typeof(items[key]) == "undefined") { var url = settings.url; if (key != "lSelectRoot") { var parameter = settings.parameter; if (parameter != null) { if(url.indexOf("?") > 0) { url = url + "&" + parameter + "=" + key; } else { url = url + "?" + parameter + "=" + key; } } } $.ajaxSetup({async: false}); $.getJSON(url, function(json) { items[key] = json; }); } return items[key]; } // 填充option function fill(element, key, selected) { var json = getJson(key); if (!json) { return false; } var length = 0; for (j in json){ length ++; } if (length == 0) { return false; } else { element.empty(); if(settings.emptyOption != null) { element.append('<option value="">' + settings.emptyOption + '</option>'); } $.each(json, function(id, object) { var optionValue = ""; if (object.value.indexOf(",") >= 0) { var optionValueArray = object.value.split(","); optionValue = optionValueArray[optionValueArray.length - 1]; } else { optionValue = object.value; } var option; if(selected && optionValue == selected) { option = $('<option value="' + object.value + '" selected>' + object.title + '</option>'); } else { option = $('<option value="' + object.value + '">' + object.title + '</option>'); } element.append(option); }); return true; } } // 增加select function addSelect(element, selected) { var $nextSelect; var isFill; if(element.is("select")) { element.nextAll("." + selectGroupClass).remove(); if(element.val() == "") { return; } element.after('<select class="' + settings.cssClass + ' ' + selectGroupClass + '" style="display: none;"></select>'); $nextSelect = element.next("." + selectGroupClass); isFill = fill($nextSelect, element.val(), selected); } else { element.after('<select class="' + settings.cssClass + ' ' + selectGroupClass + '" style="display: none;"></select>'); $nextSelect = element.next("." + selectGroupClass); isFill = fill($nextSelect, "lSelectRoot", selected); } if (isFill) { element.css(settings.cssStyle); if(settings.isFadeIn) { $nextSelect.fadeIn(); bindSelect($nextSelect); } else { $nextSelect.show(); } return $nextSelect; } else { $nextSelect.remove(); } } }); } }); })(jQuery);
JavaScript
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function () { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function () { alert("OK"); document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicity call 'app.receivedEvent(...);' onDeviceReady: function () { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function (id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } };
JavaScript

JavaScript
var DBDefer; //数据库缓存 var DBVersion = null; //数据库版本 var DBHandle = null; //处理 //初始化数据库 function InitializeDatabase() { DBDefer = $.Deferred(); //获取数据库信息 var dbBase = GetDataBase(); //检查数据库是否存在 dbBase.transaction(CheckDataVersionTableExistsQuery, DetermineDataVersionError, successCB); //创建了一个promise对象,具有state、always、then、primise方法 return DBDefer.promise(); } function CreateDatabase() { var defer = $.Deferred(); var db = GetDatabase(); db.transaction(function (tx) { tx.executeSql(DropDataVersionSql); tx.executeSql(CreateDataVersionSql); // insert current version tx.executeSql(InsertSysVersionEntrySql, [VersionId, "1.0"]); // create company tables tx.executeSql(CreateDataTableCompanySql); tx.executeSql(CreateDataTableCompanyAddressSql); tx.executeSql(CreateDataTableCompanyContactNumberSql); tx.executeSql(CreateDataTableCompanyEmailSql); // create contact table tx.executeSql(CreateDataTableContactSql); // create helpdesk case table tx.executeSql(CreateDataTableHelpdeskCaseSql); // create user account table tx.executeSql(CreateDataTableUserAccountSql); // create helpdesk resolution table tx.executeSql(CreateDataTableHelpdeskCaseResolutionSql); //alert('Running in Test Mode. Data will be reinitialized.'); DBDefer.resolve(); defer.resolve(true); }, DetermineDataVersionError); return defer.promise(); } // 事务执行成功后调用的回调函数 function successCB() { console.log("成功!"); alert("OK"); } // var CheckDataVersionTableExistsSql = "SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name='SysVersion';"; //检查数据库是否存在 function CheckDataVersionTableExistsQuery(tx, results) { tx.executeSql(CheckDataVersionTableExistsSql, [], CheckDataVersionTableExistsSuccess, DetermineDataVersionError); } //检查数据库版本 function CheckDataVersionTableExistsSuccess(tx, results) { if (results.rows.length <= 0) { DBVersion = null; DBDefer.reject(); return; } var tablecount = results.rows.item(0).cnt; if (tablecount > 0) { // table exists CheckDataVersionQuery(); } else { // table don't exist CreateDatabase(); CheckDataVersionQuery(); } } function GetDataBase() { if (DBHandle != null) return DBHandle; DBHandle = window.openDatabase("SugarDB", "1.0", "SugarDB", 5000000); return DBHandle; } //事务执行出错后调用的回调函数 function DetermineDataVersionError(tx, err) { alert(tx.message); DBVersion = null; DBDefer.reject(); }
JavaScript
$(function () { /***********创建数据库****************************************************/ InitializeDatabase(); /***************************************************************/ /*登录*/ $("#btnLogin").click(function () { var username = document.getElementById("username").value; var password = document.getElementById("password").value; var b = verify(username, password); if (b) loginSys(username, password); }); }); /*初始化数据库*/ function InitializeDatabase() { var db = window.openDatabase("SugarDB", "1.0", "SugarDB", 5000000); db.transaction(DoCreateDataTable, errorCB); } function DoCreateDataTable(tx) { //检查LoginInfo表是否存在 var CheckDataVersionTableExistsSql = "SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name='LoginInfo';"; tx.executeSql(CheckDataVersionTableExistsSql, [], querySuccess, errorCB); } function querySuccess(tx, results) { var tablecount = results.rows.item(0).cnt; //判断是否存在表 if (tablecount <= 0) { //创建数据登录用户信息表 var CreateDataTableUserSql = "create table if not exists LoginInfo (id integer not null primary key ,loginName text,password text,details text,createtime text,sex integer)"; tx.executeSql(CreateDataTableUserSql); //插入初始数据 // var InsertDataTableUserSql = "insert into LoginInfo (id,loginName,password,details) values(1,'admin','admin','')"; // tx.executeSql(InsertDataTableUserSql); alert("创建数据表"); } } function errorCB(err) { console.log("错误处理的SQL:" + err.code + "错误信息:" + err.message); alert("错误信息:" + err.message); } // 事务执行成功后调用的回调函数 function successCB() { alert("创建成功!"); } /*验证*/ function verify(username, password) { if (username == "") { alert("请输入帐号!"); return false; } if (password == "") { alert("请输入密码!"); return false; } return true; } //登陆操作 function loginSys(username, password) { $.ajax({ type: "POST", dataType: "text", //cache:true, url: "ashx/LoginHandler.ashx?action=Login", data: { username: username, password: password }, success: function (status) { if (status == "0") { window.location.href = "index.html"; } else { alert('账号或密码错误!'); } }, error: function (err) { alert(err.responseTest); alert('获取账号信息失败...请联系管理员!'); } }); }
JavaScript
function sessionusername(username) { $.cookie('name', username); } function Getusername() { var name = $.cookie('name'); return name; } function OutUserName() { $.cookie('name', null); }
JavaScript
var VersionId = 1000; var CurrentSyncUrlId = 1100; var CurrentVersion = "1.3"; var CheckDataVersionTableExistsSql = "SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name='SysVersion';"; var GetSysVersionEntrySql = "SELECT Val FROM SysVersion WHERE Id = ?"; var DropDataVersionSql = "DROP TABLE IF EXISTS SysVersion"; var CreateDataVersionSql = "CREATE TABLE IF NOT EXISTS SysVersion (Id INTEGER, Val TEXT);"; var DeleteSysVersionEntrySql = "DELETE FROM SysVersion WHERE Id = ?"; var InsertSysVersionEntrySql = "INSERT INTO SysVersion (Id, Val) VALUES (?,?)"; /* VersionVal = "1.0" */ var CreateDataTableCompanySql = "CREATE TABLE IF NOT EXISTS Company (AndroidId INTEGER NOT NULL PRIMARY KEY,Id INTEGER, CompanyName TEXT);"; var CreateDataTableCompanyAddressSql = "CREATE TABLE IF NOT EXISTS CompanyAddress (AndroidId INTEGER NOT NULL PRIMARY KEY,Id INTEGER, Address TEXT, PostalCode TEXT, AddressType TEXT, CompanyId INTEGER);"; var CreateDataTableCompanyEmailSql = "CREATE TABLE IF NOT EXISTS CompanyEmail (AndroidId INTEGER NOT NULL PRIMARY KEY,Id INTEGER, Email TEXT, CompanyId INTEGER, Name TEXT);"; var CreateDataTableCompanyContactNumberSql = "CREATE TABLE IF NOT EXISTS CompanyContactNumber "+ "(AndroidId INTEGER NOT NULL PRIMARY KEY,Id INTEGER, ContactNumber TEXT, CompanyId INTEGER, ContactName TEXT);"; var CreateDataTableContactSql = "CREATE TABLE IF NOT EXISTS Contact (Id INTEGER, FirstName TEXT, MiddleName TEXT, LastName TEXT, OfficeNumber TEXT, Email TEXT, MobileNumber TEXT, CompanyId INTEGER);"; var CreateDataTableHelpdeskCaseSql = "CREATE TABLE IF NOT EXISTS HelpdeskCase (DeviceId TEXT, CaseId INTEGER NOT NULL PRIMARY KEY, " + "ContactId INTEGER, CaseOpenDate TEXT, CaseCloseDate TEXT, CaseNumber TEXT, EngineerUserId INTEGER, "+ "IssueDetail TEXT, LastModifiedDate TEXT, Status INTEGER);"; var CreateDataTableUserAccountSql = "CREATE TABLE IF NOT EXISTS UserAccount (UserId INTEGER, FirstName TEXT, MiddleName TEXT, LastName TEXT);"; var CreateDataTableHelpdeskCaseResolutionSql = "CREATE TABLE IF NOT EXISTS HelpdeskCaseResolution (ResolutionId INTEGER NOT NULL PRIMARY KEY, " + "DeviceId INTEGER, CaseId INTEGER, Notes TEXT, NotesType INTEGER, ResolutionDate TEXT, UserId INTEGER, LastModifiedDate TEXT)"; var DropDataTableCompanySql = "DROP TABLE IF EXISTS Company"; var DropDataTableCompanyAddressSql = "DROP TABLE IF EXISTS CompanyAddress"; var DropDataTableCompanyEmailSql = "DROP TABLE IF EXISTS CompanyEmail"; var DropDataTableCompanyContactNumberSql = "DROP TABLE IF EXISTS CompanyContactNumber"; var DropDataTableContactSql = "DROP TABLE IF EXISTS Contact"; var DropDataTableHelpdeskCaseSql = "DROP TABLE IF EXISTS HelpdeskCase"; var DropDataTableUserAccountSql = "DROP TABLE IF EXISTS UserAccount"; var DropDataTableHelpdeskCaseResolutionSql = "DROP TABLE IF EXISTS HelpdeskCaseResolution"; /* VersionVal = "1.1" */ var UpdateSysVersionEntrySql = "UPDATE SysVersion SET Val=? WHERE Id=?;"; var AlterDataTableCompanyDeletedSql="ALTER TABLE Company ADD Deleted Text;"; var AlterDataTableCompanyOperateDateSql="ALTER TABLE Company ADD OperateDate Text;"; var AlterDataTableCompanyAddressDeletedSql= "ALTER TABLE CompanyAddress ADD Deleted Text;"; var AlterDataTableCompanyAddressOperateDateSql= "ALTER TABLE CompanyAddress ADD OperateDate Text;"; var AlterDataTableCompanyEmailDeletedSql ="ALTER TABLE CompanyEmail ADD Deleted Text;"; var AlterDataTableCompanyEmailOperateDateSql ="ALTER TABLE CompanyEmail ADD OperateDate Text;"; var AlterDataTableCompanyContactNumberDeletedSql= "ALTER TABLE CompanyContactNumber ADD Deleted Text;"; var AlterDataTableCompanyContactNumberOperateDateSql= "ALTER TABLE CompanyContactNumber ADD OperateDate Text;"; var AlterDataTableHelpdeskCaseDeletedSql = "ALTER TABLE HelpdeskCase ADD Deleted Text;"; var AlterDataTableHelpdeskCaseOperateDateSql = "ALTER TABLE HelpdeskCase ADD OperateDate Text;"; var AlterDataTableUserAccountDeletedSql = "ALTER TABLE UserAccount ADD Deleted Text;"; var AlterDataTableUserAccountOperateDateSql = "ALTER TABLE UserAccount ADD OperateDate Text;"; var AlterDataTableHelpdeskCaseResolutionDeletedSql="ALTER TABLE HelpdeskCaseResolution ADD Deleted Text;"; var AlterDataTableHelpdeskCaseResolutionOperateDateSql="ALTER TABLE HelpdeskCaseResolution ADD OperateDate Text;"; var AlterDataTableHelpdeskCaseContactCaseIdSql="ALTER TABLE HelpdeskCase ADD ContactCaseId Text;"; var AlterDataTableCompanyRelationshipSql="Alter table Company add Relationship integer"; var AlterDataTableCompanyIndustrySql="Alter table Company add Industry integer"; var AlterDataTableCompanyStatusSql="Alter table Company add Status integer"; var AlterDataTableCompanyAccountManagerSql="Alter table Company add AccountManager integer"; var AlterDataTableCompanySourceSql="Alter table Company add Source integer"; var AlterDataTableEmployeeSql="Alter table Company add Employee integer"; var AlterDataTableWebsiteSql="Alter table Company add Website Text"; var AlterDataTableCompanyAndroidCompanyId="Alter table Company add AndroidCompanyId Text"; var AlterDataTableCompanyAddressAndroidCompanyId="Alter table CompanyAddress add AndroidCompanyId Text"; var AlterDataTableCompanyEmailAndroidCompanyId="Alter table CompanyEmail add AndroidCompanyId Text"; var AlterDataTableCompanyContactNumberAndroidCompanyId="Alter table CompanyContactNumber add AndroidCompanyId Text"; var AlterDataTableCompanyAddressCity="Alter table CompanyAddress add City Text"; var AlterDataTableCompanyAddressCountry="Alter table CompanyAddress add Country Text"; var CreateDataTableNewContactSql = "CREATE TABLE IF NOT EXISTS Contact (AndroidId INTEGER NOT NULL PRIMARY KEY,Id INTEGER, FirstName TEXT, MiddleName TEXT, "+ "LastName TEXT,Designation TEXT,Classification TEXT,AccountManager INTEGER, OfficeNumber TEXT,FaxNumber TEXT,"+ "Email TEXT,Notes TEXT,Salutation INTEGER,Gender INTEGER,Department TEXT,Section TEXT,CompanyId INTEGER, "+ "MobileNumber TEXT,HomeNumber TEXT,AlternateEmail TEXT,Deleted Text,OperateDate Text,ContactCaseId Text,AndroidCompanyId Text);"; var CreateDataTableClassificationSql="Create Table if not exists Classification(Id integer,Name Text,Deleted Text,OperateDate Text);"; var CreateDataTableUpdatePropertySql="Create Table If not exists UpdateProperty(Id integer,AndroidUUID Text,LastUpdateTime Text);"; var CreateDataTableEmployeeSql="Create table if not exists Employee(Id integer ,Name Text)"; var CreateDataTableRelationshipSql = " Create Table if not exists Relationship(Id integer,Name Text)"; var CreateDataTableSourceSql = " Create Table if not exists Source(Id integer,Name Text)"; var CreateDataTableIndustrySql = " Create Table if not exists Industry(Id integer,Name Text)"; var DropDataTableClassificationSql="Drop table if exists Classification"; var InsertDataTableUpdatePropertySql="Insert into UpdateProperty(Id,AndroidUUID) values (?,?);"; var DBDefer; var DBVersion = null; var DBHandle = null; function InitializeDatabase () { DBDefer = $.Deferred(); var dbBase = GetDatabase(); dbBase.transaction(CheckDataVersionTableExistsQuery, DetermineDataVersionError); return DBDefer.promise(); } function CheckDataVersionTableExistsQuery (tx,results) { tx.executeSql(CheckDataVersionTableExistsSql, [], CheckDataVersionTableExistsSuccess, DetermineDataVersionError); } function CheckDataVersionTableExistsSuccess (tx, results) { if (results.rows.length <= 0){ DBVersion = null; DBDefer.reject(); return; } var tablecount = results.rows.item(0).cnt; if (tablecount > 0){ // table exists CheckDataVersionQuery(); } else{ // table don't exist CreateDatabase (); CheckDataVersionQuery(); } } function CheckDataVersionQuery () { var db = GetDatabase(); db.transaction(function (tx) { tx.executeSql (GetSysVersionEntrySql, [VersionId], function (tx, results) { if (results.rows.length <= 0){ DBVersion = null; DBDefer.reject(); return; } DBVersion = results.rows.item(0).Val; ExecuteVersionFun(DBVersion); DBDefer.resolve(); }, DetermineDataVersionError) ; }); } function ExecuteVersionFun(version, innerDef) { var IntVersion = 9; if (null != version && null != innerDef) { IntVersion = version; }else if(null != version){ if (!isNaN(version)) { IntVersion = parseInt(parseFloat(version) * 10 + 1); } } if (IntVersion > 9) { eval("VersionFunction_" + IntVersion + "();"); } var IntCurrentVersion = parseInt(parseFloat(CurrentVersion) * 10); if (IntVersion < IntCurrentVersion) { IntVersion = IntVersion + 1; ExecuteVersionFun(IntVersion, true); } } /*VersionVal = "1.1"*/ function VersionFunction_11() { var db = GetDatabase(); db.transaction(function (tx) { // update current version tx.executeSql(UpdateSysVersionEntrySql,["1.1",VersionId]); // Alter company tables tx.executeSql(AlterDataTableCompanyDeletedSql); tx.executeSql(AlterDataTableCompanyAddressDeletedSql); tx.executeSql(AlterDataTableCompanyContactNumberDeletedSql); tx.executeSql(AlterDataTableCompanyEmailDeletedSql); tx.executeSql(AlterDataTableCompanyOperateDateSql); tx.executeSql(AlterDataTableCompanyAddressOperateDateSql); tx.executeSql(AlterDataTableCompanyContactNumberOperateDateSql); tx.executeSql(AlterDataTableCompanyEmailOperateDateSql); tx.executeSql(AlterDataTableCompanyRelationshipSql); tx.executeSql(AlterDataTableCompanyIndustrySql); tx.executeSql(AlterDataTableCompanyStatusSql); tx.executeSql(AlterDataTableCompanyAccountManagerSql); tx.executeSql(AlterDataTableCompanySourceSql); tx.executeSql(AlterDataTableEmployeeSql); tx.executeSql(AlterDataTableWebsiteSql); tx.executeSql(AlterDataTableCompanyAndroidCompanyId); tx.executeSql(AlterDataTableCompanyAddressAndroidCompanyId); tx.executeSql(AlterDataTableCompanyEmailAndroidCompanyId); tx.executeSql(AlterDataTableCompanyContactNumberAndroidCompanyId); tx.executeSql(AlterDataTableCompanyAddressCity); tx.executeSql(AlterDataTableCompanyAddressCountry); // New contact table tx.executeSql(DropDataTableContactSql); tx.executeSql(CreateDataTableNewContactSql); // Alter user account table tx.executeSql(AlterDataTableUserAccountDeletedSql); tx.executeSql(AlterDataTableUserAccountOperateDateSql); // Alter helpdeskcase table tx.executeSql(AlterDataTableHelpdeskCaseDeletedSql); tx.executeSql(AlterDataTableHelpdeskCaseOperateDateSql); tx.executeSql(AlterDataTableHelpdeskCaseContactCaseIdSql); // Alter helpdesk resolution table tx.executeSql(AlterDataTableHelpdeskCaseResolutionDeletedSql); tx.executeSql(AlterDataTableHelpdeskCaseResolutionOperateDateSql); //create Classification table tx.executeSql(CreateDataTableClassificationSql); //create UpdateTime table var uuid=device.uuid; tx.executeSql(CreateDataTableUpdatePropertySql); tx.executeSql(InsertDataTableUpdatePropertySql,["1",uuid]); //create table Employee tx.executeSql(CreateDataTableEmployeeSql); //Create table Relationship tx.executeSql(CreateDataTableRelationshipSql); //Create table Source tx.executeSql(CreateDataTableSourceSql); //Create table Industry tx.executeSql(CreateDataTableIndustrySql); },DetermineDataVersionError); } function VersionFunction_12() { } function VersionFunction_13() { } function GetSysVersion (id) { DBDefer = $.Deferred(); var db = GetDatabase(); db.transaction(function (tx) { tx.executeSql(GetSysVersionEntrySql, [id], function (tx, result) { if (result.rows.length > 0) DBDefer.resolve (result.rows.item(0).Val); else DBDefer.resolve (null); }, DetermineDataVersionError); }, DetermineDataVersionError); return DBDefer.promise(); } function InsertSysVersion (id, val) { DBDefer = $.Deferred(); var db = GetDatabase(); db.transaction(function (tx) { tx.executeSql(InsertSysVersionEntrySql, [id, val], function (tx, result) { DBDefer.resolve(true); },DetermineDataVersionError); }, DetermineDataVersionError); return DBDefer.promise(); } function DeleteSysVersion (id) { DBDefer = $.Deferred(); var db = GetDatabase(); db.transaction(function (tx) { tx.executeSql(DeleteSysVersionEntrySql, [id], function (tx, result) { DBDefer.resolve(true); },DetermineDataVersionError); }, DetermineDataVersionError); return DBDefer.promise(); } function DetermineDataVersionError (tx, err) { alert (tx.message); DBVersion = null; DBDefer.reject(); } function GetDatabase () { if (DBHandle != null) return DBHandle; DBHandle = window.openDatabase("HelpDeskDB", "1.0", "HelpDeskDB", 5000000); return DBHandle; } function CreateDatabase () { var defer=$.Deferred(); var db = GetDatabase(); db.transaction(function (tx) { tx.executeSql(DropDataVersionSql); tx.executeSql(CreateDataVersionSql); // insert current version tx.executeSql(InsertSysVersionEntrySql,[VersionId, "1.0"]); // create company tables tx.executeSql(CreateDataTableCompanySql); tx.executeSql(CreateDataTableCompanyAddressSql); tx.executeSql(CreateDataTableCompanyContactNumberSql); tx.executeSql(CreateDataTableCompanyEmailSql); // create contact table tx.executeSql(CreateDataTableContactSql); // create helpdesk case table tx.executeSql(CreateDataTableHelpdeskCaseSql); // create user account table tx.executeSql(CreateDataTableUserAccountSql); // create helpdesk resolution table tx.executeSql(CreateDataTableHelpdeskCaseResolutionSql); //alert('Running in Test Mode. Data will be reinitialized.'); DBDefer.resolve(); defer.resolve(true); }, DetermineDataVersionError); return defer.promise(); } function DBEmptyHandler (tx, results) { return; } function InsertDummyData () { var dummy1 = { "Id" : "1", "CompanyName" : "Company 1", "Address" : [{ "Id" : "1", "Address" : "This is a test address", "PostalCode" : "123456", "AddressType" : "SampleAddress", "CompanyId" : "1" }, { "Id" : "2", "Address" : "This is a test address 2", "PostalCode" : "123450", "AddressType" : "SampleAddress 2", "CompanyId" : "1" }], "Email" : [{ "Id" : "1", "Email" : "test@company1.com", "CompanyId" : "1", "Name" : "Main Email" }, { "Id" : "2", "Email" : "test2@company1.com", "CompanyId" : "1", "Name" : "Main Email2" } ], "ContactNumber" : [{ "Id" : "1", "ContactNumber" : "01234567", "CompanyId" : "1", "ContactName" : "Tel" }, { "Id" : "2", "ContactNumber" : "01234560", "CompanyId" : "1", "ContactName" : "Tel2" } ] }; var dummy2 = { "Id" : "2", "CompanyName" : "Company 2", "Address" : [{ "Id" : "10", "Address" : "This is a test address", "PostalCode" : "222222", "AddressType" : "SampleAddress", "CompanyId" : "2" }], "Email" : [{ "Id" : "10", "Email" : "test@company2.com", "CompanyId" : "2", "Name" : "Main Email" }], "ContactNumber" : [{ "Id" : "10", "ContactNumber" : "01234567", "CompanyId" : "2", "ContactName" : "Tel" }] }; var contact1 = { "Id" : "1", "FirstName" : "Person", "MiddleName" : "", "LastName" : "1", "OfficeNumber" : "6123456", "Email" : "contact1@test.com", "MobileNumber" : "91234567", "CompanyId" : "1" }; var contact2 = { "Id" : "2", "FirstName" : "Person", "MiddleName" : "", "LastName" : "2", "OfficeNumber" : "6123450", "Email" : "contact2@test.com", "MobileNumber" : "91234560", "CompanyId" : "1" }; var contact3 = { "Id" : "3", "FirstName" : "Person", "MiddleName" : "", "LastName" : "3", "OfficeNumber" : "6123400", "Email" : "contact3@test.com", "MobileNumber" : "91234500", "CompanyId" : "2" }; var case1 = { DeviceId : DeviceId, "ContactId" : "1", "CaseOpenDate" : "2000-01-01 09:00:00", "CaseCloseDate" : "", "CaseNumber" : "C30000001", "Status" : "0", "EngineerUserId" : "1", "IssueDetail" : "this is a sample issue", "LastModifiedDate" : "2000-01-02 10:00:00" }; } function DropTables () { var db = GetDatabase(); db.transaction (function (tx) { tx.executeSql(DropDataVersionSql); tx.executeSql(DropDataTableCompanySql); tx.executeSql(DropDataTableCompanyAddressSql); tx.executeSql(DropDataTableCompanyContactNumberSql); tx.executeSql(DropDataTableCompanyEmailSql); tx.executeSql(DropDataTableContactSql); tx.executeSql(DropDataTableHelpdeskCaseSql); tx.executeSql(DropDataTableUserAccountSql); tx.executeSql(DropDataTableHelpdeskCaseResolutionSql); //tx.executeSql(DropDataTableClassification); }); }
JavaScript
(function() { var SQLiteFactory, SQLitePlugin, SQLitePluginCallback, SQLitePluginTransaction, SQLitePluginTransactionCB, get_unique_id, pcb, root, transaction_callback_queue, transaction_queue; root = this; SQLitePlugin = function(openargs, openSuccess, openError) { var dbname; console.log("SQLitePlugin"); if (!(openargs && openargs['name'])) { throw new Error("Cannot create a SQLitePlugin instance without a db name"); } dbname = openargs.name; this.openargs = openargs; this.dbname = dbname; this.openSuccess = openSuccess; this.openError = openError; this.openSuccess || (this.openSuccess = function() { return console.log("DB opened: " + dbname); }); this.openError || (this.openError = function(e) { return console.log(e.message); }); this.open(this.openSuccess, this.openError); }; SQLitePlugin.prototype.openDBs = {}; SQLitePlugin.prototype.transaction = function(fn, error, success) { var t; t = new SQLitePluginTransaction(this.dbname); fn(t); t.complete(success, error); }; SQLitePlugin.prototype.open = function(success, error) { console.log("SQLitePlugin.prototype.open"); if (!(this.dbname in this.openDBs)) { this.openDBs[this.dbname] = true; cordova.exec(success, error, "SQLitePlugin", "open", [this.openargs]); } }; SQLitePlugin.prototype.close = function(success, error) { console.log("SQLitePlugin.prototype.close"); if (this.dbname in this.openDBs) { delete this.openDBs[this.dbname]; cordova.exec(null, null, "SQLitePlugin", "close", [this.dbname]); } }; pcb = function() { return 1; }; SQLitePlugin.prototype.executePragmaStatement = function(statement, success, error) { console.log("SQLitePlugin::executePragmaStatement"); pcb = success; cordova.exec((function() { return 1; }), error, "SQLitePlugin", "executePragmaStatement", [this.dbname, statement]); }; SQLitePluginCallback = { p1: function(id, result) { var mycb; console.log("PRAGMA CB"); mycb = pcb; pcb = function() { return 1; }; mycb(result); } }; get_unique_id = function() { var id, id2; id = new Date().getTime(); id2 = new Date().getTime(); while (id === id2) { id2 = new Date().getTime(); } return id2 + "000"; }; transaction_queue = []; transaction_callback_queue = {}; SQLitePluginTransaction = function(dbname) { this.dbname = dbname; this.executes = []; this.trans_id = get_unique_id(); this.__completed = false; this.__submitted = false; this.optimization_no_nested_callbacks = false; console.log("SQLitePluginTransaction - this.trans_id:" + this.trans_id); transaction_queue[this.trans_id] = []; transaction_callback_queue[this.trans_id] = new Object(); }; SQLitePluginTransactionCB = {}; SQLitePluginTransactionCB.queryCompleteCallback = function(transId, queryId, result) { var query, x; console.log("SQLitePluginTransaction.queryCompleteCallback"); query = null; for (x in transaction_queue[transId]) { if (transaction_queue[transId][x]["query_id"] === queryId) { query = transaction_queue[transId][x]; if (transaction_queue[transId].length === 1) { transaction_queue[transId] = []; } else { transaction_queue[transId].splice(x, 1); } break; } } if (query && query["callback"]) return query["callback"](result); }; SQLitePluginTransactionCB.queryErrorCallback = function(transId, queryId, result) { var query, x; query = null; for (x in transaction_queue[transId]) { if (transaction_queue[transId][x]["query_id"] === queryId) { query = transaction_queue[transId][x]; if (transaction_queue[transId].length === 1) { transaction_queue[transId] = []; } else { transaction_queue[transId].splice(x, 1); } break; } } if (query && query["err_callback"]) return query["err_callback"](result); }; SQLitePluginTransactionCB.txCompleteCallback = function(transId) { if (typeof transId !== "undefined") { if (transId && transaction_callback_queue[transId] && transaction_callback_queue[transId]["success"]) { return transaction_callback_queue[transId]["success"](); } } else { return console.log("SQLitePluginTransaction.txCompleteCallback---transId = NULL"); } }; SQLitePluginTransactionCB.txErrorCallback = function(transId, error) { if (typeof transId !== "undefined") { console.log("SQLitePluginTransaction.txErrorCallback---transId:" + transId); if (transId && transaction_callback_queue[transId]["error"]) { transaction_callback_queue[transId]["error"](error); } delete transaction_queue[transId]; return delete transaction_callback_queue[transId]; } else { return console.log("SQLitePluginTransaction.txErrorCallback---transId = NULL"); } }; SQLitePluginTransaction.prototype.add_to_transaction = function(trans_id, query, params, callback, err_callback) { var new_query; new_query = new Object(); new_query["trans_id"] = trans_id; if (callback || !this.optimization_no_nested_callbacks) { new_query["query_id"] = get_unique_id(); } else { if (this.optimization_no_nested_callbacks) new_query["query_id"] = ""; } new_query["query"] = query; if (params) { new_query["params"] = params; } else { new_query["params"] = []; } new_query["callback"] = callback; new_query["err_callback"] = err_callback; if (!transaction_queue[trans_id]) transaction_queue[trans_id] = []; transaction_queue[trans_id].push(new_query); }; SQLitePluginTransaction.prototype.executeSql = function(sql, values, success, error) { var errorcb, successcb, txself; console.log("SQLitePluginTransaction.prototype.executeSql"); errorcb = void 0; successcb = void 0; txself = void 0; txself = this; successcb = null; if (success) { console.log("success not null:" + sql); successcb = function(execres) { var res, saveres; console.log("executeSql callback:" + JSON.stringify(execres)); res = void 0; saveres = void 0; saveres = execres; res = { rows: { item: function(i) { return saveres[i]; }, length: saveres.length }, rowsAffected: saveres.rowsAffected, insertId: saveres.insertId || null }; return success(txself, res); }; } else { console.log("success NULL:" + sql); } errorcb = null; if (error) { errorcb = function(res) { return error(txself, res); }; } console.log("executeSql - add_to_transaction" + sql); this.add_to_transaction(this.trans_id, sql, values, successcb, errorcb); }; SQLitePluginTransaction.prototype.complete = function(success, error) { var errorcb, successcb, txself; console.log("SQLitePluginTransaction.prototype.complete"); if (this.__completed) throw new Error("Transaction already run"); if (this.__submitted) throw new Error("Transaction already submitted"); this.__submitted = true; txself = this; successcb = function() { if (transaction_queue[txself.trans_id].length > 0 && !txself.optimization_no_nested_callbacks) { txself.__submitted = false; return txself.complete(success, error); } else { this.__completed = true; if (success) return success(txself); } }; errorcb = function(res) { return null; }; if (error) { errorcb = function(res) { return error(txself, res); }; } transaction_callback_queue[this.trans_id]["success"] = successcb; transaction_callback_queue[this.trans_id]["error"] = errorcb; cordova.exec(null, null, "SQLitePlugin", "executeSqlBatch", [this.dbname, transaction_queue[this.trans_id]]); }; SQLiteFactory = { opendb: function() { var errorcb, first, okcb, openargs; if (arguments.length < 1) return null; first = arguments[0]; openargs = null; okcb = null; errorcb = null; if (first.constructor === String) { openargs = { name: first }; if (arguments.length >= 5) { okcb = arguments[4]; if (arguments.length > 5) errorcb = arguments[5]; } } else { openargs = first; if (arguments.length >= 2) { okcb = arguments[1]; if (arguments.length > 2) errorcb = arguments[2]; } } return new SQLitePlugin(openargs, okcb, errorcb); } }; root.SQLitePluginCallback = SQLitePluginCallback; root.SQLitePluginTransactionCB = SQLitePluginTransactionCB; return root.sqlitePlugin = { openDatabase: SQLiteFactory.opendb }; })();
JavaScript
/*! * jQuery Mobile 1.4.2 * Git HEAD hash: 9d9a42a27d0c693e8b5569c3a10d771916af5045 <> Date: Fri Feb 28 2014 17:32:01 UTC * http://jquerymobile.com * * Copyright 2010, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license. * http://jquery.org/license * */ (function ( root, doc, factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], function ( $ ) { factory( $, root, doc ); return $.mobile; }); } else { // Browser globals factory( root.jQuery, root, doc ); } }( this, document, function ( jQuery, window, document, undefined ) { (function( $ ) { $.mobile = {}; }( jQuery )); (function( $, window, undefined ) { $.extend( $.mobile, { // Version of the jQuery Mobile Framework version: "1.4.2", // Deprecated and no longer used in 1.4 remove in 1.5 // Define the url parameter used for referencing widget-generated sub-pages. // Translates to example.html&ui-page=subpageIdentifier // hash segment before &ui-page= is used to make Ajax request subPageUrlKey: "ui-page", hideUrlBar: true, // Keepnative Selector keepNative: ":jqmData(role='none'), :jqmData(role='nojs')", // Deprecated in 1.4 remove in 1.5 // Class assigned to page currently in view, and during transitions activePageClass: "ui-page-active", // Deprecated in 1.4 remove in 1.5 // Class used for "active" button state, from CSS framework activeBtnClass: "ui-btn-active", // Deprecated in 1.4 remove in 1.5 // Class used for "focus" form element state, from CSS framework focusClass: "ui-focus", // Automatically handle clicks and form submissions through Ajax, when same-domain ajaxEnabled: true, // Automatically load and show pages based on location.hash hashListeningEnabled: true, // disable to prevent jquery from bothering with links linkBindingEnabled: true, // Set default page transition - 'none' for no transitions defaultPageTransition: "fade", // Set maximum window width for transitions to apply - 'false' for no limit maxTransitionWidth: false, // Minimum scroll distance that will be remembered when returning to a page // Deprecated remove in 1.5 minScrollBack: 0, // Set default dialog transition - 'none' for no transitions defaultDialogTransition: "pop", // Error response message - appears when an Ajax page request fails pageLoadErrorMessage: "Error Loading Page", // For error messages, which theme does the box uses? pageLoadErrorMessageTheme: "a", // replace calls to window.history.back with phonegaps navigation helper // where it is provided on the window object phonegapNavigationEnabled: false, //automatically initialize the DOM when it's ready autoInitializePage: true, pushStateEnabled: true, // allows users to opt in to ignoring content by marking a parent element as // data-ignored ignoreContentEnabled: false, buttonMarkup: { hoverDelay: 200 }, // disable the alteration of the dynamic base tag or links in the case // that a dynamic base tag isn't supported dynamicBaseEnabled: true, // default the property to remove dependency on assignment in init module pageContainer: $(), //enable cross-domain page support allowCrossDomainPages: false, dialogHashKey: "&ui-state=dialog" }); })( jQuery, this ); (function( $, window, undefined ) { var nsNormalizeDict = {}, oldFind = $.find, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, jqmDataRE = /:jqmData\(([^)]*)\)/g; $.extend( $.mobile, { // Namespace used framework-wide for data-attrs. Default is no namespace ns: "", // Retrieve an attribute from an element and perform some massaging of the value getAttribute: function( element, key ) { var data; element = element.jquery ? element[0] : element; if ( element && element.getAttribute ) { data = element.getAttribute( "data-" + $.mobile.ns + key ); } // Copied from core's src/data.js:dataAttr() // Convert from a string to a proper data type try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( err ) {} return data; }, // Expose our cache for testing purposes. nsNormalizeDict: nsNormalizeDict, // Take a data attribute property, prepend the namespace // and then camel case the attribute string. Add the result // to our nsNormalizeDict so we don't have to do this again. nsNormalize: function( prop ) { return nsNormalizeDict[ prop ] || ( nsNormalizeDict[ prop ] = $.camelCase( $.mobile.ns + prop ) ); }, // Find the closest javascript page element to gather settings data jsperf test // http://jsperf.com/single-complex-selector-vs-many-complex-selectors/edit // possibly naive, but it shows that the parsing overhead for *just* the page selector vs // the page and dialog selector is negligable. This could probably be speed up by // doing a similar parent node traversal to the one found in the inherited theme code above closestPageData: function( $target ) { return $target .closest( ":jqmData(role='page'), :jqmData(role='dialog')" ) .data( "mobile-page" ); } }); // Mobile version of data and removeData and hasData methods // ensures all data is set and retrieved using jQuery Mobile's data namespace $.fn.jqmData = function( prop, value ) { var result; if ( typeof prop !== "undefined" ) { if ( prop ) { prop = $.mobile.nsNormalize( prop ); } // undefined is permitted as an explicit input for the second param // in this case it returns the value and does not set it to undefined if ( arguments.length < 2 || value === undefined ) { result = this.data( prop ); } else { result = this.data( prop, value ); } } return result; }; $.jqmData = function( elem, prop, value ) { var result; if ( typeof prop !== "undefined" ) { result = $.data( elem, prop ? $.mobile.nsNormalize( prop ) : prop, value ); } return result; }; $.fn.jqmRemoveData = function( prop ) { return this.removeData( $.mobile.nsNormalize( prop ) ); }; $.jqmRemoveData = function( elem, prop ) { return $.removeData( elem, $.mobile.nsNormalize( prop ) ); }; $.find = function( selector, context, ret, extra ) { if ( selector.indexOf( ":jqmData" ) > -1 ) { selector = selector.replace( jqmDataRE, "[data-" + ( $.mobile.ns || "" ) + "$1]" ); } return oldFind.call( this, selector, context, ret, extra ); }; $.extend( $.find, oldFind ); })( jQuery, this ); /*! * jQuery UI Core c0ab71056b936627e8a7821f03c044aec6280a40 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/category/ui-core/ */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "c0ab71056b936627e8a7821f03c044aec6280a40", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); }).eq(0); } return ( /fixed/ ).test( this.css( "position") ) || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.support.selectstart = "onselectstart" in document.createElement( "div" ); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; })( jQuery ); (function( $, window, undefined ) { // Subtract the height of external toolbars from the page height, if the page does not have // internal toolbars of the same type var compensateToolbars = function( page, desiredHeight ) { var pageParent = page.parent(), toolbarsAffectingHeight = [], externalHeaders = pageParent.children( ":jqmData(role='header')" ), internalHeaders = page.children( ":jqmData(role='header')" ), externalFooters = pageParent.children( ":jqmData(role='footer')" ), internalFooters = page.children( ":jqmData(role='footer')" ); // If we have no internal headers, but we do have external headers, then their height // reduces the page height if ( internalHeaders.length === 0 && externalHeaders.length > 0 ) { toolbarsAffectingHeight = toolbarsAffectingHeight.concat( externalHeaders.toArray() ); } // If we have no internal footers, but we do have external footers, then their height // reduces the page height if ( internalFooters.length === 0 && externalFooters.length > 0 ) { toolbarsAffectingHeight = toolbarsAffectingHeight.concat( externalFooters.toArray() ); } $.each( toolbarsAffectingHeight, function( index, value ) { desiredHeight -= $( value ).outerHeight(); }); // Height must be at least zero return Math.max( 0, desiredHeight ); }; $.extend( $.mobile, { // define the window and the document objects window: $( window ), document: $( document ), // TODO: Remove and use $.ui.keyCode directly keyCode: $.ui.keyCode, // Place to store various widget extensions behaviors: {}, // Scroll page vertically: scroll to 0 to hide iOS address bar, or pass a Y value silentScroll: function( ypos ) { if ( $.type( ypos ) !== "number" ) { ypos = $.mobile.defaultHomeScroll; } // prevent scrollstart and scrollstop events $.event.special.scrollstart.enabled = false; setTimeout(function() { window.scrollTo( 0, ypos ); $.mobile.document.trigger( "silentscroll", { x: 0, y: ypos }); }, 20 ); setTimeout(function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, getClosestBaseUrl: function( ele ) { // Find the closest page and extract out its url. var url = $( ele ).closest( ".ui-page" ).jqmData( "url" ), base = $.mobile.path.documentBase.hrefNoHash; if ( !$.mobile.dynamicBaseEnabled || !url || !$.mobile.path.isPath( url ) ) { url = base; } return $.mobile.path.makeUrlAbsolute( url, base ); }, removeActiveLinkClass: function( forceRemoval ) { if ( !!$.mobile.activeClickedLink && ( !$.mobile.activeClickedLink.closest( "." + $.mobile.activePageClass ).length || forceRemoval ) ) { $.mobile.activeClickedLink.removeClass( $.mobile.activeBtnClass ); } $.mobile.activeClickedLink = null; }, // DEPRECATED in 1.4 // Find the closest parent with a theme class on it. Note that // we are not using $.fn.closest() on purpose here because this // method gets called quite a bit and we need it to be as fast // as possible. getInheritedTheme: function( el, defaultTheme ) { var e = el[ 0 ], ltr = "", re = /ui-(bar|body|overlay)-([a-z])\b/, c, m; while ( e ) { c = e.className || ""; if ( c && ( m = re.exec( c ) ) && ( ltr = m[ 2 ] ) ) { // We found a parent with a theme class // on it so bail from this loop. break; } e = e.parentNode; } // Return the theme letter we found, if none, return the // specified default. return ltr || defaultTheme || "a"; }, enhanceable: function( elements ) { return this.haveParents( elements, "enhance" ); }, hijackable: function( elements ) { return this.haveParents( elements, "ajax" ); }, haveParents: function( elements, attr ) { if ( !$.mobile.ignoreContentEnabled ) { return elements; } var count = elements.length, $newSet = $(), e, $element, excluded, i, c; for ( i = 0; i < count; i++ ) { $element = elements.eq( i ); excluded = false; e = elements[ i ]; while ( e ) { c = e.getAttribute ? e.getAttribute( "data-" + $.mobile.ns + attr ) : ""; if ( c === "false" ) { excluded = true; break; } e = e.parentNode; } if ( !excluded ) { $newSet = $newSet.add( $element ); } } return $newSet; }, getScreenHeight: function() { // Native innerHeight returns more accurate value for this across platforms, // jQuery version is here as a normalized fallback for platforms like Symbian return window.innerHeight || $.mobile.window.height(); }, //simply set the active page's minimum height to screen height, depending on orientation resetActivePageHeight: function( height ) { var page = $( "." + $.mobile.activePageClass ), pageHeight = page.height(), pageOuterHeight = page.outerHeight( true ); height = compensateToolbars( page, ( typeof height === "number" ) ? height : $.mobile.getScreenHeight() ); page.css( "min-height", height - ( pageOuterHeight - pageHeight ) ); }, loading: function() { // If this is the first call to this function, instantiate a loader widget var loader = this.loading._widget || $( $.mobile.loader.prototype.defaultHtml ).loader(), // Call the appropriate method on the loader returnValue = loader.loader.apply( loader, arguments ); // Make sure the loader is retained for future calls to this function. this.loading._widget = loader; return returnValue; } }); $.addDependents = function( elem, newDependents ) { var $elem = $( elem ), dependents = $elem.jqmData( "dependents" ) || $(); $elem.jqmData( "dependents", $( dependents ).add( newDependents ) ); }; // plugins $.fn.extend({ removeWithDependents: function() { $.removeWithDependents( this ); }, // Enhance child elements enhanceWithin: function() { var index, widgetElements = {}, keepNative = $.mobile.page.prototype.keepNativeSelector(), that = this; // Add no js class to elements if ( $.mobile.nojs ) { $.mobile.nojs( this ); } // Bind links for ajax nav if ( $.mobile.links ) { $.mobile.links( this ); } // Degrade inputs for styleing if ( $.mobile.degradeInputsWithin ) { $.mobile.degradeInputsWithin( this ); } // Run buttonmarkup if ( $.fn.buttonMarkup ) { this.find( $.fn.buttonMarkup.initSelector ).not( keepNative ) .jqmEnhanceable().buttonMarkup(); } // Add classes for fieldContain if ( $.fn.fieldcontain ) { this.find( ":jqmData(role='fieldcontain')" ).not( keepNative ) .jqmEnhanceable().fieldcontain(); } // Enhance widgets $.each( $.mobile.widgets, function( name, constructor ) { // If initSelector not false find elements if ( constructor.initSelector ) { // Filter elements that should not be enhanced based on parents var elements = $.mobile.enhanceable( that.find( constructor.initSelector ) ); // If any matching elements remain filter ones with keepNativeSelector if ( elements.length > 0 ) { // $.mobile.page.prototype.keepNativeSelector is deprecated this is just for backcompat // Switch to $.mobile.keepNative in 1.5 which is just a value not a function elements = elements.not( keepNative ); } // Enhance whatever is left if ( elements.length > 0 ) { widgetElements[ constructor.prototype.widgetName ] = elements; } } }); for ( index in widgetElements ) { widgetElements[ index ][ index ](); } return this; }, addDependents: function( newDependents ) { $.addDependents( this, newDependents ); }, // note that this helper doesn't attempt to handle the callback // or setting of an html element's text, its only purpose is // to return the html encoded version of the text in all cases. (thus the name) getEncodedText: function() { return $( "<a>" ).text( this.text() ).html(); }, // fluent helper function for the mobile namespaced equivalent jqmEnhanceable: function() { return $.mobile.enhanceable( this ); }, jqmHijackable: function() { return $.mobile.hijackable( this ); } }); $.removeWithDependents = function( nativeElement ) { var element = $( nativeElement ); ( element.jqmData( "dependents" ) || $() ).remove(); element.remove(); }; $.addDependents = function( nativeElement, newDependents ) { var element = $( nativeElement ), dependents = element.jqmData( "dependents" ) || $(); element.jqmData( "dependents", $( dependents ).add( newDependents ) ); }; $.find.matches = function( expr, set ) { return $.find( expr, null, null, set ); }; $.find.matchesSelector = function( node, expr ) { return $.find( expr, null, null, [ node ] ).length > 0; }; })( jQuery, this ); /*! * jQuery UI Widget c0ab71056b936627e8a7821f03c044aec6280a40 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); })( jQuery ); (function( $, undefined ) { var rcapitals = /[A-Z]/g, replaceFunction = function( c ) { return "-" + c.toLowerCase(); }; $.extend( $.Widget.prototype, { _getCreateOptions: function() { var option, value, elem = this.element[ 0 ], options = {}; // if ( !$.mobile.getAttribute( elem, "defaults" ) ) { for ( option in this.options ) { value = $.mobile.getAttribute( elem, option.replace( rcapitals, replaceFunction ) ); if ( value != null ) { options[ option ] = value; } } } return options; } }); //TODO: Remove in 1.5 for backcompat only $.mobile.widget = $.Widget; })( jQuery ); (function( $ ) { // TODO move loader class down into the widget settings var loaderClass = "ui-loader", $html = $( "html" ); $.widget( "mobile.loader", { // NOTE if the global config settings are defined they will override these // options options: { // the theme for the loading message theme: "a", // whether the text in the loading message is shown textVisible: false, // custom html for the inner content of the loading message html: "", // the text to be displayed when the popup is shown text: "loading" }, defaultHtml: "<div class='" + loaderClass + "'>" + "<span class='ui-icon-loading'></span>" + "<h1></h1>" + "</div>", // For non-fixed supportin browsers. Position at y center (if scrollTop supported), above the activeBtn (if defined), or just 100px from top fakeFixLoader: function() { var activeBtn = $( "." + $.mobile.activeBtnClass ).first(); this.element .css({ top: $.support.scrollTop && this.window.scrollTop() + this.window.height() / 2 || activeBtn.length && activeBtn.offset().top || 100 }); }, // check position of loader to see if it appears to be "fixed" to center // if not, use abs positioning checkLoaderPosition: function() { var offset = this.element.offset(), scrollTop = this.window.scrollTop(), screenHeight = $.mobile.getScreenHeight(); if ( offset.top < scrollTop || ( offset.top - scrollTop ) > screenHeight ) { this.element.addClass( "ui-loader-fakefix" ); this.fakeFixLoader(); this.window .unbind( "scroll", this.checkLoaderPosition ) .bind( "scroll", $.proxy( this.fakeFixLoader, this ) ); } }, resetHtml: function() { this.element.html( $( this.defaultHtml ).html() ); }, // Turn on/off page loading message. Theme doubles as an object argument // with the following shape: { theme: '', text: '', html: '', textVisible: '' } // NOTE that the $.mobile.loading* settings and params past the first are deprecated // TODO sweet jesus we need to break some of this out show: function( theme, msgText, textonly ) { var textVisible, message, loadSettings; this.resetHtml(); // use the prototype options so that people can set them globally at // mobile init. Consistency, it's what's for dinner if ( $.type( theme ) === "object" ) { loadSettings = $.extend( {}, this.options, theme ); theme = loadSettings.theme; } else { loadSettings = this.options; // here we prefer the theme value passed as a string argument, then // we prefer the global option because we can't use undefined default // prototype options, then the prototype option theme = theme || loadSettings.theme; } // set the message text, prefer the param, then the settings object // then loading message message = msgText || ( loadSettings.text === false ? "" : loadSettings.text ); // prepare the dom $html.addClass( "ui-loading" ); textVisible = loadSettings.textVisible; // add the proper css given the options (theme, text, etc) // Force text visibility if the second argument was supplied, or // if the text was explicitly set in the object args this.element.attr("class", loaderClass + " ui-corner-all ui-body-" + theme + " ui-loader-" + ( textVisible || msgText || theme.text ? "verbose" : "default" ) + ( loadSettings.textonly || textonly ? " ui-loader-textonly" : "" ) ); // TODO verify that jquery.fn.html is ok to use in both cases here // this might be overly defensive in preventing unknowing xss // if the html attribute is defined on the loading settings, use that // otherwise use the fallbacks from above if ( loadSettings.html ) { this.element.html( loadSettings.html ); } else { this.element.find( "h1" ).text( message ); } // attach the loader to the DOM this.element.appendTo( $.mobile.pageContainer ); // check that the loader is visible this.checkLoaderPosition(); // on scroll check the loader position this.window.bind( "scroll", $.proxy( this.checkLoaderPosition, this ) ); }, hide: function() { $html.removeClass( "ui-loading" ); if ( this.options.text ) { this.element.removeClass( "ui-loader-fakefix" ); } $.mobile.window.unbind( "scroll", this.fakeFixLoader ); $.mobile.window.unbind( "scroll", this.checkLoaderPosition ); } }); })(jQuery, this); /*! * jQuery hashchange event - v1.3 - 7/21/2010 * http://benalman.com/projects/jquery-hashchange-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ // Script: jQuery hashchange event // // *Version: 1.3, Last updated: 7/21/2010* // // Project Home - http://benalman.com/projects/jquery-hashchange-plugin/ // GitHub - http://github.com/cowboy/jquery-hashchange/ // Source - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.js // (Minified) - http://github.com/cowboy/jquery-hashchange/raw/master/jquery.ba-hashchange.min.js (0.8kb gzipped) // // About: License // // Copyright (c) 2010 "Cowboy" Ben Alman, // Dual licensed under the MIT and GPL licenses. // http://benalman.com/about/license/ // // About: Examples // // These working examples, complete with fully commented code, illustrate a few // ways in which this plugin can be used. // // hashchange event - http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/ // document.domain - http://benalman.com/code/projects/jquery-hashchange/examples/document_domain/ // // About: Support and Testing // // Information about what version or versions of jQuery this plugin has been // tested with, what browsers it has been tested in, and where the unit tests // reside (so you can test it yourself). // // jQuery Versions - 1.2.6, 1.3.2, 1.4.1, 1.4.2 // Browsers Tested - Internet Explorer 6-8, Firefox 2-4, Chrome 5-6, Safari 3.2-5, // Opera 9.6-10.60, iPhone 3.1, Android 1.6-2.2, BlackBerry 4.6-5. // Unit Tests - http://benalman.com/code/projects/jquery-hashchange/unit/ // // About: Known issues // // While this jQuery hashchange event implementation is quite stable and // robust, there are a few unfortunate browser bugs surrounding expected // hashchange event-based behaviors, independent of any JavaScript // window.onhashchange abstraction. See the following examples for more // information: // // Chrome: Back Button - http://benalman.com/code/projects/jquery-hashchange/examples/bug-chrome-back-button/ // Firefox: Remote XMLHttpRequest - http://benalman.com/code/projects/jquery-hashchange/examples/bug-firefox-remote-xhr/ // WebKit: Back Button in an Iframe - http://benalman.com/code/projects/jquery-hashchange/examples/bug-webkit-hash-iframe/ // Safari: Back Button from a different domain - http://benalman.com/code/projects/jquery-hashchange/examples/bug-safari-back-from-diff-domain/ // // Also note that should a browser natively support the window.onhashchange // event, but not report that it does, the fallback polling loop will be used. // // About: Release History // // 1.3 - (7/21/2010) Reorganized IE6/7 Iframe code to make it more // "removable" for mobile-only development. Added IE6/7 document.title // support. Attempted to make Iframe as hidden as possible by using // techniques from http://www.paciellogroup.com/blog/?p=604. Added // support for the "shortcut" format $(window).hashchange( fn ) and // $(window).hashchange() like jQuery provides for built-in events. // Renamed jQuery.hashchangeDelay to <jQuery.fn.hashchange.delay> and // lowered its default value to 50. Added <jQuery.fn.hashchange.domain> // and <jQuery.fn.hashchange.src> properties plus document-domain.html // file to address access denied issues when setting document.domain in // IE6/7. // 1.2 - (2/11/2010) Fixed a bug where coming back to a page using this plugin // from a page on another domain would cause an error in Safari 4. Also, // IE6/7 Iframe is now inserted after the body (this actually works), // which prevents the page from scrolling when the event is first bound. // Event can also now be bound before DOM ready, but it won't be usable // before then in IE6/7. // 1.1 - (1/21/2010) Incorporated document.documentMode test to fix IE8 bug // where browser version is incorrectly reported as 8.0, despite // inclusion of the X-UA-Compatible IE=EmulateIE7 meta tag. // 1.0 - (1/9/2010) Initial Release. Broke out the jQuery BBQ event.special // window.onhashchange functionality into a separate plugin for users // who want just the basic event & back button support, without all the // extra awesomeness that BBQ provides. This plugin will be included as // part of jQuery BBQ, but also be available separately. (function($,window,undefined){ '$:nomunge'; // Used by YUI compressor. // Reused string. var str_hashchange = 'hashchange', // Method / object references. doc = document, fake_onhashchange, special = $.event.special, // Does the browser support window.onhashchange? Note that IE8 running in // IE7 compatibility mode reports true for 'onhashchange' in window, even // though the event isn't supported, so also test document.documentMode. doc_mode = doc.documentMode, supports_onhashchange = 'on' + str_hashchange in window && ( doc_mode === undefined || doc_mode > 7 ); // Get location.hash (or what you'd expect location.hash to be) sans any // leading #. Thanks for making this necessary, Firefox! function get_fragment( url ) { url = url || location.href; return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' ); }; // Method: jQuery.fn.hashchange // // Bind a handler to the window.onhashchange event or trigger all bound // window.onhashchange event handlers. This behavior is consistent with // jQuery's built-in event handlers. // // Usage: // // > jQuery(window).hashchange( [ handler ] ); // // Arguments: // // handler - (Function) Optional handler to be bound to the hashchange // event. This is a "shortcut" for the more verbose form: // jQuery(window).bind( 'hashchange', handler ). If handler is omitted, // all bound window.onhashchange event handlers will be triggered. This // is a shortcut for the more verbose // jQuery(window).trigger( 'hashchange' ). These forms are described in // the <hashchange event> section. // // Returns: // // (jQuery) The initial jQuery collection of elements. // Allow the "shortcut" format $(elem).hashchange( fn ) for binding and // $(elem).hashchange() for triggering, like jQuery does for built-in events. $.fn[ str_hashchange ] = function( fn ) { return fn ? this.bind( str_hashchange, fn ) : this.trigger( str_hashchange ); }; // Property: jQuery.fn.hashchange.delay // // The numeric interval (in milliseconds) at which the <hashchange event> // polling loop executes. Defaults to 50. // Property: jQuery.fn.hashchange.domain // // If you're setting document.domain in your JavaScript, and you want hash // history to work in IE6/7, not only must this property be set, but you must // also set document.domain BEFORE jQuery is loaded into the page. This // property is only applicable if you are supporting IE6/7 (or IE8 operating // in "IE7 compatibility" mode). // // In addition, the <jQuery.fn.hashchange.src> property must be set to the // path of the included "document-domain.html" file, which can be renamed or // modified if necessary (note that the document.domain specified must be the // same in both your main JavaScript as well as in this file). // // Usage: // // jQuery.fn.hashchange.domain = document.domain; // Property: jQuery.fn.hashchange.src // // If, for some reason, you need to specify an Iframe src file (for example, // when setting document.domain as in <jQuery.fn.hashchange.domain>), you can // do so using this property. Note that when using this property, history // won't be recorded in IE6/7 until the Iframe src file loads. This property // is only applicable if you are supporting IE6/7 (or IE8 operating in "IE7 // compatibility" mode). // // Usage: // // jQuery.fn.hashchange.src = 'path/to/file.html'; $.fn[ str_hashchange ].delay = 50; /* $.fn[ str_hashchange ].domain = null; $.fn[ str_hashchange ].src = null; */ // Event: hashchange event // // Fired when location.hash changes. In browsers that support it, the native // HTML5 window.onhashchange event is used, otherwise a polling loop is // initialized, running every <jQuery.fn.hashchange.delay> milliseconds to // see if the hash has changed. In IE6/7 (and IE8 operating in "IE7 // compatibility" mode), a hidden Iframe is created to allow the back button // and hash-based history to work. // // Usage as described in <jQuery.fn.hashchange>: // // > // Bind an event handler. // > jQuery(window).hashchange( function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).hashchange(); // // A more verbose usage that allows for event namespacing: // // > // Bind an event handler. // > jQuery(window).bind( 'hashchange', function(e) { // > var hash = location.hash; // > ... // > }); // > // > // Manually trigger the event handler. // > jQuery(window).trigger( 'hashchange' ); // // Additional Notes: // // * The polling loop and Iframe are not created until at least one handler // is actually bound to the 'hashchange' event. // * If you need the bound handler(s) to execute immediately, in cases where // a location.hash exists on page load, via bookmark or page refresh for // example, use jQuery(window).hashchange() or the more verbose // jQuery(window).trigger( 'hashchange' ). // * The event can be bound before DOM ready, but since it won't be usable // before then in IE6/7 (due to the necessary Iframe), recommended usage is // to bind it inside a DOM ready handler. // Override existing $.event.special.hashchange methods (allowing this plugin // to be defined after jQuery BBQ in BBQ's source code). special[ str_hashchange ] = $.extend( special[ str_hashchange ], { // Called only when the first 'hashchange' event is bound to window. setup: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to create our own. And we don't want to call this // until the user binds to the event, just in case they never do, since it // will create a polling loop and possibly even a hidden Iframe. $( fake_onhashchange.start ); }, // Called only when the last 'hashchange' event is unbound from window. teardown: function() { // If window.onhashchange is supported natively, there's nothing to do.. if ( supports_onhashchange ) { return false; } // Otherwise, we need to stop ours (if possible). $( fake_onhashchange.stop ); } }); // fake_onhashchange does all the work of triggering the window.onhashchange // event for browsers that don't natively support it, including creating a // polling loop to watch for hash changes and in IE 6/7 creating a hidden // Iframe to enable back and forward. fake_onhashchange = (function(){ var self = {}, timeout_id, // Remember the initial hash so it doesn't get triggered immediately. last_hash = get_fragment(), fn_retval = function(val){ return val; }, history_set = fn_retval, history_get = fn_retval; // Start the polling loop. self.start = function() { timeout_id || poll(); }; // Stop the polling loop. self.stop = function() { timeout_id && clearTimeout( timeout_id ); timeout_id = undefined; }; // This polling loop checks every $.fn.hashchange.delay milliseconds to see // if location.hash has changed, and triggers the 'hashchange' event on // window when necessary. function poll() { var hash = get_fragment(), history_hash = history_get( last_hash ); if ( hash !== last_hash ) { history_set( last_hash = hash, history_hash ); $(window).trigger( str_hashchange ); } else if ( history_hash !== last_hash ) { location.href = location.href.replace( /#.*/, '' ) + history_hash; } timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay ); }; // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv window.attachEvent && !window.addEventListener && !supports_onhashchange && (function(){ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8 // when running in "IE7 compatibility" mode. var iframe, iframe_src; // When the event is bound and polling starts in IE 6/7, create a hidden // Iframe for history handling. self.start = function(){ if ( !iframe ) { iframe_src = $.fn[ str_hashchange ].src; iframe_src = iframe_src && iframe_src + get_fragment(); // Create hidden Iframe. Attempt to make Iframe as hidden as possible // by using techniques from http://www.paciellogroup.com/blog/?p=604. iframe = $('<iframe tabindex="-1" title="empty"/>').hide() // When Iframe has completely loaded, initialize the history and // start polling. .one( 'load', function(){ iframe_src || history_set( get_fragment() ); poll(); }) // Load Iframe src if specified, otherwise nothing. .attr( 'src', iframe_src || 'javascript:0' ) // Append Iframe after the end of the body to prevent unnecessary // initial page scrolling (yes, this works). .insertAfter( 'body' )[0].contentWindow; // Whenever `document.title` changes, update the Iframe's title to // prettify the back/next history menu entries. Since IE sometimes // errors with "Unspecified error" the very first time this is set // (yes, very useful) wrap this with a try/catch block. doc.onpropertychange = function(){ try { if ( event.propertyName === 'title' ) { iframe.document.title = doc.title; } } catch(e) {} }; } }; // Override the "stop" method since an IE6/7 Iframe was created. Even // if there are no longer any bound event handlers, the polling loop // is still necessary for back/next to work at all! self.stop = fn_retval; // Get history by looking at the hidden Iframe's location.hash. history_get = function() { return get_fragment( iframe.location.href ); }; // Set a new history item by opening and then closing the Iframe // document, *then* setting its location.hash. If document.domain has // been set, update that as well. history_set = function( hash, history_hash ) { var iframe_doc = iframe.document, domain = $.fn[ str_hashchange ].domain; if ( hash !== history_hash ) { // Update Iframe with any initial `document.title` that might be set. iframe_doc.title = doc.title; // Opening the Iframe's document after it has been closed is what // actually adds a history entry. iframe_doc.open(); // Set document.domain for the Iframe document as well, if necessary. domain && iframe_doc.write( '<script>document.domain="' + domain + '"</script>' ); iframe_doc.close(); // Update the Iframe's hash, for great justice. iframe.location.hash = hash; } }; })(); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ return self; })(); })(jQuery,this); (function( $, undefined ) { /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ window.matchMedia = window.matchMedia || (function( doc, undefined ) { var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, // fakeBody required for <FF4 when executed in <head> fakeBody = doc.createElement( "body" ), div = doc.createElement( "div" ); div.id = "mq-test-1"; div.style.cssText = "position:absolute;top:-100em"; fakeBody.style.background = "none"; fakeBody.appendChild(div); return function(q){ div.innerHTML = "&shy;<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>"; docElem.insertBefore( fakeBody, refNode ); bool = div.offsetWidth === 42; docElem.removeChild( fakeBody ); return { matches: bool, media: q }; }; }( document )); // $.mobile.media uses matchMedia to return a boolean. $.mobile.media = function( q ) { return window.matchMedia( q ).matches; }; })(jQuery); (function( $, undefined ) { var support = { touch: "ontouchend" in document }; $.mobile.support = $.mobile.support || {}; $.extend( $.support, support ); $.extend( $.mobile.support, support ); }( jQuery )); (function( $, undefined ) { $.extend( $.support, { orientation: "orientation" in window && "onorientationchange" in window }); }( jQuery )); (function( $, undefined ) { // thx Modernizr function propExists( prop ) { var uc_prop = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ), props = ( prop + " " + vendors.join( uc_prop + " " ) + uc_prop ).split( " " ), v; for ( v in props ) { if ( fbCSS[ props[ v ] ] !== undefined ) { return true; } } } var fakeBody = $( "<body>" ).prependTo( "html" ), fbCSS = fakeBody[ 0 ].style, vendors = [ "Webkit", "Moz", "O" ], webos = "palmGetResource" in window, //only used to rule out scrollTop operamini = window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]", bb = window.blackberry && !propExists( "-webkit-transform" ), //only used to rule out box shadow, as it's filled opaque on BB 5 and lower nokiaLTE7_3; // inline SVG support test function inlineSVG() { // Thanks Modernizr & Erik Dahlstrom var w = window, svg = !!w.document.createElementNS && !!w.document.createElementNS( "http://www.w3.org/2000/svg", "svg" ).createSVGRect && !( w.opera && navigator.userAgent.indexOf( "Chrome" ) === -1 ), support = function( data ) { if ( !( data && svg ) ) { $( "html" ).addClass( "ui-nosvg" ); } }, img = new w.Image(); img.onerror = function() { support( false ); }; img.onload = function() { support( img.width === 1 && img.height === 1 ); }; img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; } function transform3dTest() { var mqProp = "transform-3d", // Because the `translate3d` test below throws false positives in Android: ret = $.mobile.media( "(-" + vendors.join( "-" + mqProp + "),(-" ) + "-" + mqProp + "),(" + mqProp + ")" ), el, transforms, t; if ( ret ) { return !!ret; } el = document.createElement( "div" ); transforms = { // We’re omitting Opera for the time being; MS uses unprefixed. "MozTransform": "-moz-transform", "transform": "transform" }; fakeBody.append( el ); for ( t in transforms ) { if ( el.style[ t ] !== undefined ) { el.style[ t ] = "translate3d( 100px, 1px, 1px )"; ret = window.getComputedStyle( el ).getPropertyValue( transforms[ t ] ); } } return ( !!ret && ret !== "none" ); } // Test for dynamic-updating base tag support ( allows us to avoid href,src attr rewriting ) function baseTagTest() { var fauxBase = location.protocol + "//" + location.host + location.pathname + "ui-dir/", base = $( "head base" ), fauxEle = null, href = "", link, rebase; if ( !base.length ) { base = fauxEle = $( "<base>", { "href": fauxBase }).appendTo( "head" ); } else { href = base.attr( "href" ); } link = $( "<a href='testurl' />" ).prependTo( fakeBody ); rebase = link[ 0 ].href; base[ 0 ].href = href || location.pathname; if ( fauxEle ) { fauxEle.remove(); } return rebase.indexOf( fauxBase ) === 0; } // Thanks Modernizr function cssPointerEventsTest() { var element = document.createElement( "x" ), documentElement = document.documentElement, getComputedStyle = window.getComputedStyle, supports; if ( !( "pointerEvents" in element.style ) ) { return false; } element.style.pointerEvents = "auto"; element.style.pointerEvents = "x"; documentElement.appendChild( element ); supports = getComputedStyle && getComputedStyle( element, "" ).pointerEvents === "auto"; documentElement.removeChild( element ); return !!supports; } function boundingRect() { var div = document.createElement( "div" ); return typeof div.getBoundingClientRect !== "undefined"; } // non-UA-based IE version check by James Padolsey, modified by jdalton - from http://gist.github.com/527683 // allows for inclusion of IE 6+, including Windows Mobile 7 $.extend( $.mobile, { browser: {} } ); $.mobile.browser.oldIE = (function() { var v = 3, div = document.createElement( "div" ), a = div.all || []; do { div.innerHTML = "<!--[if gt IE " + ( ++v ) + "]><br><![endif]-->"; } while( a[0] ); return v > 4 ? v : !v; })(); function fixedPosition() { var w = window, ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], ffmatch = ua.match( /Fennec\/([0-9]+)/ ), ffversion = !!ffmatch && ffmatch[ 1 ], operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ), omversion = !!operammobilematch && operammobilematch[ 1 ]; if ( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ( ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534 ) || // Opera Mini ( w.operamini && ({}).toString.call( w.operamini ) === "[object OperaMini]" ) || ( operammobilematch && omversion < 7458 ) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) ( ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533 ) || // Firefox Mobile before 6.0 - ( ffversion && ffversion < 6 ) || // WebOS less than 3 ( "palmGetResource" in window && wkversion && wkversion < 534 ) || // MeeGo ( ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1 ) ) { return false; } return true; } $.extend( $.support, { // Note, Chrome for iOS has an extremely quirky implementation of popstate. // We've chosen to take the shortest path to a bug fix here for issue #5426 // See the following link for information about the regex chosen // https://developers.google.com/chrome/mobile/docs/user-agent#chrome_for_ios_user-agent pushState: "pushState" in history && "replaceState" in history && // When running inside a FF iframe, calling replaceState causes an error !( window.navigator.userAgent.indexOf( "Firefox" ) >= 0 && window.top !== window ) && ( window.navigator.userAgent.search(/CriOS/) === -1 ), mediaquery: $.mobile.media( "only all" ), cssPseudoElement: !!propExists( "content" ), touchOverflow: !!propExists( "overflowScrolling" ), cssTransform3d: transform3dTest(), boxShadow: !!propExists( "boxShadow" ) && !bb, fixedPosition: fixedPosition(), scrollTop: ("pageXOffset" in window || "scrollTop" in document.documentElement || "scrollTop" in fakeBody[ 0 ]) && !webos && !operamini, dynamicBaseTag: baseTagTest(), cssPointerEvents: cssPointerEventsTest(), boundingRect: boundingRect(), inlineSVG: inlineSVG }); fakeBody.remove(); // $.mobile.ajaxBlacklist is used to override ajaxEnabled on platforms that have known conflicts with hash history updates (BB5, Symbian) // or that generally work better browsing in regular http for full page refreshes (Opera Mini) // Note: This detection below is used as a last resort. // We recommend only using these detection methods when all other more reliable/forward-looking approaches are not possible nokiaLTE7_3 = (function() { var ua = window.navigator.userAgent; //The following is an attempt to match Nokia browsers that are running Symbian/s60, with webkit, version 7.3 or older return ua.indexOf( "Nokia" ) > -1 && ( ua.indexOf( "Symbian/3" ) > -1 || ua.indexOf( "Series60/5" ) > -1 ) && ua.indexOf( "AppleWebKit" ) > -1 && ua.match( /(BrowserNG|NokiaBrowser)\/7\.[0-3]/ ); })(); // Support conditions that must be met in order to proceed // default enhanced qualifications are media query support OR IE 7+ $.mobile.gradeA = function() { return ( ( $.support.mediaquery && $.support.cssPseudoElement ) || $.mobile.browser.oldIE && $.mobile.browser.oldIE >= 8 ) && ( $.support.boundingRect || $.fn.jquery.match(/1\.[0-7+]\.[0-9+]?/) !== null ); }; $.mobile.ajaxBlacklist = // BlackBerry browsers, pre-webkit window.blackberry && !window.WebKitPoint || // Opera Mini operamini || // Symbian webkits pre 7.3 nokiaLTE7_3; // Lastly, this workaround is the only way we've found so far to get pre 7.3 Symbian webkit devices // to render the stylesheets when they're referenced before this script, as we'd recommend doing. // This simply reappends the CSS in place, which for some reason makes it apply if ( nokiaLTE7_3 ) { $(function() { $( "head link[rel='stylesheet']" ).attr( "rel", "alternate stylesheet" ).attr( "rel", "stylesheet" ); }); } // For ruling out shadows via css if ( !$.support.boxShadow ) { $( "html" ).addClass( "ui-noboxshadow" ); } })( jQuery ); (function( $, undefined ) { var $win = $.mobile.window, self, dummyFnToInitNavigate = function() { }; $.event.special.beforenavigate = { setup: function() { $win.on( "navigate", dummyFnToInitNavigate ); }, teardown: function() { $win.off( "navigate", dummyFnToInitNavigate ); } }; $.event.special.navigate = self = { bound: false, pushStateEnabled: true, originalEventName: undefined, // If pushstate support is present and push state support is defined to // be true on the mobile namespace. isPushStateEnabled: function() { return $.support.pushState && $.mobile.pushStateEnabled === true && this.isHashChangeEnabled(); }, // !! assumes mobile namespace is present isHashChangeEnabled: function() { return $.mobile.hashListeningEnabled === true; }, // TODO a lot of duplication between popstate and hashchange popstate: function( event ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ), state = event.originalEvent.state || {}; beforeNavigate.originalEvent = event; $win.trigger( beforeNavigate ); if ( beforeNavigate.isDefaultPrevented() ) { return; } if ( event.historyState ) { $.extend(state, event.historyState); } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // NOTE we let the current stack unwind because any assignment to // location.hash will stop the world and run this event handler. By // doing this we create a similar behavior to hashchange on hash // assignment setTimeout(function() { $win.trigger( newEvent, { state: state }); }, 0); }, hashchange: function( event /*, data */ ) { var newEvent = new $.Event( "navigate" ), beforeNavigate = new $.Event( "beforenavigate" ); beforeNavigate.originalEvent = event; $win.trigger( beforeNavigate ); if ( beforeNavigate.isDefaultPrevented() ) { return; } // Make sure the original event is tracked for the end // user to inspect incase they want to do something special newEvent.originalEvent = event; // Trigger the hashchange with state provided by the user // that altered the hash $win.trigger( newEvent, { // Users that want to fully normalize the two events // will need to do history management down the stack and // add the state to the event before this binding is fired // TODO consider allowing for the explicit addition of callbacks // to be fired before this value is set to avoid event timing issues state: event.hashchangeState || {} }); }, // TODO We really only want to set this up once // but I'm not clear if there's a beter way to achieve // this with the jQuery special event structure setup: function( /* data, namespaces */ ) { if ( self.bound ) { return; } self.bound = true; if ( self.isPushStateEnabled() ) { self.originalEventName = "popstate"; $win.bind( "popstate.navigate", self.popstate ); } else if ( self.isHashChangeEnabled() ) { self.originalEventName = "hashchange"; $win.bind( "hashchange.navigate", self.hashchange ); } } }; })( jQuery ); (function( $, undefined ) { var path, $base, dialogHashKey = "&ui-state=dialog"; $.mobile.path = path = { uiStateKey: "&ui-state", // This scary looking regular expression parses an absolute URL or its relative // variants (protocol, site, document, query, and hash), into the various // components (protocol, host, path, query, fragment, etc that make up the // URL as well as some other commonly used sub-parts. When used with RegExp.exec() // or String.match, it parses the URL into a results array that looks like this: // // [0]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread#msg-content // [1]: http://jblas:password@mycompany.com:8080/mail/inbox?msg=1234&type=unread // [2]: http://jblas:password@mycompany.com:8080/mail/inbox // [3]: http://jblas:password@mycompany.com:8080 // [4]: http: // [5]: // // [6]: jblas:password@mycompany.com:8080 // [7]: jblas:password // [8]: jblas // [9]: password // [10]: mycompany.com:8080 // [11]: mycompany.com // [12]: 8080 // [13]: /mail/inbox // [14]: /mail/ // [15]: inbox // [16]: ?msg=1234&type=unread // [17]: #msg-content // urlParseRE: /^\s*(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/, // Abstraction to address xss (Issue #4787) by removing the authority in // browsers that auto decode it. All references to location.href should be // replaced with a call to this method so that it can be dealt with properly here getLocation: function( url ) { var uri = url ? this.parseUrl( url ) : location, hash = this.parseUrl( url || location.href ).hash; // mimic the browser with an empty string when the hash is empty hash = hash === "#" ? "" : hash; // Make sure to parse the url or the location object for the hash because using location.hash // is autodecoded in firefox, the rest of the url should be from the object (location unless // we're testing) to avoid the inclusion of the authority return uri.protocol + "//" + uri.host + uri.pathname + uri.search + hash; }, //return the original document url getDocumentUrl: function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentUrl ) : path.documentUrl.href; }, parseLocation: function() { return this.parseUrl( this.getLocation() ); }, //Parse a URL into a structure that allows easy access to //all of the URL components by name. parseUrl: function( url ) { // If we're passed an object, we'll assume that it is // a parsed url object and just return it back to the caller. if ( $.type( url ) === "object" ) { return url; } var matches = path.urlParseRE.exec( url || "" ) || []; // Create an object that allows the caller to access the sub-matches // by name. Note that IE returns an empty string instead of undefined, // like all other browsers do, so we normalize everything so its consistent // no matter what browser we're running on. return { href: matches[ 0 ] || "", hrefNoHash: matches[ 1 ] || "", hrefNoSearch: matches[ 2 ] || "", domain: matches[ 3 ] || "", protocol: matches[ 4 ] || "", doubleSlash: matches[ 5 ] || "", authority: matches[ 6 ] || "", username: matches[ 8 ] || "", password: matches[ 9 ] || "", host: matches[ 10 ] || "", hostname: matches[ 11 ] || "", port: matches[ 12 ] || "", pathname: matches[ 13 ] || "", directory: matches[ 14 ] || "", filename: matches[ 15 ] || "", search: matches[ 16 ] || "", hash: matches[ 17 ] || "" }; }, //Turn relPath into an asbolute path. absPath is //an optional absolute path which describes what //relPath is relative to. makePathAbsolute: function( relPath, absPath ) { var absStack, relStack, i, d; if ( relPath && relPath.charAt( 0 ) === "/" ) { return relPath; } relPath = relPath || ""; absPath = absPath ? absPath.replace( /^\/|(\/[^\/]*|[^\/]+)$/g, "" ) : ""; absStack = absPath ? absPath.split( "/" ) : []; relStack = relPath.split( "/" ); for ( i = 0; i < relStack.length; i++ ) { d = relStack[ i ]; switch ( d ) { case ".": break; case "..": if ( absStack.length ) { absStack.pop(); } break; default: absStack.push( d ); break; } } return "/" + absStack.join( "/" ); }, //Returns true if both urls have the same domain. isSameDomain: function( absUrl1, absUrl2 ) { return path.parseUrl( absUrl1 ).domain === path.parseUrl( absUrl2 ).domain; }, //Returns true for any relative variant. isRelativeUrl: function( url ) { // All relative Url variants have one thing in common, no protocol. return path.parseUrl( url ).protocol === ""; }, //Returns true for an absolute url. isAbsoluteUrl: function( url ) { return path.parseUrl( url ).protocol !== ""; }, //Turn the specified realtive URL into an absolute one. This function //can handle all relative variants (protocol, site, document, query, fragment). makeUrlAbsolute: function( relUrl, absUrl ) { if ( !path.isRelativeUrl( relUrl ) ) { return relUrl; } if ( absUrl === undefined ) { absUrl = this.documentBase; } var relObj = path.parseUrl( relUrl ), absObj = path.parseUrl( absUrl ), protocol = relObj.protocol || absObj.protocol, doubleSlash = relObj.protocol ? relObj.doubleSlash : ( relObj.doubleSlash || absObj.doubleSlash ), authority = relObj.authority || absObj.authority, hasPath = relObj.pathname !== "", pathname = path.makePathAbsolute( relObj.pathname || absObj.filename, absObj.pathname ), search = relObj.search || ( !hasPath && absObj.search ) || "", hash = relObj.hash; return protocol + doubleSlash + authority + pathname + search + hash; }, //Add search (aka query) params to the specified url. addSearchParams: function( url, params ) { var u = path.parseUrl( url ), p = ( typeof params === "object" ) ? $.param( params ) : params, s = u.search || "?"; return u.hrefNoSearch + s + ( s.charAt( s.length - 1 ) !== "?" ? "&" : "" ) + p + ( u.hash || "" ); }, convertUrlToDataUrl: function( absUrl ) { var u = path.parseUrl( absUrl ); if ( path.isEmbeddedPage( u ) ) { // For embedded pages, remove the dialog hash key as in getFilePath(), // and remove otherwise the Data Url won't match the id of the embedded Page. return u.hash .split( dialogHashKey )[0] .replace( /^#/, "" ) .replace( /\?.*$/, "" ); } else if ( path.isSameDomain( u, this.documentBase ) ) { return u.hrefNoHash.replace( this.documentBase.domain, "" ).split( dialogHashKey )[0]; } return window.decodeURIComponent(absUrl); }, //get path from current hash, or from a file path get: function( newPath ) { if ( newPath === undefined ) { newPath = path.parseLocation().hash; } return path.stripHash( newPath ).replace( /[^\/]*\.[^\/*]+$/, "" ); }, //set location hash to path set: function( path ) { location.hash = path; }, //test if a given url (string) is a path //NOTE might be exceptionally naive isPath: function( url ) { return ( /\// ).test( url ); }, //return a url path with the window's location protocol/hostname/pathname removed clean: function( url ) { return url.replace( this.documentBase.domain, "" ); }, //just return the url without an initial # stripHash: function( url ) { return url.replace( /^#/, "" ); }, stripQueryParams: function( url ) { return url.replace( /\?.*$/, "" ); }, //remove the preceding hash, any query params, and dialog notations cleanHash: function( hash ) { return path.stripHash( hash.replace( /\?.*$/, "" ).replace( dialogHashKey, "" ) ); }, isHashValid: function( hash ) { return ( /^#[^#]+$/ ).test( hash ); }, //check whether a url is referencing the same domain, or an external domain or different protocol //could be mailto, etc isExternal: function( url ) { var u = path.parseUrl( url ); return u.protocol && u.domain !== this.documentUrl.domain ? true : false; }, hasProtocol: function( url ) { return ( /^(:?\w+:)/ ).test( url ); }, isEmbeddedPage: function( url ) { var u = path.parseUrl( url ); //if the path is absolute, then we need to compare the url against //both the this.documentUrl and the documentBase. The main reason for this //is that links embedded within external documents will refer to the //application document, whereas links embedded within the application //document will be resolved against the document base. if ( u.protocol !== "" ) { return ( !this.isPath(u.hash) && u.hash && ( u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ) ) ); } return ( /^#/ ).test( u.href ); }, squash: function( url, resolutionUrl ) { var href, cleanedUrl, search, stateIndex, isPath = this.isPath( url ), uri = this.parseUrl( url ), preservedHash = uri.hash, uiState = ""; // produce a url against which we can resole the provided path resolutionUrl = resolutionUrl || (path.isPath(url) ? path.getLocation() : path.getDocumentUrl()); // If the url is anything but a simple string, remove any preceding hash // eg #foo/bar -> foo/bar // #foo -> #foo cleanedUrl = isPath ? path.stripHash( url ) : url; // If the url is a full url with a hash check if the parsed hash is a path // if it is, strip the #, and use it otherwise continue without change cleanedUrl = path.isPath( uri.hash ) ? path.stripHash( uri.hash ) : cleanedUrl; // Split the UI State keys off the href stateIndex = cleanedUrl.indexOf( this.uiStateKey ); // store the ui state keys for use if ( stateIndex > -1 ) { uiState = cleanedUrl.slice( stateIndex ); cleanedUrl = cleanedUrl.slice( 0, stateIndex ); } // make the cleanedUrl absolute relative to the resolution url href = path.makeUrlAbsolute( cleanedUrl, resolutionUrl ); // grab the search from the resolved url since parsing from // the passed url may not yield the correct result search = this.parseUrl( href ).search; // TODO all this crap is terrible, clean it up if ( isPath ) { // reject the hash if it's a path or it's just a dialog key if ( path.isPath( preservedHash ) || preservedHash.replace("#", "").indexOf( this.uiStateKey ) === 0) { preservedHash = ""; } // Append the UI State keys where it exists and it's been removed // from the url if ( uiState && preservedHash.indexOf( this.uiStateKey ) === -1) { preservedHash += uiState; } // make sure that pound is on the front of the hash if ( preservedHash.indexOf( "#" ) === -1 && preservedHash !== "" ) { preservedHash = "#" + preservedHash; } // reconstruct each of the pieces with the new search string and hash href = path.parseUrl( href ); href = href.protocol + "//" + href.host + href.pathname + search + preservedHash; } else { href += href.indexOf( "#" ) > -1 ? uiState : "#" + uiState; } return href; }, isPreservableHash: function( hash ) { return hash.replace( "#", "" ).indexOf( this.uiStateKey ) === 0; }, // Escape weird characters in the hash if it is to be used as a selector hashToSelector: function( hash ) { var hasHash = ( hash.substring( 0, 1 ) === "#" ); if ( hasHash ) { hash = hash.substring( 1 ); } return ( hasHash ? "#" : "" ) + hash.replace( /([!"#$%&'()*+,./:;<=>?@[\]^`{|}~])/g, "\\$1" ); }, // return the substring of a filepath before the sub-page key, for making // a server request getFilePath: function( path ) { var splitkey = "&" + $.mobile.subPageUrlKey; return path && path.split( splitkey )[0].split( dialogHashKey )[0]; }, // check if the specified url refers to the first page in the main // application document. isFirstPageUrl: function( url ) { // We only deal with absolute paths. var u = path.parseUrl( path.makeUrlAbsolute( url, this.documentBase ) ), // Does the url have the same path as the document? samePath = u.hrefNoHash === this.documentUrl.hrefNoHash || ( this.documentBaseDiffers && u.hrefNoHash === this.documentBase.hrefNoHash ), // Get the first page element. fp = $.mobile.firstPage, // Get the id of the first page element if it has one. fpId = fp && fp[0] ? fp[0].id : undefined; // The url refers to the first page if the path matches the document and // it either has no hash value, or the hash is exactly equal to the id // of the first page element. return samePath && ( !u.hash || u.hash === "#" || ( fpId && u.hash.replace( /^#/, "" ) === fpId ) ); }, // Some embedded browsers, like the web view in Phone Gap, allow // cross-domain XHR requests if the document doing the request was loaded // via the file:// protocol. This is usually to allow the application to // "phone home" and fetch app specific data. We normally let the browser // handle external/cross-domain urls, but if the allowCrossDomainPages // option is true, we will allow cross-domain http/https requests to go // through our page loading logic. isPermittedCrossDomainRequest: function( docUrl, reqUrl ) { return $.mobile.allowCrossDomainPages && (docUrl.protocol === "file:" || docUrl.protocol === "content:") && reqUrl.search( /^https?:/ ) !== -1; } }; path.documentUrl = path.parseLocation(); $base = $( "head" ).find( "base" ); path.documentBase = $base.length ? path.parseUrl( path.makeUrlAbsolute( $base.attr( "href" ), path.documentUrl.href ) ) : path.documentUrl; path.documentBaseDiffers = (path.documentUrl.hrefNoHash !== path.documentBase.hrefNoHash); //return the original document base url path.getDocumentBase = function( asParsedObject ) { return asParsedObject ? $.extend( {}, path.documentBase ) : path.documentBase.href; }; // DEPRECATED as of 1.4.0 - remove in 1.5.0 $.extend( $.mobile, { //return the original document url getDocumentUrl: path.getDocumentUrl, //return the original document base url getDocumentBase: path.getDocumentBase }); })( jQuery ); (function( $, undefined ) { $.mobile.History = function( stack, index ) { this.stack = stack || []; this.activeIndex = index || 0; }; $.extend($.mobile.History.prototype, { getActive: function() { return this.stack[ this.activeIndex ]; }, getLast: function() { return this.stack[ this.previousIndex ]; }, getNext: function() { return this.stack[ this.activeIndex + 1 ]; }, getPrev: function() { return this.stack[ this.activeIndex - 1 ]; }, // addNew is used whenever a new page is added add: function( url, data ) { data = data || {}; //if there's forward history, wipe it if ( this.getNext() ) { this.clearForward(); } // if the hash is included in the data make sure the shape // is consistent for comparison if ( data.hash && data.hash.indexOf( "#" ) === -1) { data.hash = "#" + data.hash; } data.url = url; this.stack.push( data ); this.activeIndex = this.stack.length - 1; }, //wipe urls ahead of active index clearForward: function() { this.stack = this.stack.slice( 0, this.activeIndex + 1 ); }, find: function( url, stack, earlyReturn ) { stack = stack || this.stack; var entry, i, length = stack.length, index; for ( i = 0; i < length; i++ ) { entry = stack[i]; if ( decodeURIComponent(url) === decodeURIComponent(entry.url) || decodeURIComponent(url) === decodeURIComponent(entry.hash) ) { index = i; if ( earlyReturn ) { return index; } } } return index; }, closest: function( url ) { var closest, a = this.activeIndex; // First, take the slice of the history stack before the current index and search // for a url match. If one is found, we'll avoid avoid looking through forward history // NOTE the preference for backward history movement is driven by the fact that // most mobile browsers only have a dedicated back button, and users rarely use // the forward button in desktop browser anyhow closest = this.find( url, this.stack.slice(0, a) ); // If nothing was found in backward history check forward. The `true` // value passed as the third parameter causes the find method to break // on the first match in the forward history slice. The starting index // of the slice must then be added to the result to get the element index // in the original history stack :( :( // // TODO this is hyper confusing and should be cleaned up (ugh so bad) if ( closest === undefined ) { closest = this.find( url, this.stack.slice(a), true ); closest = closest === undefined ? closest : closest + a; } return closest; }, direct: function( opts ) { var newActiveIndex = this.closest( opts.url ), a = this.activeIndex; // save new page index, null check to prevent falsey 0 result // record the previous index for reference if ( newActiveIndex !== undefined ) { this.activeIndex = newActiveIndex; this.previousIndex = a; } // invoke callbacks where appropriate // // TODO this is also convoluted and confusing if ( newActiveIndex < a ) { ( opts.present || opts.back || $.noop )( this.getActive(), "back" ); } else if ( newActiveIndex > a ) { ( opts.present || opts.forward || $.noop )( this.getActive(), "forward" ); } else if ( newActiveIndex === undefined && opts.missing ) { opts.missing( this.getActive() ); } } }); })( jQuery ); (function( $, undefined ) { var path = $.mobile.path, initialHref = location.href; $.mobile.Navigator = function( history ) { this.history = history; this.ignoreInitialHashChange = true; $.mobile.window.bind({ "popstate.history": $.proxy( this.popstate, this ), "hashchange.history": $.proxy( this.hashchange, this ) }); }; $.extend($.mobile.Navigator.prototype, { squash: function( url, data ) { var state, href, hash = path.isPath(url) ? path.stripHash(url) : url; href = path.squash( url ); // make sure to provide this information when it isn't explicitly set in the // data object that was passed to the squash method state = $.extend({ hash: hash, url: href }, data); // replace the current url with the new href and store the state // Note that in some cases we might be replacing an url with the // same url. We do this anyways because we need to make sure that // all of our history entries have a state object associated with // them. This allows us to work around the case where $.mobile.back() // is called to transition from an external page to an embedded page. // In that particular case, a hashchange event is *NOT* generated by the browser. // Ensuring each history entry has a state object means that onPopState() // will always trigger our hashchange callback even when a hashchange event // is not fired. window.history.replaceState( state, state.title || document.title, href ); return state; }, hash: function( url, href ) { var parsed, loc, hash, resolved; // Grab the hash for recording. If the passed url is a path // we used the parsed version of the squashed url to reconstruct, // otherwise we assume it's a hash and store it directly parsed = path.parseUrl( url ); loc = path.parseLocation(); if ( loc.pathname + loc.search === parsed.pathname + parsed.search ) { // If the pathname and search of the passed url is identical to the current loc // then we must use the hash. Otherwise there will be no event // eg, url = "/foo/bar?baz#bang", location.href = "http://example.com/foo/bar?baz" hash = parsed.hash ? parsed.hash : parsed.pathname + parsed.search; } else if ( path.isPath(url) ) { resolved = path.parseUrl( href ); // If the passed url is a path, make it domain relative and remove any trailing hash hash = resolved.pathname + resolved.search + (path.isPreservableHash( resolved.hash )? resolved.hash.replace( "#", "" ) : ""); } else { hash = url; } return hash; }, // TODO reconsider name go: function( url, data, noEvents ) { var state, href, hash, popstateEvent, isPopStateEvent = $.event.special.navigate.isPushStateEnabled(); // Get the url as it would look squashed on to the current resolution url href = path.squash( url ); // sort out what the hash sould be from the url hash = this.hash( url, href ); // Here we prevent the next hash change or popstate event from doing any // history management. In the case of hashchange we don't swallow it // if there will be no hashchange fired (since that won't reset the value) // and will swallow the following hashchange if ( noEvents && hash !== path.stripHash(path.parseLocation().hash) ) { this.preventNextHashChange = noEvents; } // IMPORTANT in the case where popstate is supported the event will be triggered // directly, stopping further execution - ie, interupting the flow of this // method call to fire bindings at this expression. Below the navigate method // there is a binding to catch this event and stop its propagation. // // We then trigger a new popstate event on the window with a null state // so that the navigate events can conclude their work properly // // if the url is a path we want to preserve the query params that are available on // the current url. this.preventHashAssignPopState = true; window.location.hash = hash; // If popstate is enabled and the browser triggers `popstate` events when the hash // is set (this often happens immediately in browsers like Chrome), then the // this flag will be set to false already. If it's a browser that does not trigger // a `popstate` on hash assignement or `replaceState` then we need avoid the branch // that swallows the event created by the popstate generated by the hash assignment // At the time of this writing this happens with Opera 12 and some version of IE this.preventHashAssignPopState = false; state = $.extend({ url: href, hash: hash, title: document.title }, data); if ( isPopStateEvent ) { popstateEvent = new $.Event( "popstate" ); popstateEvent.originalEvent = { type: "popstate", state: null }; this.squash( url, state ); // Trigger a new faux popstate event to replace the one that we // caught that was triggered by the hash setting above. if ( !noEvents ) { this.ignorePopState = true; $.mobile.window.trigger( popstateEvent ); } } // record the history entry so that the information can be included // in hashchange event driven navigate events in a similar fashion to // the state that's provided by popstate this.history.add( state.url, state ); }, // This binding is intended to catch the popstate events that are fired // when execution of the `$.navigate` method stops at window.location.hash = url; // and completely prevent them from propagating. The popstate event will then be // retriggered after execution resumes // // TODO grab the original event here and use it for the synthetic event in the // second half of the navigate execution that will follow this binding popstate: function( event ) { var hash, state; // Partly to support our test suite which manually alters the support // value to test hashchange. Partly to prevent all around weirdness if ( !$.event.special.navigate.isPushStateEnabled() ) { return; } // If this is the popstate triggered by the actual alteration of the hash // prevent it completely. History is tracked manually if ( this.preventHashAssignPopState ) { this.preventHashAssignPopState = false; event.stopImmediatePropagation(); return; } // if this is the popstate triggered after the `replaceState` call in the go // method, then simply ignore it. The history entry has already been captured if ( this.ignorePopState ) { this.ignorePopState = false; return; } // If there is no state, and the history stack length is one were // probably getting the page load popstate fired by browsers like chrome // avoid it and set the one time flag to false. // TODO: Do we really need all these conditions? Comparing location hrefs // should be sufficient. if ( !event.originalEvent.state && this.history.stack.length === 1 && this.ignoreInitialHashChange ) { this.ignoreInitialHashChange = false; if ( location.href === initialHref ) { event.preventDefault(); return; } } // account for direct manipulation of the hash. That is, we will receive a popstate // when the hash is changed by assignment, and it won't have a state associated. We // then need to squash the hash. See below for handling of hash assignment that // matches an existing history entry // TODO it might be better to only add to the history stack // when the hash is adjacent to the active history entry hash = path.parseLocation().hash; if ( !event.originalEvent.state && hash ) { // squash the hash that's been assigned on the URL with replaceState // also grab the resulting state object for storage state = this.squash( hash ); // record the new hash as an additional history entry // to match the browser's treatment of hash assignment this.history.add( state.url, state ); // pass the newly created state information // along with the event event.historyState = state; // do not alter history, we've added a new history entry // so we know where we are return; } // If all else fails this is a popstate that comes from the back or forward buttons // make sure to set the state of our history stack properly, and record the directionality this.history.direct({ url: (event.originalEvent.state || {}).url || hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.historyState = $.extend({}, historyEntry); event.historyState.direction = direction; } }); }, // NOTE must bind before `navigate` special event hashchange binding otherwise the // navigation data won't be attached to the hashchange event in time for those // bindings to attach it to the `navigate` special event // TODO add a check here that `hashchange.navigate` is bound already otherwise it's // broken (exception?) hashchange: function( event ) { var history, hash; // If hashchange listening is explicitly disabled or pushstate is supported // avoid making use of the hashchange handler. if (!$.event.special.navigate.isHashChangeEnabled() || $.event.special.navigate.isPushStateEnabled() ) { return; } // On occasion explicitly want to prevent the next hash from propogating because we only // with to alter the url to represent the new state do so here if ( this.preventNextHashChange ) { this.preventNextHashChange = false; event.stopImmediatePropagation(); return; } history = this.history; hash = path.parseLocation().hash; // If this is a hashchange caused by the back or forward button // make sure to set the state of our history stack properly this.history.direct({ url: hash, // When the url is either forward or backward in history include the entry // as data on the event object for merging as data in the navigate event present: function( historyEntry, direction ) { // make sure to create a new object to pass down as the navigate event data event.hashchangeState = $.extend({}, historyEntry); event.hashchangeState.direction = direction; }, // When we don't find a hash in our history clearly we're aiming to go there // record the entry as new for future traversal // // NOTE it's not entirely clear that this is the right thing to do given that we // can't know the users intention. It might be better to explicitly _not_ // support location.hash assignment in preference to $.navigate calls // TODO first arg to add should be the href, but it causes issues in identifying // embeded pages missing: function() { history.add( hash, { hash: hash, title: document.title }); } }); } }); })( jQuery ); (function( $, undefined ) { // TODO consider queueing navigation activity until previous activities have completed // so that end users don't have to think about it. Punting for now // TODO !! move the event bindings into callbacks on the navigate event $.mobile.navigate = function( url, data, noEvents ) { $.mobile.navigate.navigator.go( url, data, noEvents ); }; // expose the history on the navigate method in anticipation of full integration with // existing navigation functionalty that is tightly coupled to the history information $.mobile.navigate.history = new $.mobile.History(); // instantiate an instance of the navigator for use within the $.navigate method $.mobile.navigate.navigator = new $.mobile.Navigator( $.mobile.navigate.history ); var loc = $.mobile.path.parseLocation(); $.mobile.navigate.history.add( loc.href, {hash: loc.hash} ); })( jQuery ); (function( $, undefined ) { var props = { "animation": {}, "transition": {} }, testElement = document.createElement( "a" ), vendorPrefixes = [ "", "webkit-", "moz-", "o-" ]; $.each( [ "animation", "transition" ], function( i, test ) { // Get correct name for test var testName = ( i === 0 ) ? test + "-" + "name" : test; $.each( vendorPrefixes, function( j, prefix ) { if ( testElement.style[ $.camelCase( prefix + testName ) ] !== undefined ) { props[ test ][ "prefix" ] = prefix; return false; } }); // Set event and duration names for later use props[ test ][ "duration" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "duration" ); props[ test ][ "event" ] = $.camelCase( props[ test ][ "prefix" ] + test + "-" + "end" ); // All lower case if not a vendor prop if ( props[ test ][ "prefix" ] === "" ) { props[ test ][ "event" ] = props[ test ][ "event" ].toLowerCase(); } }); // If a valid prefix was found then the it is supported by the browser $.support.cssTransitions = ( props[ "transition" ][ "prefix" ] !== undefined ); $.support.cssAnimations = ( props[ "animation" ][ "prefix" ] !== undefined ); // Remove the testElement $( testElement ).remove(); // Animation complete callback $.fn.animationComplete = function( callback, type, fallbackTime ) { var timer, duration, that = this, animationType = ( !type || type === "animation" ) ? "animation" : "transition"; // Make sure selected type is supported by browser if ( ( $.support.cssTransitions && animationType === "transition" ) || ( $.support.cssAnimations && animationType === "animation" ) ) { // If a fallback time was not passed set one if ( fallbackTime === undefined ) { // Make sure the was not bound to document before checking .css if ( $( this ).context !== document ) { // Parse the durration since its in second multiple by 1000 for milliseconds // Multiply by 3 to make sure we give the animation plenty of time. duration = parseFloat( $( this ).css( props[ animationType ].duration ) ) * 3000; } // If we could not read a duration use the default if ( duration === 0 || duration === undefined || isNaN( duration ) ) { duration = $.fn.animationComplete.defaultDuration; } } // Sets up the fallback if event never comes timer = setTimeout( function() { $( that ).off( props[ animationType ].event ); callback.apply( that ); }, duration ); // Bind the event return $( this ).one( props[ animationType ].event, function() { // Clear the timer so we dont call callback twice clearTimeout( timer ); callback.call( this, arguments ); }); } else { // CSS animation / transitions not supported // Defer execution for consistency between webkit/non webkit setTimeout( $.proxy( callback, this ), 0 ); return $( this ); } }; // Allow default callback to be configured on mobileInit $.fn.animationComplete.defaultDuration = 1000; })( jQuery ); // This plugin is an experiment for abstracting away the touch and mouse // events so that developers don't have to worry about which method of input // the device their document is loaded on supports. // // The idea here is to allow the developer to register listeners for the // basic mouse events, such as mousedown, mousemove, mouseup, and click, // and the plugin will take care of registering the correct listeners // behind the scenes to invoke the listener at the fastest possible time // for that device, while still retaining the order of event firing in // the traditional mouse environment, should multiple handlers be registered // on the same element for different events. // // The current version exposes the following virtual events to jQuery bind methods: // "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel" (function( $, window, document, undefined ) { var dataPropertyName = "virtualMouseBindings", touchTargetPropertyName = "virtualTouchID", virtualEventNames = "vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split( " " ), touchEventProps = "clientX clientY pageX pageY screenX screenY".split( " " ), mouseHookProps = $.event.mouseHooks ? $.event.mouseHooks.props : [], mouseEventProps = $.event.props.concat( mouseHookProps ), activeDocHandlers = {}, resetTimerID = 0, startX = 0, startY = 0, didScroll = false, clickBlockList = [], blockMouseTriggers = false, blockTouchTriggers = false, eventCaptureSupported = "addEventListener" in document, $document = $( document ), nextTouchID = 1, lastTouchID = 0, threshold, i; $.vmouse = { moveDistanceThreshold: 10, clickDistanceThreshold: 10, resetTimerDuration: 1500 }; function getNativeEvent( event ) { while ( event && typeof event.originalEvent !== "undefined" ) { event = event.originalEvent; } return event; } function createVirtualEvent( event, eventType ) { var t = event.type, oe, props, ne, prop, ct, touch, i, j, len; event = $.Event( event ); event.type = eventType; oe = event.originalEvent; props = $.event.props; // addresses separation of $.event.props in to $.event.mouseHook.props and Issue 3280 // https://github.com/jquery/jquery-mobile/issues/3280 if ( t.search( /^(mouse|click)/ ) > -1 ) { props = mouseEventProps; } // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if ( oe ) { for ( i = props.length, prop; i; ) { prop = props[ --i ]; event[ prop ] = oe[ prop ]; } } // make sure that if the mouse and click virtual events are generated // without a .which one is defined if ( t.search(/mouse(down|up)|click/) > -1 && !event.which ) { event.which = 1; } if ( t.search(/^touch/) !== -1 ) { ne = getNativeEvent( oe ); t = ne.touches; ct = ne.changedTouches; touch = ( t && t.length ) ? t[0] : ( ( ct && ct.length ) ? ct[ 0 ] : undefined ); if ( touch ) { for ( j = 0, len = touchEventProps.length; j < len; j++) { prop = touchEventProps[ j ]; event[ prop ] = touch[ prop ]; } } } return event; } function getVirtualBindingFlags( element ) { var flags = {}, b, k; while ( element ) { b = $.data( element, dataPropertyName ); for ( k in b ) { if ( b[ k ] ) { flags[ k ] = flags.hasVirtualBinding = true; } } element = element.parentNode; } return flags; } function getClosestElementWithVirtualBinding( element, eventType ) { var b; while ( element ) { b = $.data( element, dataPropertyName ); if ( b && ( !eventType || b[ eventType ] ) ) { return element; } element = element.parentNode; } return null; } function enableTouchBindings() { blockTouchTriggers = false; } function disableTouchBindings() { blockTouchTriggers = true; } function enableMouseBindings() { lastTouchID = 0; clickBlockList.length = 0; blockMouseTriggers = false; // When mouse bindings are enabled, our // touch bindings are disabled. disableTouchBindings(); } function disableMouseBindings() { // When mouse bindings are disabled, our // touch bindings are enabled. enableTouchBindings(); } function startResetTimer() { clearResetTimer(); resetTimerID = setTimeout( function() { resetTimerID = 0; enableMouseBindings(); }, $.vmouse.resetTimerDuration ); } function clearResetTimer() { if ( resetTimerID ) { clearTimeout( resetTimerID ); resetTimerID = 0; } } function triggerVirtualEvent( eventType, event, flags ) { var ve; if ( ( flags && flags[ eventType ] ) || ( !flags && getClosestElementWithVirtualBinding( event.target, eventType ) ) ) { ve = createVirtualEvent( event, eventType ); $( event.target).trigger( ve ); } return ve; } function mouseEventCallback( event ) { var touchID = $.data( event.target, touchTargetPropertyName ), ve; if ( !blockMouseTriggers && ( !lastTouchID || lastTouchID !== touchID ) ) { ve = triggerVirtualEvent( "v" + event.type, event ); if ( ve ) { if ( ve.isDefaultPrevented() ) { event.preventDefault(); } if ( ve.isPropagationStopped() ) { event.stopPropagation(); } if ( ve.isImmediatePropagationStopped() ) { event.stopImmediatePropagation(); } } } } function handleTouchStart( event ) { var touches = getNativeEvent( event ).touches, target, flags, t; if ( touches && touches.length === 1 ) { target = event.target; flags = getVirtualBindingFlags( target ); if ( flags.hasVirtualBinding ) { lastTouchID = nextTouchID++; $.data( target, touchTargetPropertyName, lastTouchID ); clearResetTimer(); disableMouseBindings(); didScroll = false; t = getNativeEvent( event ).touches[ 0 ]; startX = t.pageX; startY = t.pageY; triggerVirtualEvent( "vmouseover", event, flags ); triggerVirtualEvent( "vmousedown", event, flags ); } } } function handleScroll( event ) { if ( blockTouchTriggers ) { return; } if ( !didScroll ) { triggerVirtualEvent( "vmousecancel", event, getVirtualBindingFlags( event.target ) ); } didScroll = true; startResetTimer(); } function handleTouchMove( event ) { if ( blockTouchTriggers ) { return; } var t = getNativeEvent( event ).touches[ 0 ], didCancel = didScroll, moveThreshold = $.vmouse.moveDistanceThreshold, flags = getVirtualBindingFlags( event.target ); didScroll = didScroll || ( Math.abs( t.pageX - startX ) > moveThreshold || Math.abs( t.pageY - startY ) > moveThreshold ); if ( didScroll && !didCancel ) { triggerVirtualEvent( "vmousecancel", event, flags ); } triggerVirtualEvent( "vmousemove", event, flags ); startResetTimer(); } function handleTouchEnd( event ) { if ( blockTouchTriggers ) { return; } disableTouchBindings(); var flags = getVirtualBindingFlags( event.target ), ve, t; triggerVirtualEvent( "vmouseup", event, flags ); if ( !didScroll ) { ve = triggerVirtualEvent( "vclick", event, flags ); if ( ve && ve.isDefaultPrevented() ) { // The target of the mouse events that follow the touchend // event don't necessarily match the target used during the // touch. This means we need to rely on coordinates for blocking // any click that is generated. t = getNativeEvent( event ).changedTouches[ 0 ]; clickBlockList.push({ touchID: lastTouchID, x: t.clientX, y: t.clientY }); // Prevent any mouse events that follow from triggering // virtual event notifications. blockMouseTriggers = true; } } triggerVirtualEvent( "vmouseout", event, flags); didScroll = false; startResetTimer(); } function hasVirtualBindings( ele ) { var bindings = $.data( ele, dataPropertyName ), k; if ( bindings ) { for ( k in bindings ) { if ( bindings[ k ] ) { return true; } } } return false; } function dummyMouseHandler() {} function getSpecialEventObject( eventType ) { var realType = eventType.substr( 1 ); return { setup: function(/* data, namespace */) { // If this is the first virtual mouse binding for this element, // add a bindings object to its data. if ( !hasVirtualBindings( this ) ) { $.data( this, dataPropertyName, {} ); } // If setup is called, we know it is the first binding for this // eventType, so initialize the count for the eventType to zero. var bindings = $.data( this, dataPropertyName ); bindings[ eventType ] = true; // If this is the first virtual mouse event for this type, // register a global handler on the document. activeDocHandlers[ eventType ] = ( activeDocHandlers[ eventType ] || 0 ) + 1; if ( activeDocHandlers[ eventType ] === 1 ) { $document.bind( realType, mouseEventCallback ); } // Some browsers, like Opera Mini, won't dispatch mouse/click events // for elements unless they actually have handlers registered on them. // To get around this, we register dummy handlers on the elements. $( this ).bind( realType, dummyMouseHandler ); // For now, if event capture is not supported, we rely on mouse handlers. if ( eventCaptureSupported ) { // If this is the first virtual mouse binding for the document, // register our touchstart handler on the document. activeDocHandlers[ "touchstart" ] = ( activeDocHandlers[ "touchstart" ] || 0) + 1; if ( activeDocHandlers[ "touchstart" ] === 1 ) { $document.bind( "touchstart", handleTouchStart ) .bind( "touchend", handleTouchEnd ) // On touch platforms, touching the screen and then dragging your finger // causes the window content to scroll after some distance threshold is // exceeded. On these platforms, a scroll prevents a click event from being // dispatched, and on some platforms, even the touchend is suppressed. To // mimic the suppression of the click event, we need to watch for a scroll // event. Unfortunately, some platforms like iOS don't dispatch scroll // events until *AFTER* the user lifts their finger (touchend). This means // we need to watch both scroll and touchmove events to figure out whether // or not a scroll happenens before the touchend event is fired. .bind( "touchmove", handleTouchMove ) .bind( "scroll", handleScroll ); } } }, teardown: function(/* data, namespace */) { // If this is the last virtual binding for this eventType, // remove its global handler from the document. --activeDocHandlers[ eventType ]; if ( !activeDocHandlers[ eventType ] ) { $document.unbind( realType, mouseEventCallback ); } if ( eventCaptureSupported ) { // If this is the last virtual mouse binding in existence, // remove our document touchstart listener. --activeDocHandlers[ "touchstart" ]; if ( !activeDocHandlers[ "touchstart" ] ) { $document.unbind( "touchstart", handleTouchStart ) .unbind( "touchmove", handleTouchMove ) .unbind( "touchend", handleTouchEnd ) .unbind( "scroll", handleScroll ); } } var $this = $( this ), bindings = $.data( this, dataPropertyName ); // teardown may be called when an element was // removed from the DOM. If this is the case, // jQuery core may have already stripped the element // of any data bindings so we need to check it before // using it. if ( bindings ) { bindings[ eventType ] = false; } // Unregister the dummy event handler. $this.unbind( realType, dummyMouseHandler ); // If this is the last virtual mouse binding on the // element, remove the binding data from the element. if ( !hasVirtualBindings( this ) ) { $this.removeData( dataPropertyName ); } } }; } // Expose our custom events to the jQuery bind/unbind mechanism. for ( i = 0; i < virtualEventNames.length; i++ ) { $.event.special[ virtualEventNames[ i ] ] = getSpecialEventObject( virtualEventNames[ i ] ); } // Add a capture click handler to block clicks. // Note that we require event capture support for this so if the device // doesn't support it, we punt for now and rely solely on mouse events. if ( eventCaptureSupported ) { document.addEventListener( "click", function( e ) { var cnt = clickBlockList.length, target = e.target, x, y, ele, i, o, touchID; if ( cnt ) { x = e.clientX; y = e.clientY; threshold = $.vmouse.clickDistanceThreshold; // The idea here is to run through the clickBlockList to see if // the current click event is in the proximity of one of our // vclick events that had preventDefault() called on it. If we find // one, then we block the click. // // Why do we have to rely on proximity? // // Because the target of the touch event that triggered the vclick // can be different from the target of the click event synthesized // by the browser. The target of a mouse/click event that is synthesized // from a touch event seems to be implementation specific. For example, // some browsers will fire mouse/click events for a link that is near // a touch event, even though the target of the touchstart/touchend event // says the user touched outside the link. Also, it seems that with most // browsers, the target of the mouse/click event is not calculated until the // time it is dispatched, so if you replace an element that you touched // with another element, the target of the mouse/click will be the new // element underneath that point. // // Aside from proximity, we also check to see if the target and any // of its ancestors were the ones that blocked a click. This is necessary // because of the strange mouse/click target calculation done in the // Android 2.1 browser, where if you click on an element, and there is a // mouse/click handler on one of its ancestors, the target will be the // innermost child of the touched element, even if that child is no where // near the point of touch. ele = target; while ( ele ) { for ( i = 0; i < cnt; i++ ) { o = clickBlockList[ i ]; touchID = 0; if ( ( ele === target && Math.abs( o.x - x ) < threshold && Math.abs( o.y - y ) < threshold ) || $.data( ele, touchTargetPropertyName ) === o.touchID ) { // XXX: We may want to consider removing matches from the block list // instead of waiting for the reset timer to fire. e.preventDefault(); e.stopPropagation(); return; } } ele = ele.parentNode; } } }, true); } })( jQuery, window, document ); (function( $, window, undefined ) { var $document = $( document ), supportTouch = $.mobile.support.touch, scrollEvent = "touchmove scroll", touchStartEvent = supportTouch ? "touchstart" : "mousedown", touchStopEvent = supportTouch ? "touchend" : "mouseup", touchMoveEvent = supportTouch ? "touchmove" : "mousemove"; // setup new event shortcuts $.each( ( "touchstart touchmove touchend " + "tap taphold " + "swipe swipeleft swiperight " + "scrollstart scrollstop" ).split( " " ), function( i, name ) { $.fn[ name ] = function( fn ) { return fn ? this.bind( name, fn ) : this.trigger( name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ name ] = true; } }); function triggerCustomEvent( obj, eventType, event, bubble ) { var originalType = event.type; event.type = eventType; if ( bubble ) { $.event.trigger( event, undefined, obj ); } else { $.event.dispatch.call( obj, event ); } event.type = originalType; } // also handles scrollstop $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this, $this = $( thisObject ), scrolling, timer; function trigger( event, state ) { scrolling = state; triggerCustomEvent( thisObject, scrolling ? "scrollstart" : "scrollstop", event ); } // iPhone triggers scroll after a small delay; use touchmove instead $this.bind( scrollEvent, function( event ) { if ( !$.event.special.scrollstart.enabled ) { return; } if ( !scrolling ) { trigger( event, true ); } clearTimeout( timer ); timer = setTimeout( function() { trigger( event, false ); }, 50 ); }); }, teardown: function() { $( this ).unbind( scrollEvent ); } }; // also handles taphold $.event.special.tap = { tapholdThreshold: 750, emitTapOnTaphold: true, setup: function() { var thisObject = this, $this = $( thisObject ), isTaphold = false; $this.bind( "vmousedown", function( event ) { isTaphold = false; if ( event.which && event.which !== 1 ) { return false; } var origTarget = event.target, timer; function clearTapTimer() { clearTimeout( timer ); } function clearTapHandlers() { clearTapTimer(); $this.unbind( "vclick", clickHandler ) .unbind( "vmouseup", clearTapTimer ); $document.unbind( "vmousecancel", clearTapHandlers ); } function clickHandler( event ) { clearTapHandlers(); // ONLY trigger a 'tap' event if the start target is // the same as the stop target. if ( !isTaphold && origTarget === event.target ) { triggerCustomEvent( thisObject, "tap", event ); } else if ( isTaphold ) { event.stopPropagation(); } } $this.bind( "vmouseup", clearTapTimer ) .bind( "vclick", clickHandler ); $document.bind( "vmousecancel", clearTapHandlers ); timer = setTimeout( function() { if ( !$.event.special.tap.emitTapOnTaphold ) { isTaphold = true; } triggerCustomEvent( thisObject, "taphold", $.Event( "taphold", { target: origTarget } ) ); }, $.event.special.tap.tapholdThreshold ); }); }, teardown: function() { $( this ).unbind( "vmousedown" ).unbind( "vclick" ).unbind( "vmouseup" ); $document.unbind( "vmousecancel" ); } }; // Also handles swipeleft, swiperight $.event.special.swipe = { // More than this horizontal displacement, and we will suppress scrolling. scrollSupressionThreshold: 30, // More time than this, and it isn't a swipe. durationThreshold: 1000, // Swipe horizontal displacement must be more than this. horizontalDistanceThreshold: 30, // Swipe vertical displacement must be less than this. verticalDistanceThreshold: 30, getLocation: function ( event ) { var winPageX = window.pageXOffset, winPageY = window.pageYOffset, x = event.clientX, y = event.clientY; if ( event.pageY === 0 && Math.floor( y ) > Math.floor( event.pageY ) || event.pageX === 0 && Math.floor( x ) > Math.floor( event.pageX ) ) { // iOS4 clientX/clientY have the value that should have been // in pageX/pageY. While pageX/page/ have the value 0 x = x - winPageX; y = y - winPageY; } else if ( y < ( event.pageY - winPageY) || x < ( event.pageX - winPageX ) ) { // Some Android browsers have totally bogus values for clientX/Y // when scrolling/zooming a page. Detectable since clientX/clientY // should never be smaller than pageX/pageY minus page scroll x = event.pageX - winPageX; y = event.pageY - winPageY; } return { x: x, y: y }; }, start: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, location = $.event.special.swipe.getLocation( data ); return { time: ( new Date() ).getTime(), coords: [ location.x, location.y ], origin: $( event.target ) }; }, stop: function( event ) { var data = event.originalEvent.touches ? event.originalEvent.touches[ 0 ] : event, location = $.event.special.swipe.getLocation( data ); return { time: ( new Date() ).getTime(), coords: [ location.x, location.y ] }; }, handleSwipe: function( start, stop, thisObject, origTarget ) { if ( stop.time - start.time < $.event.special.swipe.durationThreshold && Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.horizontalDistanceThreshold && Math.abs( start.coords[ 1 ] - stop.coords[ 1 ] ) < $.event.special.swipe.verticalDistanceThreshold ) { var direction = start.coords[0] > stop.coords[ 0 ] ? "swipeleft" : "swiperight"; triggerCustomEvent( thisObject, "swipe", $.Event( "swipe", { target: origTarget, swipestart: start, swipestop: stop }), true ); triggerCustomEvent( thisObject, direction,$.Event( direction, { target: origTarget, swipestart: start, swipestop: stop } ), true ); return true; } return false; }, // This serves as a flag to ensure that at most one swipe event event is // in work at any given time eventInProgress: false, setup: function() { var events, thisObject = this, $this = $( thisObject ), context = {}; // Retrieve the events data for this element and add the swipe context events = $.data( this, "mobile-events" ); if ( !events ) { events = { length: 0 }; $.data( this, "mobile-events", events ); } events.length++; events.swipe = context; context.start = function( event ) { // Bail if we're already working on a swipe event if ( $.event.special.swipe.eventInProgress ) { return; } $.event.special.swipe.eventInProgress = true; var stop, start = $.event.special.swipe.start( event ), origTarget = event.target, emitted = false; context.move = function( event ) { if ( !start ) { return; } stop = $.event.special.swipe.stop( event ); if ( !emitted ) { emitted = $.event.special.swipe.handleSwipe( start, stop, thisObject, origTarget ); if ( emitted ) { // Reset the context to make way for the next swipe event $.event.special.swipe.eventInProgress = false; } } // prevent scrolling if ( Math.abs( start.coords[ 0 ] - stop.coords[ 0 ] ) > $.event.special.swipe.scrollSupressionThreshold ) { event.preventDefault(); } }; context.stop = function() { emitted = true; // Reset the context to make way for the next swipe event $.event.special.swipe.eventInProgress = false; $document.off( touchMoveEvent, context.move ); context.move = null; }; $document.on( touchMoveEvent, context.move ) .one( touchStopEvent, context.stop ); }; $this.on( touchStartEvent, context.start ); }, teardown: function() { var events, context; events = $.data( this, "mobile-events" ); if ( events ) { context = events.swipe; delete events.swipe; events.length--; if ( events.length === 0 ) { $.removeData( this, "mobile-events" ); } } if ( context ) { if ( context.start ) { $( this ).off( touchStartEvent, context.start ); } if ( context.move ) { $document.off( touchMoveEvent, context.move ); } if ( context.stop ) { $document.off( touchStopEvent, context.stop ); } } } }; $.each({ scrollstop: "scrollstart", taphold: "tap", swipeleft: "swipe", swiperight: "swipe" }, function( event, sourceEvent ) { $.event.special[ event ] = { setup: function() { $( this ).bind( sourceEvent, $.noop ); }, teardown: function() { $( this ).unbind( sourceEvent ); } }; }); })( jQuery, this ); // throttled resize event (function( $ ) { $.event.special.throttledresize = { setup: function() { $( this ).bind( "resize", handler ); }, teardown: function() { $( this ).unbind( "resize", handler ); } }; var throttle = 250, handler = function() { curr = ( new Date() ).getTime(); diff = curr - lastCall; if ( diff >= throttle ) { lastCall = curr; $( this ).trigger( "throttledresize" ); } else { if ( heldCall ) { clearTimeout( heldCall ); } // Promise a held call will still execute heldCall = setTimeout( handler, throttle - diff ); } }, lastCall = 0, heldCall, curr, diff; })( jQuery ); (function( $, window ) { var win = $( window ), event_name = "orientationchange", get_orientation, last_orientation, initial_orientation_is_landscape, initial_orientation_is_default, portrait_map = { "0": true, "180": true }, ww, wh, landscape_threshold; // It seems that some device/browser vendors use window.orientation values 0 and 180 to // denote the "default" orientation. For iOS devices, and most other smart-phones tested, // the default orientation is always "portrait", but in some Android and RIM based tablets, // the default orientation is "landscape". The following code attempts to use the window // dimensions to figure out what the current orientation is, and then makes adjustments // to the to the portrait_map if necessary, so that we can properly decode the // window.orientation value whenever get_orientation() is called. // // Note that we used to use a media query to figure out what the orientation the browser // thinks it is in: // // initial_orientation_is_landscape = $.mobile.media("all and (orientation: landscape)"); // // but there was an iPhone/iPod Touch bug beginning with iOS 4.2, up through iOS 5.1, // where the browser *ALWAYS* applied the landscape media query. This bug does not // happen on iPad. if ( $.support.orientation ) { // Check the window width and height to figure out what the current orientation // of the device is at this moment. Note that we've initialized the portrait map // values to 0 and 180, *AND* we purposely check for landscape so that if we guess // wrong, , we default to the assumption that portrait is the default orientation. // We use a threshold check below because on some platforms like iOS, the iPhone // form-factor can report a larger width than height if the user turns on the // developer console. The actual threshold value is somewhat arbitrary, we just // need to make sure it is large enough to exclude the developer console case. ww = window.innerWidth || win.width(); wh = window.innerHeight || win.height(); landscape_threshold = 50; initial_orientation_is_landscape = ww > wh && ( ww - wh ) > landscape_threshold; // Now check to see if the current window.orientation is 0 or 180. initial_orientation_is_default = portrait_map[ window.orientation ]; // If the initial orientation is landscape, but window.orientation reports 0 or 180, *OR* // if the initial orientation is portrait, but window.orientation reports 90 or -90, we // need to flip our portrait_map values because landscape is the default orientation for // this device/browser. if ( ( initial_orientation_is_landscape && initial_orientation_is_default ) || ( !initial_orientation_is_landscape && !initial_orientation_is_default ) ) { portrait_map = { "-90": true, "90": true }; } } $.event.special.orientationchange = $.extend( {}, $.event.special.orientationchange, { setup: function() { // If the event is supported natively, return false so that jQuery // will bind to the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Get the current orientation to avoid initial double-triggering. last_orientation = get_orientation(); // Because the orientationchange event doesn't exist, simulate the // event by testing window dimensions on resize. win.bind( "throttledresize", handler ); }, teardown: function() { // If the event is not supported natively, return false so that // jQuery will unbind the event using DOM methods. if ( $.support.orientation && !$.event.special.orientationchange.disabled ) { return false; } // Because the orientationchange event doesn't exist, unbind the // resize event handler. win.unbind( "throttledresize", handler ); }, add: function( handleObj ) { // Save a reference to the bound event handler. var old_handler = handleObj.handler; handleObj.handler = function( event ) { // Modify event object, adding the .orientation property. event.orientation = get_orientation(); // Call the originally-bound event handler and return its result. return old_handler.apply( this, arguments ); }; } }); // If the event is not supported natively, this handler will be bound to // the window resize event to simulate the orientationchange event. function handler() { // Get the current orientation. var orientation = get_orientation(); if ( orientation !== last_orientation ) { // The orientation has changed, so trigger the orientationchange event. last_orientation = orientation; win.trigger( event_name ); } } // Get the current page orientation. This method is exposed publicly, should it // be needed, as jQuery.event.special.orientationchange.orientation() $.event.special.orientationchange.orientation = get_orientation = function() { var isPortrait = true, elem = document.documentElement; // prefer window orientation to the calculation based on screensize as // the actual screen resize takes place before or after the orientation change event // has been fired depending on implementation (eg android 2.3 is before, iphone after). // More testing is required to determine if a more reliable method of determining the new screensize // is possible when orientationchange is fired. (eg, use media queries + element + opacity) if ( $.support.orientation ) { // if the window orientation registers as 0 or 180 degrees report // portrait, otherwise landscape isPortrait = portrait_map[ window.orientation ]; } else { isPortrait = elem && elem.clientWidth / elem.clientHeight < 1.1; } return isPortrait ? "portrait" : "landscape"; }; $.fn[ event_name ] = function( fn ) { return fn ? this.bind( event_name, fn ) : this.trigger( event_name ); }; // jQuery < 1.8 if ( $.attrFn ) { $.attrFn[ event_name ] = true; } }( jQuery, this )); (function( $, undefined ) { // existing base tag? var baseElement = $( "head" ).children( "base" ), // base element management, defined depending on dynamic base tag support // TODO move to external widget base = { // define base element, for use in routing asset urls that are referenced // in Ajax-requested markup element: ( baseElement.length ? baseElement : $( "<base>", { href: $.mobile.path.documentBase.hrefNoHash } ).prependTo( $( "head" ) ) ), linkSelector: "[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]", // set the generated BASE element's href to a new page's base path set: function( href ) { // we should do nothing if the user wants to manage their url base // manually if ( !$.mobile.dynamicBaseEnabled ) { return; } // we should use the base tag if we can manipulate it dynamically if ( $.support.dynamicBaseTag ) { base.element.attr( "href", $.mobile.path.makeUrlAbsolute( href, $.mobile.path.documentBase ) ); } }, rewrite: function( href, page ) { var newPath = $.mobile.path.get( href ); page.find( base.linkSelector ).each(function( i, link ) { var thisAttr = $( link ).is( "[href]" ) ? "href" : $( link ).is( "[src]" ) ? "src" : "action", thisUrl = $( link ).attr( thisAttr ); // XXX_jblas: We need to fix this so that it removes the document // base URL, and then prepends with the new page URL. // if full path exists and is same, chop it - helps IE out thisUrl = thisUrl.replace( location.protocol + "//" + location.host + location.pathname, "" ); if ( !/^(\w+:|#|\/)/.test( thisUrl ) ) { $( link ).attr( thisAttr, newPath + thisUrl ); } }); }, // set the generated BASE element's href to a new page's base path reset: function(/* href */) { base.element.attr( "href", $.mobile.path.documentBase.hrefNoSearch ); } }; $.mobile.base = base; })( jQuery ); (function( $, undefined ) { $.mobile.widgets = {}; var originalWidget = $.widget, // Record the original, non-mobileinit-modified version of $.mobile.keepNative // so we can later determine whether someone has modified $.mobile.keepNative keepNativeFactoryDefault = $.mobile.keepNative; $.widget = (function( orig ) { return function() { var constructor = orig.apply( this, arguments ), name = constructor.prototype.widgetName; constructor.initSelector = ( ( constructor.prototype.initSelector !== undefined ) ? constructor.prototype.initSelector : ":jqmData(role='" + name + "')" ); $.mobile.widgets[ name ] = constructor; return constructor; }; })( $.widget ); // Make sure $.widget still has bridge and extend methods $.extend( $.widget, originalWidget ); // For backcompat remove in 1.5 $.mobile.document.on( "create", function( event ) { $( event.target ).enhanceWithin(); }); $.widget( "mobile.page", { options: { theme: "a", domCache: false, // Deprecated in 1.4 remove in 1.5 keepNativeDefault: $.mobile.keepNative, // Deprecated in 1.4 remove in 1.5 contentTheme: null, enhanced: false }, // DEPRECATED for > 1.4 // TODO remove at 1.5 _createWidget: function() { $.Widget.prototype._createWidget.apply( this, arguments ); this._trigger( "init" ); }, _create: function() { // If false is returned by the callbacks do not create the page if ( this._trigger( "beforecreate" ) === false ) { return false; } if ( !this.options.enhanced ) { this._enhance(); } this._on( this.element, { pagebeforehide: "removeContainerBackground", pagebeforeshow: "_handlePageBeforeShow" }); this.element.enhanceWithin(); // Dialog widget is deprecated in 1.4 remove this in 1.5 if ( $.mobile.getAttribute( this.element[0], "role" ) === "dialog" && $.mobile.dialog ) { this.element.dialog(); } }, _enhance: function () { var attrPrefix = "data-" + $.mobile.ns, self = this; if ( this.options.role ) { this.element.attr( "data-" + $.mobile.ns + "role", this.options.role ); } this.element .attr( "tabindex", "0" ) .addClass( "ui-page ui-page-theme-" + this.options.theme ); // Manipulation of content os Deprecated as of 1.4 remove in 1.5 this.element.find( "[" + attrPrefix + "role='content']" ).each( function() { var $this = $( this ), theme = this.getAttribute( attrPrefix + "theme" ) || undefined; self.options.contentTheme = theme || self.options.contentTheme || ( self.options.dialog && self.options.theme ) || ( self.element.jqmData("role") === "dialog" && self.options.theme ); $this.addClass( "ui-content" ); if ( self.options.contentTheme ) { $this.addClass( "ui-body-" + ( self.options.contentTheme ) ); } // Add ARIA role $this.attr( "role", "main" ).addClass( "ui-content" ); }); }, bindRemove: function( callback ) { var page = this.element; // when dom caching is not enabled or the page is embedded bind to remove the page on hide if ( !page.data( "mobile-page" ).options.domCache && page.is( ":jqmData(external-page='true')" ) ) { // TODO use _on - that is, sort out why it doesn't work in this case page.bind( "pagehide.remove", callback || function( e, data ) { //check if this is a same page transition and if so don't remove the page if( !data.samePage ){ var $this = $( this ), prEvent = new $.Event( "pageremove" ); $this.trigger( prEvent ); if ( !prEvent.isDefaultPrevented() ) { $this.removeWithDependents(); } } }); } }, _setOptions: function( o ) { if ( o.theme !== undefined ) { this.element.removeClass( "ui-page-theme-" + this.options.theme ).addClass( "ui-page-theme-" + o.theme ); } if ( o.contentTheme !== undefined ) { this.element.find( "[data-" + $.mobile.ns + "='content']" ).removeClass( "ui-body-" + this.options.contentTheme ) .addClass( "ui-body-" + o.contentTheme ); } }, _handlePageBeforeShow: function(/* e */) { this.setContainerBackground(); }, // Deprecated in 1.4 remove in 1.5 removeContainerBackground: function() { this.element.closest( ":mobile-pagecontainer" ).pagecontainer({ "theme": "none" }); }, // Deprecated in 1.4 remove in 1.5 // set the page container background to the page theme setContainerBackground: function( theme ) { this.element.parent().pagecontainer( { "theme": theme || this.options.theme } ); }, // Deprecated in 1.4 remove in 1.5 keepNativeSelector: function() { var options = this.options, keepNative = $.trim( options.keepNative || "" ), globalValue = $.trim( $.mobile.keepNative ), optionValue = $.trim( options.keepNativeDefault ), // Check if $.mobile.keepNative has changed from the factory default newDefault = ( keepNativeFactoryDefault === globalValue ? "" : globalValue ), // If $.mobile.keepNative has not changed, use options.keepNativeDefault oldDefault = ( newDefault === "" ? optionValue : "" ); // Concatenate keepNative selectors from all sources where the value has // changed or, if nothing has changed, return the default return ( ( keepNative ? [ keepNative ] : [] ) .concat( newDefault ? [ newDefault ] : [] ) .concat( oldDefault ? [ oldDefault ] : [] ) .join( ", " ) ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.pagecontainer", { options: { theme: "a" }, initSelector: false, _create: function() { this.setLastScrollEnabled = true; this._on( this.window, { // disable an scroll setting when a hashchange has been fired, // this only works because the recording of the scroll position // is delayed for 100ms after the browser might have changed the // position because of the hashchange navigate: "_disableRecordScroll", // bind to scrollstop for the first page, "pagechange" won't be // fired in that case scrollstop: "_delayedRecordScroll" }); // TODO consider moving the navigation handler OUT of widget into // some other object as glue between the navigate event and the // content widget load and change methods this._on( this.window, { navigate: "_filterNavigateEvents" }); // TODO move from page* events to content* events this._on({ pagechange: "_afterContentChange" }); // handle initial hashchange from chrome :( this.window.one( "navigate", $.proxy(function() { this.setLastScrollEnabled = true; }, this)); }, _setOptions: function( options ) { if ( options.theme !== undefined && options.theme !== "none" ) { this.element.removeClass( "ui-overlay-" + this.options.theme ) .addClass( "ui-overlay-" + options.theme ); } else if ( options.theme !== undefined ) { this.element.removeClass( "ui-overlay-" + this.options.theme ); } this._super( options ); }, _disableRecordScroll: function() { this.setLastScrollEnabled = false; }, _enableRecordScroll: function() { this.setLastScrollEnabled = true; }, // TODO consider the name here, since it's purpose specific _afterContentChange: function() { // once the page has changed, re-enable the scroll recording this.setLastScrollEnabled = true; // remove any binding that previously existed on the get scroll // which may or may not be different than the scroll element // determined for this page previously this._off( this.window, "scrollstop" ); // determine and bind to the current scoll element which may be the // window or in the case of touch overflow the element touch overflow this._on( this.window, { scrollstop: "_delayedRecordScroll" }); }, _recordScroll: function() { // this barrier prevents setting the scroll value based on // the browser scrolling the window based on a hashchange if ( !this.setLastScrollEnabled ) { return; } var active = this._getActiveHistory(), currentScroll, minScroll, defaultScroll; if ( active ) { currentScroll = this._getScroll(); minScroll = this._getMinScroll(); defaultScroll = this._getDefaultScroll(); // Set active page's lastScroll prop. If the location we're // scrolling to is less than minScrollBack, let it go. active.lastScroll = currentScroll < minScroll ? defaultScroll : currentScroll; } }, _delayedRecordScroll: function() { setTimeout( $.proxy(this, "_recordScroll"), 100 ); }, _getScroll: function() { return this.window.scrollTop(); }, _getMinScroll: function() { return $.mobile.minScrollBack; }, _getDefaultScroll: function() { return $.mobile.defaultHomeScroll; }, _filterNavigateEvents: function( e, data ) { var url; if ( e.originalEvent && e.originalEvent.isDefaultPrevented() ) { return; } url = e.originalEvent.type.indexOf( "hashchange" ) > -1 ? data.state.hash : data.state.url; if ( !url ) { url = this._getHash(); } if ( !url || url === "#" || url.indexOf( "#" + $.mobile.path.uiStateKey ) === 0 ) { url = location.href; } this._handleNavigate( url, data.state ); }, _getHash: function() { return $.mobile.path.parseLocation().hash; }, // TODO active page should be managed by the container (ie, it should be a property) getActivePage: function() { return this.activePage; }, // TODO the first page should be a property set during _create using the logic // that currently resides in init _getInitialContent: function() { return $.mobile.firstPage; }, // TODO each content container should have a history object _getHistory: function() { return $.mobile.navigate.history; }, // TODO use _getHistory _getActiveHistory: function() { return $.mobile.navigate.history.getActive(); }, // TODO the document base should be determined at creation _getDocumentBase: function() { return $.mobile.path.documentBase; }, back: function() { this.go( -1 ); }, forward: function() { this.go( 1 ); }, go: function( steps ) { //if hashlistening is enabled use native history method if ( $.mobile.hashListeningEnabled ) { window.history.go( steps ); } else { //we are not listening to the hash so handle history internally var activeIndex = $.mobile.navigate.history.activeIndex, index = activeIndex + parseInt( steps, 10 ), url = $.mobile.navigate.history.stack[ index ].url, direction = ( steps >= 1 )? "forward" : "back"; //update the history object $.mobile.navigate.history.activeIndex = index; $.mobile.navigate.history.previousIndex = activeIndex; //change to the new page this.change( url, { direction: direction, changeHash: false, fromHashChange: true } ); } }, // TODO rename _handleDestination _handleDestination: function( to ) { var history; // clean the hash for comparison if it's a url if ( $.type(to) === "string" ) { to = $.mobile.path.stripHash( to ); } if ( to ) { history = this._getHistory(); // At this point, 'to' can be one of 3 things, a cached page // element from a history stack entry, an id, or site-relative / // absolute URL. If 'to' is an id, we need to resolve it against // the documentBase, not the location.href, since the hashchange // could've been the result of a forward/backward navigation // that crosses from an external page/dialog to an internal // page/dialog. // // TODO move check to history object or path object? to = !$.mobile.path.isPath( to ) ? ( $.mobile.path.makeUrlAbsolute( "#" + to, this._getDocumentBase() ) ) : to; // If we're about to go to an initial URL that contains a // reference to a non-existent internal page, go to the first // page instead. We know that the initial hash refers to a // non-existent page, because the initial hash did not end // up in the initial history entry // TODO move check to history object? if ( to === $.mobile.path.makeUrlAbsolute( "#" + history.initialDst, this._getDocumentBase() ) && history.stack.length && history.stack[0].url !== history.initialDst.replace( $.mobile.dialogHashKey, "" ) ) { to = this._getInitialContent(); } } return to || this._getInitialContent(); }, _handleDialog: function( changePageOptions, data ) { var to, active, activeContent = this.getActivePage(); // If current active page is not a dialog skip the dialog and continue // in the same direction if ( activeContent && !activeContent.hasClass( "ui-dialog" ) ) { // determine if we're heading forward or backward and continue // accordingly past the current dialog if ( data.direction === "back" ) { this.back(); } else { this.forward(); } // prevent changePage call return false; } else { // if the current active page is a dialog and we're navigating // to a dialog use the dialog objected saved in the stack to = data.pageUrl; active = this._getActiveHistory(); // make sure to set the role, transition and reversal // as most of this is lost by the domCache cleaning $.extend( changePageOptions, { role: active.role, transition: active.transition, reverse: data.direction === "back" }); } return to; }, _handleNavigate: function( url, data ) { //find first page via hash // TODO stripping the hash twice with handleUrl var to = $.mobile.path.stripHash( url ), history = this._getHistory(), // transition is false if it's the first page, undefined // otherwise (and may be overridden by default) transition = history.stack.length === 0 ? "none" : undefined, // default options for the changPage calls made after examining // the current state of the page and the hash, NOTE that the // transition is derived from the previous history entry changePageOptions = { changeHash: false, fromHashChange: true, reverse: data.direction === "back" }; $.extend( changePageOptions, data, { transition: ( history.getLast() || {} ).transition || transition }); // TODO move to _handleDestination ? // If this isn't the first page, if the current url is a dialog hash // key, and the initial destination isn't equal to the current target // page, use the special dialog handling if ( history.activeIndex > 0 && to.indexOf( $.mobile.dialogHashKey ) > -1 && history.initialDst !== to ) { to = this._handleDialog( changePageOptions, data ); if ( to === false ) { return; } } this._changeContent( this._handleDestination( to ), changePageOptions ); }, _changeContent: function( to, opts ) { $.mobile.changePage( to, opts ); }, _getBase: function() { return $.mobile.base; }, _getNs: function() { return $.mobile.ns; }, _enhance: function( content, role ) { // TODO consider supporting a custom callback, and passing in // the settings which includes the role return content.page({ role: role }); }, _include: function( page, settings ) { // append to page and enhance page.appendTo( this.element ); // use the page widget to enhance this._enhance( page, settings.role ); // remove page on hide page.page( "bindRemove" ); }, _find: function( absUrl ) { // TODO consider supporting a custom callback var fileUrl = this._createFileUrl( absUrl ), dataUrl = this._createDataUrl( absUrl ), page, initialContent = this._getInitialContent(); // Check to see if the page already exists in the DOM. // NOTE do _not_ use the :jqmData pseudo selector because parenthesis // are a valid url char and it breaks on the first occurence page = this.element .children( "[data-" + this._getNs() +"url='" + dataUrl + "']" ); // If we failed to find the page, check to see if the url is a // reference to an embedded page. If so, it may have been dynamically // injected by a developer, in which case it would be lacking a // data-url attribute and in need of enhancement. if ( page.length === 0 && dataUrl && !$.mobile.path.isPath( dataUrl ) ) { page = this.element.children( $.mobile.path.hashToSelector("#" + dataUrl) ) .attr( "data-" + this._getNs() + "url", dataUrl ) .jqmData( "url", dataUrl ); } // If we failed to find a page in the DOM, check the URL to see if it // refers to the first page in the application. Also check to make sure // our cached-first-page is actually in the DOM. Some user deployed // apps are pruning the first page from the DOM for various reasons. // We check for this case here because we don't want a first-page with // an id falling through to the non-existent embedded page error case. if ( page.length === 0 && $.mobile.path.isFirstPageUrl( fileUrl ) && initialContent && initialContent.parent().length ) { page = $( initialContent ); } return page; }, _getLoader: function() { return $.mobile.loading(); }, _showLoading: function( delay, theme, msg, textonly ) { // This configurable timeout allows cached pages a brief // delay to load without showing a message if ( this._loadMsg ) { return; } this._loadMsg = setTimeout($.proxy(function() { this._getLoader().loader( "show", theme, msg, textonly ); this._loadMsg = 0; }, this), delay ); }, _hideLoading: function() { // Stop message show timer clearTimeout( this._loadMsg ); this._loadMsg = 0; // Hide loading message this._getLoader().loader( "hide" ); }, _showError: function() { // make sure to remove the current loading message this._hideLoading(); // show the error message this._showLoading( 0, $.mobile.pageLoadErrorMessageTheme, $.mobile.pageLoadErrorMessage, true ); // hide the error message after a delay // TODO configuration setTimeout( $.proxy(this, "_hideLoading"), 1500 ); }, _parse: function( html, fileUrl ) { // TODO consider allowing customization of this method. It's very JQM specific var page, all = $( "<div></div>" ); //workaround to allow scripts to execute when included in page divs all.get( 0 ).innerHTML = html; page = all.find( ":jqmData(role='page'), :jqmData(role='dialog')" ).first(); //if page elem couldn't be found, create one and insert the body element's contents if ( !page.length ) { page = $( "<div data-" + this._getNs() + "role='page'>" + ( html.split( /<\/?body[^>]*>/gmi )[1] || "" ) + "</div>" ); } // TODO tagging a page with external to make sure that embedded pages aren't // removed by the various page handling code is bad. Having page handling code // in many places is bad. Solutions post 1.0 page.attr( "data-" + this._getNs() + "url", $.mobile.path.convertUrlToDataUrl(fileUrl) ) .attr( "data-" + this._getNs() + "external-page", true ); return page; }, _setLoadedTitle: function( page, html ) { //page title regexp var newPageTitle = html.match( /<title[^>]*>([^<]*)/ ) && RegExp.$1; if ( newPageTitle && !page.jqmData("title") ) { newPageTitle = $( "<div>" + newPageTitle + "</div>" ).text(); page.jqmData( "title", newPageTitle ); } }, _isRewritableBaseTag: function() { return $.mobile.dynamicBaseEnabled && !$.support.dynamicBaseTag; }, _createDataUrl: function( absoluteUrl ) { return $.mobile.path.convertUrlToDataUrl( absoluteUrl ); }, _createFileUrl: function( absoluteUrl ) { return $.mobile.path.getFilePath( absoluteUrl ); }, _triggerWithDeprecated: function( name, data, page ) { var deprecatedEvent = $.Event( "page" + name ), newEvent = $.Event( this.widgetName + name ); // DEPRECATED // trigger the old deprecated event on the page if it's provided ( page || this.element ).trigger( deprecatedEvent, data ); // use the widget trigger method for the new content* event this.element.trigger( newEvent, data ); return { deprecatedEvent: deprecatedEvent, event: newEvent }; }, // TODO it would be nice to split this up more but everything appears to be "one off" // or require ordering such that other bits are sprinkled in between parts that // could be abstracted out as a group _loadSuccess: function( absUrl, triggerData, settings, deferred ) { var fileUrl = this._createFileUrl( absUrl ), dataUrl = this._createDataUrl( absUrl ); return $.proxy(function( html, textStatus, xhr ) { //pre-parse html to check for a data-url, //use it as the new fileUrl, base path, etc var content, // TODO handle dialogs again pageElemRegex = new RegExp( "(<[^>]+\\bdata-" + this._getNs() + "role=[\"']?page[\"']?[^>]*>)" ), dataUrlRegex = new RegExp( "\\bdata-" + this._getNs() + "url=[\"']?([^\"'>]*)[\"']?" ); // data-url must be provided for the base tag so resource requests // can be directed to the correct url. loading into a temprorary // element makes these requests immediately if ( pageElemRegex.test( html ) && RegExp.$1 && dataUrlRegex.test( RegExp.$1 ) && RegExp.$1 ) { fileUrl = $.mobile.path.getFilePath( $("<div>" + RegExp.$1 + "</div>").text() ); } //dont update the base tag if we are prefetching if ( settings.prefetch === undefined ) { this._getBase().set( fileUrl ); } content = this._parse( html, fileUrl ); this._setLoadedTitle( content, html ); // Add the content reference and xhr to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; // DEPRECATED triggerData.page = content; triggerData.content = content; // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( !this._trigger( "load", undefined, triggerData ) ) { return; } // rewrite src and href attrs to use a base url if the base tag won't work if ( this._isRewritableBaseTag() && content ) { this._getBase().rewrite( fileUrl, content ); } this._include( content, settings ); // Enhancing the content may result in new dialogs/sub content being inserted // into the DOM. If the original absUrl refers to a sub-content, that is the // real content we are interested in. if ( absUrl.indexOf( "&" + $.mobile.subPageUrlKey ) > -1 ) { content = this.element.children( "[data-" + this._getNs() +"url='" + dataUrl + "']" ); } // Remove loading message. if ( settings.showLoadMsg ) { this._hideLoading(); } // BEGIN DEPRECATED --------------------------------------------------- // Let listeners know the content loaded successfully. this.element.trigger( "pageload" ); // END DEPRECATED ----------------------------------------------------- deferred.resolve( absUrl, settings, content ); }, this); }, _loadDefaults: { type: "get", data: undefined, // DEPRECATED reloadPage: false, reload: false, // By default we rely on the role defined by the @data-role attribute. role: undefined, showLoadMsg: false, // This delay allows loads that pull from browser cache to // occur without showing the loading message. loadMsgDelay: 50 }, load: function( url, options ) { // This function uses deferred notifications to let callers // know when the content is done loading, or if an error has occurred. var deferred = ( options && options.deferred ) || $.Deferred(), // The default load options with overrides specified by the caller. settings = $.extend( {}, this._loadDefaults, options ), // The DOM element for the content after it has been loaded. content = null, // The absolute version of the URL passed into the function. This // version of the URL may contain dialog/subcontent params in it. absUrl = $.mobile.path.makeUrlAbsolute( url, this._findBaseWithDefault() ), fileUrl, dataUrl, pblEvent, triggerData; // DEPRECATED reloadPage settings.reload = settings.reloadPage; // If the caller provided data, and we're using "get" request, // append the data to the URL. if ( settings.data && settings.type === "get" ) { absUrl = $.mobile.path.addSearchParams( absUrl, settings.data ); settings.data = undefined; } // If the caller is using a "post" request, reload must be true if ( settings.data && settings.type === "post" ) { settings.reload = true; } // The absolute version of the URL minus any dialog/subcontent params. // In otherwords the real URL of the content to be loaded. fileUrl = this._createFileUrl( absUrl ); // The version of the Url actually stored in the data-url attribute of // the content. For embedded content, it is just the id of the page. For // content within the same domain as the document base, it is the site // relative path. For cross-domain content (Phone Gap only) the entire // absolute Url is used to load the content. dataUrl = this._createDataUrl( absUrl ); content = this._find( absUrl ); // If it isn't a reference to the first content and refers to missing // embedded content reject the deferred and return if ( content.length === 0 && $.mobile.path.isEmbeddedPage(fileUrl) && !$.mobile.path.isFirstPageUrl(fileUrl) ) { deferred.reject( absUrl, settings ); return; } // Reset base to the default document base // TODO figure out why we doe this this._getBase().reset(); // If the content we are interested in is already in the DOM, // and the caller did not indicate that we should force a // reload of the file, we are done. Resolve the deferrred so that // users can bind to .done on the promise if ( content.length && !settings.reload ) { this._enhance( content, settings.role ); deferred.resolve( absUrl, settings, content ); //if we are reloading the content make sure we update // the base if its not a prefetch if ( !settings.prefetch ) { this._getBase().set(url); } return; } triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings }; // Let listeners know we're about to load content. pblEvent = this._triggerWithDeprecated( "beforeload", triggerData ); // If the default behavior is prevented, stop here! if ( pblEvent.deprecatedEvent.isDefaultPrevented() || pblEvent.event.isDefaultPrevented() ) { return; } if ( settings.showLoadMsg ) { this._showLoading( settings.loadMsgDelay ); } // Reset base to the default document base. // only reset if we are not prefetching if ( settings.prefetch === undefined ) { this._getBase().reset(); } if ( !( $.mobile.allowCrossDomainPages || $.mobile.path.isSameDomain($.mobile.path.documentUrl, absUrl ) ) ) { deferred.reject( absUrl, settings ); return; } // Load the new content. $.ajax({ url: fileUrl, type: settings.type, data: settings.data, contentType: settings.contentType, dataType: "html", success: this._loadSuccess( absUrl, triggerData, settings, deferred ), error: this._loadError( absUrl, triggerData, settings, deferred ) }); }, _loadError: function( absUrl, triggerData, settings, deferred ) { return $.proxy(function( xhr, textStatus, errorThrown ) { //set base back to current path this._getBase().set( $.mobile.path.get() ); // Add error info to our triggerData. triggerData.xhr = xhr; triggerData.textStatus = textStatus; triggerData.errorThrown = errorThrown; // Let listeners know the page load failed. var plfEvent = this._triggerWithDeprecated( "loadfailed", triggerData ); // If the default behavior is prevented, stop here! // Note that it is the responsibility of the listener/handler // that called preventDefault(), to resolve/reject the // deferred object within the triggerData. if ( plfEvent.deprecatedEvent.isDefaultPrevented() || plfEvent.event.isDefaultPrevented() ) { return; } // Remove loading message. if ( settings.showLoadMsg ) { this._showError(); } deferred.reject( absUrl, settings ); }, this); }, _getTransitionHandler: function( transition ) { transition = $.mobile._maybeDegradeTransition( transition ); //find the transition handler for the specified transition. If there //isn't one in our transitionHandlers dictionary, use the default one. //call the handler immediately to kick-off the transition. return $.mobile.transitionHandlers[ transition ] || $.mobile.defaultTransitionHandler; }, // TODO move into transition handlers? _triggerCssTransitionEvents: function( to, from, prefix ) { var samePage = false; prefix = prefix || ""; // TODO decide if these events should in fact be triggered on the container if ( from ) { //Check if this is a same page transition and tell the handler in page if( to[0] === from[0] ){ samePage = true; } //trigger before show/hide events // TODO deprecate nextPage in favor of next this._triggerWithDeprecated( prefix + "hide", { nextPage: to, samePage: samePage }, from ); } // TODO deprecate prevPage in favor of previous this._triggerWithDeprecated( prefix + "show", { prevPage: from || $( "" ) }, to ); }, // TODO make private once change has been defined in the widget _cssTransition: function( to, from, options ) { var transition = options.transition, reverse = options.reverse, deferred = options.deferred, TransitionHandler, promise; this._triggerCssTransitionEvents( to, from, "before" ); // TODO put this in a binding to events *outside* the widget this._hideLoading(); TransitionHandler = this._getTransitionHandler( transition ); promise = ( new TransitionHandler( transition, reverse, to, from ) ).transition(); // TODO temporary accomodation of argument deferred promise.done(function() { deferred.resolve.apply( deferred, arguments ); }); promise.done($.proxy(function() { this._triggerCssTransitionEvents( to, from ); }, this)); }, _releaseTransitionLock: function() { //release transition lock so navigation is free again isPageTransitioning = false; if ( pageTransitionQueue.length > 0 ) { $.mobile.changePage.apply( null, pageTransitionQueue.pop() ); } }, _removeActiveLinkClass: function( force ) { //clear out the active button state $.mobile.removeActiveLinkClass( force ); }, _loadUrl: function( to, triggerData, settings ) { // preserve the original target as the dataUrl value will be // simplified eg, removing ui-state, and removing query params // from the hash this is so that users who want to use query // params have access to them in the event bindings for the page // life cycle See issue #5085 settings.target = to; settings.deferred = $.Deferred(); this.load( to, settings ); settings.deferred.done($.proxy(function( url, options, content ) { isPageTransitioning = false; // store the original absolute url so that it can be provided // to events in the triggerData of the subsequent changePage call options.absUrl = triggerData.absUrl; this.transition( content, triggerData, options ); }, this)); settings.deferred.fail($.proxy(function(/* url, options */) { this._removeActiveLinkClass( true ); this._releaseTransitionLock(); this._triggerWithDeprecated( "changefailed", triggerData ); }, this)); }, _triggerPageBeforeChange: function( to, triggerData, settings ) { var pbcEvent = new $.Event( "pagebeforechange" ); $.extend(triggerData, { toPage: to, options: settings }); // NOTE: preserve the original target as the dataUrl value will be // simplified eg, removing ui-state, and removing query params from // the hash this is so that users who want to use query params have // access to them in the event bindings for the page life cycle // See issue #5085 if ( $.type(to) === "string" ) { // if the toPage is a string simply convert it triggerData.absUrl = $.mobile.path.makeUrlAbsolute( to, this._findBaseWithDefault() ); } else { // if the toPage is a jQuery object grab the absolute url stored // in the loadPage callback where it exists triggerData.absUrl = settings.absUrl; } // Let listeners know we're about to change the current page. this.element.trigger( pbcEvent, triggerData ); // If the default behavior is prevented, stop here! if ( pbcEvent.isDefaultPrevented() ) { return false; } return true; }, change: function( to, options ) { // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition // to service the request. if ( isPageTransitioning ) { pageTransitionQueue.unshift( arguments ); return; } var settings = $.extend( {}, $.mobile.changePage.defaults, options ), triggerData = {}; // Make sure we have a fromPage. settings.fromPage = settings.fromPage || this.activePage; // if the page beforechange default is prevented return early if ( !this._triggerPageBeforeChange(to, triggerData, settings) ) { return; } // We allow "pagebeforechange" observers to modify the to in // the trigger data to allow for redirects. Make sure our to is // updated. We also need to re-evaluate whether it is a string, // because an object can also be replaced by a string to = triggerData.toPage; // If the caller passed us a url, call loadPage() // to make sure it is loaded into the DOM. We'll listen // to the promise object it returns so we know when // it is done loading or if an error ocurred. if ( $.type(to) === "string" ) { // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; this._loadUrl( to, triggerData, settings ); } else { this.transition( to, triggerData, settings ); } }, transition: function( toPage, triggerData, settings ) { var fromPage, url, pageUrl, fileUrl, active, activeIsInitialPage, historyDir, pageTitle, isDialog, alreadyThere, newPageTitle, params, cssTransitionDeferred, beforeTransition; // If we are in the midst of a transition, queue the current request. // We'll call changePage() once we're done with the current transition // to service the request. if ( isPageTransitioning ) { // make sure to only queue the to and settings values so the arguments // work with a call to the change method pageTransitionQueue.unshift( [toPage, settings] ); return; } // DEPRECATED - this call only, in favor of the before transition // if the page beforechange default is prevented return early if ( !this._triggerPageBeforeChange(toPage, triggerData, settings) ) { return; } // if the (content|page)beforetransition default is prevented return early // Note, we have to check for both the deprecated and new events beforeTransition = this._triggerWithDeprecated( "beforetransition", triggerData ); if (beforeTransition.deprecatedEvent.isDefaultPrevented() || beforeTransition.event.isDefaultPrevented() ) { return; } // Set the isPageTransitioning flag to prevent any requests from // entering this method while we are in the midst of loading a page // or transitioning. isPageTransitioning = true; // If we are going to the first-page of the application, we need to make // sure settings.dataUrl is set to the application document url. This allows // us to avoid generating a document url with an id hash in the case where the // first-page of the document has an id attribute specified. if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) { settings.dataUrl = $.mobile.path.documentUrl.hrefNoHash; } // The caller passed us a real page DOM element. Update our // internal state and then trigger a transition to the page. fromPage = settings.fromPage; url = ( settings.dataUrl && $.mobile.path.convertUrlToDataUrl(settings.dataUrl) ) || toPage.jqmData( "url" ); // The pageUrl var is usually the same as url, except when url is obscured // as a dialog url. pageUrl always contains the file path pageUrl = url; fileUrl = $.mobile.path.getFilePath( url ); active = $.mobile.navigate.history.getActive(); activeIsInitialPage = $.mobile.navigate.history.activeIndex === 0; historyDir = 0; pageTitle = document.title; isDialog = ( settings.role === "dialog" || toPage.jqmData( "role" ) === "dialog" ) && toPage.jqmData( "dialog" ) !== true; // By default, we prevent changePage requests when the fromPage and toPage // are the same element, but folks that generate content // manually/dynamically and reuse pages want to be able to transition to // the same page. To allow this, they will need to change the default // value of allowSamePageTransition to true, *OR*, pass it in as an // option when they manually call changePage(). It should be noted that // our default transition animations assume that the formPage and toPage // are different elements, so they may behave unexpectedly. It is up to // the developer that turns on the allowSamePageTransitiona option to // either turn off transition animations, or make sure that an appropriate // animation transition is used. if ( fromPage && fromPage[0] === toPage[0] && !settings.allowSamePageTransition ) { isPageTransitioning = false; this._triggerWithDeprecated( "transition", triggerData ); this.element.trigger( "pagechange", triggerData ); // Even if there is no page change to be done, we should keep the // urlHistory in sync with the hash changes if ( settings.fromHashChange ) { $.mobile.navigate.history.direct({ url: url }); } return; } // We need to make sure the page we are given has already been enhanced. toPage.page({ role: settings.role }); // If the changePage request was sent from a hashChange event, check to // see if the page is already within the urlHistory stack. If so, we'll // assume the user hit the forward/back button and will try to match the // transition accordingly. if ( settings.fromHashChange ) { historyDir = settings.direction === "back" ? -1 : 1; } // Kill the keyboard. // XXX_jblas: We need to stop crawling the entire document to kill focus. // Instead, we should be tracking focus with a delegate() // handler so we already have the element in hand at this // point. // Wrap this in a try/catch block since IE9 throw "Unspecified error" if // document.activeElement is undefined when we are in an IFrame. try { if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { $( document.activeElement ).blur(); } else { $( "input:focus, textarea:focus, select:focus" ).blur(); } } catch( e ) {} // Record whether we are at a place in history where a dialog used to be - // if so, do not add a new history entry and do not change the hash either alreadyThere = false; // If we're displaying the page as a dialog, we don't want the url // for the dialog content to be used in the hash. Instead, we want // to append the dialogHashKey to the url of the current page. if ( isDialog && active ) { // on the initial page load active.url is undefined and in that case // should be an empty string. Moving the undefined -> empty string back // into urlHistory.addNew seemed imprudent given undefined better // represents the url state // If we are at a place in history that once belonged to a dialog, reuse // this state without adding to urlHistory and without modifying the // hash. However, if a dialog is already displayed at this point, and // we're about to display another dialog, then we must add another hash // and history entry on top so that one may navigate back to the // original dialog if ( active.url && active.url.indexOf( $.mobile.dialogHashKey ) > -1 && this.activePage && !this.activePage.hasClass( "ui-dialog" ) && $.mobile.navigate.history.activeIndex > 0 ) { settings.changeHash = false; alreadyThere = true; } // Normally, we tack on a dialog hash key, but if this is the location // of a stale dialog, we reuse the URL from the entry url = ( active.url || "" ); // account for absolute urls instead of just relative urls use as hashes if ( !alreadyThere && url.indexOf("#") > -1 ) { url += $.mobile.dialogHashKey; } else { url += "#" + $.mobile.dialogHashKey; } // tack on another dialogHashKey if this is the same as the initial hash // this makes sure that a history entry is created for this dialog if ( $.mobile.navigate.history.activeIndex === 0 && url === $.mobile.navigate.history.initialDst ) { url += $.mobile.dialogHashKey; } } // if title element wasn't found, try the page div data attr too // If this is a deep-link or a reload ( active === undefined ) then just // use pageTitle newPageTitle = ( !active ) ? pageTitle : toPage.jqmData( "title" ) || toPage.children( ":jqmData(role='header')" ).find( ".ui-title" ).text(); if ( !!newPageTitle && pageTitle === document.title ) { pageTitle = newPageTitle; } if ( !toPage.jqmData( "title" ) ) { toPage.jqmData( "title", pageTitle ); } // Make sure we have a transition defined. settings.transition = settings.transition || ( ( historyDir && !activeIsInitialPage ) ? active.transition : undefined ) || ( isDialog ? $.mobile.defaultDialogTransition : $.mobile.defaultPageTransition ); //add page to history stack if it's not back or forward if ( !historyDir && alreadyThere ) { $.mobile.navigate.history.getActive().pageUrl = pageUrl; } // Set the location hash. if ( url && !settings.fromHashChange ) { // rebuilding the hash here since we loose it earlier on // TODO preserve the originally passed in path if ( !$.mobile.path.isPath( url ) && url.indexOf( "#" ) < 0 ) { url = "#" + url; } // TODO the property names here are just silly params = { transition: settings.transition, title: pageTitle, pageUrl: pageUrl, role: settings.role }; if ( settings.changeHash !== false && $.mobile.hashListeningEnabled ) { $.mobile.navigate( url, params, true); } else if ( toPage[ 0 ] !== $.mobile.firstPage[ 0 ] ) { $.mobile.navigate.history.add( url, params ); } } //set page title document.title = pageTitle; //set "toPage" as activePage deprecated in 1.4 remove in 1.5 $.mobile.activePage = toPage; //new way to handle activePage this.activePage = toPage; // If we're navigating back in the URL history, set reverse accordingly. settings.reverse = settings.reverse || historyDir < 0; cssTransitionDeferred = $.Deferred(); this._cssTransition(toPage, fromPage, { transition: settings.transition, reverse: settings.reverse, deferred: cssTransitionDeferred }); cssTransitionDeferred.done($.proxy(function( name, reverse, $to, $from, alreadyFocused ) { $.mobile.removeActiveLinkClass(); //if there's a duplicateCachedPage, remove it from the DOM now that it's hidden if ( settings.duplicateCachedPage ) { settings.duplicateCachedPage.remove(); } // despite visibility: hidden addresses issue #2965 // https://github.com/jquery/jquery-mobile/issues/2965 if ( !alreadyFocused ) { $.mobile.focusPage( toPage ); } this._releaseTransitionLock(); this.element.trigger( "pagechange", triggerData ); this._triggerWithDeprecated( "transition", triggerData ); }, this)); }, // determine the current base url _findBaseWithDefault: function() { var closestBase = ( this.activePage && $.mobile.getClosestBaseUrl( this.activePage ) ); return closestBase || $.mobile.path.documentBase.hrefNoHash; } }); // The following handlers should be bound after mobileinit has been triggered // the following deferred is resolved in the init file $.mobile.navreadyDeferred = $.Deferred(); //these variables make all page containers use the same queue and only navigate one at a time // queue to hold simultanious page transitions var pageTransitionQueue = [], // indicates whether or not page is in process of transitioning isPageTransitioning = false; })( jQuery ); (function( $, undefined ) { // resolved on domready var domreadyDeferred = $.Deferred(), // resolved and nulled on window.load() loadDeferred = $.Deferred(), documentUrl = $.mobile.path.documentUrl, // used to track last vclicked element to make sure its value is added to form data $lastVClicked = null; /* Event Bindings - hashchange, submit, and click */ function findClosestLink( ele ) { while ( ele ) { // Look for the closest element with a nodeName of "a". // Note that we are checking if we have a valid nodeName // before attempting to access it. This is because the // node we get called with could have originated from within // an embedded SVG document where some symbol instance elements // don't have nodeName defined on them, or strings are of type // SVGAnimatedString. if ( ( typeof ele.nodeName === "string" ) && ele.nodeName.toLowerCase() === "a" ) { break; } ele = ele.parentNode; } return ele; } $.mobile.loadPage = function( url, opts ) { var container; opts = opts || {}; container = ( opts.pageContainer || $.mobile.pageContainer ); // create the deferred that will be supplied to loadPage callers // and resolved by the content widget's load method opts.deferred = $.Deferred(); // Preferring to allow exceptions for uninitialized opts.pageContainer // widgets so we know if we need to force init here for users container.pagecontainer( "load", url, opts ); // provide the deferred return opts.deferred.promise(); }; //define vars for interal use /* internal utility functions */ // NOTE Issue #4950 Android phonegap doesn't navigate back properly // when a full page refresh has taken place. It appears that hashchange // and replacestate history alterations work fine but we need to support // both forms of history traversal in our code that uses backward history // movement $.mobile.back = function() { var nav = window.navigator; // if the setting is on and the navigator object is // available use the phonegap navigation capability if ( this.phonegapNavigationEnabled && nav && nav.app && nav.app.backHistory ) { nav.app.backHistory(); } else { $.mobile.pageContainer.pagecontainer( "back" ); } }; // Direct focus to the page title, or otherwise first focusable element $.mobile.focusPage = function ( page ) { var autofocus = page.find( "[autofocus]" ), pageTitle = page.find( ".ui-title:eq(0)" ); if ( autofocus.length ) { autofocus.focus(); return; } if ( pageTitle.length ) { pageTitle.focus(); } else{ page.focus(); } }; // No-op implementation of transition degradation $.mobile._maybeDegradeTransition = $.mobile._maybeDegradeTransition || function( transition ) { return transition; }; // Exposed $.mobile methods $.mobile.changePage = function( to, options ) { $.mobile.pageContainer.pagecontainer( "change", to, options ); }; $.mobile.changePage.defaults = { transition: undefined, reverse: false, changeHash: true, fromHashChange: false, role: undefined, // By default we rely on the role defined by the @data-role attribute. duplicateCachedPage: undefined, pageContainer: undefined, showLoadMsg: true, //loading message shows by default when pages are being fetched during changePage dataUrl: undefined, fromPage: undefined, allowSamePageTransition: false }; $.mobile._registerInternalEvents = function() { var getAjaxFormData = function( $form, calculateOnly ) { var url, ret = true, formData, vclickedName, method; if ( !$.mobile.ajaxEnabled || // test that the form is, itself, ajax false $form.is( ":jqmData(ajax='false')" ) || // test that $.mobile.ignoreContentEnabled is set and // the form or one of it's parents is ajax=false !$form.jqmHijackable().length || $form.attr( "target" ) ) { return false; } url = ( $lastVClicked && $lastVClicked.attr( "formaction" ) ) || $form.attr( "action" ); method = ( $form.attr( "method" ) || "get" ).toLowerCase(); // If no action is specified, browsers default to using the // URL of the document containing the form. Since we dynamically // pull in pages from external documents, the form should submit // to the URL for the source document of the page containing // the form. if ( !url ) { // Get the @data-url for the page containing the form. url = $.mobile.getClosestBaseUrl( $form ); // NOTE: If the method is "get", we need to strip off the query string // because it will get replaced with the new form data. See issue #5710. if ( method === "get" ) { url = $.mobile.path.parseUrl( url ).hrefNoSearch; } if ( url === $.mobile.path.documentBase.hrefNoHash ) { // The url we got back matches the document base, // which means the page must be an internal/embedded page, // so default to using the actual document url as a browser // would. url = documentUrl.hrefNoSearch; } } url = $.mobile.path.makeUrlAbsolute( url, $.mobile.getClosestBaseUrl( $form ) ); if ( ( $.mobile.path.isExternal( url ) && !$.mobile.path.isPermittedCrossDomainRequest( documentUrl, url ) ) ) { return false; } if ( !calculateOnly ) { formData = $form.serializeArray(); if ( $lastVClicked && $lastVClicked[ 0 ].form === $form[ 0 ] ) { vclickedName = $lastVClicked.attr( "name" ); if ( vclickedName ) { // Make sure the last clicked element is included in the form $.each( formData, function( key, value ) { if ( value.name === vclickedName ) { // Unset vclickedName - we've found it in the serialized data already vclickedName = ""; return false; } }); if ( vclickedName ) { formData.push( { name: vclickedName, value: $lastVClicked.attr( "value" ) } ); } } } ret = { url: url, options: { type: method, data: $.param( formData ), transition: $form.jqmData( "transition" ), reverse: $form.jqmData( "direction" ) === "reverse", reloadPage: true } }; } return ret; }; //bind to form submit events, handle with Ajax $.mobile.document.delegate( "form", "submit", function( event ) { var formData; if ( !event.isDefaultPrevented() ) { formData = getAjaxFormData( $( this ) ); if ( formData ) { $.mobile.changePage( formData.url, formData.options ); event.preventDefault(); } } }); //add active state on vclick $.mobile.document.bind( "vclick", function( event ) { var $btn, btnEls, target = event.target, needClosest = false; // if this isn't a left click we don't care. Its important to note // that when the virtual event is generated it will create the which attr if ( event.which > 1 || !$.mobile.linkBindingEnabled ) { return; } // Record that this element was clicked, in case we need it for correct // form submission during the "submit" handler above $lastVClicked = $( target ); // Try to find a target element to which the active class will be applied if ( $.data( target, "mobile-button" ) ) { // If the form will not be submitted via AJAX, do not add active class if ( !getAjaxFormData( $( target ).closest( "form" ), true ) ) { return; } // We will apply the active state to this button widget - the parent // of the input that was clicked will have the associated data if ( target.parentNode ) { target = target.parentNode; } } else { target = findClosestLink( target ); if ( !( target && $.mobile.path.parseUrl( target.getAttribute( "href" ) || "#" ).hash !== "#" ) ) { return; } // TODO teach $.mobile.hijackable to operate on raw dom elements so the // link wrapping can be avoided if ( !$( target ).jqmHijackable().length ) { return; } } // Avoid calling .closest by using the data set during .buttonMarkup() // List items have the button data in the parent of the element clicked if ( !!~target.className.indexOf( "ui-link-inherit" ) ) { if ( target.parentNode ) { btnEls = $.data( target.parentNode, "buttonElements" ); } // Otherwise, look for the data on the target itself } else { btnEls = $.data( target, "buttonElements" ); } // If found, grab the button's outer element if ( btnEls ) { target = btnEls.outer; } else { needClosest = true; } $btn = $( target ); // If the outer element wasn't found by the our heuristics, use .closest() if ( needClosest ) { $btn = $btn.closest( ".ui-btn" ); } if ( $btn.length > 0 && !( $btn.hasClass( "ui-state-disabled" || // DEPRECATED as of 1.4.0 - remove after 1.4.0 release // only ui-state-disabled should be present thereafter $btn.hasClass( "ui-disabled" ) ) ) ) { $.mobile.removeActiveLinkClass( true ); $.mobile.activeClickedLink = $btn; $.mobile.activeClickedLink.addClass( $.mobile.activeBtnClass ); } }); // click routing - direct to HTTP or Ajax, accordingly $.mobile.document.bind( "click", function( event ) { if ( !$.mobile.linkBindingEnabled || event.isDefaultPrevented() ) { return; } var link = findClosestLink( event.target ), $link = $( link ), //remove active link class if external (then it won't be there if you come back) httpCleanup = function() { window.setTimeout(function() { $.mobile.removeActiveLinkClass( true ); }, 200 ); }, baseUrl, href, useDefaultUrlHandling, isExternal, transition, reverse, role; // If a button was clicked, clean up the active class added by vclick above if ( $.mobile.activeClickedLink && $.mobile.activeClickedLink[ 0 ] === event.target.parentNode ) { httpCleanup(); } // If there is no link associated with the click or its not a left // click we want to ignore the click // TODO teach $.mobile.hijackable to operate on raw dom elements so the link wrapping // can be avoided if ( !link || event.which > 1 || !$link.jqmHijackable().length ) { return; } //if there's a data-rel=back attr, go back in history if ( $link.is( ":jqmData(rel='back')" ) ) { $.mobile.back(); return false; } baseUrl = $.mobile.getClosestBaseUrl( $link ); //get href, if defined, otherwise default to empty hash href = $.mobile.path.makeUrlAbsolute( $link.attr( "href" ) || "#", baseUrl ); //if ajax is disabled, exit early if ( !$.mobile.ajaxEnabled && !$.mobile.path.isEmbeddedPage( href ) ) { httpCleanup(); //use default click handling return; } // XXX_jblas: Ideally links to application pages should be specified as // an url to the application document with a hash that is either // the site relative path or id to the page. But some of the // internal code that dynamically generates sub-pages for nested // lists and select dialogs, just write a hash in the link they // create. This means the actual URL path is based on whatever // the current value of the base tag is at the time this code // is called. For now we are just assuming that any url with a // hash in it is an application page reference. if ( href.search( "#" ) !== -1 ) { href = href.replace( /[^#]*#/, "" ); if ( !href ) { //link was an empty hash meant purely //for interaction, so we ignore it. event.preventDefault(); return; } else if ( $.mobile.path.isPath( href ) ) { //we have apath so make it the href we want to load. href = $.mobile.path.makeUrlAbsolute( href, baseUrl ); } else { //we have a simple id so use the documentUrl as its base. href = $.mobile.path.makeUrlAbsolute( "#" + href, documentUrl.hrefNoHash ); } } // Should we handle this link, or let the browser deal with it? useDefaultUrlHandling = $link.is( "[rel='external']" ) || $link.is( ":jqmData(ajax='false')" ) || $link.is( "[target]" ); // Some embedded browsers, like the web view in Phone Gap, allow cross-domain XHR // requests if the document doing the request was loaded via the file:// protocol. // This is usually to allow the application to "phone home" and fetch app specific // data. We normally let the browser handle external/cross-domain urls, but if the // allowCrossDomainPages option is true, we will allow cross-domain http/https // requests to go through our page loading logic. //check for protocol or rel and its not an embedded page //TODO overlap in logic from isExternal, rel=external check should be // moved into more comprehensive isExternalLink isExternal = useDefaultUrlHandling || ( $.mobile.path.isExternal( href ) && !$.mobile.path.isPermittedCrossDomainRequest( documentUrl, href ) ); if ( isExternal ) { httpCleanup(); //use default click handling return; } //use ajax transition = $link.jqmData( "transition" ); reverse = $link.jqmData( "direction" ) === "reverse" || // deprecated - remove by 1.0 $link.jqmData( "back" ); //this may need to be more specific as we use data-rel more role = $link.attr( "data-" + $.mobile.ns + "rel" ) || undefined; $.mobile.changePage( href, { transition: transition, reverse: reverse, role: role, link: $link } ); event.preventDefault(); }); //prefetch pages when anchors with data-prefetch are encountered $.mobile.document.delegate( ".ui-page", "pageshow.prefetch", function() { var urls = []; $( this ).find( "a:jqmData(prefetch)" ).each(function() { var $link = $( this ), url = $link.attr( "href" ); if ( url && $.inArray( url, urls ) === -1 ) { urls.push( url ); $.mobile.loadPage( url, { role: $link.attr( "data-" + $.mobile.ns + "rel" ),prefetch: true } ); } }); }); // TODO ensure that the navigate binding in the content widget happens at the right time $.mobile.pageContainer.pagecontainer(); //set page min-heights to be device specific $.mobile.document.bind( "pageshow", function() { // We need to wait for window.load to make sure that styles have already been rendered, // otherwise heights of external toolbars will have the wrong value if ( loadDeferred ) { loadDeferred.done( $.mobile.resetActivePageHeight ); } else { $.mobile.resetActivePageHeight(); } }); $.mobile.window.bind( "throttledresize", $.mobile.resetActivePageHeight ); };//navreadyDeferred done callback $( function() { domreadyDeferred.resolve(); } ); $.mobile.window.load( function() { // Resolve and null the deferred loadDeferred.resolve(); loadDeferred = null; }); $.when( domreadyDeferred, $.mobile.navreadyDeferred ).done( function() { $.mobile._registerInternalEvents(); } ); })( jQuery ); (function( $, window, undefined ) { // TODO remove direct references to $.mobile and properties, we should // favor injection with params to the constructor $.mobile.Transition = function() { this.init.apply( this, arguments ); }; $.extend($.mobile.Transition.prototype, { toPreClass: " ui-page-pre-in", init: function( name, reverse, $to, $from ) { $.extend(this, { name: name, reverse: reverse, $to: $to, $from: $from, deferred: new $.Deferred() }); }, cleanFrom: function() { this.$from .removeClass( $.mobile.activePageClass + " out in reverse " + this.name ) .height( "" ); }, // NOTE overridden by child object prototypes, noop'd here as defaults beforeDoneIn: function() {}, beforeDoneOut: function() {}, beforeStartOut: function() {}, doneIn: function() { this.beforeDoneIn(); this.$to.removeClass( "out in reverse " + this.name ).height( "" ); this.toggleViewportClass(); // In some browsers (iOS5), 3D transitions block the ability to scroll to the desired location during transition // This ensures we jump to that spot after the fact, if we aren't there already. if ( $.mobile.window.scrollTop() !== this.toScroll ) { this.scrollPage(); } if ( !this.sequential ) { this.$to.addClass( $.mobile.activePageClass ); } this.deferred.resolve( this.name, this.reverse, this.$to, this.$from, true ); }, doneOut: function( screenHeight, reverseClass, none, preventFocus ) { this.beforeDoneOut(); this.startIn( screenHeight, reverseClass, none, preventFocus ); }, hideIn: function( callback ) { // Prevent flickering in phonegap container: see comments at #4024 regarding iOS this.$to.css( "z-index", -10 ); callback.call( this ); this.$to.css( "z-index", "" ); }, scrollPage: function() { // By using scrollTo instead of silentScroll, we can keep things better in order // Just to be precautios, disable scrollstart listening like silentScroll would $.event.special.scrollstart.enabled = false; //if we are hiding the url bar or the page was previously scrolled scroll to hide or return to position if ( $.mobile.hideUrlBar || this.toScroll !== $.mobile.defaultHomeScroll ) { window.scrollTo( 0, this.toScroll ); } // reenable scrollstart listening like silentScroll would setTimeout( function() { $.event.special.scrollstart.enabled = true; }, 150 ); }, startIn: function( screenHeight, reverseClass, none, preventFocus ) { this.hideIn(function() { this.$to.addClass( $.mobile.activePageClass + this.toPreClass ); // Send focus to page as it is now display: block if ( !preventFocus ) { $.mobile.focusPage( this.$to ); } // Set to page height this.$to.height( screenHeight + this.toScroll ); if ( !none ) { this.scrollPage(); } }); this.$to .removeClass( this.toPreClass ) .addClass( this.name + " in " + reverseClass ); if ( !none ) { this.$to.animationComplete( $.proxy(function() { this.doneIn(); }, this )); } else { this.doneIn(); } }, startOut: function( screenHeight, reverseClass, none ) { this.beforeStartOut( screenHeight, reverseClass, none ); // Set the from page's height and start it transitioning out // Note: setting an explicit height helps eliminate tiling in the transitions this.$from .height( screenHeight + $.mobile.window.scrollTop() ) .addClass( this.name + " out" + reverseClass ); }, toggleViewportClass: function() { $.mobile.pageContainer.toggleClass( "ui-mobile-viewport-transitioning viewport-" + this.name ); }, transition: function() { // NOTE many of these could be calculated/recorded in the constructor, it's my // opinion that binding them as late as possible has value with regards to // better transitions with fewer bugs. Ie, it's not guaranteed that the // object will be created and transition will be run immediately after as // it is today. So we wait until transition is invoked to gather the following var none, reverseClass = this.reverse ? " reverse" : "", screenHeight = $.mobile.getScreenHeight(), maxTransitionOverride = $.mobile.maxTransitionWidth !== false && $.mobile.window.width() > $.mobile.maxTransitionWidth; this.toScroll = $.mobile.navigate.history.getActive().lastScroll || $.mobile.defaultHomeScroll; none = !$.support.cssTransitions || !$.support.cssAnimations || maxTransitionOverride || !this.name || this.name === "none" || Math.max( $.mobile.window.scrollTop(), this.toScroll ) > $.mobile.getMaxScrollForTransition(); this.toggleViewportClass(); if ( this.$from && !none ) { this.startOut( screenHeight, reverseClass, none ); } else { this.doneOut( screenHeight, reverseClass, none, true ); } return this.deferred.promise(); } }); })( jQuery, this ); (function( $ ) { $.mobile.SerialTransition = function() { this.init.apply(this, arguments); }; $.extend($.mobile.SerialTransition.prototype, $.mobile.Transition.prototype, { sequential: true, beforeDoneOut: function() { if ( this.$from ) { this.cleanFrom(); } }, beforeStartOut: function( screenHeight, reverseClass, none ) { this.$from.animationComplete($.proxy(function() { this.doneOut( screenHeight, reverseClass, none ); }, this )); } }); })( jQuery ); (function( $ ) { $.mobile.ConcurrentTransition = function() { this.init.apply(this, arguments); }; $.extend($.mobile.ConcurrentTransition.prototype, $.mobile.Transition.prototype, { sequential: false, beforeDoneIn: function() { if ( this.$from ) { this.cleanFrom(); } }, beforeStartOut: function( screenHeight, reverseClass, none ) { this.doneOut( screenHeight, reverseClass, none ); } }); })( jQuery ); (function( $ ) { // generate the handlers from the above var defaultGetMaxScrollForTransition = function() { return $.mobile.getScreenHeight() * 3; }; //transition handler dictionary for 3rd party transitions $.mobile.transitionHandlers = { "sequential": $.mobile.SerialTransition, "simultaneous": $.mobile.ConcurrentTransition }; // Make our transition handler the public default. $.mobile.defaultTransitionHandler = $.mobile.transitionHandlers.sequential; $.mobile.transitionFallbacks = {}; // If transition is defined, check if css 3D transforms are supported, and if not, if a fallback is specified $.mobile._maybeDegradeTransition = function( transition ) { if ( transition && !$.support.cssTransform3d && $.mobile.transitionFallbacks[ transition ] ) { transition = $.mobile.transitionFallbacks[ transition ]; } return transition; }; // Set the getMaxScrollForTransition to default if no implementation was set by user $.mobile.getMaxScrollForTransition = $.mobile.getMaxScrollForTransition || defaultGetMaxScrollForTransition; })( jQuery ); /* * fallback transition for flip in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flip = "fade"; })( jQuery, this ); /* * fallback transition for flow in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.flow = "fade"; })( jQuery, this ); /* * fallback transition for pop in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.pop = "fade"; })( jQuery, this ); /* * fallback transition for slide in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Use the simultaneous transitions handler for slide transitions $.mobile.transitionHandlers.slide = $.mobile.transitionHandlers.simultaneous; // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slide = "fade"; })( jQuery, this ); /* * fallback transition for slidedown in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slidedown = "fade"; })( jQuery, this ); /* * fallback transition for slidefade in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { // Set the slide transitions's fallback to "fade" $.mobile.transitionFallbacks.slidefade = "fade"; })( jQuery, this ); /* * fallback transition for slideup in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.slideup = "fade"; })( jQuery, this ); /* * fallback transition for turn in non-3D supporting browsers (which tend to handle complex transitions poorly in general */ (function( $, window, undefined ) { $.mobile.transitionFallbacks.turn = "fade"; })( jQuery, this ); (function( $, undefined ) { $.mobile.degradeInputs = { color: false, date: false, datetime: false, "datetime-local": false, email: false, month: false, number: false, range: "number", search: "text", tel: false, time: false, url: false, week: false }; // Backcompat remove in 1.5 $.mobile.page.prototype.options.degradeInputs = $.mobile.degradeInputs; // Auto self-init widgets $.mobile.degradeInputsWithin = function( target ) { target = $( target ); // Degrade inputs to avoid poorly implemented native functionality target.find( "input" ).not( $.mobile.page.prototype.keepNativeSelector() ).each(function() { var element = $( this ), type = this.getAttribute( "type" ), optType = $.mobile.degradeInputs[ type ] || "text", html, hasType, findstr, repstr; if ( $.mobile.degradeInputs[ type ] ) { html = $( "<div>" ).html( element.clone() ).html(); // In IE browsers, the type sometimes doesn't exist in the cloned markup, so we replace the closing tag instead hasType = html.indexOf( " type=" ) > -1; findstr = hasType ? /\s+type=["']?\w+['"]?/ : /\/?>/; repstr = " type=\"" + optType + "\" data-" + $.mobile.ns + "type=\"" + type + "\"" + ( hasType ? "" : ">" ); element.replaceWith( html.replace( findstr, repstr ) ); } }); }; })( jQuery ); (function( $, window, undefined ) { $.widget( "mobile.page", $.mobile.page, { options: { // Accepts left, right and none closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true, dialog: false }, _create: function() { this._super(); if ( this.options.dialog ) { $.extend( this, { _inner: this.element.children(), _headerCloseButton: null }); if ( !this.options.enhanced ) { this._setCloseBtn( this.options.closeBtn ); } } }, _enhance: function() { this._super(); // Class the markup for dialog styling and wrap interior if ( this.options.dialog ) { this.element.addClass( "ui-dialog" ) .wrapInner( $( "<div/>", { // ARIA role "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + ( this.options.corners ? " ui-corner-all" : "" ) })); } }, _setOptions: function( options ) { var closeButtonLocation, closeButtonText, currentOpts = this.options; if ( options.corners !== undefined ) { this._inner.toggleClass( "ui-corner-all", !!options.corners ); } if ( options.overlayTheme !== undefined ) { if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) { currentOpts.overlayTheme = options.overlayTheme; this._handlePageBeforeShow(); } } if ( options.closeBtnText !== undefined ) { closeButtonLocation = currentOpts.closeBtn; closeButtonText = options.closeBtnText; } if ( options.closeBtn !== undefined ) { closeButtonLocation = options.closeBtn; } if ( closeButtonLocation ) { this._setCloseBtn( closeButtonLocation, closeButtonText ); } this._super( options ); }, _handlePageBeforeShow: function () { if ( this.options.overlayTheme && this.options.dialog ) { this.removeContainerBackground(); this.setContainerBackground( this.options.overlayTheme ); } else { this._super(); } }, _setCloseBtn: function( location, text ) { var dst, btn = this._headerCloseButton; // Sanitize value location = "left" === location ? "left" : "right" === location ? "right" : "none"; if ( "none" === location ) { if ( btn ) { btn.remove(); btn = null; } } else if ( btn ) { btn.removeClass( "ui-btn-left ui-btn-right" ).addClass( "ui-btn-" + location ); if ( text ) { btn.text( text ); } } else { dst = this._inner.find( ":jqmData(role='header')" ).first(); btn = $( "<a></a>", { "href": "#", "class": "ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-" + location }) .attr( "data-" + $.mobile.ns + "rel", "back" ) .text( text || this.options.closeBtnText || "" ) .prependTo( dst ); } this._headerCloseButton = btn; } }); })( jQuery, this ); (function( $, window, undefined ) { $.widget( "mobile.dialog", { options: { // Accepts left, right and none closeBtn: "left", closeBtnText: "Close", overlayTheme: "a", corners: true }, // Override the theme set by the page plugin on pageshow _handlePageBeforeShow: function() { this._isCloseable = true; if ( this.options.overlayTheme ) { this.element .page( "removeContainerBackground" ) .page( "setContainerBackground", this.options.overlayTheme ); } }, _handlePageBeforeHide: function() { this._isCloseable = false; }, // click and submit events: // - clicks and submits should use the closing transition that the dialog // opened with unless a data-transition is specified on the link/form // - if the click was on the close button, or the link has a data-rel="back" // it'll go back in history naturally _handleVClickSubmit: function( event ) { var attrs, $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ); if ( $target.length && !$target.jqmData( "transition" ) ) { attrs = {}; attrs[ "data-" + $.mobile.ns + "transition" ] = ( $.mobile.navigate.history.getActive() || {} )[ "transition" ] || $.mobile.defaultDialogTransition; attrs[ "data-" + $.mobile.ns + "direction" ] = "reverse"; $target.attr( attrs ); } }, _create: function() { var elem = this.element, opts = this.options; // Class the markup for dialog styling and wrap interior elem.addClass( "ui-dialog" ) .wrapInner( $( "<div/>", { // ARIA role "role" : "dialog", "class" : "ui-dialog-contain ui-overlay-shadow" + ( !!opts.corners ? " ui-corner-all" : "" ) })); $.extend( this, { _isCloseable: false, _inner: elem.children(), _headerCloseButton: null }); this._on( elem, { vclick: "_handleVClickSubmit", submit: "_handleVClickSubmit", pagebeforeshow: "_handlePageBeforeShow", pagebeforehide: "_handlePageBeforeHide" }); this._setCloseBtn( opts.closeBtn ); }, _setOptions: function( options ) { var closeButtonLocation, closeButtonText, currentOpts = this.options; if ( options.corners !== undefined ) { this._inner.toggleClass( "ui-corner-all", !!options.corners ); } if ( options.overlayTheme !== undefined ) { if ( $.mobile.activePage[ 0 ] === this.element[ 0 ] ) { currentOpts.overlayTheme = options.overlayTheme; this._handlePageBeforeShow(); } } if ( options.closeBtnText !== undefined ) { closeButtonLocation = currentOpts.closeBtn; closeButtonText = options.closeBtnText; } if ( options.closeBtn !== undefined ) { closeButtonLocation = options.closeBtn; } if ( closeButtonLocation ) { this._setCloseBtn( closeButtonLocation, closeButtonText ); } this._super( options ); }, _setCloseBtn: function( location, text ) { var dst, btn = this._headerCloseButton; // Sanitize value location = "left" === location ? "left" : "right" === location ? "right" : "none"; if ( "none" === location ) { if ( btn ) { btn.remove(); btn = null; } } else if ( btn ) { btn.removeClass( "ui-btn-left ui-btn-right" ).addClass( "ui-btn-" + location ); if ( text ) { btn.text( text ); } } else { dst = this._inner.find( ":jqmData(role='header')" ).first(); btn = $( "<a></a>", { "role": "button", "href": "#", "class": "ui-btn ui-corner-all ui-icon-delete ui-btn-icon-notext ui-btn-" + location }) .text( text || this.options.closeBtnText || "" ) .prependTo( dst ); this._on( btn, { click: "close" } ); } this._headerCloseButton = btn; }, // Close method goes back in history close: function() { var hist = $.mobile.navigate.history; if ( this._isCloseable ) { this._isCloseable = false; // If the hash listening is enabled and there is at least one preceding history // entry it's ok to go back. Initial pages with the dialog hash state are an example // where the stack check is necessary if ( $.mobile.hashListeningEnabled && hist.activeIndex > 0 ) { $.mobile.back(); } else { $.mobile.pageContainer.pagecontainer( "back" ); } } } }); })( jQuery, this ); (function( $, undefined ) { var rInitialLetter = /([A-Z])/g, // Construct iconpos class from iconpos value iconposClass = function( iconpos ) { return ( "ui-btn-icon-" + ( iconpos === null ? "left" : iconpos ) ); }; $.widget( "mobile.collapsible", { options: { enhanced: false, expandCueText: null, collapseCueText: null, collapsed: true, heading: "h1,h2,h3,h4,h5,h6,legend", collapsedIcon: null, expandedIcon: null, iconpos: null, theme: null, contentTheme: null, inset: null, corners: null, mini: null }, _create: function() { var elem = this.element, ui = { accordion: elem .closest( ":jqmData(role='collapsible-set')," + ":jqmData(role='collapsibleset')" + ( $.mobile.collapsibleset ? ", :mobile-collapsibleset" : "" ) ) .addClass( "ui-collapsible-set" ) }; this._ui = ui; this._renderedOptions = this._getOptions( this.options ); if ( this.options.enhanced ) { ui.heading = $( ".ui-collapsible-heading", this.element[ 0 ] ); ui.content = ui.heading.next(); ui.anchor = $( "a", ui.heading[ 0 ] ).first(); ui.status = ui.anchor.children( ".ui-collapsible-heading-status" ); } else { this._enhance( elem, ui ); } this._on( ui.heading, { "tap": function() { ui.heading.find( "a" ).first().addClass( $.mobile.activeBtnClass ); }, "click": function( event ) { this._handleExpandCollapse( !ui.heading.hasClass( "ui-collapsible-heading-collapsed" ) ); event.preventDefault(); event.stopPropagation(); } }); }, // Adjust the keys inside options for inherited values _getOptions: function( options ) { var key, accordion = this._ui.accordion, accordionWidget = this._ui.accordionWidget; // Copy options options = $.extend( {}, options ); if ( accordion.length && !accordionWidget ) { this._ui.accordionWidget = accordionWidget = accordion.data( "mobile-collapsibleset" ); } for ( key in options ) { // Retrieve the option value first from the options object passed in and, if // null, from the parent accordion or, if that's null too, or if there's no // parent accordion, then from the defaults. options[ key ] = ( options[ key ] != null ) ? options[ key ] : ( accordionWidget ) ? accordionWidget.options[ key ] : accordion.length ? $.mobile.getAttribute( accordion[ 0 ], key.replace( rInitialLetter, "-$1" ).toLowerCase() ): null; if ( null == options[ key ] ) { options[ key ] = $.mobile.collapsible.defaults[ key ]; } } return options; }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _enhance: function( elem, ui ) { var iconclass, opts = this._renderedOptions, contentThemeClass = this._themeClassFromOption( "ui-body-", opts.contentTheme ); elem.addClass( "ui-collapsible " + ( opts.inset ? "ui-collapsible-inset " : "" ) + ( opts.inset && opts.corners ? "ui-corner-all " : "" ) + ( contentThemeClass ? "ui-collapsible-themed-content " : "" ) ); ui.originalHeading = elem.children( this.options.heading ).first(), ui.content = elem .wrapInner( "<div " + "class='ui-collapsible-content " + contentThemeClass + "'></div>" ) .children( ".ui-collapsible-content" ), ui.heading = ui.originalHeading; // Replace collapsibleHeading if it's a legend if ( ui.heading.is( "legend" ) ) { ui.heading = $( "<div role='heading'>"+ ui.heading.html() +"</div>" ); ui.placeholder = $( "<div><!-- placeholder for legend --></div>" ).insertBefore( ui.originalHeading ); ui.originalHeading.remove(); } iconclass = ( opts.collapsed ? ( opts.collapsedIcon ? "ui-icon-" + opts.collapsedIcon : "" ): ( opts.expandedIcon ? "ui-icon-" + opts.expandedIcon : "" ) ); ui.status = $( "<span class='ui-collapsible-heading-status'></span>" ); ui.anchor = ui.heading .detach() //modify markup & attributes .addClass( "ui-collapsible-heading" ) .append( ui.status ) .wrapInner( "<a href='#' class='ui-collapsible-heading-toggle'></a>" ) .find( "a" ) .first() .addClass( "ui-btn " + ( iconclass ? iconclass + " " : "" ) + ( iconclass ? iconposClass( opts.iconpos ) + " " : "" ) + this._themeClassFromOption( "ui-btn-", opts.theme ) + " " + ( opts.mini ? "ui-mini " : "" ) ); //drop heading in before content ui.heading.insertBefore( ui.content ); this._handleExpandCollapse( this.options.collapsed ); return ui; }, refresh: function() { this._applyOptions( this.options ); this._renderedOptions = this._getOptions( this.options ); }, _applyOptions: function( options ) { var isCollapsed, newTheme, oldTheme, hasCorners, hasIcon, elem = this.element, currentOpts = this._renderedOptions, ui = this._ui, anchor = ui.anchor, status = ui.status, opts = this._getOptions( options ); // First and foremost we need to make sure the collapsible is in the proper // state, in case somebody decided to change the collapsed option at the // same time as another option if ( options.collapsed !== undefined ) { this._handleExpandCollapse( options.collapsed ); } isCollapsed = elem.hasClass( "ui-collapsible-collapsed" ); // We only need to apply the cue text for the current state right away. // The cue text for the alternate state will be stored in the options // and applied the next time the collapsible's state is toggled if ( isCollapsed ) { if ( opts.expandCueText !== undefined ) { status.text( opts.expandCueText ); } } else { if ( opts.collapseCueText !== undefined ) { status.text( opts.collapseCueText ); } } // Update icon // Is it supposed to have an icon? hasIcon = // If the collapsedIcon is being set, consult that ( opts.collapsedIcon !== undefined ? opts.collapsedIcon !== false : // Otherwise consult the existing option value currentOpts.collapsedIcon !== false ); // If any icon-related options have changed, make sure the new icon // state is reflected by first removing all icon-related classes // reflecting the current state and then adding all icon-related // classes for the new state if ( !( opts.iconpos === undefined && opts.collapsedIcon === undefined && opts.expandedIcon === undefined ) ) { // Remove all current icon-related classes anchor.removeClass( [ iconposClass( currentOpts.iconpos ) ] .concat( ( currentOpts.expandedIcon ? [ "ui-icon-" + currentOpts.expandedIcon ] : [] ) ) .concat( ( currentOpts.collapsedIcon ? [ "ui-icon-" + currentOpts.collapsedIcon ] : [] ) ) .join( " " ) ); // Add new classes if an icon is supposed to be present if ( hasIcon ) { anchor.addClass( [ iconposClass( opts.iconpos !== undefined ? opts.iconpos : currentOpts.iconpos ) ] .concat( isCollapsed ? [ "ui-icon-" + ( opts.collapsedIcon !== undefined ? opts.collapsedIcon : currentOpts.collapsedIcon ) ] : [ "ui-icon-" + ( opts.expandedIcon !== undefined ? opts.expandedIcon : currentOpts.expandedIcon ) ] ) .join( " " ) ); } } if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-btn-", currentOpts.theme ); newTheme = this._themeClassFromOption( "ui-btn-", opts.theme ); anchor.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.contentTheme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", currentOpts.contentTheme ); newTheme = this._themeClassFromOption( "ui-body-", opts.contentTheme ); ui.content.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.inset !== undefined ) { elem.toggleClass( "ui-collapsible-inset", opts.inset ); hasCorners = !!( opts.inset && ( opts.corners || currentOpts.corners ) ); } if ( opts.corners !== undefined ) { hasCorners = !!( opts.corners && ( opts.inset || currentOpts.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } if ( opts.mini !== undefined ) { anchor.toggleClass( "ui-mini", opts.mini ); } }, _setOptions: function( options ) { this._applyOptions( options ); this._super( options ); this._renderedOptions = this._getOptions( this.options ); }, _handleExpandCollapse: function( isCollapse ) { var opts = this._renderedOptions, ui = this._ui; ui.status.text( isCollapse ? opts.expandCueText : opts.collapseCueText ); ui.heading .toggleClass( "ui-collapsible-heading-collapsed", isCollapse ) .find( "a" ).first() .toggleClass( "ui-icon-" + opts.expandedIcon, !isCollapse ) // logic or cause same icon for expanded/collapsed state would remove the ui-icon-class .toggleClass( "ui-icon-" + opts.collapsedIcon, ( isCollapse || opts.expandedIcon === opts.collapsedIcon ) ) .removeClass( $.mobile.activeBtnClass ); this.element.toggleClass( "ui-collapsible-collapsed", isCollapse ); ui.content .toggleClass( "ui-collapsible-content-collapsed", isCollapse ) .attr( "aria-hidden", isCollapse ) .trigger( "updatelayout" ); this.options.collapsed = isCollapse; this._trigger( isCollapse ? "collapse" : "expand" ); }, expand: function() { this._handleExpandCollapse( false ); }, collapse: function() { this._handleExpandCollapse( true ); }, _destroy: function() { var ui = this._ui, opts = this.options; if ( opts.enhanced ) { return; } if ( ui.placeholder ) { ui.originalHeading.insertBefore( ui.placeholder ); ui.placeholder.remove(); ui.heading.remove(); } else { ui.status.remove(); ui.heading .removeClass( "ui-collapsible-heading ui-collapsible-heading-collapsed" ) .children() .contents() .unwrap(); } ui.anchor.contents().unwrap(); ui.content.contents().unwrap(); this.element .removeClass( "ui-collapsible ui-collapsible-collapsed " + "ui-collapsible-themed-content ui-collapsible-inset ui-corner-all" ); } }); // Defaults to be used by all instances of collapsible if per-instance values // are unset or if nothing is specified by way of inheritance from an accordion. // Note that this hash does not contain options "collapsed" or "heading", // because those are not inheritable. $.mobile.collapsible.defaults = { expandCueText: " click to expand contents", collapseCueText: " click to collapse contents", collapsedIcon: "plus", contentTheme: "inherit", expandedIcon: "minus", iconpos: "left", inset: true, corners: true, theme: "inherit", mini: false }; })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.addFirstLastClasses = { _getVisibles: function( $els, create ) { var visibles; if ( create ) { visibles = $els.not( ".ui-screen-hidden" ); } else { visibles = $els.filter( ":visible" ); if ( visibles.length === 0 ) { visibles = $els.not( ".ui-screen-hidden" ); } } return visibles; }, _addFirstLastClasses: function( $els, $visibles, create ) { $els.removeClass( "ui-first-child ui-last-child" ); $visibles.eq( 0 ).addClass( "ui-first-child" ).end().last().addClass( "ui-last-child" ); if ( !create ) { this.element.trigger( "updatelayout" ); } }, _removeFirstLastClasses: function( $els ) { $els.removeClass( "ui-first-child ui-last-child" ); } }; })( jQuery ); (function( $, undefined ) { var childCollapsiblesSelector = ":mobile-collapsible, " + $.mobile.collapsible.initSelector; $.widget( "mobile.collapsibleset", $.extend( { // The initSelector is deprecated as of 1.4.0. In 1.5.0 we will use // :jqmData(role='collapsibleset') which will allow us to get rid of the line // below altogether, because the autoinit will generate such an initSelector initSelector: ":jqmData(role='collapsible-set'),:jqmData(role='collapsibleset')", options: $.extend( { enhanced: false }, $.mobile.collapsible.defaults ), _handleCollapsibleExpand: function( event ) { var closestCollapsible = $( event.target ).closest( ".ui-collapsible" ); if ( closestCollapsible.parent().is( ":mobile-collapsibleset, :jqmData(role='collapsible-set')" ) ) { closestCollapsible .siblings( ".ui-collapsible:not(.ui-collapsible-collapsed)" ) .collapsible( "collapse" ); } }, _create: function() { var elem = this.element, opts = this.options; $.extend( this, { _classes: "" }); if ( !opts.enhanced ) { elem.addClass( "ui-collapsible-set " + this._themeClassFromOption( "ui-group-theme-", opts.theme ) + " " + ( opts.corners && opts.inset ? "ui-corner-all " : "" ) ); this.element.find( $.mobile.collapsible.initSelector ).collapsible(); } this._on( elem, { collapsibleexpand: "_handleCollapsibleExpand" } ); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : prefix + value ) : "" ); }, _init: function() { this._refresh( true ); // Because the corners are handled by the collapsible itself and the default state is collapsed // That was causing https://github.com/jquery/jquery-mobile/issues/4116 this.element .children( childCollapsiblesSelector ) .filter( ":jqmData(collapsed='false')" ) .collapsible( "expand" ); }, _setOptions: function( options ) { var ret, hasCorners, elem = this.element, themeClass = this._themeClassFromOption( "ui-group-theme-", options.theme ); if ( themeClass ) { elem .removeClass( this._themeClassFromOption( "ui-group-theme-", this.options.theme ) ) .addClass( themeClass ); } if ( options.inset !== undefined ) { hasCorners = !!( options.inset && ( options.corners || this.options.corners ) ); } if ( options.corners !== undefined ) { hasCorners = !!( options.corners && ( options.inset || this.options.inset ) ); } if ( hasCorners !== undefined ) { elem.toggleClass( "ui-corner-all", hasCorners ); } ret = this._super( options ); this.element.children( ":mobile-collapsible" ).collapsible( "refresh" ); return ret; }, _destroy: function() { var el = this.element; this._removeFirstLastClasses( el.children( childCollapsiblesSelector ) ); el .removeClass( "ui-collapsible-set ui-corner-all " + this._themeClassFromOption( "ui-group-theme-", this.options.theme ) ) .children( ":mobile-collapsible" ) .collapsible( "destroy" ); }, _refresh: function( create ) { var collapsiblesInSet = this.element.children( childCollapsiblesSelector ); this.element.find( $.mobile.collapsible.initSelector ).not( ".ui-collapsible" ).collapsible(); this._addFirstLastClasses( collapsiblesInSet, this._getVisibles( collapsiblesInSet, create ), create ); }, refresh: function() { this._refresh( false ); } }, $.mobile.behaviors.addFirstLastClasses ) ); })( jQuery ); (function( $, undefined ) { // Deprecated in 1.4 $.fn.fieldcontain = function(/* options */) { return this.addClass( "ui-field-contain" ); }; })( jQuery ); (function( $, undefined ) { $.fn.grid = function( options ) { return this.each(function() { var $this = $( this ), o = $.extend({ grid: null }, options ), $kids = $this.children(), gridCols = { solo:1, a:2, b:3, c:4, d:5 }, grid = o.grid, iterator, letter; if ( !grid ) { if ( $kids.length <= 5 ) { for ( letter in gridCols ) { if ( gridCols[ letter ] === $kids.length ) { grid = letter; } } } else { grid = "a"; $this.addClass( "ui-grid-duo" ); } } iterator = gridCols[grid]; $this.addClass( "ui-grid-" + grid ); $kids.filter( ":nth-child(" + iterator + "n+1)" ).addClass( "ui-block-a" ); if ( iterator > 1 ) { $kids.filter( ":nth-child(" + iterator + "n+2)" ).addClass( "ui-block-b" ); } if ( iterator > 2 ) { $kids.filter( ":nth-child(" + iterator + "n+3)" ).addClass( "ui-block-c" ); } if ( iterator > 3 ) { $kids.filter( ":nth-child(" + iterator + "n+4)" ).addClass( "ui-block-d" ); } if ( iterator > 4 ) { $kids.filter( ":nth-child(" + iterator + "n+5)" ).addClass( "ui-block-e" ); } }); }; })( jQuery ); (function( $, undefined ) { $.widget( "mobile.navbar", { options: { iconpos: "top", grid: null }, _create: function() { var $navbar = this.element, $navbtns = $navbar.find( "a" ), iconpos = $navbtns.filter( ":jqmData(icon)" ).length ? this.options.iconpos : undefined; $navbar.addClass( "ui-navbar" ) .attr( "role", "navigation" ) .find( "ul" ) .jqmEnhanceable() .grid({ grid: this.options.grid }); $navbtns .each( function() { var icon = $.mobile.getAttribute( this, "icon" ), theme = $.mobile.getAttribute( this, "theme" ), classes = "ui-btn"; if ( theme ) { classes += " ui-btn-" + theme; } if ( icon ) { classes += " ui-icon-" + icon + " ui-btn-icon-" + iconpos; } $( this ).addClass( classes ); }); $navbar.delegate( "a", "vclick", function( /* event */ ) { var activeBtn = $( this ); if ( !( activeBtn.hasClass( "ui-state-disabled" ) || // DEPRECATED as of 1.4.0 - remove after 1.4.0 release // only ui-state-disabled should be present thereafter activeBtn.hasClass( "ui-disabled" ) || activeBtn.hasClass( $.mobile.activeBtnClass ) ) ) { $navbtns.removeClass( $.mobile.activeBtnClass ); activeBtn.addClass( $.mobile.activeBtnClass ); // The code below is a workaround to fix #1181 $( document ).one( "pagehide", function() { activeBtn.removeClass( $.mobile.activeBtnClass ); }); } }); // Buttons in the navbar with ui-state-persist class should regain their active state before page show $navbar.closest( ".ui-page" ).bind( "pagebeforeshow", function() { $navbtns.filter( ".ui-state-persist" ).addClass( $.mobile.activeBtnClass ); }); } }); })( jQuery ); (function( $, undefined ) { var getAttr = $.mobile.getAttribute; $.widget( "mobile.listview", $.extend( { options: { theme: null, countTheme: null, /* Deprecated in 1.4 */ dividerTheme: null, icon: "carat-r", splitIcon: "carat-r", splitTheme: null, corners: true, shadow: true, inset: false }, _create: function() { var t = this, listviewClasses = ""; listviewClasses += t.options.inset ? " ui-listview-inset" : ""; if ( !!t.options.inset ) { listviewClasses += t.options.corners ? " ui-corner-all" : ""; listviewClasses += t.options.shadow ? " ui-shadow" : ""; } // create listview markup t.element.addClass( " ui-listview" + listviewClasses ); t.refresh( true ); }, // TODO: Remove in 1.5 _findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) { var dict = {}; dict[ lcName ] = dict[ ucName ] = true; while ( ele ) { if ( dict[ ele.nodeName ] ) { return ele; } ele = ele[ nextProp ]; } return null; }, // TODO: Remove in 1.5 _addThumbClasses: function( containers ) { var i, img, len = containers.length; for ( i = 0; i < len; i++ ) { img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) ); if ( img.length ) { $( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.hasClass( "ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" ); } } }, _getChildrenByTagName: function( ele, lcName, ucName ) { var results = [], dict = {}; dict[ lcName ] = dict[ ucName ] = true; ele = ele.firstChild; while ( ele ) { if ( dict[ ele.nodeName ] ) { results.push( ele ); } ele = ele.nextSibling; } return $( results ); }, _beforeListviewRefresh: $.noop, _afterListviewRefresh: $.noop, refresh: function( create ) { var buttonClass, pos, numli, item, itemClass, itemTheme, itemIcon, icon, a, isDivider, startCount, newStartCount, value, last, splittheme, splitThemeClass, spliticon, altButtonClass, dividerTheme, li, o = this.options, $list = this.element, ol = !!$.nodeName( $list[ 0 ], "ol" ), start = $list.attr( "start" ), itemClassDict = {}, countBubbles = $list.find( ".ui-li-count" ), countTheme = getAttr( $list[ 0 ], "counttheme" ) || this.options.countTheme, countThemeClass = countTheme ? "ui-body-" + countTheme : "ui-body-inherit"; if ( o.theme ) { $list.addClass( "ui-group-theme-" + o.theme ); } // Check if a start attribute has been set while taking a value of 0 into account if ( ol && ( start || start === 0 ) ) { startCount = parseInt( start, 10 ) - 1; $list.css( "counter-reset", "listnumbering " + startCount ); } this._beforeListviewRefresh(); li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ); for ( pos = 0, numli = li.length; pos < numli; pos++ ) { item = li.eq( pos ); itemClass = ""; if ( create || item[ 0 ].className.search( /\bui-li-static\b|\bui-li-divider\b/ ) < 0 ) { a = this._getChildrenByTagName( item[ 0 ], "a", "A" ); isDivider = ( getAttr( item[ 0 ], "role" ) === "list-divider" ); value = item.attr( "value" ); itemTheme = getAttr( item[ 0 ], "theme" ); if ( a.length && a[ 0 ].className.search( /\bui-btn\b/ ) < 0 && !isDivider ) { itemIcon = getAttr( item[ 0 ], "icon" ); icon = ( itemIcon === false ) ? false : ( itemIcon || o.icon ); // TODO: Remove in 1.5 together with links.js (links.js / .ui-link deprecated in 1.4) a.removeClass( "ui-link" ); buttonClass = "ui-btn"; if ( itemTheme ) { buttonClass += " ui-btn-" + itemTheme; } if ( a.length > 1 ) { itemClass = "ui-li-has-alt"; last = a.last(); splittheme = getAttr( last[ 0 ], "theme" ) || o.splitTheme || getAttr( item[ 0 ], "theme", true ); splitThemeClass = splittheme ? " ui-btn-" + splittheme : ""; spliticon = getAttr( last[ 0 ], "icon" ) || getAttr( item[ 0 ], "icon" ) || o.splitIcon; altButtonClass = "ui-btn ui-btn-icon-notext ui-icon-" + spliticon + splitThemeClass; last .attr( "title", $.trim( last.getEncodedText() ) ) .addClass( altButtonClass ) .empty(); } else if ( icon ) { buttonClass += " ui-btn-icon-right ui-icon-" + icon; } a.first().addClass( buttonClass ); } else if ( isDivider ) { dividerTheme = ( getAttr( item[ 0 ], "theme" ) || o.dividerTheme || o.theme ); itemClass = "ui-li-divider ui-bar-" + ( dividerTheme ? dividerTheme : "inherit" ); item.attr( "role", "heading" ); } else if ( a.length <= 0 ) { itemClass = "ui-li-static ui-body-" + ( itemTheme ? itemTheme : "inherit" ); } if ( ol && value ) { newStartCount = parseInt( value , 10 ) - 1; item.css( "counter-reset", "listnumbering " + newStartCount ); } } // Instead of setting item class directly on the list item // at this point in time, push the item into a dictionary // that tells us what class to set on it so we can do this after this // processing loop is finished. if ( !itemClassDict[ itemClass ] ) { itemClassDict[ itemClass ] = []; } itemClassDict[ itemClass ].push( item[ 0 ] ); } // Set the appropriate listview item classes on each list item. // The main reason we didn't do this // in the for-loop above is because we can eliminate per-item function overhead // by calling addClass() and children() once or twice afterwards. This // can give us a significant boost on platforms like WP7.5. for ( itemClass in itemClassDict ) { $( itemClassDict[ itemClass ] ).addClass( itemClass ); } countBubbles.each( function() { $( this ).closest( "li" ).addClass( "ui-li-has-count" ); }); if ( countThemeClass ) { countBubbles.addClass( countThemeClass ); } // Deprecated in 1.4. From 1.5 you have to add class ui-li-has-thumb or ui-li-has-icon to the LI. this._addThumbClasses( li ); this._addThumbClasses( li.find( ".ui-btn" ) ); this._afterListviewRefresh(); this._addFirstLastClasses( li, this._getVisibles( li, create ), create ); } }, $.mobile.behaviors.addFirstLastClasses ) ); })( jQuery ); (function( $, undefined ) { function defaultAutodividersSelector( elt ) { // look for the text in the given element var text = $.trim( elt.text() ) || null; if ( !text ) { return null; } // create the text for the divider (first uppercased letter) text = text.slice( 0, 1 ).toUpperCase(); return text; } $.widget( "mobile.listview", $.mobile.listview, { options: { autodividers: false, autodividersSelector: defaultAutodividersSelector }, _beforeListviewRefresh: function() { if ( this.options.autodividers ) { this._replaceDividers(); this._superApply( arguments ); } }, _replaceDividers: function() { var i, lis, li, dividerText, lastDividerText = null, list = this.element, divider; list.children( "li:jqmData(role='list-divider')" ).remove(); lis = list.children( "li" ); for ( i = 0; i < lis.length ; i++ ) { li = lis[ i ]; dividerText = this.options.autodividersSelector( $( li ) ); if ( dividerText && lastDividerText !== dividerText ) { divider = document.createElement( "li" ); divider.appendChild( document.createTextNode( dividerText ) ); divider.setAttribute( "data-" + $.mobile.ns + "role", "list-divider" ); li.parentNode.insertBefore( divider, li ); } lastDividerText = dividerText; } } }); })( jQuery ); (function( $, undefined ) { var rdivider = /(^|\s)ui-li-divider($|\s)/, rhidden = /(^|\s)ui-screen-hidden($|\s)/; $.widget( "mobile.listview", $.mobile.listview, { options: { hideDividers: false }, _afterListviewRefresh: function() { var items, idx, item, hideDivider = true; this._superApply( arguments ); if ( this.options.hideDividers ) { items = this._getChildrenByTagName( this.element[ 0 ], "li", "LI" ); for ( idx = items.length - 1 ; idx > -1 ; idx-- ) { item = items[ idx ]; if ( item.className.match( rdivider ) ) { if ( hideDivider ) { item.className = item.className + " ui-screen-hidden"; } hideDivider = true; } else { if ( !item.className.match( rhidden ) ) { hideDivider = false; } } } } } }); })( jQuery ); (function( $, undefined ) { $.mobile.nojs = function( target ) { $( ":jqmData(role='nojs')", target ).addClass( "ui-nojs" ); }; })( jQuery ); (function( $, undefined ) { $.mobile.behaviors.formReset = { _handleFormReset: function() { this._on( this.element.closest( "form" ), { reset: function() { this._delay( "_reset" ); } }); } }; })( jQuery ); /* * "checkboxradio" plugin */ (function( $, undefined ) { var escapeId = $.mobile.path.hashToSelector; $.widget( "mobile.checkboxradio", $.extend( { initSelector: "input:not( :jqmData(role='flipswitch' ) )[type='checkbox'],input[type='radio']:not( :jqmData(role='flipswitch' ))", options: { theme: "inherit", mini: false, wrapperClass: null, enhanced: false, iconpos: "left" }, _create: function() { var input = this.element, o = this.options, inheritAttr = function( input, dataAttr ) { return input.jqmData( dataAttr ) || input.closest( "form, fieldset" ).jqmData( dataAttr ); }, // NOTE: Windows Phone could not find the label through a selector // filter works though. parentLabel = input.closest( "label" ), label = parentLabel.length ? parentLabel : input .closest( "form, fieldset, :jqmData(role='page'), :jqmData(role='dialog')" ) .find( "label" ) .filter( "[for='" + escapeId( input[0].id ) + "']" ) .first(), inputtype = input[0].type, checkedClass = "ui-" + inputtype + "-on", uncheckedClass = "ui-" + inputtype + "-off"; if ( inputtype !== "checkbox" && inputtype !== "radio" ) { return; } if ( this.element[0].disabled ) { this.options.disabled = true; } o.iconpos = inheritAttr( input, "iconpos" ) || label.attr( "data-" + $.mobile.ns + "iconpos" ) || o.iconpos, // Establish options o.mini = inheritAttr( input, "mini" ) || o.mini; // Expose for other methods $.extend( this, { input: input, label: label, parentLabel: parentLabel, inputtype: inputtype, checkedClass: checkedClass, uncheckedClass: uncheckedClass }); if ( !this.options.enhanced ) { this._enhance(); } this._on( label, { vmouseover: "_handleLabelVMouseOver", vclick: "_handleLabelVClick" }); this._on( input, { vmousedown: "_cacheVals", vclick: "_handleInputVClick", focus: "_handleInputFocus", blur: "_handleInputBlur" }); this._handleFormReset(); this.refresh(); }, _enhance: function() { this.label.addClass( "ui-btn ui-corner-all"); if ( this.parentLabel.length > 0 ) { this.input.add( this.label ).wrapAll( this._wrapper() ); } else { //this.element.replaceWith( this.input.add( this.label ).wrapAll( this._wrapper() ) ); this.element.wrap( this._wrapper() ); this.element.parent().prepend( this.label ); } // Wrap the input + label in a div this._setOptions({ "theme": this.options.theme, "iconpos": this.options.iconpos, "mini": this.options.mini }); }, _wrapper: function() { return $( "<div class='" + ( this.options.wrapperClass ? this.options.wrapperClass : "" ) + " ui-" + this.inputtype + ( this.options.disabled ? " ui-state-disabled" : "" ) + "' ></div>" ); }, _handleInputFocus: function() { this.label.addClass( $.mobile.focusClass ); }, _handleInputBlur: function() { this.label.removeClass( $.mobile.focusClass ); }, _handleInputVClick: function() { // Adds checked attribute to checked input when keyboard is used this.element.prop( "checked", this.element.is( ":checked" ) ); this._getInputSet().not( this.element ).prop( "checked", false ); this._updateAll(); }, _handleLabelVMouseOver: function( event ) { if ( this.label.parent().hasClass( "ui-state-disabled" ) ) { event.stopPropagation(); } }, _handleLabelVClick: function( event ) { var input = this.element; if ( input.is( ":disabled" ) ) { event.preventDefault(); return; } this._cacheVals(); input.prop( "checked", this.inputtype === "radio" && true || !input.prop( "checked" ) ); // trigger click handler's bound directly to the input as a substitute for // how label clicks behave normally in the browsers // TODO: it would be nice to let the browser's handle the clicks and pass them // through to the associate input. we can swallow that click at the parent // wrapper element level input.triggerHandler( "click" ); // Input set for common radio buttons will contain all the radio // buttons, but will not for checkboxes. clearing the checked status // of other radios ensures the active button state is applied properly this._getInputSet().not( input ).prop( "checked", false ); this._updateAll(); return false; }, _cacheVals: function() { this._getInputSet().each( function() { $( this ).attr("data-" + $.mobile.ns + "cacheVal", this.checked ); }); }, // Returns those radio buttons that are supposed to be in the same group as // this radio button. In the case of a checkbox or a radio lacking a name // attribute, it returns this.element. _getInputSet: function() { var selector, formId, radio = this.element[ 0 ], name = radio.name, form = radio.form, doc = this.element.parents().last().get( 0 ), // A radio is always a member of its own group radios = this.element; // Only start running selectors if this is an attached radio button with a name if ( name && this.inputtype === "radio" && doc ) { selector = "input[type='radio'][name='" + escapeId( name ) + "']"; // If we're inside a form if ( form ) { formId = form.id; // If the form has an ID, collect radios scattered throught the document which // nevertheless are part of the form by way of the value of their form attribute if ( formId ) { radios = $( selector + "[form='" + escapeId( formId ) + "']", doc ); } // Also add to those the radios in the form itself radios = $( form ).find( selector ).filter( function() { // Some radios inside the form may belong to some other form by virtue of // having a form attribute defined on them, so we must filter them out here return ( this.form === form ); }).add( radios ); // If we're outside a form } else { // Collect all those radios which are also outside of a form and match our name radios = $( selector, doc ).filter( function() { return !this.form; }); } } return radios; }, _updateAll: function() { var self = this; this._getInputSet().each( function() { var $this = $( this ); if ( this.checked || self.inputtype === "checkbox" ) { $this.trigger( "change" ); } }) .checkboxradio( "refresh" ); }, _reset: function() { this.refresh(); }, // Is the widget supposed to display an icon? _hasIcon: function() { var controlgroup, controlgroupWidget, controlgroupConstructor = $.mobile.controlgroup; // If the controlgroup widget is defined ... if ( controlgroupConstructor ) { controlgroup = this.element.closest( ":mobile-controlgroup," + controlgroupConstructor.prototype.initSelector ); // ... and the checkbox is in a controlgroup ... if ( controlgroup.length > 0 ) { // ... look for a controlgroup widget instance, and ... controlgroupWidget = $.data( controlgroup[ 0 ], "mobile-controlgroup" ); // ... if found, decide based on the option value, ... return ( ( controlgroupWidget ? controlgroupWidget.options.type : // ... otherwise decide based on the "type" data attribute. controlgroup.attr( "data-" + $.mobile.ns + "type" ) ) !== "horizontal" ); } } // Normally, the widget displays an icon. return true; }, refresh: function() { var hasIcon = this._hasIcon(), isChecked = this.element[ 0 ].checked, active = $.mobile.activeBtnClass, iconposClass = "ui-btn-icon-" + this.options.iconpos, addClasses = [], removeClasses = []; if ( hasIcon ) { removeClasses.push( active ); addClasses.push( iconposClass ); } else { removeClasses.push( iconposClass ); ( isChecked ? addClasses : removeClasses ).push( active ); } if ( isChecked ) { addClasses.push( this.checkedClass ); removeClasses.push( this.uncheckedClass ); } else { addClasses.push( this.uncheckedClass ); removeClasses.push( this.checkedClass ); } this.label .addClass( addClasses.join( " " ) ) .removeClass( removeClasses.join( " " ) ); }, widget: function() { return this.label.parent(); }, _setOptions: function( options ) { var label = this.label, currentOptions = this.options, outer = this.widget(), hasIcon = this._hasIcon(); if ( options.disabled !== undefined ) { this.input.prop( "disabled", !!options.disabled ); outer.toggleClass( "ui-state-disabled", !!options.disabled ); } if ( options.mini !== undefined ) { outer.toggleClass( "ui-mini", !!options.mini ); } if ( options.theme !== undefined ) { label .removeClass( "ui-btn-" + currentOptions.theme ) .addClass( "ui-btn-" + options.theme ); } if ( options.wrapperClass !== undefined ) { outer .removeClass( currentOptions.wrapperClass ) .addClass( options.wrapperClass ); } if ( options.iconpos !== undefined && hasIcon ) { label.removeClass( "ui-btn-icon-" + currentOptions.iconpos ).addClass( "ui-btn-icon-" + options.iconpos ); } else if ( !hasIcon ) { label.removeClass( "ui-btn-icon-" + currentOptions.iconpos ); } this._super( options ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.button", { initSelector: "input[type='button'], input[type='submit'], input[type='reset']", options: { theme: null, icon: null, iconpos: "left", iconshadow: false, /* TODO: Deprecated in 1.4, remove in 1.5. */ corners: true, shadow: true, inline: null, mini: null, wrapperClass: null, enhanced: false }, _create: function() { if ( this.element.is( ":disabled" ) ) { this.options.disabled = true; } if ( !this.options.enhanced ) { this._enhance(); } $.extend( this, { wrapper: this.element.parent() }); this._on( { focus: function() { this.widget().addClass( $.mobile.focusClass ); }, blur: function() { this.widget().removeClass( $.mobile.focusClass ); } }); this.refresh( true ); }, _enhance: function() { this.element.wrap( this._button() ); }, _button: function() { var options = this.options, iconClasses = this._getIconClasses( this.options ); return $("<div class='ui-btn ui-input-btn" + ( options.wrapperClass ? " " + options.wrapperClass : "" ) + ( options.theme ? " ui-btn-" + options.theme : "" ) + ( options.corners ? " ui-corner-all" : "" ) + ( options.shadow ? " ui-shadow" : "" ) + ( options.inline ? " ui-btn-inline" : "" ) + ( options.mini ? " ui-mini" : "" ) + ( options.disabled ? " ui-state-disabled" : "" ) + ( iconClasses ? ( " " + iconClasses ) : "" ) + "' >" + this.element.val() + "</div>" ); }, widget: function() { return this.wrapper; }, _destroy: function() { this.element.insertBefore( this.button ); this.button.remove(); }, _getIconClasses: function( options ) { return ( options.icon ? ( "ui-icon-" + options.icon + ( options.iconshadow ? " ui-shadow-icon" : "" ) + /* TODO: Deprecated in 1.4, remove in 1.5. */ " ui-btn-icon-" + options.iconpos ) : "" ); }, _setOptions: function( options ) { var outer = this.widget(); if ( options.theme !== undefined ) { outer .removeClass( this.options.theme ) .addClass( "ui-btn-" + options.theme ); } if ( options.corners !== undefined ) { outer.toggleClass( "ui-corner-all", options.corners ); } if ( options.shadow !== undefined ) { outer.toggleClass( "ui-shadow", options.shadow ); } if ( options.inline !== undefined ) { outer.toggleClass( "ui-btn-inline", options.inline ); } if ( options.mini !== undefined ) { outer.toggleClass( "ui-mini", options.mini ); } if ( options.disabled !== undefined ) { this.element.prop( "disabled", options.disabled ); outer.toggleClass( "ui-state-disabled", options.disabled ); } if ( options.icon !== undefined || options.iconshadow !== undefined || /* TODO: Deprecated in 1.4, remove in 1.5. */ options.iconpos !== undefined ) { outer .removeClass( this._getIconClasses( this.options ) ) .addClass( this._getIconClasses( $.extend( {}, this.options, options ) ) ); } this._super( options ); }, refresh: function( create ) { var originalElement, isDisabled = this.element.prop( "disabled" ); if ( this.options.icon && this.options.iconpos === "notext" && this.element.attr( "title" ) ) { this.element.attr( "title", this.element.val() ); } if ( !create ) { originalElement = this.element.detach(); $( this.wrapper ).text( this.element.val() ).append( originalElement ); } if ( this.options.disabled !== isDisabled ) { this._setOptions({ disabled: isDisabled }); } } }); })( jQuery ); (function( $ ) { var meta = $( "meta[name=viewport]" ), initialContent = meta.attr( "content" ), disabledZoom = initialContent + ",maximum-scale=1, user-scalable=no", enabledZoom = initialContent + ",maximum-scale=10, user-scalable=yes", disabledInitially = /(user-scalable[\s]*=[\s]*no)|(maximum-scale[\s]*=[\s]*1)[$,\s]/.test( initialContent ); $.mobile.zoom = $.extend( {}, { enabled: !disabledInitially, locked: false, disable: function( lock ) { if ( !disabledInitially && !$.mobile.zoom.locked ) { meta.attr( "content", disabledZoom ); $.mobile.zoom.enabled = false; $.mobile.zoom.locked = lock || false; } }, enable: function( unlock ) { if ( !disabledInitially && ( !$.mobile.zoom.locked || unlock === true ) ) { meta.attr( "content", enabledZoom ); $.mobile.zoom.enabled = true; $.mobile.zoom.locked = false; } }, restore: function() { if ( !disabledInitially ) { meta.attr( "content", initialContent ); $.mobile.zoom.enabled = true; } } }); }( jQuery )); (function( $, undefined ) { $.widget( "mobile.textinput", { initSelector: "input[type='text']," + "input[type='search']," + ":jqmData(type='search')," + "input[type='number']," + ":jqmData(type='number')," + "input[type='password']," + "input[type='email']," + "input[type='url']," + "input[type='tel']," + "textarea," + "input[type='time']," + "input[type='date']," + "input[type='month']," + "input[type='week']," + "input[type='datetime']," + "input[type='datetime-local']," + "input[type='color']," + "input:not([type])," + "input[type='file']", options: { theme: null, corners: true, mini: false, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, wrapperClass: "", enhanced: false }, _create: function() { var options = this.options, isSearch = this.element.is( "[type='search'], :jqmData(type='search')" ), isTextarea = this.element[ 0 ].tagName === "TEXTAREA", isRange = this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='range']" ), inputNeedsWrap = ( (this.element.is( "input" ) || this.element.is( "[data-" + ( $.mobile.ns || "" ) + "type='search']" ) ) && !isRange ); if ( this.element.prop( "disabled" ) ) { options.disabled = true; } $.extend( this, { classes: this._classesFromOptions(), isSearch: isSearch, isTextarea: isTextarea, isRange: isRange, inputNeedsWrap: inputNeedsWrap }); this._autoCorrect(); if ( !options.enhanced ) { this._enhance(); } this._on( { "focus": "_handleFocus", "blur": "_handleBlur" }); }, refresh: function() { this.setOptions({ "disabled" : this.element.is( ":disabled" ) }); }, _enhance: function() { var elementClasses = []; if ( this.isTextarea ) { elementClasses.push( "ui-input-text" ); } if ( this.isTextarea || this.isRange ) { elementClasses.push( "ui-shadow-inset" ); } //"search" and "text" input widgets if ( this.inputNeedsWrap ) { this.element.wrap( this._wrap() ); } else { elementClasses = elementClasses.concat( this.classes ); } this.element.addClass( elementClasses.join( " " ) ); }, widget: function() { return ( this.inputNeedsWrap ) ? this.element.parent() : this.element; }, _classesFromOptions: function() { var options = this.options, classes = []; classes.push( "ui-body-" + ( ( options.theme === null ) ? "inherit" : options.theme ) ); if ( options.corners ) { classes.push( "ui-corner-all" ); } if ( options.mini ) { classes.push( "ui-mini" ); } if ( options.disabled ) { classes.push( "ui-state-disabled" ); } if ( options.wrapperClass ) { classes.push( options.wrapperClass ); } return classes; }, _wrap: function() { return $( "<div class='" + ( this.isSearch ? "ui-input-search " : "ui-input-text " ) + this.classes.join( " " ) + " " + "ui-shadow-inset'></div>" ); }, _autoCorrect: function() { // XXX: Temporary workaround for issue 785 (Apple bug 8910589). // Turn off autocorrect and autocomplete on non-iOS 5 devices // since the popup they use can't be dismissed by the user. Note // that we test for the presence of the feature by looking for // the autocorrect property on the input element. We currently // have no test for iOS 5 or newer so we're temporarily using // the touchOverflow support flag for jQM 1.0. Yes, I feel dirty. // - jblas if ( typeof this.element[0].autocorrect !== "undefined" && !$.support.touchOverflow ) { // Set the attribute instead of the property just in case there // is code that attempts to make modifications via HTML. this.element[0].setAttribute( "autocorrect", "off" ); this.element[0].setAttribute( "autocomplete", "off" ); } }, _handleBlur: function() { this.widget().removeClass( $.mobile.focusClass ); if ( this.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }, _handleFocus: function() { // In many situations, iOS will zoom into the input upon tap, this // prevents that from happening if ( this.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } this.widget().addClass( $.mobile.focusClass ); }, _setOptions: function ( options ) { var outer = this.widget(); this._super( options ); if ( !( options.disabled === undefined && options.mini === undefined && options.corners === undefined && options.theme === undefined && options.wrapperClass === undefined ) ) { outer.removeClass( this.classes.join( " " ) ); this.classes = this._classesFromOptions(); outer.addClass( this.classes.join( " " ) ); } if ( options.disabled !== undefined ) { this.element.prop( "disabled", !!options.disabled ); } }, _destroy: function() { if ( this.options.enhanced ) { return; } if ( this.inputNeedsWrap ) { this.element.unwrap(); } this.element.removeClass( "ui-input-text " + this.classes.join( " " ) ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.slider", $.extend( { initSelector: "input[type='range'], :jqmData(type='range'), :jqmData(role='slider')", widgetEventPrefix: "slide", options: { theme: null, trackTheme: null, corners: true, mini: false, highlight: false }, _create: function() { // TODO: Each of these should have comments explain what they're for var self = this, control = this.element, trackTheme = this.options.trackTheme || $.mobile.getAttribute( control[ 0 ], "theme" ), trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", cornerClass = ( this.options.corners || control.jqmData( "corners" ) ) ? " ui-corner-all" : "", miniClass = ( this.options.mini || control.jqmData( "mini" ) ) ? " ui-mini" : "", cType = control[ 0 ].nodeName.toLowerCase(), isToggleSwitch = ( cType === "select" ), isRangeslider = control.parent().is( ":jqmData(role='rangeslider')" ), selectClass = ( isToggleSwitch ) ? "ui-slider-switch" : "", controlID = control.attr( "id" ), $label = $( "[for='" + controlID + "']" ), labelID = $label.attr( "id" ) || controlID + "-label", min = !isToggleSwitch ? parseFloat( control.attr( "min" ) ) : 0, max = !isToggleSwitch ? parseFloat( control.attr( "max" ) ) : control.find( "option" ).length-1, step = window.parseFloat( control.attr( "step" ) || 1 ), domHandle = document.createElement( "a" ), handle = $( domHandle ), domSlider = document.createElement( "div" ), slider = $( domSlider ), valuebg = this.options.highlight && !isToggleSwitch ? (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; return $( bg ).prependTo( slider ); })() : false, options, wrapper, j, length, i, optionsCount, origTabIndex, side, activeClass, sliderImg; $label.attr( "id", labelID ); this.isToggleSwitch = isToggleSwitch; domHandle.setAttribute( "href", "#" ); domSlider.setAttribute( "role", "application" ); domSlider.className = [ this.isToggleSwitch ? "ui-slider ui-slider-track ui-shadow-inset " : "ui-slider-track ui-shadow-inset ", selectClass, trackThemeClass, cornerClass, miniClass ].join( "" ); domHandle.className = "ui-slider-handle"; domSlider.appendChild( domHandle ); handle.attr({ "role": "slider", "aria-valuemin": min, "aria-valuemax": max, "aria-valuenow": this._value(), "aria-valuetext": this._value(), "title": this._value(), "aria-labelledby": labelID }); $.extend( this, { slider: slider, handle: handle, control: control, type: cType, step: step, max: max, min: min, valuebg: valuebg, isRangeslider: isRangeslider, dragging: false, beforeStart: null, userModified: false, mouseMoved: false }); if ( isToggleSwitch ) { // TODO: restore original tabindex (if any) in a destroy method origTabIndex = control.attr( "tabindex" ); if ( origTabIndex ) { handle.attr( "tabindex", origTabIndex ); } control.attr( "tabindex", "-1" ).focus(function() { $( this ).blur(); handle.focus(); }); wrapper = document.createElement( "div" ); wrapper.className = "ui-slider-inneroffset"; for ( j = 0, length = domSlider.childNodes.length; j < length; j++ ) { wrapper.appendChild( domSlider.childNodes[j] ); } domSlider.appendChild( wrapper ); // slider.wrapInner( "<div class='ui-slider-inneroffset'></div>" ); // make the handle move with a smooth transition handle.addClass( "ui-slider-handle-snapping" ); options = control.find( "option" ); for ( i = 0, optionsCount = options.length; i < optionsCount; i++ ) { side = !i ? "b" : "a"; activeClass = !i ? "" : " " + $.mobile.activeBtnClass; sliderImg = document.createElement( "span" ); sliderImg.className = [ "ui-slider-label ui-slider-label-", side, activeClass ].join( "" ); sliderImg.setAttribute( "role", "img" ); sliderImg.appendChild( document.createTextNode( options[i].innerHTML ) ); $( sliderImg ).prependTo( slider ); } self._labels = $( ".ui-slider-label", slider ); } // monitor the input for updated values control.addClass( isToggleSwitch ? "ui-slider-switch" : "ui-slider-input" ); this._on( control, { "change": "_controlChange", "keyup": "_controlKeyup", "blur": "_controlBlur", "vmouseup": "_controlVMouseUp" }); slider.bind( "vmousedown", $.proxy( this._sliderVMouseDown, this ) ) .bind( "vclick", false ); // We have to instantiate a new function object for the unbind to work properly // since the method itself is defined in the prototype (causing it to unbind everything) this._on( document, { "vmousemove": "_preventDocumentDrag" }); this._on( slider.add( document ), { "vmouseup": "_sliderVMouseUp" }); slider.insertAfter( control ); // wrap in a div for styling purposes if ( !isToggleSwitch && !isRangeslider ) { wrapper = this.options.mini ? "<div class='ui-slider ui-mini'>" : "<div class='ui-slider'>"; control.add( slider ).wrapAll( wrapper ); } // bind the handle event callbacks and set the context to the widget instance this._on( this.handle, { "vmousedown": "_handleVMouseDown", "keydown": "_handleKeydown", "keyup": "_handleKeyup" }); this.handle.bind( "vclick", false ); this._handleFormReset(); this.refresh( undefined, undefined, true ); }, _setOptions: function( options ) { if ( options.theme !== undefined ) { this._setTheme( options.theme ); } if ( options.trackTheme !== undefined ) { this._setTrackTheme( options.trackTheme ); } if ( options.corners !== undefined ) { this._setCorners( options.corners ); } if ( options.mini !== undefined ) { this._setMini( options.mini ); } if ( options.highlight !== undefined ) { this._setHighlight( options.highlight ); } if ( options.disabled !== undefined ) { this._setDisabled( options.disabled ); } this._super( options ); }, _controlChange: function( event ) { // if the user dragged the handle, the "change" event was triggered from inside refresh(); don't call refresh() again if ( this._trigger( "controlchange", event ) === false ) { return false; } if ( !this.mouseMoved ) { this.refresh( this._value(), true ); } }, _controlKeyup: function(/* event */) { // necessary? this.refresh( this._value(), true, true ); }, _controlBlur: function(/* event */) { this.refresh( this._value(), true ); }, // it appears the clicking the up and down buttons in chrome on // range/number inputs doesn't trigger a change until the field is // blurred. Here we check thif the value has changed and refresh _controlVMouseUp: function(/* event */) { this._checkedRefresh(); }, // NOTE force focus on handle _handleVMouseDown: function(/* event */) { this.handle.focus(); }, _handleKeydown: function( event ) { var index = this._value(); if ( this.options.disabled ) { return; } // In all cases prevent the default and mark the handle as active switch ( event.keyCode ) { case $.mobile.keyCode.HOME: case $.mobile.keyCode.END: case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; this.handle.addClass( "ui-state-active" ); /* TODO: We don't use this class for styling. Do we need to add it? */ } break; } // move the slider according to the keypress switch ( event.keyCode ) { case $.mobile.keyCode.HOME: this.refresh( this.min ); break; case $.mobile.keyCode.END: this.refresh( this.max ); break; case $.mobile.keyCode.PAGE_UP: case $.mobile.keyCode.UP: case $.mobile.keyCode.RIGHT: this.refresh( index + this.step ); break; case $.mobile.keyCode.PAGE_DOWN: case $.mobile.keyCode.DOWN: case $.mobile.keyCode.LEFT: this.refresh( index - this.step ); break; } }, // remove active mark _handleKeyup: function(/* event */) { if ( this._keySliding ) { this._keySliding = false; this.handle.removeClass( "ui-state-active" ); /* See comment above. */ } }, _sliderVMouseDown: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this.options.disabled || !( event.which === 1 || event.which === 0 || event.which === undefined ) ) { return false; } if ( this._trigger( "beforestart", event ) === false ) { return false; } this.dragging = true; this.userModified = false; this.mouseMoved = false; if ( this.isToggleSwitch ) { this.beforeStart = this.element[0].selectedIndex; } this.refresh( event ); this._trigger( "start" ); return false; }, _sliderVMouseUp: function() { if ( this.dragging ) { this.dragging = false; if ( this.isToggleSwitch ) { // make the handle move with a smooth transition this.handle.addClass( "ui-slider-handle-snapping" ); if ( this.mouseMoved ) { // this is a drag, change the value only if user dragged enough if ( this.userModified ) { this.refresh( this.beforeStart === 0 ? 1 : 0 ); } else { this.refresh( this.beforeStart ); } } else { // this is just a click, change the value this.refresh( this.beforeStart === 0 ? 1 : 0 ); } } this.mouseMoved = false; this._trigger( "stop" ); return false; } }, _preventDocumentDrag: function( event ) { // NOTE: we don't do this in refresh because we still want to // support programmatic alteration of disabled inputs if ( this._trigger( "drag", event ) === false) { return false; } if ( this.dragging && !this.options.disabled ) { // this.mouseMoved must be updated before refresh() because it will be used in the control "change" event this.mouseMoved = true; if ( this.isToggleSwitch ) { // make the handle move in sync with the mouse this.handle.removeClass( "ui-slider-handle-snapping" ); } this.refresh( event ); // only after refresh() you can calculate this.userModified this.userModified = this.beforeStart !== this.element[0].selectedIndex; return false; } }, _checkedRefresh: function() { if ( this.value !== this._value() ) { this.refresh( this._value() ); } }, _value: function() { return this.isToggleSwitch ? this.element[0].selectedIndex : parseFloat( this.element.val() ) ; }, _reset: function() { this.refresh( undefined, false, true ); }, refresh: function( val, isfromControl, preventInputUpdate ) { // NOTE: we don't return here because we want to support programmatic // alteration of the input value, which should still update the slider var self = this, parentTheme = $.mobile.getAttribute( this.element[ 0 ], "theme" ), theme = this.options.theme || parentTheme, themeClass = theme ? " ui-btn-" + theme : "", trackTheme = this.options.trackTheme || parentTheme, trackThemeClass = trackTheme ? " ui-bar-" + trackTheme : " ui-bar-inherit", cornerClass = this.options.corners ? " ui-corner-all" : "", miniClass = this.options.mini ? " ui-mini" : "", left, width, data, tol, pxStep, percent, control, isInput, optionElements, min, max, step, newval, valModStep, alignValue, percentPerStep, handlePercent, aPercent, bPercent, valueChanged; self.slider[0].className = [ this.isToggleSwitch ? "ui-slider ui-slider-switch ui-slider-track ui-shadow-inset" : "ui-slider-track ui-shadow-inset", trackThemeClass, cornerClass, miniClass ].join( "" ); if ( this.options.disabled || this.element.prop( "disabled" ) ) { this.disable(); } // set the stored value for comparison later this.value = this._value(); if ( this.options.highlight && !this.isToggleSwitch && this.slider.find( ".ui-slider-bg" ).length === 0 ) { this.valuebg = (function() { var bg = document.createElement( "div" ); bg.className = "ui-slider-bg " + $.mobile.activeBtnClass; return $( bg ).prependTo( self.slider ); })(); } this.handle.addClass( "ui-btn" + themeClass + " ui-shadow" ); control = this.element; isInput = !this.isToggleSwitch; optionElements = isInput ? [] : control.find( "option" ); min = isInput ? parseFloat( control.attr( "min" ) ) : 0; max = isInput ? parseFloat( control.attr( "max" ) ) : optionElements.length - 1; step = ( isInput && parseFloat( control.attr( "step" ) ) > 0 ) ? parseFloat( control.attr( "step" ) ) : 1; if ( typeof val === "object" ) { data = val; // a slight tolerance helped get to the ends of the slider tol = 8; left = this.slider.offset().left; width = this.slider.width(); pxStep = width/((max-min)/step); if ( !this.dragging || data.pageX < left - tol || data.pageX > left + width + tol ) { return; } if ( pxStep > 1 ) { percent = ( ( data.pageX - left ) / width ) * 100; } else { percent = Math.round( ( ( data.pageX - left ) / width ) * 100 ); } } else { if ( val == null ) { val = isInput ? parseFloat( control.val() || 0 ) : control[0].selectedIndex; } percent = ( parseFloat( val ) - min ) / ( max - min ) * 100; } if ( isNaN( percent ) ) { return; } newval = ( percent / 100 ) * ( max - min ) + min; //from jQuery UI slider, the following source will round to the nearest step valModStep = ( newval - min ) % step; alignValue = newval - valModStep; if ( Math.abs( valModStep ) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } percentPerStep = 100/((max-min)/step); // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see jQueryUI: #4124) newval = parseFloat( alignValue.toFixed(5) ); if ( typeof pxStep === "undefined" ) { pxStep = width / ( (max-min) / step ); } if ( pxStep > 1 && isInput ) { percent = ( newval - min ) * percentPerStep * ( 1 / step ); } if ( percent < 0 ) { percent = 0; } if ( percent > 100 ) { percent = 100; } if ( newval < min ) { newval = min; } if ( newval > max ) { newval = max; } this.handle.css( "left", percent + "%" ); this.handle[0].setAttribute( "aria-valuenow", isInput ? newval : optionElements.eq( newval ).attr( "value" ) ); this.handle[0].setAttribute( "aria-valuetext", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); this.handle[0].setAttribute( "title", isInput ? newval : optionElements.eq( newval ).getEncodedText() ); if ( this.valuebg ) { this.valuebg.css( "width", percent + "%" ); } // drag the label widths if ( this._labels ) { handlePercent = this.handle.width() / this.slider.width() * 100; aPercent = percent && handlePercent + ( 100 - handlePercent ) * percent / 100; bPercent = percent === 100 ? 0 : Math.min( handlePercent + 100 - aPercent, 100 ); this._labels.each(function() { var ab = $( this ).hasClass( "ui-slider-label-a" ); $( this ).width( ( ab ? aPercent : bPercent ) + "%" ); }); } if ( !preventInputUpdate ) { valueChanged = false; // update control"s value if ( isInput ) { valueChanged = control.val() !== newval; control.val( newval ); } else { valueChanged = control[ 0 ].selectedIndex !== newval; control[ 0 ].selectedIndex = newval; } if ( this._trigger( "beforechange", val ) === false) { return false; } if ( !isfromControl && valueChanged ) { control.trigger( "change" ); } } }, _setHighlight: function( value ) { value = !!value; if ( value ) { this.options.highlight = !!value; this.refresh(); } else if ( this.valuebg ) { this.valuebg.remove(); this.valuebg = false; } }, _setTheme: function( value ) { this.handle .removeClass( "ui-btn-" + this.options.theme ) .addClass( "ui-btn-" + value ); var currentTheme = this.options.theme ? this.options.theme : "inherit", newTheme = value ? value : "inherit"; this.control .removeClass( "ui-body-" + currentTheme ) .addClass( "ui-body-" + newTheme ); }, _setTrackTheme: function( value ) { var currentTrackTheme = this.options.trackTheme ? this.options.trackTheme : "inherit", newTrackTheme = value ? value : "inherit"; this.slider .removeClass( "ui-body-" + currentTrackTheme ) .addClass( "ui-body-" + newTrackTheme ); }, _setMini: function( value ) { value = !!value; if ( !this.isToggleSwitch && !this.isRangeslider ) { this.slider.parent().toggleClass( "ui-mini", value ); this.element.toggleClass( "ui-mini", value ); } this.slider.toggleClass( "ui-mini", value ); }, _setCorners: function( value ) { this.slider.toggleClass( "ui-corner-all", value ); if ( !this.isToggleSwitch ) { this.control.toggleClass( "ui-corner-all", value ); } }, _setDisabled: function( value ) { value = !!value; this.element.prop( "disabled", value ); this.slider .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { var popup; function getPopup() { if ( !popup ) { popup = $( "<div></div>", { "class": "ui-slider-popup ui-shadow ui-corner-all" }); } return popup.clone(); } $.widget( "mobile.slider", $.mobile.slider, { options: { popupEnabled: false, showValue: false }, _create: function() { this._super(); $.extend( this, { _currentValue: null, _popup: null, _popupVisible: false }); this._setOption( "popupEnabled", this.options.popupEnabled ); this._on( this.handle, { "vmousedown" : "_showPopup" } ); this._on( this.slider.add( this.document ), { "vmouseup" : "_hidePopup" } ); this._refresh(); }, // position the popup centered 5px above the handle _positionPopup: function() { var dstOffset = this.handle.offset(); this._popup.offset( { left: dstOffset.left + ( this.handle.width() - this._popup.width() ) / 2, top: dstOffset.top - this._popup.outerHeight() - 5 }); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "showValue" ) { this.handle.html( value && !this.options.mini ? this._value() : "" ); } else if ( key === "popupEnabled" ) { if ( value && !this._popup ) { this._popup = getPopup() .addClass( "ui-body-" + ( this.options.theme || "a" ) ) .hide() .insertBefore( this.element ); } } }, // show value on the handle and in popup refresh: function() { this._super.apply( this, arguments ); this._refresh(); }, _refresh: function() { var o = this.options, newValue; if ( o.popupEnabled ) { // remove the title attribute from the handle (which is // responsible for the annoying tooltip); NB we have // to do it here as the jqm slider sets it every time // the slider's value changes :( this.handle.removeAttr( "title" ); } newValue = this._value(); if ( newValue === this._currentValue ) { return; } this._currentValue = newValue; if ( o.popupEnabled && this._popup ) { this._positionPopup(); this._popup.html( newValue ); } else if ( o.showValue && !this.options.mini ) { this.handle.html( newValue ); } }, _showPopup: function() { if ( this.options.popupEnabled && !this._popupVisible ) { this.handle.html( "" ); this._popup.show(); this._positionPopup(); this._popupVisible = true; } }, _hidePopup: function() { var o = this.options; if ( o.popupEnabled && this._popupVisible ) { if ( o.showValue && !o.mini ) { this.handle.html( this._value() ); } this._popup.hide(); this._popupVisible = false; } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.flipswitch", $.extend({ options: { onText: "On", offText: "Off", theme: null, enhanced: false, wrapperClass: null, corners: true, mini: false }, _create: function() { if ( !this.options.enhanced ) { this._enhance(); } else { $.extend( this, { flipswitch: this.element.parent(), on: this.element.find( ".ui-flipswitch-on" ).eq( 0 ), off: this.element.find( ".ui-flipswitch-off" ).eq(0), type: this.element.get( 0 ).tagName }); } this._handleFormReset(); // Transfer tabindex to "on" element and make input unfocusable this._originalTabIndex = this.element.attr( "tabindex" ); if ( this._originalTabIndex != null ) { this.on.attr( "tabindex", this._originalTabIndex ); } this.element.attr( "tabindex", "-1" ); this._on({ "focus" : "_handleInputFocus" }); if ( this.element.is( ":disabled" ) ) { this._setOptions({ "disabled": true }); } this._on( this.flipswitch, { "click": "_toggle", "swipeleft": "_left", "swiperight": "_right" }); this._on( this.on, { "keydown": "_keydown" }); this._on( { "change": "refresh" }); }, _handleInputFocus: function() { this.on.focus(); }, widget: function() { return this.flipswitch; }, _left: function() { this.flipswitch.removeClass( "ui-flipswitch-active" ); if ( this.type === "SELECT" ) { this.element.get( 0 ).selectedIndex = 0; } else { this.element.prop( "checked", false ); } this.element.trigger( "change" ); }, _right: function() { this.flipswitch.addClass( "ui-flipswitch-active" ); if ( this.type === "SELECT" ) { this.element.get( 0 ).selectedIndex = 1; } else { this.element.prop( "checked", true ); } this.element.trigger( "change" ); }, _enhance: function() { var flipswitch = $( "<div>" ), options = this.options, element = this.element, theme = options.theme ? options.theme : "inherit", // The "on" button is an anchor so it's focusable on = $( "<a></a>", { "href": "#" }), off = $( "<span></span>" ), type = element.get( 0 ).tagName, onText = ( type === "INPUT" ) ? options.onText : element.find( "option" ).eq( 1 ).text(), offText = ( type === "INPUT" ) ? options.offText : element.find( "option" ).eq( 0 ).text(); on .addClass( "ui-flipswitch-on ui-btn ui-shadow ui-btn-inherit" ) .text( onText ); off .addClass( "ui-flipswitch-off" ) .text( offText ); flipswitch .addClass( "ui-flipswitch ui-shadow-inset " + "ui-bar-" + theme + " " + ( options.wrapperClass ? options.wrapperClass : "" ) + " " + ( ( element.is( ":checked" ) || element .find( "option" ) .eq( 1 ) .is( ":selected" ) ) ? "ui-flipswitch-active" : "" ) + ( element.is(":disabled") ? " ui-state-disabled": "") + ( options.corners ? " ui-corner-all": "" ) + ( options.mini ? " ui-mini": "" ) ) .append( on, off ); element .addClass( "ui-flipswitch-input" ) .after( flipswitch ) .appendTo( flipswitch ); $.extend( this, { flipswitch: flipswitch, on: on, off: off, type: type }); }, _reset: function() { this.refresh(); }, refresh: function() { var direction, existingDirection = this.flipswitch.hasClass( "ui-flipswitch-active" ) ? "_right" : "_left"; if ( this.type === "SELECT" ) { direction = ( this.element.get( 0 ).selectedIndex > 0 ) ? "_right": "_left"; } else { direction = this.element.prop( "checked" ) ? "_right": "_left"; } if ( direction !== existingDirection ) { this[ direction ](); } }, _toggle: function() { var direction = this.flipswitch.hasClass( "ui-flipswitch-active" ) ? "_left" : "_right"; this[ direction ](); }, _keydown: function( e ) { if ( e.which === $.mobile.keyCode.LEFT ) { this._left(); } else if ( e.which === $.mobile.keyCode.RIGHT ) { this._right(); } else if ( e.which === $.mobile.keyCode.SPACE ) { this._toggle(); e.preventDefault(); } }, _setOptions: function( options ) { if ( options.theme !== undefined ) { var currentTheme = options.theme ? options.theme : "inherit", newTheme = options.theme ? options.theme : "inherit"; this.widget() .removeClass( "ui-bar-" + currentTheme ) .addClass( "ui-bar-" + newTheme ); } if ( options.onText !== undefined ) { this.on.text( options.onText ); } if ( options.offText !== undefined ) { this.off.text( options.offText ); } if ( options.disabled !== undefined ) { this.widget().toggleClass( "ui-state-disabled", options.disabled ); } if ( options.mini !== undefined ) { this.widget().toggleClass( "ui-mini", options.mini ); } if ( options.corners !== undefined ) { this.widget().toggleClass( "ui-corner-all", options.corners ); } this._super( options ); }, _destroy: function() { if ( this.options.enhanced ) { return; } if ( this._originalTabIndex != null ) { this.element.attr( "tabindex", this._originalTabIndex ); } else { this.element.removeAttr( "tabindex" ); } this.on.remove(); this.off.remove(); this.element.unwrap(); this.flipswitch.remove(); this.removeClass( "ui-flipswitch-input" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.rangeslider", $.extend( { options: { theme: null, trackTheme: null, corners: true, mini: false, highlight: true }, _create: function() { var $el = this.element, elClass = this.options.mini ? "ui-rangeslider ui-mini" : "ui-rangeslider", _inputFirst = $el.find( "input" ).first(), _inputLast = $el.find( "input" ).last(), _label = $el.find( "label" ).first(), _sliderWidgetFirst = $.data( _inputFirst.get( 0 ), "mobile-slider" ) || $.data( _inputFirst.slider().get( 0 ), "mobile-slider" ), _sliderWidgetLast = $.data( _inputLast.get(0), "mobile-slider" ) || $.data( _inputLast.slider().get( 0 ), "mobile-slider" ), _sliderFirst = _sliderWidgetFirst.slider, _sliderLast = _sliderWidgetLast.slider, firstHandle = _sliderWidgetFirst.handle, _sliders = $( "<div class='ui-rangeslider-sliders' />" ).appendTo( $el ); _inputFirst.addClass( "ui-rangeslider-first" ); _inputLast.addClass( "ui-rangeslider-last" ); $el.addClass( elClass ); _sliderFirst.appendTo( _sliders ); _sliderLast.appendTo( _sliders ); _label.insertBefore( $el ); firstHandle.prependTo( _sliderLast ); $.extend( this, { _inputFirst: _inputFirst, _inputLast: _inputLast, _sliderFirst: _sliderFirst, _sliderLast: _sliderLast, _label: _label, _targetVal: null, _sliderTarget: false, _sliders: _sliders, _proxy: false }); this.refresh(); this._on( this.element.find( "input.ui-slider-input" ), { "slidebeforestart": "_slidebeforestart", "slidestop": "_slidestop", "slidedrag": "_slidedrag", "slidebeforechange": "_change", "blur": "_change", "keyup": "_change" }); this._on({ "mousedown":"_change" }); this._on( this.element.closest( "form" ), { "reset":"_handleReset" }); this._on( firstHandle, { "vmousedown": "_dragFirstHandle" }); }, _handleReset: function() { var self = this; //we must wait for the stack to unwind before updateing other wise sliders will not have updated yet setTimeout( function() { self._updateHighlight(); },0); }, _dragFirstHandle: function( event ) { //if the first handle is dragged send the event to the first slider $.data( this._inputFirst.get(0), "mobile-slider" ).dragging = true; $.data( this._inputFirst.get(0), "mobile-slider" ).refresh( event ); return false; }, _slidedrag: function( event ) { var first = $( event.target ).is( this._inputFirst ), otherSlider = ( first ) ? this._inputLast : this._inputFirst; this._sliderTarget = false; //if the drag was initiated on an extreme and the other handle is focused send the events to //the closest handle if ( ( this._proxy === "first" && first ) || ( this._proxy === "last" && !first ) ) { $.data( otherSlider.get(0), "mobile-slider" ).dragging = true; $.data( otherSlider.get(0), "mobile-slider" ).refresh( event ); return false; } }, _slidestop: function( event ) { var first = $( event.target ).is( this._inputFirst ); this._proxy = false; //this stops dragging of the handle and brings the active track to the front //this makes clicks on the track go the the last handle used this.element.find( "input" ).trigger( "vmouseup" ); this._sliderFirst.css( "z-index", first ? 1 : "" ); }, _slidebeforestart: function( event ) { this._sliderTarget = false; //if the track is the target remember this and the original value if ( $( event.originalEvent.target ).hasClass( "ui-slider-track" ) ) { this._sliderTarget = true; this._targetVal = $( event.target ).val(); } }, _setOptions: function( options ) { if ( options.theme !== undefined ) { this._setTheme( options.theme ); } if ( options.trackTheme !== undefined ) { this._setTrackTheme( options.trackTheme ); } if ( options.mini !== undefined ) { this._setMini( options.mini ); } if ( options.highlight !== undefined ) { this._setHighlight( options.highlight ); } this._super( options ); this.refresh(); }, refresh: function() { var $el = this.element, o = this.options; if ( this._inputFirst.is( ":disabled" ) || this._inputLast.is( ":disabled" ) ) { this.options.disabled = true; } $el.find( "input" ).slider({ theme: o.theme, trackTheme: o.trackTheme, disabled: o.disabled, corners: o.corners, mini: o.mini, highlight: o.highlight }).slider( "refresh" ); this._updateHighlight(); }, _change: function( event ) { if ( event.type === "keyup" ) { this._updateHighlight(); return false; } var self = this, min = parseFloat( this._inputFirst.val(), 10 ), max = parseFloat( this._inputLast.val(), 10 ), first = $( event.target ).hasClass( "ui-rangeslider-first" ), thisSlider = first ? this._inputFirst : this._inputLast, otherSlider = first ? this._inputLast : this._inputFirst; if ( ( this._inputFirst.val() > this._inputLast.val() && event.type === "mousedown" && !$(event.target).hasClass("ui-slider-handle")) ) { thisSlider.blur(); } else if ( event.type === "mousedown" ) { return; } if ( min > max && !this._sliderTarget ) { //this prevents min from being greater then max thisSlider.val( first ? max: min ).slider( "refresh" ); this._trigger( "normalize" ); } else if ( min > max ) { //this makes it so clicks on the target on either extreme go to the closest handle thisSlider.val( this._targetVal ).slider( "refresh" ); //You must wait for the stack to unwind so first slider is updated before updating second setTimeout( function() { otherSlider.val( first ? min: max ).slider( "refresh" ); $.data( otherSlider.get(0), "mobile-slider" ).handle.focus(); self._sliderFirst.css( "z-index", first ? "" : 1 ); self._trigger( "normalize" ); }, 0 ); this._proxy = ( first ) ? "first" : "last"; } //fixes issue where when both _sliders are at min they cannot be adjusted if ( min === max ) { $.data( thisSlider.get(0), "mobile-slider" ).handle.css( "z-index", 1 ); $.data( otherSlider.get(0), "mobile-slider" ).handle.css( "z-index", 0 ); } else { $.data( otherSlider.get(0), "mobile-slider" ).handle.css( "z-index", "" ); $.data( thisSlider.get(0), "mobile-slider" ).handle.css( "z-index", "" ); } this._updateHighlight(); if ( min >= max ) { return false; } }, _updateHighlight: function() { var min = parseInt( $.data( this._inputFirst.get(0), "mobile-slider" ).handle.get(0).style.left, 10 ), max = parseInt( $.data( this._inputLast.get(0), "mobile-slider" ).handle.get(0).style.left, 10 ), width = (max - min); this.element.find( ".ui-slider-bg" ).css({ "margin-left": min + "%", "width": width + "%" }); }, _setTheme: function( value ) { this._inputFirst.slider( "option", "theme", value ); this._inputLast.slider( "option", "theme", value ); }, _setTrackTheme: function( value ) { this._inputFirst.slider( "option", "trackTheme", value ); this._inputLast.slider( "option", "trackTheme", value ); }, _setMini: function( value ) { this._inputFirst.slider( "option", "mini", value ); this._inputLast.slider( "option", "mini", value ); this.element.toggleClass( "ui-mini", !!value ); }, _setHighlight: function( value ) { this._inputFirst.slider( "option", "highlight", value ); this._inputLast.slider( "option", "highlight", value ); }, _destroy: function() { this._label.prependTo( this.element ); this.element.removeClass( "ui-rangeslider ui-mini" ); this._inputFirst.after( this._sliderFirst ); this._inputLast.after( this._sliderLast ); this._sliders.remove(); this.element.find( "input" ).removeClass( "ui-rangeslider-first ui-rangeslider-last" ).slider( "destroy" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.textinput, { options: { clearBtn: false, clearBtnText: "Clear text" }, _create: function() { this._super(); if ( !!this.options.clearBtn || this.isSearch ) { this._addClearBtn(); } }, clearButton: function() { return $( "<a href='#' class='ui-input-clear ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all" + "' title='" + this.options.clearBtnText + "'>" + this.options.clearBtnText + "</a>" ); }, _clearBtnClick: function( event ) { this.element.val( "" ) .focus() .trigger( "change" ); this._clearBtn.addClass( "ui-input-clear-hidden" ); event.preventDefault(); }, _addClearBtn: function() { if ( !this.options.enhanced ) { this._enhanceClear(); } $.extend( this, { _clearBtn: this.widget().find("a.ui-input-clear") }); this._bindClearEvents(); this._toggleClear(); }, _enhanceClear: function() { this.clearButton().appendTo( this.widget() ); this.widget().addClass( "ui-input-has-clear" ); }, _bindClearEvents: function() { this._on( this._clearBtn, { "click": "_clearBtnClick" }); this._on({ "keyup": "_toggleClear", "change": "_toggleClear", "input": "_toggleClear", "focus": "_toggleClear", "blur": "_toggleClear", "cut": "_toggleClear", "paste": "_toggleClear" }); }, _unbindClear: function() { this._off( this._clearBtn, "click"); this._off( this.element, "keyup change input focus blur cut paste" ); }, _setOptions: function( options ) { this._super( options ); if ( options.clearBtn !== undefined && !this.element.is( "textarea, :jqmData(type='range')" ) ) { if ( options.clearBtn ) { this._addClearBtn(); } else { this._destroyClear(); } } if ( options.clearBtnText !== undefined && this._clearBtn !== undefined ) { this._clearBtn.text( options.clearBtnText ) .attr("title", options.clearBtnText); } }, _toggleClear: function() { this._delay( "_toggleClearClass", 0 ); }, _toggleClearClass: function() { this._clearBtn.toggleClass( "ui-input-clear-hidden", !this.element.val() ); }, _destroyClear: function() { this.widget().removeClass( "ui-input-has-clear" ); this._unbindClear(); this._clearBtn.remove(); }, _destroy: function() { this._super(); this._destroyClear(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.textinput", $.mobile.textinput, { options: { autogrow:true, keyupTimeoutBuffer: 100 }, _create: function() { this._super(); if ( this.options.autogrow && this.isTextarea ) { this._autogrow(); } }, _autogrow: function() { this.element.addClass( "ui-textinput-autogrow" ); this._on({ "keyup": "_timeout", "change": "_timeout", "input": "_timeout", "paste": "_timeout" }); // Attach to the various you-have-become-visible notifications that the // various framework elements emit. // TODO: Remove all but the updatelayout handler once #6426 is fixed. this._on( true, this.document, { // TODO: Move to non-deprecated event "pageshow": "_handleShow", "popupbeforeposition": "_handleShow", "updatelayout": "_handleShow", "panelopen": "_handleShow" }); }, // Synchronously fix the widget height if this widget's parents are such // that they show/hide content at runtime. We still need to check whether // the widget is actually visible in case it is contained inside multiple // such containers. For example: panel contains collapsible contains // autogrow textinput. The panel may emit "panelopen" indicating that its // content has become visible, but the collapsible is still collapsed, so // the autogrow textarea is still not visible. _handleShow: function( event ) { if ( $.contains( event.target, this.element[ 0 ] ) && this.element.is( ":visible" ) ) { if ( event.type !== "popupbeforeposition" ) { this.element .addClass( "ui-textinput-autogrow-resize" ) .animationComplete( $.proxy( function() { this.element.removeClass( "ui-textinput-autogrow-resize" ); }, this ), "transition" ); } this._timeout(); } }, _unbindAutogrow: function() { this.element.removeClass( "ui-textinput-autogrow" ); this._off( this.element, "keyup change input paste" ); this._off( this.document, "pageshow popupbeforeposition updatelayout panelopen" ); }, keyupTimeout: null, _prepareHeightUpdate: function( delay ) { if ( this.keyupTimeout ) { clearTimeout( this.keyupTimeout ); } if ( delay === undefined ) { this._updateHeight(); } else { this.keyupTimeout = this._delay( "_updateHeight", delay ); } }, _timeout: function() { this._prepareHeightUpdate( this.options.keyupTimeoutBuffer ); }, _updateHeight: function() { var paddingTop, paddingBottom, paddingHeight, scrollHeight, clientHeight, borderTop, borderBottom, borderHeight, height, scrollTop = this.window.scrollTop(); this.keyupTimeout = 0; // IE8 textareas have the onpage property - others do not if ( !( "onpage" in this.element[ 0 ] ) ) { this.element.css({ "height": 0, "min-height": 0, "max-height": 0 }); } scrollHeight = this.element[ 0 ].scrollHeight; clientHeight = this.element[ 0 ].clientHeight; borderTop = parseFloat( this.element.css( "border-top-width" ) ); borderBottom = parseFloat( this.element.css( "border-bottom-width" ) ); borderHeight = borderTop + borderBottom; height = scrollHeight + borderHeight + 15; // Issue 6179: Padding is not included in scrollHeight and // clientHeight by Firefox if no scrollbar is visible. Because // textareas use the border-box box-sizing model, padding should be // included in the new (assigned) height. Because the height is set // to 0, clientHeight == 0 in Firefox. Therefore, we can use this to // check if padding must be added. if ( clientHeight === 0 ) { paddingTop = parseFloat( this.element.css( "padding-top" ) ); paddingBottom = parseFloat( this.element.css( "padding-bottom" ) ); paddingHeight = paddingTop + paddingBottom; height += paddingHeight; } this.element.css({ "height": height, "min-height": "", "max-height": "" }); this.window.scrollTop( scrollTop ); }, refresh: function() { if ( this.options.autogrow && this.isTextarea ) { this._updateHeight(); } }, _setOptions: function( options ) { this._super( options ); if ( options.autogrow !== undefined && this.isTextarea ) { if ( options.autogrow ) { this._autogrow(); } else { this._unbindAutogrow(); } } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.selectmenu", $.extend( { initSelector: "select:not( :jqmData(role='slider')):not( :jqmData(role='flipswitch') )", options: { theme: null, icon: "carat-d", iconpos: "right", inline: false, corners: true, shadow: true, iconshadow: false, /* TODO: Deprecated in 1.4, remove in 1.5. */ overlayTheme: null, dividerTheme: null, hidePlaceholderMenuItems: true, closeText: "Close", nativeMenu: true, // This option defaults to true on iOS devices. preventFocusZoom: /iPhone|iPad|iPod/.test( navigator.platform ) && navigator.userAgent.indexOf( "AppleWebKit" ) > -1, mini: false }, _button: function() { return $( "<div/>" ); }, _setDisabled: function( value ) { this.element.attr( "disabled", value ); this.button.attr( "aria-disabled", value ); return this._setOption( "disabled", value ); }, _focusButton : function() { var self = this; setTimeout( function() { self.button.focus(); }, 40); }, _selectOptions: function() { return this.select.find( "option" ); }, // setup items that are generally necessary for select menu extension _preExtension: function() { var inline = this.options.inline || this.element.jqmData( "inline" ), mini = this.options.mini || this.element.jqmData( "mini" ), classes = ""; // TODO: Post 1.1--once we have time to test thoroughly--any classes manually applied to the original element should be carried over to the enhanced element, with an `-enhanced` suffix. See https://github.com/jquery/jquery-mobile/issues/3577 /* if ( $el[0].className.length ) { classes = $el[0].className; } */ if ( !!~this.element[0].className.indexOf( "ui-btn-left" ) ) { classes = " ui-btn-left"; } if ( !!~this.element[0].className.indexOf( "ui-btn-right" ) ) { classes = " ui-btn-right"; } if ( inline ) { classes += " ui-btn-inline"; } if ( mini ) { classes += " ui-mini"; } this.select = this.element.removeClass( "ui-btn-left ui-btn-right" ).wrap( "<div class='ui-select" + classes + "'>" ); this.selectId = this.select.attr( "id" ) || ( "select-" + this.uuid ); this.buttonId = this.selectId + "-button"; this.label = $( "label[for='"+ this.selectId +"']" ); this.isMultiple = this.select[ 0 ].multiple; }, _destroy: function() { var wrapper = this.element.parents( ".ui-select" ); if ( wrapper.length > 0 ) { if ( wrapper.is( ".ui-btn-left, .ui-btn-right" ) ) { this.element.addClass( wrapper.hasClass( "ui-btn-left" ) ? "ui-btn-left" : "ui-btn-right" ); } this.element.insertAfter( wrapper ); wrapper.remove(); } }, _create: function() { this._preExtension(); this.button = this._button(); var self = this, options = this.options, iconpos = options.icon ? ( options.iconpos || this.select.jqmData( "iconpos" ) ) : false, button = this.button .insertBefore( this.select ) .attr( "id", this.buttonId ) .addClass( "ui-btn" + ( options.icon ? ( " ui-icon-" + options.icon + " ui-btn-icon-" + iconpos + ( options.iconshadow ? " ui-shadow-icon" : "" ) ) : "" ) + /* TODO: Remove in 1.5. */ ( options.theme ? " ui-btn-" + options.theme : "" ) + ( options.corners ? " ui-corner-all" : "" ) + ( options.shadow ? " ui-shadow" : "" ) ); this.setButtonText(); // Opera does not properly support opacity on select elements // In Mini, it hides the element, but not its text // On the desktop,it seems to do the opposite // for these reasons, using the nativeMenu option results in a full native select in Opera if ( options.nativeMenu && window.opera && window.opera.version ) { button.addClass( "ui-select-nativeonly" ); } // Add counter for multi selects if ( this.isMultiple ) { this.buttonCount = $( "<span>" ) .addClass( "ui-li-count ui-body-inherit" ) .hide() .appendTo( button.addClass( "ui-li-has-count" ) ); } // Disable if specified if ( options.disabled || this.element.attr( "disabled" )) { this.disable(); } // Events on native select this.select.change(function() { self.refresh(); if ( !!options.nativeMenu ) { this.blur(); } }); this._handleFormReset(); this._on( this.button, { keydown: "_handleKeydown" }); this.build(); }, build: function() { var self = this; this.select .appendTo( self.button ) .bind( "vmousedown", function() { // Add active class to button self.button.addClass( $.mobile.activeBtnClass ); }) .bind( "focus", function() { self.button.addClass( $.mobile.focusClass ); }) .bind( "blur", function() { self.button.removeClass( $.mobile.focusClass ); }) .bind( "focus vmouseover", function() { self.button.trigger( "vmouseover" ); }) .bind( "vmousemove", function() { // Remove active class on scroll/touchmove self.button.removeClass( $.mobile.activeBtnClass ); }) .bind( "change blur vmouseout", function() { self.button.trigger( "vmouseout" ) .removeClass( $.mobile.activeBtnClass ); }); // In many situations, iOS will zoom into the select upon tap, this prevents that from happening self.button.bind( "vmousedown", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.label.bind( "click focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.select.bind( "focus", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.disable( true ); } }); self.button.bind( "mouseup", function() { if ( self.options.preventFocusZoom ) { setTimeout(function() { $.mobile.zoom.enable( true ); }, 0 ); } }); self.select.bind( "blur", function() { if ( self.options.preventFocusZoom ) { $.mobile.zoom.enable( true ); } }); }, selected: function() { return this._selectOptions().filter( ":selected" ); }, selectedIndices: function() { var self = this; return this.selected().map(function() { return self._selectOptions().index( this ); }).get(); }, setButtonText: function() { var self = this, selected = this.selected(), text = this.placeholder, span = $( document.createElement( "span" ) ); this.button.children( "span" ).not( ".ui-li-count" ).remove().end().end().prepend( (function() { if ( selected.length ) { text = selected.map(function() { return $( this ).text(); }).get().join( ", " ); } else { text = self.placeholder; } if ( text ) { span.text( text ); } else { // Set the contents to &nbsp; which we write as &#160; to be XHTML compliant - see gh-6699 span.html( "&#160;" ); } // TODO possibly aggregate multiple select option classes return span .addClass( self.select.attr( "class" ) ) .addClass( selected.attr( "class" ) ) .removeClass( "ui-screen-hidden" ); })()); }, setButtonCount: function() { var selected = this.selected(); // multiple count inside button if ( this.isMultiple ) { this.buttonCount[ selected.length > 1 ? "show" : "hide" ]().text( selected.length ); } }, _handleKeydown: function( /* event */ ) { this._delay( "_refreshButton" ); }, _reset: function() { this.refresh(); }, _refreshButton: function() { this.setButtonText(); this.setButtonCount(); }, refresh: function() { this._refreshButton(); }, // open and close preserved in native selects // to simplify users code when looping over selects open: $.noop, close: $.noop, disable: function() { this._setDisabled( true ); this.button.addClass( "ui-state-disabled" ); }, enable: function() { this._setDisabled( false ); this.button.removeClass( "ui-state-disabled" ); } }, $.mobile.behaviors.formReset ) ); })( jQuery ); (function( $, undefined ) { $.mobile.links = function( target ) { //links within content areas, tests included with page $( target ) .find( "a" ) .jqmEnhanceable() .filter( ":jqmData(rel='popup')[href][href!='']" ) .each( function() { // Accessibility info for popups var element = this, idref = element.getAttribute( "href" ).substring( 1 ); if ( idref ) { element.setAttribute( "aria-haspopup", true ); element.setAttribute( "aria-owns", idref ); element.setAttribute( "aria-expanded", false ); } }) .end() .not( ".ui-btn, :jqmData(role='none'), :jqmData(role='nojs')" ) .addClass( "ui-link" ); }; })( jQuery ); (function( $, undefined ) { function fitSegmentInsideSegment( windowSize, segmentSize, offset, desired ) { var returnValue = desired; if ( windowSize < segmentSize ) { // Center segment if it's bigger than the window returnValue = offset + ( windowSize - segmentSize ) / 2; } else { // Otherwise center it at the desired coordinate while keeping it completely inside the window returnValue = Math.min( Math.max( offset, desired - segmentSize / 2 ), offset + windowSize - segmentSize ); } return returnValue; } function getWindowCoordinates( theWindow ) { return { x: theWindow.scrollLeft(), y: theWindow.scrollTop(), cx: ( theWindow[ 0 ].innerWidth || theWindow.width() ), cy: ( theWindow[ 0 ].innerHeight || theWindow.height() ) }; } $.widget( "mobile.popup", { options: { wrapperClass: null, theme: null, overlayTheme: null, shadow: true, corners: true, transition: "none", positionTo: "origin", tolerance: null, closeLinkSelector: "a:jqmData(rel='back')", closeLinkEvents: "click.popup", navigateEvents: "navigate.popup", closeEvents: "navigate.popup pagebeforechange.popup", dismissible: true, enhanced: false, // NOTE Windows Phone 7 has a scroll position caching issue that // requires us to disable popup history management by default // https://github.com/jquery/jquery-mobile/issues/4784 // // NOTE this option is modified in _create! history: !$.mobile.browser.oldIE }, _create: function() { var theElement = this.element, myId = theElement.attr( "id" ), currentOptions = this.options; // We need to adjust the history option to be false if there's no AJAX nav. // We can't do it in the option declarations because those are run before // it is determined whether there shall be AJAX nav. currentOptions.history = currentOptions.history && $.mobile.ajaxEnabled && $.mobile.hashListeningEnabled; // Define instance variables $.extend( this, { _scrollTop: 0, _page: theElement.closest( ".ui-page" ), _ui: null, _fallbackTransition: "", _currentTransition: false, _prerequisites: null, _isOpen: false, _tolerance: null, _resizeData: null, _ignoreResizeTo: 0, _orientationchangeInProgress: false }); if ( this._page.length === 0 ) { this._page = $( "body" ); } if ( currentOptions.enhanced ) { this._ui = { container: theElement.parent(), screen: theElement.parent().prev(), placeholder: $( this.document[ 0 ].getElementById( myId + "-placeholder" ) ) }; } else { this._ui = this._enhance( theElement, myId ); this._applyTransition( currentOptions.transition ); } this ._setTolerance( currentOptions.tolerance ) ._ui.focusElement = this._ui.container; // Event handlers this._on( this._ui.screen, { "vclick": "_eatEventAndClose" } ); this._on( this.window, { orientationchange: $.proxy( this, "_handleWindowOrientationchange" ), resize: $.proxy( this, "_handleWindowResize" ), keyup: $.proxy( this, "_handleWindowKeyUp" ) }); this._on( this.document, { "focusin": "_handleDocumentFocusIn" } ); }, _enhance: function( theElement, myId ) { var currentOptions = this.options, wrapperClass = currentOptions.wrapperClass, ui = { screen: $( "<div class='ui-screen-hidden ui-popup-screen " + this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) + "'></div>" ), placeholder: $( "<div style='display: none;'><!-- placeholder --></div>" ), container: $( "<div class='ui-popup-container ui-popup-hidden ui-popup-truncate" + ( wrapperClass ? ( " " + wrapperClass ) : "" ) + "'></div>" ) }, fragment = this.document[ 0 ].createDocumentFragment(); fragment.appendChild( ui.screen[ 0 ] ); fragment.appendChild( ui.container[ 0 ] ); if ( myId ) { ui.screen.attr( "id", myId + "-screen" ); ui.container.attr( "id", myId + "-popup" ); ui.placeholder .attr( "id", myId + "-placeholder" ) .html( "<!-- placeholder for " + myId + " -->" ); } // Apply the proto this._page[ 0 ].appendChild( fragment ); // Leave a placeholder where the element used to be ui.placeholder.insertAfter( theElement ); theElement .detach() .addClass( "ui-popup " + this._themeClassFromOption( "ui-body-", currentOptions.theme ) + " " + ( currentOptions.shadow ? "ui-overlay-shadow " : "" ) + ( currentOptions.corners ? "ui-corner-all " : "" ) ) .appendTo( ui.container ); return ui; }, _eatEventAndClose: function( theEvent ) { theEvent.preventDefault(); theEvent.stopImmediatePropagation(); if ( this.options.dismissible ) { this.close(); } return false; }, // Make sure the screen covers the entire document - CSS is sometimes not // enough to accomplish this. _resizeScreen: function() { var screen = this._ui.screen, popupHeight = this._ui.container.outerHeight( true ), screenHeight = screen.removeAttr( "style" ).height(), // Subtracting 1 here is necessary for an obscure Andrdoid 4.0 bug where // the browser hangs if the screen covers the entire document :/ documentHeight = this.document.height() - 1; if ( screenHeight < documentHeight ) { screen.height( documentHeight ); } else if ( popupHeight > screenHeight ) { screen.height( popupHeight ); } }, _handleWindowKeyUp: function( theEvent ) { if ( this._isOpen && theEvent.keyCode === $.mobile.keyCode.ESCAPE ) { return this._eatEventAndClose( theEvent ); } }, _expectResizeEvent: function() { var windowCoordinates = getWindowCoordinates( this.window ); if ( this._resizeData ) { if ( windowCoordinates.x === this._resizeData.windowCoordinates.x && windowCoordinates.y === this._resizeData.windowCoordinates.y && windowCoordinates.cx === this._resizeData.windowCoordinates.cx && windowCoordinates.cy === this._resizeData.windowCoordinates.cy ) { // timeout not refreshed return false; } else { // clear existing timeout - it will be refreshed below clearTimeout( this._resizeData.timeoutId ); } } this._resizeData = { timeoutId: this._delay( "_resizeTimeout", 200 ), windowCoordinates: windowCoordinates }; return true; }, _resizeTimeout: function() { if ( this._isOpen ) { if ( !this._expectResizeEvent() ) { if ( this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-open the popup while leaving the screen intact this._ui.container.removeClass( "ui-popup-hidden ui-popup-truncate" ); this.reposition( { positionTo: "window" } ); this._ignoreResizeEvents(); } this._resizeScreen(); this._resizeData = null; this._orientationchangeInProgress = false; } } else { this._resizeData = null; this._orientationchangeInProgress = false; } }, _stopIgnoringResizeEvents: function() { this._ignoreResizeTo = 0; }, _ignoreResizeEvents: function() { if ( this._ignoreResizeTo ) { clearTimeout( this._ignoreResizeTo ); } this._ignoreResizeTo = this._delay( "_stopIgnoringResizeEvents", 1000 ); }, _handleWindowResize: function(/* theEvent */) { if ( this._isOpen && this._ignoreResizeTo === 0 ) { if ( ( this._expectResizeEvent() || this._orientationchangeInProgress ) && !this._ui.container.hasClass( "ui-popup-hidden" ) ) { // effectively rapid-close the popup while leaving the screen intact this._ui.container .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); } } }, _handleWindowOrientationchange: function(/* theEvent */) { if ( !this._orientationchangeInProgress && this._isOpen && this._ignoreResizeTo === 0 ) { this._expectResizeEvent(); this._orientationchangeInProgress = true; } }, // When the popup is open, attempting to focus on an element that is not a // child of the popup will redirect focus to the popup _handleDocumentFocusIn: function( theEvent ) { var target, targetElement = theEvent.target, ui = this._ui; if ( !this._isOpen ) { return; } if ( targetElement !== ui.container[ 0 ] ) { target = $( targetElement ); if ( 0 === target.parents().filter( ui.container[ 0 ] ).length ) { $( this.document[ 0 ].activeElement ).one( "focus", function(/* theEvent */) { target.blur(); }); ui.focusElement.focus(); theEvent.preventDefault(); theEvent.stopImmediatePropagation(); return false; } else if ( ui.focusElement[ 0 ] === ui.container[ 0 ] ) { ui.focusElement = target; } } this._ignoreResizeEvents(); }, _themeClassFromOption: function( prefix, value ) { return ( value ? ( value === "none" ? "" : ( prefix + value ) ) : ( prefix + "inherit" ) ); }, _applyTransition: function( value ) { if ( value ) { this._ui.container.removeClass( this._fallbackTransition ); if ( value !== "none" ) { this._fallbackTransition = $.mobile._maybeDegradeTransition( value ); if ( this._fallbackTransition === "none" ) { this._fallbackTransition = ""; } this._ui.container.addClass( this._fallbackTransition ); } } return this; }, _setOptions: function( newOptions ) { var currentOptions = this.options, theElement = this.element, screen = this._ui.screen; if ( newOptions.wrapperClass !== undefined ) { this._ui.container .removeClass( currentOptions.wrapperClass ) .addClass( newOptions.wrapperClass ); } if ( newOptions.theme !== undefined ) { theElement .removeClass( this._themeClassFromOption( "ui-body-", currentOptions.theme ) ) .addClass( this._themeClassFromOption( "ui-body-", newOptions.theme ) ); } if ( newOptions.overlayTheme !== undefined ) { screen .removeClass( this._themeClassFromOption( "ui-overlay-", currentOptions.overlayTheme ) ) .addClass( this._themeClassFromOption( "ui-overlay-", newOptions.overlayTheme ) ); if ( this._isOpen ) { screen.addClass( "in" ); } } if ( newOptions.shadow !== undefined ) { theElement.toggleClass( "ui-overlay-shadow", newOptions.shadow ); } if ( newOptions.corners !== undefined ) { theElement.toggleClass( "ui-corner-all", newOptions.corners ); } if ( newOptions.transition !== undefined ) { if ( !this._currentTransition ) { this._applyTransition( newOptions.transition ); } } if ( newOptions.tolerance !== undefined ) { this._setTolerance( newOptions.tolerance ); } if ( newOptions.disabled !== undefined ) { if ( newOptions.disabled ) { this.close(); } } return this._super( newOptions ); }, _setTolerance: function( value ) { var tol = { t: 30, r: 15, b: 30, l: 15 }, ar; if ( value !== undefined ) { ar = String( value ).split( "," ); $.each( ar, function( idx, val ) { ar[ idx ] = parseInt( val, 10 ); } ); switch( ar.length ) { // All values are to be the same case 1: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.r = tol.b = tol.l = ar[ 0 ]; } break; // The first value denotes top/bottom tolerance, and the second value denotes left/right tolerance case 2: if ( !isNaN( ar[ 0 ] ) ) { tol.t = tol.b = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.l = tol.r = ar[ 1 ]; } break; // The array contains values in the order top, right, bottom, left case 4: if ( !isNaN( ar[ 0 ] ) ) { tol.t = ar[ 0 ]; } if ( !isNaN( ar[ 1 ] ) ) { tol.r = ar[ 1 ]; } if ( !isNaN( ar[ 2 ] ) ) { tol.b = ar[ 2 ]; } if ( !isNaN( ar[ 3 ] ) ) { tol.l = ar[ 3 ]; } break; default: break; } } this._tolerance = tol; return this; }, _clampPopupWidth: function( infoOnly ) { var menuSize, windowCoordinates = getWindowCoordinates( this.window ), // rectangle within which the popup must fit rectangle = { x: this._tolerance.l, y: windowCoordinates.y + this._tolerance.t, cx: windowCoordinates.cx - this._tolerance.l - this._tolerance.r, cy: windowCoordinates.cy - this._tolerance.t - this._tolerance.b }; if ( !infoOnly ) { // Clamp the width of the menu before grabbing its size this._ui.container.css( "max-width", rectangle.cx ); } menuSize = { cx: this._ui.container.outerWidth( true ), cy: this._ui.container.outerHeight( true ) }; return { rc: rectangle, menuSize: menuSize }; }, _calculateFinalLocation: function( desired, clampInfo ) { var returnValue, rectangle = clampInfo.rc, menuSize = clampInfo.menuSize; // Center the menu over the desired coordinates, while not going outside // the window tolerances. This will center wrt. the window if the popup is // too large. returnValue = { left: fitSegmentInsideSegment( rectangle.cx, menuSize.cx, rectangle.x, desired.x ), top: fitSegmentInsideSegment( rectangle.cy, menuSize.cy, rectangle.y, desired.y ) }; // Make sure the top of the menu is visible returnValue.top = Math.max( 0, returnValue.top ); // If the height of the menu is smaller than the height of the document // align the bottom with the bottom of the document returnValue.top -= Math.min( returnValue.top, Math.max( 0, returnValue.top + menuSize.cy - this.document.height() ) ); return returnValue; }, // Try and center the overlay over the given coordinates _placementCoords: function( desired ) { return this._calculateFinalLocation( desired, this._clampPopupWidth() ); }, _createPrerequisites: function( screenPrerequisite, containerPrerequisite, whenDone ) { var prerequisites, self = this; // It is important to maintain both the local variable prerequisites and // self._prerequisites. The local variable remains in the closure of the // functions which call the callbacks passed in. The comparison between the // local variable and self._prerequisites is necessary, because once a // function has been passed to .animationComplete() it will be called next // time an animation completes, even if that's not the animation whose end // the function was supposed to catch (for example, if an abort happens // during the opening animation, the .animationComplete handler is not // called for that animation anymore, but the handler remains attached, so // it is called the next time the popup is opened - making it stale. // Comparing the local variable prerequisites to the widget-level variable // self._prerequisites ensures that callbacks triggered by a stale // .animationComplete will be ignored. prerequisites = { screen: $.Deferred(), container: $.Deferred() }; prerequisites.screen.then( function() { if ( prerequisites === self._prerequisites ) { screenPrerequisite(); } }); prerequisites.container.then( function() { if ( prerequisites === self._prerequisites ) { containerPrerequisite(); } }); $.when( prerequisites.screen, prerequisites.container ).done( function() { if ( prerequisites === self._prerequisites ) { self._prerequisites = null; whenDone(); } }); self._prerequisites = prerequisites; }, _animate: function( args ) { // NOTE before removing the default animation of the screen // this had an animate callback that would resolve the deferred // now the deferred is resolved immediately // TODO remove the dependency on the screen deferred this._ui.screen .removeClass( args.classToRemove ) .addClass( args.screenClassToAdd ); args.prerequisites.screen.resolve(); if ( args.transition && args.transition !== "none" ) { if ( args.applyTransition ) { this._applyTransition( args.transition ); } if ( this._fallbackTransition ) { this._ui.container .addClass( args.containerClassToAdd ) .removeClass( args.classToRemove ) .animationComplete( $.proxy( args.prerequisites.container, "resolve" ) ); return; } } this._ui.container.removeClass( args.classToRemove ); args.prerequisites.container.resolve(); }, // The desired coordinates passed in will be returned untouched if no reference element can be identified via // desiredPosition.positionTo. Nevertheless, this function ensures that its return value always contains valid // x and y coordinates by specifying the center middle of the window if the coordinates are absent. // options: { x: coordinate, y: coordinate, positionTo: string: "origin", "window", or jQuery selector _desiredCoords: function( openOptions ) { var offset, dst = null, windowCoordinates = getWindowCoordinates( this.window ), x = openOptions.x, y = openOptions.y, pTo = openOptions.positionTo; // Establish which element will serve as the reference if ( pTo && pTo !== "origin" ) { if ( pTo === "window" ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; y = windowCoordinates.cy / 2 + windowCoordinates.y; } else { try { dst = $( pTo ); } catch( err ) { dst = null; } if ( dst ) { dst.filter( ":visible" ); if ( dst.length === 0 ) { dst = null; } } } } // If an element was found, center over it if ( dst ) { offset = dst.offset(); x = offset.left + dst.outerWidth() / 2; y = offset.top + dst.outerHeight() / 2; } // Make sure x and y are valid numbers - center over the window if ( $.type( x ) !== "number" || isNaN( x ) ) { x = windowCoordinates.cx / 2 + windowCoordinates.x; } if ( $.type( y ) !== "number" || isNaN( y ) ) { y = windowCoordinates.cy / 2 + windowCoordinates.y; } return { x: x, y: y }; }, _reposition: function( openOptions ) { // We only care about position-related parameters for repositioning openOptions = { x: openOptions.x, y: openOptions.y, positionTo: openOptions.positionTo }; this._trigger( "beforeposition", undefined, openOptions ); this._ui.container.offset( this._placementCoords( this._desiredCoords( openOptions ) ) ); }, reposition: function( openOptions ) { if ( this._isOpen ) { this._reposition( openOptions ); } }, _openPrerequisitesComplete: function() { var id = this.element.attr( "id" ); this._ui.container.addClass( "ui-popup-active" ); this._isOpen = true; this._resizeScreen(); this._ui.container.attr( "tabindex", "0" ).focus(); this._ignoreResizeEvents(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", true ); } this._trigger( "afteropen" ); }, _open: function( options ) { var openOptions = $.extend( {}, this.options, options ), // TODO move blacklist to private method androidBlacklist = ( function() { var ua = navigator.userAgent, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9\.]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], androidmatch = ua.match( /Android (\d+(?:\.\d+))/ ), andversion = !!androidmatch && androidmatch[ 1 ], chromematch = ua.indexOf( "Chrome" ) > -1; // Platform is Android, WebKit version is greater than 534.13 ( Android 3.2.1 ) and not Chrome. if ( androidmatch !== null && andversion === "4.0" && wkversion && wkversion > 534.13 && !chromematch ) { return true; } return false; }()); // Count down to triggering "popupafteropen" - we have two prerequisites: // 1. The popup window animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.noop, $.noop, $.proxy( this, "_openPrerequisitesComplete" ) ); this._currentTransition = openOptions.transition; this._applyTransition( openOptions.transition ); this._ui.screen.removeClass( "ui-screen-hidden" ); this._ui.container.removeClass( "ui-popup-truncate" ); // Give applications a chance to modify the contents of the container before it appears this._reposition( openOptions ); this._ui.container.removeClass( "ui-popup-hidden" ); if ( this.options.overlayTheme && androidBlacklist ) { /* TODO: The native browser on Android 4.0.X ("Ice Cream Sandwich") suffers from an issue where the popup overlay appears to be z-indexed above the popup itself when certain other styles exist on the same page -- namely, any element set to `position: fixed` and certain types of input. These issues are reminiscent of previously uncovered bugs in older versions of Android's native browser: https://github.com/scottjehl/Device-Bugs/issues/3 This fix closes the following bugs ( I use "closes" with reluctance, and stress that this issue should be revisited as soon as possible ): https://github.com/jquery/jquery-mobile/issues/4816 https://github.com/jquery/jquery-mobile/issues/4844 https://github.com/jquery/jquery-mobile/issues/4874 */ // TODO sort out why this._page isn't working this.element.closest( ".ui-page" ).addClass( "ui-popup-open" ); } this._animate({ additionalCondition: true, transition: openOptions.transition, classToRemove: "", screenClassToAdd: "in", containerClassToAdd: "in", applyTransition: false, prerequisites: this._prerequisites }); }, _closePrerequisiteScreen: function() { this._ui.screen .removeClass( "out" ) .addClass( "ui-screen-hidden" ); }, _closePrerequisiteContainer: function() { this._ui.container .removeClass( "reverse out" ) .addClass( "ui-popup-hidden ui-popup-truncate" ) .removeAttr( "style" ); }, _closePrerequisitesDone: function() { var container = this._ui.container, id = this.element.attr( "id" ); container.removeAttr( "tabindex" ); // remove the global mutex for popups $.mobile.popup.active = undefined; // Blur elements inside the container, including the container $( ":focus", container[ 0 ] ).add( container[ 0 ] ).blur(); if ( id ) { this.document.find( "[aria-haspopup='true'][aria-owns='" + id + "']" ).attr( "aria-expanded", false ); } // alert users that the popup is closed this._trigger( "afterclose" ); }, _close: function( immediate ) { this._ui.container.removeClass( "ui-popup-active" ); this._page.removeClass( "ui-popup-open" ); this._isOpen = false; // Count down to triggering "popupafterclose" - we have two prerequisites: // 1. The popup window reverse animation completes (container()) // 2. The screen opacity animation completes (screen()) this._createPrerequisites( $.proxy( this, "_closePrerequisiteScreen" ), $.proxy( this, "_closePrerequisiteContainer" ), $.proxy( this, "_closePrerequisitesDone" ) ); this._animate( { additionalCondition: this._ui.screen.hasClass( "in" ), transition: ( immediate ? "none" : ( this._currentTransition ) ), classToRemove: "in", screenClassToAdd: "out", containerClassToAdd: "reverse out", applyTransition: true, prerequisites: this._prerequisites }); }, _unenhance: function() { if ( this.options.enhanced ) { return; } // Put the element back to where the placeholder was and remove the "ui-popup" class this._setOptions( { theme: $.mobile.popup.prototype.options.theme } ); this.element // Cannot directly insertAfter() - we need to detach() first, because // insertAfter() will do nothing if the payload div was not attached // to the DOM at the time the widget was created, and so the payload // will remain inside the container even after we call insertAfter(). // If that happens and we remove the container a few lines below, we // will cause an infinite recursion - #5244 .detach() .insertAfter( this._ui.placeholder ) .removeClass( "ui-popup ui-overlay-shadow ui-corner-all ui-body-inherit" ); this._ui.screen.remove(); this._ui.container.remove(); this._ui.placeholder.remove(); }, _destroy: function() { if ( $.mobile.popup.active === this ) { this.element.one( "popupafterclose", $.proxy( this, "_unenhance" ) ); this.close(); } else { this._unenhance(); } return this; }, _closePopup: function( theEvent, data ) { var parsedDst, toUrl, currentOptions = this.options, immediate = false; if ( ( theEvent && theEvent.isDefaultPrevented() ) || $.mobile.popup.active !== this ) { return; } // restore location on screen window.scrollTo( 0, this._scrollTop ); if ( theEvent && theEvent.type === "pagebeforechange" && data ) { // Determine whether we need to rapid-close the popup, or whether we can // take the time to run the closing transition if ( typeof data.toPage === "string" ) { parsedDst = data.toPage; } else { parsedDst = data.toPage.jqmData( "url" ); } parsedDst = $.mobile.path.parseUrl( parsedDst ); toUrl = parsedDst.pathname + parsedDst.search + parsedDst.hash; if ( this._myUrl !== $.mobile.path.makeUrlAbsolute( toUrl ) ) { // Going to a different page - close immediately immediate = true; } else { theEvent.preventDefault(); } } // remove nav bindings this.window.off( currentOptions.closeEvents ); // unbind click handlers added when history is disabled this.element.undelegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents ); this._close( immediate ); }, // any navigation event after a popup is opened should close the popup // NOTE the pagebeforechange is bound to catch navigation events that don't // alter the url (eg, dialogs from popups) _bindContainerClose: function() { this.window .on( this.options.closeEvents, $.proxy( this, "_closePopup" ) ); }, widget: function() { return this._ui.container; }, // TODO no clear deliniation of what should be here and // what should be in _open. Seems to be "visual" vs "history" for now open: function( options ) { var url, hashkey, activePage, currentIsDialog, hasHash, urlHistory, self = this, currentOptions = this.options; // make sure open is idempotent if ( $.mobile.popup.active || currentOptions.disabled ) { return this; } // set the global popup mutex $.mobile.popup.active = this; this._scrollTop = this.window.scrollTop(); // if history alteration is disabled close on navigate events // and leave the url as is if ( !( currentOptions.history ) ) { self._open( options ); self._bindContainerClose(); // When histoy is disabled we have to grab the data-rel // back link clicks so we can close the popup instead of // relying on history to do it for us self.element .delegate( currentOptions.closeLinkSelector, currentOptions.closeLinkEvents, function( theEvent ) { self.close(); theEvent.preventDefault(); }); return this; } // cache some values for min/readability urlHistory = $.mobile.navigate.history; hashkey = $.mobile.dialogHashKey; activePage = $.mobile.activePage; currentIsDialog = ( activePage ? activePage.hasClass( "ui-dialog" ) : false ); this._myUrl = url = urlHistory.getActive().url; hasHash = ( url.indexOf( hashkey ) > -1 ) && !currentIsDialog && ( urlHistory.activeIndex > 0 ); if ( hasHash ) { self._open( options ); self._bindContainerClose(); return this; } // if the current url has no dialog hash key proceed as normal // otherwise, if the page is a dialog simply tack on the hash key if ( url.indexOf( hashkey ) === -1 && !currentIsDialog ) { url = url + (url.indexOf( "#" ) > -1 ? hashkey : "#" + hashkey); } else { url = $.mobile.path.parseLocation().hash + hashkey; } // Tack on an extra hashkey if this is the first page and we've just reconstructed the initial hash if ( urlHistory.activeIndex === 0 && url === urlHistory.initialDst ) { url += hashkey; } // swallow the the initial navigation event, and bind for the next this.window.one( "beforenavigate", function( theEvent ) { theEvent.preventDefault(); self._open( options ); self._bindContainerClose(); }); this.urlAltered = true; $.mobile.navigate( url, { role: "dialog" } ); return this; }, close: function() { // make sure close is idempotent if ( $.mobile.popup.active !== this ) { return this; } this._scrollTop = this.window.scrollTop(); if ( this.options.history && this.urlAltered ) { $.mobile.back(); this.urlAltered = false; } else { // simulate the nav bindings having fired this._closePopup(); } return this; } }); // TODO this can be moved inside the widget $.mobile.popup.handleLink = function( $link ) { var offset, path = $.mobile.path, // NOTE make sure to get only the hash from the href because ie7 (wp7) // returns the absolute href in this case ruining the element selection popup = $( path.hashToSelector( path.parseUrl( $link.attr( "href" ) ).hash ) ).first(); if ( popup.length > 0 && popup.data( "mobile-popup" ) ) { offset = $link.offset(); popup.popup( "open", { x: offset.left + $link.outerWidth() / 2, y: offset.top + $link.outerHeight() / 2, transition: $link.jqmData( "transition" ), positionTo: $link.jqmData( "position-to" ) }); } //remove after delay setTimeout( function() { $link.removeClass( $.mobile.activeBtnClass ); }, 300 ); }; // TODO move inside _create $.mobile.document.on( "pagebeforechange", function( theEvent, data ) { if ( data.options.role === "popup" ) { $.mobile.popup.handleLink( data.options.link ); theEvent.preventDefault(); } }); })( jQuery ); /* * custom "selectmenu" plugin */ (function( $, undefined ) { var unfocusableItemSelector = ".ui-disabled,.ui-state-disabled,.ui-li-divider,.ui-screen-hidden,:jqmData(role='placeholder')", goToAdjacentItem = function( item, target, direction ) { var adjacent = item[ direction + "All" ]() .not( unfocusableItemSelector ) .first(); // if there's a previous option, focus it if ( adjacent.length ) { target .blur() .attr( "tabindex", "-1" ); adjacent.find( "a" ).first().focus(); } }; $.widget( "mobile.selectmenu", $.mobile.selectmenu, { _create: function() { var o = this.options; // Custom selects cannot exist inside popups, so revert the "nativeMenu" // option to true if a parent is a popup o.nativeMenu = o.nativeMenu || ( this.element.parents( ":jqmData(role='popup'),:mobile-popup" ).length > 0 ); return this._super(); }, _handleSelectFocus: function() { this.element.blur(); this.button.focus(); }, _handleKeydown: function( event ) { this._super( event ); this._handleButtonVclickKeydown( event ); }, _handleButtonVclickKeydown: function( event ) { if ( this.options.disabled || this.isOpen ) { return; } if (event.type === "vclick" || event.keyCode && (event.keyCode === $.mobile.keyCode.ENTER || event.keyCode === $.mobile.keyCode.SPACE)) { this._decideFormat(); if ( this.menuType === "overlay" ) { this.button.attr( "href", "#" + this.popupId ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "popup" ); } else { this.button.attr( "href", "#" + this.dialogId ).attr( "data-" + ( $.mobile.ns || "" ) + "rel", "dialog" ); } this.isOpen = true; // Do not prevent default, so the navigation may have a chance to actually open the chosen format } }, _handleListFocus: function( e ) { var params = ( e.type === "focusin" ) ? { tabindex: "0", event: "vmouseover" }: { tabindex: "-1", event: "vmouseout" }; $( e.target ) .attr( "tabindex", params.tabindex ) .trigger( params.event ); }, _handleListKeydown: function( event ) { var target = $( event.target ), li = target.closest( "li" ); // switch logic based on which key was pressed switch ( event.keyCode ) { // up or left arrow keys case 38: goToAdjacentItem( li, target, "prev" ); return false; // down or right arrow keys case 40: goToAdjacentItem( li, target, "next" ); return false; // If enter or space is pressed, trigger click case 13: case 32: target.trigger( "click" ); return false; } }, _handleMenuPageHide: function() { // TODO centralize page removal binding / handling in the page plugin. // Suggestion from @jblas to do refcounting // // TODO extremely confusing dependency on the open method where the pagehide.remove // bindings are stripped to prevent the parent page from disappearing. The way // we're keeping pages in the DOM right now sucks // // rebind the page remove that was unbound in the open function // to allow for the parent page removal from actions other than the use // of a dialog sized custom select // // doing this here provides for the back button on the custom select dialog this.thisPage.page( "bindRemove" ); }, _handleHeaderCloseClick: function() { if ( this.menuType === "overlay" ) { this.close(); return false; } }, build: function() { var selectId, popupId, dialogId, label, thisPage, isMultiple, menuId, themeAttr, overlayTheme, overlayThemeAttr, dividerThemeAttr, menuPage, listbox, list, header, headerTitle, menuPageContent, menuPageClose, headerClose, self, o = this.options; if ( o.nativeMenu ) { return this._super(); } self = this; selectId = this.selectId; popupId = selectId + "-listbox"; dialogId = selectId + "-dialog"; label = this.label; thisPage = this.element.closest( ".ui-page" ); isMultiple = this.element[ 0 ].multiple; menuId = selectId + "-menu"; themeAttr = o.theme ? ( " data-" + $.mobile.ns + "theme='" + o.theme + "'" ) : ""; overlayTheme = o.overlayTheme || o.theme || null; overlayThemeAttr = overlayTheme ? ( " data-" + $.mobile.ns + "overlay-theme='" + overlayTheme + "'" ) : ""; dividerThemeAttr = ( o.dividerTheme && isMultiple ) ? ( " data-" + $.mobile.ns + "divider-theme='" + o.dividerTheme + "'" ) : ""; menuPage = $( "<div data-" + $.mobile.ns + "role='dialog' class='ui-selectmenu' id='" + dialogId + "'" + themeAttr + overlayThemeAttr + ">" + "<div data-" + $.mobile.ns + "role='header'>" + "<div class='ui-title'>" + label.getEncodedText() + "</div>"+ "</div>"+ "<div data-" + $.mobile.ns + "role='content'></div>"+ "</div>" ); listbox = $( "<div id='" + popupId + "' class='ui-selectmenu'></div>" ).insertAfter( this.select ).popup({ theme: o.overlayTheme }); list = $( "<ul class='ui-selectmenu-list' id='" + menuId + "' role='listbox' aria-labelledby='" + this.buttonId + "'" + themeAttr + dividerThemeAttr + "></ul>" ).appendTo( listbox ); header = $( "<div class='ui-header ui-bar-" + ( o.theme ? o.theme : "inherit" ) + "'></div>" ).prependTo( listbox ); headerTitle = $( "<h1 class='ui-title'></h1>" ).appendTo( header ); if ( this.isMultiple ) { headerClose = $( "<a>", { "role": "button", "text": o.closeText, "href": "#", "class": "ui-btn ui-corner-all ui-btn-left ui-btn-icon-notext ui-icon-delete" }).appendTo( header ); } $.extend( this, { selectId: selectId, menuId: menuId, popupId: popupId, dialogId: dialogId, thisPage: thisPage, menuPage: menuPage, label: label, isMultiple: isMultiple, theme: o.theme, listbox: listbox, list: list, header: header, headerTitle: headerTitle, headerClose: headerClose, menuPageContent: menuPageContent, menuPageClose: menuPageClose, placeholder: "" }); // Create list from select, update state this.refresh(); if ( this._origTabIndex === undefined ) { // Map undefined to false, because this._origTabIndex === undefined // indicates that we have not yet checked whether the select has // originally had a tabindex attribute, whereas false indicates that // we have checked the select for such an attribute, and have found // none present. this._origTabIndex = ( this.select[ 0 ].getAttribute( "tabindex" ) === null ) ? false : this.select.attr( "tabindex" ); } this.select.attr( "tabindex", "-1" ); this._on( this.select, { focus : "_handleSelectFocus" } ); // Button events this._on( this.button, { vclick: "_handleButtonVclickKeydown" }); // Events for list items this.list.attr( "role", "listbox" ); this._on( this.list, { focusin : "_handleListFocus", focusout : "_handleListFocus", keydown: "_handleListKeydown" }); this.list .delegate( "li:not(.ui-disabled,.ui-state-disabled,.ui-li-divider)", "click", function( event ) { // index of option tag to be selected var oldIndex = self.select[ 0 ].selectedIndex, newIndex = $.mobile.getAttribute( this, "option-index" ), option = self._selectOptions().eq( newIndex )[ 0 ]; // toggle selected status on the tag for multi selects option.selected = self.isMultiple ? !option.selected : true; // toggle checkbox class for multiple selects if ( self.isMultiple ) { $( this ).find( "a" ) .toggleClass( "ui-checkbox-on", option.selected ) .toggleClass( "ui-checkbox-off", !option.selected ); } // trigger change if value changed if ( self.isMultiple || oldIndex !== newIndex ) { self.select.trigger( "change" ); } // hide custom select for single selects only - otherwise focus clicked item // We need to grab the clicked item the hard way, because the list may have been rebuilt if ( self.isMultiple ) { self.list.find( "li:not(.ui-li-divider)" ).eq( newIndex ) .find( "a" ).first().focus(); } else { self.close(); } event.preventDefault(); }); // button refocus ensures proper height calculation // by removing the inline style and ensuring page inclusion this._on( this.menuPage, { pagehide: "_handleMenuPageHide" } ); // Events on the popup this._on( this.listbox, { popupafterclose: "close" } ); // Close button on small overlays if ( this.isMultiple ) { this._on( this.headerClose, { click: "_handleHeaderCloseClick" } ); } return this; }, _isRebuildRequired: function() { var list = this.list.find( "li" ), options = this._selectOptions().not( ".ui-screen-hidden" ); // TODO exceedingly naive method to determine difference // ignores value changes etc in favor of a forcedRebuild // from the user in the refresh method return options.text() !== list.text(); }, selected: function() { return this._selectOptions().filter( ":selected:not( :jqmData(placeholder='true') )" ); }, refresh: function( force ) { var self, indices; if ( this.options.nativeMenu ) { return this._super( force ); } self = this; if ( force || this._isRebuildRequired() ) { self._buildList(); } indices = this.selectedIndices(); self.setButtonText(); self.setButtonCount(); self.list.find( "li:not(.ui-li-divider)" ) .find( "a" ).removeClass( $.mobile.activeBtnClass ).end() .attr( "aria-selected", false ) .each(function( i ) { if ( $.inArray( i, indices ) > -1 ) { var item = $( this ); // Aria selected attr item.attr( "aria-selected", true ); // Multiple selects: add the "on" checkbox state to the icon if ( self.isMultiple ) { item.find( "a" ).removeClass( "ui-checkbox-off" ).addClass( "ui-checkbox-on" ); } else { if ( item.hasClass( "ui-screen-hidden" ) ) { item.next().find( "a" ).addClass( $.mobile.activeBtnClass ); } else { item.find( "a" ).addClass( $.mobile.activeBtnClass ); } } } }); }, close: function() { if ( this.options.disabled || !this.isOpen ) { return; } var self = this; if ( self.menuType === "page" ) { self.menuPage.dialog( "close" ); self.list.appendTo( self.listbox ); } else { self.listbox.popup( "close" ); } self._focusButton(); // allow the dialog to be closed again self.isOpen = false; }, open: function() { this.button.click(); }, _focusMenuItem: function() { var selector = this.list.find( "a." + $.mobile.activeBtnClass ); if ( selector.length === 0 ) { selector = this.list.find( "li:not(" + unfocusableItemSelector + ") a.ui-btn" ); } selector.first().focus(); }, _decideFormat: function() { var self = this, $window = this.window, selfListParent = self.list.parent(), menuHeight = selfListParent.outerHeight(), scrollTop = $window.scrollTop(), btnOffset = self.button.offset().top, screenHeight = $window.height(); if ( menuHeight > screenHeight - 80 || !$.support.scrollTop ) { self.menuPage.appendTo( $.mobile.pageContainer ).page(); self.menuPageContent = self.menuPage.find( ".ui-content" ); self.menuPageClose = self.menuPage.find( ".ui-header a" ); // prevent the parent page from being removed from the DOM, // otherwise the results of selecting a list item in the dialog // fall into a black hole self.thisPage.unbind( "pagehide.remove" ); //for WebOS/Opera Mini (set lastscroll using button offset) if ( scrollTop === 0 && btnOffset > screenHeight ) { self.thisPage.one( "pagehide", function() { $( this ).jqmData( "lastScroll", btnOffset ); }); } self.menuPage.one( { pageshow: $.proxy( this, "_focusMenuItem" ), pagehide: $.proxy( this, "close" ) }); self.menuType = "page"; self.menuPageContent.append( self.list ); self.menuPage.find( "div .ui-title" ).text( self.label.text() ); } else { self.menuType = "overlay"; self.listbox.one( { popupafteropen: $.proxy( this, "_focusMenuItem" ) } ); } }, _buildList: function() { var self = this, o = this.options, placeholder = this.placeholder, needPlaceholder = true, dataIcon = "false", $options, numOptions, select, dataPrefix = "data-" + $.mobile.ns, dataIndexAttr = dataPrefix + "option-index", dataIconAttr = dataPrefix + "icon", dataRoleAttr = dataPrefix + "role", dataPlaceholderAttr = dataPrefix + "placeholder", fragment = document.createDocumentFragment(), isPlaceholderItem = false, optGroup, i, option, $option, parent, text, anchor, classes, optLabel, divider, item; self.list.empty().filter( ".ui-listview" ).listview( "destroy" ); $options = this._selectOptions(); numOptions = $options.length; select = this.select[ 0 ]; for ( i = 0; i < numOptions;i++, isPlaceholderItem = false) { option = $options[i]; $option = $( option ); // Do not create options based on ui-screen-hidden select options if ( $option.hasClass( "ui-screen-hidden" ) ) { continue; } parent = option.parentNode; text = $option.text(); anchor = document.createElement( "a" ); classes = []; anchor.setAttribute( "href", "#" ); anchor.appendChild( document.createTextNode( text ) ); // Are we inside an optgroup? if ( parent !== select && parent.nodeName.toLowerCase() === "optgroup" ) { optLabel = parent.getAttribute( "label" ); if ( optLabel !== optGroup ) { divider = document.createElement( "li" ); divider.setAttribute( dataRoleAttr, "list-divider" ); divider.setAttribute( "role", "option" ); divider.setAttribute( "tabindex", "-1" ); divider.appendChild( document.createTextNode( optLabel ) ); fragment.appendChild( divider ); optGroup = optLabel; } } if ( needPlaceholder && ( !option.getAttribute( "value" ) || text.length === 0 || $option.jqmData( "placeholder" ) ) ) { needPlaceholder = false; isPlaceholderItem = true; // If we have identified a placeholder, record the fact that it was // us who have added the placeholder to the option and mark it // retroactively in the select as well if ( null === option.getAttribute( dataPlaceholderAttr ) ) { this._removePlaceholderAttr = true; } option.setAttribute( dataPlaceholderAttr, true ); if ( o.hidePlaceholderMenuItems ) { classes.push( "ui-screen-hidden" ); } if ( placeholder !== text ) { placeholder = self.placeholder = text; } } item = document.createElement( "li" ); if ( option.disabled ) { classes.push( "ui-state-disabled" ); item.setAttribute( "aria-disabled", true ); } item.setAttribute( dataIndexAttr, i ); item.setAttribute( dataIconAttr, dataIcon ); if ( isPlaceholderItem ) { item.setAttribute( dataPlaceholderAttr, true ); } item.className = classes.join( " " ); item.setAttribute( "role", "option" ); anchor.setAttribute( "tabindex", "-1" ); if ( this.isMultiple ) { $( anchor ).addClass( "ui-btn ui-checkbox-off ui-btn-icon-right" ); } item.appendChild( anchor ); fragment.appendChild( item ); } self.list[0].appendChild( fragment ); // Hide header if it's not a multiselect and there's no placeholder if ( !this.isMultiple && !placeholder.length ) { this.header.addClass( "ui-screen-hidden" ); } else { this.headerTitle.text( this.placeholder ); } // Now populated, create listview self.list.listview(); }, _button: function() { return this.options.nativeMenu ? this._super() : $( "<a>", { "href": "#", "role": "button", // TODO value is undefined at creation "id": this.buttonId, "aria-haspopup": "true", // TODO value is undefined at creation "aria-owns": this.menuId }); }, _destroy: function() { if ( !this.options.nativeMenu ) { this.close(); // Restore the tabindex attribute to its original value if ( this._origTabIndex !== undefined ) { if ( this._origTabIndex !== false ) { this.select.attr( "tabindex", this._origTabIndex ); } else { this.select.removeAttr( "tabindex" ); } } // Remove the placeholder attribute if we were the ones to add it if ( this._removePlaceholderAttr ) { this._selectOptions().removeAttr( "data-" + $.mobile.ns + "placeholder" ); } // Remove the popup this.listbox.remove(); // Remove the dialog this.menuPage.remove(); } // Chain up this._super(); } }); })( jQuery ); // buttonMarkup is deprecated as of 1.4.0 and will be removed in 1.5.0. (function( $, undefined ) { // General policy: Do not access data-* attributes except during enhancement. // In all other cases we determine the state of the button exclusively from its // className. That's why optionsToClasses expects a full complement of options, // and the jQuery plugin completes the set of options from the default values. // Map classes to buttonMarkup boolean options - used in classNameToOptions() var reverseBoolOptionMap = { "ui-shadow" : "shadow", "ui-corner-all" : "corners", "ui-btn-inline" : "inline", "ui-shadow-icon" : "iconshadow", /* TODO: Remove in 1.5 */ "ui-mini" : "mini" }, getAttrFixed = function() { var ret = $.mobile.getAttribute.apply( this, arguments ); return ( ret == null ? undefined : ret ); }, capitalLettersRE = /[A-Z]/g; // optionsToClasses: // @options: A complete set of options to convert to class names. // @existingClasses: extra classes to add to the result // // Converts @options to buttonMarkup classes and returns the result as an array // that can be converted to an element's className with .join( " " ). All // possible options must be set inside @options. Use $.fn.buttonMarkup.defaults // to get a complete set and use $.extend to override your choice of options // from that set. function optionsToClasses( options, existingClasses ) { var classes = existingClasses ? existingClasses : []; // Add classes to the array - first ui-btn classes.push( "ui-btn" ); // If there is a theme if ( options.theme ) { classes.push( "ui-btn-" + options.theme ); } // If there's an icon, add the icon-related classes if ( options.icon ) { classes = classes.concat([ "ui-icon-" + options.icon, "ui-btn-icon-" + options.iconpos ]); if ( options.iconshadow ) { classes.push( "ui-shadow-icon" ); /* TODO: Remove in 1.5 */ } } // Add the appropriate class for each boolean option if ( options.inline ) { classes.push( "ui-btn-inline" ); } if ( options.shadow ) { classes.push( "ui-shadow" ); } if ( options.corners ) { classes.push( "ui-corner-all" ); } if ( options.mini ) { classes.push( "ui-mini" ); } // Create a string from the array and return it return classes; } // classNameToOptions: // @classes: A string containing a .className-style space-separated class list // // Loops over @classes and calculates an options object based on the // buttonMarkup-related classes it finds. It records unrecognized classes in an // array. // // Returns: An object containing the following items: // // "options": buttonMarkup options found to be present because of the // presence/absence of corresponding classes // // "unknownClasses": a string containing all the non-buttonMarkup-related // classes found in @classes // // "alreadyEnhanced": A boolean indicating whether the ui-btn class was among // those found to be present function classNameToOptions( classes ) { var idx, map, unknownClass, alreadyEnhanced = false, noIcon = true, o = { icon: "", inline: false, shadow: false, corners: false, iconshadow: false, mini: false }, unknownClasses = []; classes = classes.split( " " ); // Loop over the classes for ( idx = 0 ; idx < classes.length ; idx++ ) { // Assume it's an unrecognized class unknownClass = true; // Recognize boolean options from the presence of classes map = reverseBoolOptionMap[ classes[ idx ] ]; if ( map !== undefined ) { unknownClass = false; o[ map ] = true; // Recognize the presence of an icon and establish the icon position } else if ( classes[ idx ].indexOf( "ui-btn-icon-" ) === 0 ) { unknownClass = false; noIcon = false; o.iconpos = classes[ idx ].substring( 12 ); // Establish which icon is present } else if ( classes[ idx ].indexOf( "ui-icon-" ) === 0 ) { unknownClass = false; o.icon = classes[ idx ].substring( 8 ); // Establish the theme - this recognizes one-letter theme swatch names } else if ( classes[ idx ].indexOf( "ui-btn-" ) === 0 && classes[ idx ].length === 8 ) { unknownClass = false; o.theme = classes[ idx ].substring( 7 ); // Recognize that this element has already been buttonMarkup-enhanced } else if ( classes[ idx ] === "ui-btn" ) { unknownClass = false; alreadyEnhanced = true; } // If this class has not been recognized, add it to the list if ( unknownClass ) { unknownClasses.push( classes[ idx ] ); } } // If a "ui-btn-icon-*" icon position class is absent there cannot be an icon if ( noIcon ) { o.icon = ""; } return { options: o, unknownClasses: unknownClasses, alreadyEnhanced: alreadyEnhanced }; } function camelCase2Hyphenated( c ) { return "-" + c.toLowerCase(); } // $.fn.buttonMarkup: // DOM: gets/sets .className // // @options: options to apply to the elements in the jQuery object // @overwriteClasses: boolean indicating whether to honour existing classes // // Calculates the classes to apply to the elements in the jQuery object based on // the options passed in. If @overwriteClasses is true, it sets the className // property of each element in the jQuery object to the buttonMarkup classes // it calculates based on the options passed in. // // If you wish to preserve any classes that are already present on the elements // inside the jQuery object, including buttonMarkup-related classes that were // added by a previous call to $.fn.buttonMarkup() or during page enhancement // then you should omit @overwriteClasses or set it to false. $.fn.buttonMarkup = function( options, overwriteClasses ) { var idx, data, el, retrievedOptions, optionKey, defaults = $.fn.buttonMarkup.defaults; for ( idx = 0 ; idx < this.length ; idx++ ) { el = this[ idx ]; data = overwriteClasses ? // Assume this element is not enhanced and ignore its classes { alreadyEnhanced: false, unknownClasses: [] } : // Otherwise analyze existing classes to establish existing options and // classes classNameToOptions( el.className ); retrievedOptions = $.extend( {}, // If the element already has the class ui-btn, then we assume that // it has passed through buttonMarkup before - otherwise, the options // returned by classNameToOptions do not correctly reflect the state of // the element ( data.alreadyEnhanced ? data.options : {} ), // Finally, apply the options passed in options ); // If this is the first call on this element, retrieve remaining options // from the data-attributes if ( !data.alreadyEnhanced ) { for ( optionKey in defaults ) { if ( retrievedOptions[ optionKey ] === undefined ) { retrievedOptions[ optionKey ] = getAttrFixed( el, optionKey.replace( capitalLettersRE, camelCase2Hyphenated ) ); } } } el.className = optionsToClasses( // Merge all the options and apply them as classes $.extend( {}, // The defaults form the basis defaults, // Add the computed options retrievedOptions ), // ... and re-apply any unrecognized classes that were found data.unknownClasses ).join( " " ); if ( el.tagName.toLowerCase() !== "button" ) { el.setAttribute( "role", "button" ); } } return this; }; // buttonMarkup defaults. This must be a complete set, i.e., a value must be // given here for all recognized options $.fn.buttonMarkup.defaults = { icon: "", iconpos: "left", theme: null, inline: false, shadow: true, corners: true, iconshadow: false, /* TODO: Remove in 1.5. Option deprecated in 1.4. */ mini: false }; $.extend( $.fn.buttonMarkup, { initSelector: "a:jqmData(role='button'), .ui-bar > a, .ui-bar > :jqmData(role='controlgroup') > a, button" }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.controlgroup", $.extend( { options: { enhanced: false, theme: null, shadow: false, corners: true, excludeInvisible: true, type: "vertical", mini: false }, _create: function() { var elem = this.element, opts = this.options; // Run buttonmarkup if ( $.fn.buttonMarkup ) { this.element.find( $.fn.buttonMarkup.initSelector ).buttonMarkup(); } // Enhance child widgets $.each( this._childWidgets, $.proxy( function( number, widgetName ) { if ( $.mobile[ widgetName ] ) { this.element.find( $.mobile[ widgetName ].initSelector ).not( $.mobile.page.prototype.keepNativeSelector() )[ widgetName ](); } }, this )); $.extend( this, { _ui: null, _initialRefresh: true }); if ( opts.enhanced ) { this._ui = { groupLegend: elem.children( ".ui-controlgroup-label" ).children(), childWrapper: elem.children( ".ui-controlgroup-controls" ) }; } else { this._ui = this._enhance(); } }, _childWidgets: [ "checkboxradio", "selectmenu", "button" ], _themeClassFromOption: function( value ) { return ( value ? ( value === "none" ? "" : "ui-group-theme-" + value ) : "" ); }, _enhance: function() { var elem = this.element, opts = this.options, ui = { groupLegend: elem.children( "legend" ), childWrapper: elem .addClass( "ui-controlgroup " + "ui-controlgroup-" + ( opts.type === "horizontal" ? "horizontal" : "vertical" ) + " " + this._themeClassFromOption( opts.theme ) + " " + ( opts.corners ? "ui-corner-all " : "" ) + ( opts.mini ? "ui-mini " : "" ) ) .wrapInner( "<div " + "class='ui-controlgroup-controls " + ( opts.shadow === true ? "ui-shadow" : "" ) + "'></div>" ) .children() }; if ( ui.groupLegend.length > 0 ) { $( "<div role='heading' class='ui-controlgroup-label'></div>" ) .append( ui.groupLegend ) .prependTo( elem ); } return ui; }, _init: function() { this.refresh(); }, _setOptions: function( options ) { var callRefresh, returnValue, elem = this.element; // Must have one of horizontal or vertical if ( options.type !== undefined ) { elem .removeClass( "ui-controlgroup-horizontal ui-controlgroup-vertical" ) .addClass( "ui-controlgroup-" + ( options.type === "horizontal" ? "horizontal" : "vertical" ) ); callRefresh = true; } if ( options.theme !== undefined ) { elem .removeClass( this._themeClassFromOption( this.options.theme ) ) .addClass( this._themeClassFromOption( options.theme ) ); } if ( options.corners !== undefined ) { elem.toggleClass( "ui-corner-all", options.corners ); } if ( options.mini !== undefined ) { elem.toggleClass( "ui-mini", options.mini ); } if ( options.shadow !== undefined ) { this._ui.childWrapper.toggleClass( "ui-shadow", options.shadow ); } if ( options.excludeInvisible !== undefined ) { this.options.excludeInvisible = options.excludeInvisible; callRefresh = true; } returnValue = this._super( options ); if ( callRefresh ) { this.refresh(); } return returnValue; }, container: function() { return this._ui.childWrapper; }, refresh: function() { var $el = this.container(), els = $el.find( ".ui-btn" ).not( ".ui-slider-handle" ), create = this._initialRefresh; if ( $.mobile.checkboxradio ) { $el.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" ); } this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create ); this._initialRefresh = false; }, // Caveat: If the legend is not the first child of the controlgroup at enhance // time, it will be after _destroy(). _destroy: function() { var ui, buttons, opts = this.options; if ( opts.enhanced ) { return this; } ui = this._ui; buttons = this.element .removeClass( "ui-controlgroup " + "ui-controlgroup-horizontal ui-controlgroup-vertical ui-corner-all ui-mini " + this._themeClassFromOption( opts.theme ) ) .find( ".ui-btn" ) .not( ".ui-slider-handle" ); this._removeFirstLastClasses( buttons ); ui.groupLegend.unwrap(); ui.childWrapper.children().unwrap(); } }, $.mobile.behaviors.addFirstLastClasses ) ); })(jQuery); (function( $, undefined ) { $.widget( "mobile.toolbar", { initSelector: ":jqmData(role='footer'), :jqmData(role='header')", options: { theme: null, addBackBtn: false, backBtnTheme: null, backBtnText: "Back" }, _create: function() { var leftbtn, rightbtn, role = this.element.is( ":jqmData(role='header')" ) ? "header" : "footer", page = this.element.closest( ".ui-page" ); if ( page.length === 0 ) { page = false; this._on( this.document, { "pageshow": "refresh" }); } $.extend( this, { role: role, page: page, leftbtn: leftbtn, rightbtn: rightbtn }); this.element.attr( "role", role === "header" ? "banner" : "contentinfo" ).addClass( "ui-" + role ); this.refresh(); this._setOptions( this.options ); }, _setOptions: function( o ) { if ( o.addBackBtn !== undefined ) { if ( this.options.addBackBtn && this.role === "header" && $( ".ui-page" ).length > 1 && this.page[ 0 ].getAttribute( "data-" + $.mobile.ns + "url" ) !== $.mobile.path.stripHash( location.hash ) && !this.leftbtn ) { this._addBackButton(); } else { this.element.find( ".ui-toolbar-back-btn" ).remove(); } } if ( o.backBtnTheme != null ) { this.element .find( ".ui-toolbar-back-btn" ) .addClass( "ui-btn ui-btn-" + o.backBtnTheme ); } if ( o.backBtnText !== undefined ) { this.element.find( ".ui-toolbar-back-btn .ui-btn-text" ).text( o.backBtnText ); } if ( o.theme !== undefined ) { var currentTheme = this.options.theme ? this.options.theme : "inherit", newTheme = o.theme ? o.theme : "inherit"; this.element.removeClass( "ui-bar-" + currentTheme ).addClass( "ui-bar-" + newTheme ); } this._super( o ); }, refresh: function() { if ( this.role === "header" ) { this._addHeaderButtonClasses(); } if ( !this.page ) { this._setRelative(); if ( this.role === "footer" ) { this.element.appendTo( "body" ); } } this._addHeadingClasses(); this._btnMarkup(); }, //we only want this to run on non fixed toolbars so make it easy to override _setRelative: function() { $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); }, // Deprecated in 1.4. As from 1.5 button classes have to be present in the markup. _btnMarkup: function() { this.element .children( "a" ) .filter( ":not([data-" + $.mobile.ns + "role='none'])" ) .attr( "data-" + $.mobile.ns + "role", "button" ); this.element.trigger( "create" ); }, // Deprecated in 1.4. As from 1.5 ui-btn-left/right classes have to be present in the markup. _addHeaderButtonClasses: function() { var $headeranchors = this.element.children( "a, button" ); this.leftbtn = $headeranchors.hasClass( "ui-btn-left" ); this.rightbtn = $headeranchors.hasClass( "ui-btn-right" ); this.leftbtn = this.leftbtn || $headeranchors.eq( 0 ).not( ".ui-btn-right" ).addClass( "ui-btn-left" ).length; this.rightbtn = this.rightbtn || $headeranchors.eq( 1 ).addClass( "ui-btn-right" ).length; }, _addBackButton: function() { var options = this.options, theme = options.backBtnTheme || options.theme; $( "<a role='button' href='javascript:void(0);' " + "class='ui-btn ui-corner-all ui-shadow ui-btn-left " + ( theme ? "ui-btn-" + theme + " " : "" ) + "ui-toolbar-back-btn ui-icon-carat-l ui-btn-icon-left' " + "data-" + $.mobile.ns + "rel='back'>" + options.backBtnText + "</a>" ) .prependTo( this.element ); }, _addHeadingClasses: function() { this.element.children( "h1, h2, h3, h4, h5, h6" ) .addClass( "ui-title" ) // Regardless of h element number in src, it becomes h1 for the enhanced page .attr({ "role": "heading", "aria-level": "1" }); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { options: { position:null, visibleOnPageShow: true, disablePageZoom: true, transition: "slide", //can be none, fade, slide (slide maps to slideup or slidedown) fullscreen: false, tapToggle: true, tapToggleBlacklist: "a, button, input, select, textarea, .ui-header-fixed, .ui-footer-fixed, .ui-flipswitch, .ui-popup, .ui-panel, .ui-panel-dismiss-open", hideDuringFocus: "input, textarea, select", updatePagePadding: true, trackPersistentToolbars: true, // Browser detection! Weeee, here we go... // Unfortunately, position:fixed is costly, not to mention probably impossible, to feature-detect accurately. // Some tests exist, but they currently return false results in critical devices and browsers, which could lead to a broken experience. // Testing fixed positioning is also pretty obtrusive to page load, requiring injected elements and scrolling the window // The following function serves to rule out some popular browsers with known fixed-positioning issues // This is a plugin option like any other, so feel free to improve or overwrite it supportBlacklist: function() { return !$.support.fixedPosition; } }, _create: function() { this._super(); if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { this._makeFixed(); } }, _makeFixed: function() { this.element.addClass( "ui-"+ this.role +"-fixed" ); this.updatePagePadding(); this._addTransitionClass(); this._bindPageEvents(); this._bindToggleHandlers(); }, _setOptions: function( o ) { if ( o.position === "fixed" && this.options.position !== "fixed" ) { this._makeFixed(); } if ( this.options.position === "fixed" && !this.options.supportBlacklist() ) { var $page = ( !!this.page )? this.page: ( $(".ui-page-active").length > 0 )? $(".ui-page-active"): $(".ui-page").eq(0); if ( o.fullscreen !== undefined) { if ( o.fullscreen ) { this.element.addClass( "ui-"+ this.role +"-fullscreen" ); $page.addClass( "ui-page-" + this.role + "-fullscreen" ); } // If not fullscreen, add class to page to set top or bottom padding else { this.element.removeClass( "ui-"+ this.role +"-fullscreen" ); $page.removeClass( "ui-page-" + this.role + "-fullscreen" ).addClass( "ui-page-" + this.role+ "-fixed" ); } } } this._super(o); }, _addTransitionClass: function() { var tclass = this.options.transition; if ( tclass && tclass !== "none" ) { // use appropriate slide for header or footer if ( tclass === "slide" ) { tclass = this.element.hasClass( "ui-header" ) ? "slidedown" : "slideup"; } this.element.addClass( tclass ); } }, _bindPageEvents: function() { var page = ( !!this.page )? this.element.closest( ".ui-page" ): this.document; //page event bindings // Fixed toolbars require page zoom to be disabled, otherwise usability issues crop up // This method is meant to disable zoom while a fixed-positioned toolbar page is visible this._on( page , { "pagebeforeshow": "_handlePageBeforeShow", "webkitAnimationStart":"_handleAnimationStart", "animationstart":"_handleAnimationStart", "updatelayout": "_handleAnimationStart", "pageshow": "_handlePageShow", "pagebeforehide": "_handlePageBeforeHide" }); }, _handlePageBeforeShow: function( ) { var o = this.options; if ( o.disablePageZoom ) { $.mobile.zoom.disable( true ); } if ( !o.visibleOnPageShow ) { this.hide( true ); } }, _handleAnimationStart: function() { if ( this.options.updatePagePadding ) { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); } }, _handlePageShow: function() { this.updatePagePadding( ( !!this.page )? this.page: ".ui-page-active" ); if ( this.options.updatePagePadding ) { this._on( this.window, { "throttledresize": "updatePagePadding" } ); } }, _handlePageBeforeHide: function( e, ui ) { var o = this.options, thisFooter, thisHeader, nextFooter, nextHeader; if ( o.disablePageZoom ) { $.mobile.zoom.enable( true ); } if ( o.updatePagePadding ) { this._off( this.window, "throttledresize" ); } if ( o.trackPersistentToolbars ) { thisFooter = $( ".ui-footer-fixed:jqmData(id)", this.page ); thisHeader = $( ".ui-header-fixed:jqmData(id)", this.page ); nextFooter = thisFooter.length && ui.nextPage && $( ".ui-footer-fixed:jqmData(id='" + thisFooter.jqmData( "id" ) + "')", ui.nextPage ) || $(); nextHeader = thisHeader.length && ui.nextPage && $( ".ui-header-fixed:jqmData(id='" + thisHeader.jqmData( "id" ) + "')", ui.nextPage ) || $(); if ( nextFooter.length || nextHeader.length ) { nextFooter.add( nextHeader ).appendTo( $.mobile.pageContainer ); ui.nextPage.one( "pageshow", function() { nextHeader.prependTo( this ); nextFooter.appendTo( this ); }); } } }, _visible: true, // This will set the content element's top or bottom padding equal to the toolbar's height updatePagePadding: function( tbPage ) { var $el = this.element, header = ( this.role ==="header" ), pos = parseFloat( $el.css( header ? "top" : "bottom" ) ); // This behavior only applies to "fixed", not "fullscreen" if ( this.options.fullscreen ) { return; } // tbPage argument can be a Page object or an event, if coming from throttled resize. tbPage = ( tbPage && tbPage.type === undefined && tbPage ) || this.page || $el.closest( ".ui-page" ); tbPage = ( !!this.page )? this.page: ".ui-page-active"; $( tbPage ).css( "padding-" + ( header ? "top" : "bottom" ), $el.outerHeight() + pos ); }, _useTransition: function( notransition ) { var $win = this.window, $el = this.element, scroll = $win.scrollTop(), elHeight = $el.height(), pHeight = ( !!this.page )? $el.closest( ".ui-page" ).height():$(".ui-page-active").height(), viewportHeight = $.mobile.getScreenHeight(); return !notransition && ( this.options.transition && this.options.transition !== "none" && ( ( this.role === "header" && !this.options.fullscreen && scroll > elHeight ) || ( this.role === "footer" && !this.options.fullscreen && scroll + viewportHeight < pHeight - elHeight ) ) || this.options.fullscreen ); }, show: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element; if ( this._useTransition( notransition ) ) { $el .removeClass( "out " + hideClass ) .addClass( "in" ) .animationComplete(function () { $el.removeClass( "in" ); }); } else { $el.removeClass( hideClass ); } this._visible = true; }, hide: function( notransition ) { var hideClass = "ui-fixed-hidden", $el = this.element, // if it's a slide transition, our new transitions need the reverse class as well to slide outward outclass = "out" + ( this.options.transition === "slide" ? " reverse" : "" ); if ( this._useTransition( notransition ) ) { $el .addClass( outclass ) .removeClass( "in" ) .animationComplete(function() { $el.addClass( hideClass ).removeClass( outclass ); }); } else { $el.addClass( hideClass ).removeClass( outclass ); } this._visible = false; }, toggle: function() { this[ this._visible ? "hide" : "show" ](); }, _bindToggleHandlers: function() { var self = this, o = self.options, delayShow, delayHide, isVisible = true, page = ( !!this.page )? this.page: $(".ui-page"); // tap toggle page .bind( "vclick", function( e ) { if ( o.tapToggle && !$( e.target ).closest( o.tapToggleBlacklist ).length ) { self.toggle(); } }) .bind( "focusin focusout", function( e ) { //this hides the toolbars on a keyboard pop to give more screen room and prevent ios bug which //positions fixed toolbars in the middle of the screen on pop if the input is near the top or //bottom of the screen addresses issues #4410 Footer navbar moves up when clicking on a textbox in an Android environment //and issue #4113 Header and footer change their position after keyboard popup - iOS //and issue #4410 Footer navbar moves up when clicking on a textbox in an Android environment if ( screen.width < 1025 && $( e.target ).is( o.hideDuringFocus ) && !$( e.target ).closest( ".ui-header-fixed, .ui-footer-fixed" ).length ) { //Fix for issue #4724 Moving through form in Mobile Safari with "Next" and "Previous" system //controls causes fixed position, tap-toggle false Header to reveal itself // isVisible instead of self._visible because the focusin and focusout events fire twice at the same time // Also use a delay for hiding the toolbars because on Android native browser focusin is direclty followed // by a focusout when a native selects opens and the other way around when it closes. if ( e.type === "focusout" && !isVisible ) { isVisible = true; //wait for the stack to unwind and see if we have jumped to another input clearTimeout( delayHide ); delayShow = setTimeout( function() { self.show(); }, 0 ); } else if ( e.type === "focusin" && !!isVisible ) { //if we have jumped to another input clear the time out to cancel the show. clearTimeout( delayShow ); isVisible = false; delayHide = setTimeout( function() { self.hide(); }, 0 ); } } }); }, _setRelative: function() { if( this.options.position !== "fixed" ){ $( "[data-"+ $.mobile.ns + "role='page']" ).css({ "position": "relative" }); } }, _destroy: function() { var $el = this.element, header = $el.hasClass( "ui-header" ); $el.closest( ".ui-page" ).css( "padding-" + ( header ? "top" : "bottom" ), "" ); $el.removeClass( "ui-header-fixed ui-footer-fixed ui-header-fullscreen ui-footer-fullscreen in out fade slidedown slideup ui-fixed-hidden" ); $el.closest( ".ui-page" ).removeClass( "ui-page-header-fixed ui-page-footer-fixed ui-page-header-fullscreen ui-page-footer-fullscreen" ); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.toolbar", $.mobile.toolbar, { _makeFixed: function() { this._super(); this._workarounds(); }, //check the browser and version and run needed workarounds _workarounds: function() { var ua = navigator.userAgent, platform = navigator.platform, // Rendering engine is Webkit, and capture major version wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ), wkversion = !!wkmatch && wkmatch[ 1 ], os = null, self = this; //set the os we are working in if it dosent match one with workarounds return if ( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) { os = "ios"; } else if ( ua.indexOf( "Android" ) > -1 ) { os = "android"; } else { return; } //check os version if it dosent match one with workarounds return if ( os === "ios" ) { //iOS workarounds self._bindScrollWorkaround(); } else if ( os === "android" && wkversion && wkversion < 534 ) { //Android 2.3 run all Android 2.3 workaround self._bindScrollWorkaround(); self._bindListThumbWorkaround(); } else { return; } }, //Utility class for checking header and footer positions relative to viewport _viewportOffset: function() { var $el = this.element, header = $el.hasClass( "ui-header" ), offset = Math.abs( $el.offset().top - this.window.scrollTop() ); if ( !header ) { offset = Math.round( offset - this.window.height() + $el.outerHeight() ) - 60; } return offset; }, //bind events for _triggerRedraw() function _bindScrollWorkaround: function() { var self = this; //bind to scrollstop and check if the toolbars are correctly positioned this._on( this.window, { scrollstop: function() { var viewportOffset = self._viewportOffset(); //check if the header is visible and if its in the right place if ( viewportOffset > 2 && self._visible ) { self._triggerRedraw(); } }}); }, //this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3 //and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used //the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar //setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other //platforms we scope this with the class ui-android-2x-fix _bindListThumbWorkaround: function() { this.element.closest( ".ui-page" ).addClass( "ui-android-2x-fixed" ); }, //this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android //and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers. //this also addresses not on fixed toolbars page in docs //adding 1px of padding to the bottom then removing it causes a "redraw" //which positions the toolbars correctly (they will always be visually correct) _triggerRedraw: function() { var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) ); //trigger page redraw to fix incorrectly positioned fixed elements $( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) + "px" ); //if the padding is reset with out a timeout the reposition will not occure. //this is independant of JQM the browser seems to need the time to react. setTimeout( function() { $( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" ); }, 0 ); }, destroy: function() { this._super(); //Remove the class we added to the page previously in android 2.x this.element.closest( ".ui-page-active" ).removeClass( "ui-android-2x-fix" ); } }); })( jQuery ); ( function( $, undefined ) { var ieHack = ( $.mobile.browser.oldIE && $.mobile.browser.oldIE <= 8 ), uiTemplate = $( "<div class='ui-popup-arrow-guide'></div>" + "<div class='ui-popup-arrow-container" + ( ieHack ? " ie" : "" ) + "'>" + "<div class='ui-popup-arrow'></div>" + "</div>" ); function getArrow() { var clone = uiTemplate.clone(), gd = clone.eq( 0 ), ct = clone.eq( 1 ), ar = ct.children(); return { arEls: ct.add( gd ), gd: gd, ct: ct, ar: ar }; } $.widget( "mobile.popup", $.mobile.popup, { options: { arrow: "" }, _create: function() { var ar, ret = this._super(); if ( this.options.arrow ) { this._ui.arrow = ar = this._addArrow(); } return ret; }, _addArrow: function() { var theme, opts = this.options, ar = getArrow(); theme = this._themeClassFromOption( "ui-body-", opts.theme ); ar.ar.addClass( theme + ( opts.shadow ? " ui-overlay-shadow" : "" ) ); ar.arEls.hide().appendTo( this.element ); return ar; }, _unenhance: function() { var ar = this._ui.arrow; if ( ar ) { ar.arEls.remove(); } return this._super(); }, // Pretend to show an arrow described by @p and @dir and calculate the // distance from the desired point. If a best-distance is passed in, return // the minimum of the one passed in and the one calculated. _tryAnArrow: function( p, dir, desired, s, best ) { var result, r, diff, desiredForArrow = {}, tip = {}; // If the arrow has no wiggle room along the edge of the popup, it cannot // be displayed along the requested edge without it sticking out. if ( s.arFull[ p.dimKey ] > s.guideDims[ p.dimKey ] ) { return best; } desiredForArrow[ p.fst ] = desired[ p.fst ] + ( s.arHalf[ p.oDimKey ] + s.menuHalf[ p.oDimKey ] ) * p.offsetFactor - s.contentBox[ p.fst ] + ( s.clampInfo.menuSize[ p.oDimKey ] - s.contentBox[ p.oDimKey ] ) * p.arrowOffsetFactor; desiredForArrow[ p.snd ] = desired[ p.snd ]; result = s.result || this._calculateFinalLocation( desiredForArrow, s.clampInfo ); r = { x: result.left, y: result.top }; tip[ p.fst ] = r[ p.fst ] + s.contentBox[ p.fst ] + p.tipOffset; tip[ p.snd ] = Math.max( result[ p.prop ] + s.guideOffset[ p.prop ] + s.arHalf[ p.dimKey ], Math.min( result[ p.prop ] + s.guideOffset[ p.prop ] + s.guideDims[ p.dimKey ] - s.arHalf[ p.dimKey ], desired[ p.snd ] ) ); diff = Math.abs( desired.x - tip.x ) + Math.abs( desired.y - tip.y ); if ( !best || diff < best.diff ) { // Convert tip offset to coordinates inside the popup tip[ p.snd ] -= s.arHalf[ p.dimKey ] + result[ p.prop ] + s.contentBox[ p.snd ]; best = { dir: dir, diff: diff, result: result, posProp: p.prop, posVal: tip[ p.snd ] }; } return best; }, _getPlacementState: function( clamp ) { var offset, gdOffset, ar = this._ui.arrow, state = { clampInfo: this._clampPopupWidth( !clamp ), arFull: { cx: ar.ct.width(), cy: ar.ct.height() }, guideDims: { cx: ar.gd.width(), cy: ar.gd.height() }, guideOffset: ar.gd.offset() }; offset = this.element.offset(); ar.gd.css( { left: 0, top: 0, right: 0, bottom: 0 } ); gdOffset = ar.gd.offset(); state.contentBox = { x: gdOffset.left - offset.left, y: gdOffset.top - offset.top, cx: ar.gd.width(), cy: ar.gd.height() }; ar.gd.removeAttr( "style" ); // The arrow box moves between guideOffset and guideOffset + guideDims - arFull state.guideOffset = { left: state.guideOffset.left - offset.left, top: state.guideOffset.top - offset.top }; state.arHalf = { cx: state.arFull.cx / 2, cy: state.arFull.cy / 2 }; state.menuHalf = { cx: state.clampInfo.menuSize.cx / 2, cy: state.clampInfo.menuSize.cy / 2 }; return state; }, _placementCoords: function( desired ) { var state, best, params, elOffset, bgRef, optionValue = this.options.arrow, ar = this._ui.arrow; if ( !ar ) { return this._super( desired ); } ar.arEls.show(); bgRef = {}; state = this._getPlacementState( true ); params = { "l": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: 1, tipOffset: -state.arHalf.cx, arrowOffsetFactor: 0 }, "r": { fst: "x", snd: "y", prop: "top", dimKey: "cy", oDimKey: "cx", offsetFactor: -1, tipOffset: state.arHalf.cx + state.contentBox.cx, arrowOffsetFactor: 1 }, "b": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: -1, tipOffset: state.arHalf.cy + state.contentBox.cy, arrowOffsetFactor: 1 }, "t": { fst: "y", snd: "x", prop: "left", dimKey: "cx", oDimKey: "cy", offsetFactor: 1, tipOffset: -state.arHalf.cy, arrowOffsetFactor: 0 } }; // Try each side specified in the options to see on which one the arrow // should be placed such that the distance between the tip of the arrow and // the desired coordinates is the shortest. $.each( ( optionValue === true ? "l,t,r,b" : optionValue ).split( "," ), $.proxy( function( key, value ) { best = this._tryAnArrow( params[ value ], value, desired, state, best ); }, this ) ); // Could not place the arrow along any of the edges - behave as if showing // the arrow was turned off. if ( !best ) { ar.arEls.hide(); return this._super( desired ); } // Move the arrow into place ar.ct .removeClass( "ui-popup-arrow-l ui-popup-arrow-t ui-popup-arrow-r ui-popup-arrow-b" ) .addClass( "ui-popup-arrow-" + best.dir ) .removeAttr( "style" ).css( best.posProp, best.posVal ) .show(); // Do not move/size the background div on IE, because we use the arrow div for background as well. if ( !ieHack ) { elOffset = this.element.offset(); bgRef[ params[ best.dir ].fst ] = ar.ct.offset(); bgRef[ params[ best.dir ].snd ] = { left: elOffset.left + state.contentBox.x, top: elOffset.top + state.contentBox.y }; } return best.result; }, _setOptions: function( opts ) { var newTheme, oldTheme = this.options.theme, ar = this._ui.arrow, ret = this._super( opts ); if ( opts.arrow !== undefined ) { if ( !ar && opts.arrow ) { this._ui.arrow = this._addArrow(); // Important to return here so we don't set the same options all over // again below. return; } else if ( ar && !opts.arrow ) { ar.arEls.remove(); this._ui.arrow = null; } } // Reassign with potentially new arrow ar = this._ui.arrow; if ( ar ) { if ( opts.theme !== undefined ) { oldTheme = this._themeClassFromOption( "ui-body-", oldTheme ); newTheme = this._themeClassFromOption( "ui-body-", opts.theme ); ar.ar.removeClass( oldTheme ).addClass( newTheme ); } if ( opts.shadow !== undefined ) { ar.ar.toggleClass( "ui-overlay-shadow", opts.shadow ); } } return ret; }, _destroy: function() { var ar = this._ui.arrow; if ( ar ) { ar.arEls.remove(); } return this._super(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.panel", { options: { classes: { panel: "ui-panel", panelOpen: "ui-panel-open", panelClosed: "ui-panel-closed", panelFixed: "ui-panel-fixed", panelInner: "ui-panel-inner", modal: "ui-panel-dismiss", modalOpen: "ui-panel-dismiss-open", pageContainer: "ui-panel-page-container", pageWrapper: "ui-panel-wrapper", pageFixedToolbar: "ui-panel-fixed-toolbar", pageContentPrefix: "ui-panel-page-content", /* Used for wrapper and fixed toolbars position, display and open classes. */ animate: "ui-panel-animate" }, animate: true, theme: null, position: "left", dismissible: true, display: "reveal", //accepts reveal, push, overlay swipeClose: true, positionFixed: false }, _closeLink: null, _parentPage: null, _page: null, _modal: null, _panelInner: null, _wrapper: null, _fixedToolbars: null, _create: function() { var el = this.element, parentPage = el.closest( ".ui-page, :jqmData(role='page')" ); // expose some private props to other methods $.extend( this, { _closeLink: el.find( ":jqmData(rel='close')" ), _parentPage: ( parentPage.length > 0 ) ? parentPage : false, _openedPage: null, _page: this._getPage, _panelInner: this._getPanelInner(), _fixedToolbars: this._getFixedToolbars }); if ( this.options.display !== "overlay" ){ this._getWrapper(); } this._addPanelClasses(); // if animating, add the class to do so if ( $.support.cssTransform3d && !!this.options.animate ) { this.element.addClass( this.options.classes.animate ); } this._bindUpdateLayout(); this._bindCloseEvents(); this._bindLinkListeners(); this._bindPageEvents(); if ( !!this.options.dismissible ) { this._createModal(); } this._bindSwipeEvents(); }, _getPanelInner: function() { var panelInner = this.element.find( "." + this.options.classes.panelInner ); if ( panelInner.length === 0 ) { panelInner = this.element.children().wrapAll( "<div class='" + this.options.classes.panelInner + "' />" ).parent(); } return panelInner; }, _createModal: function() { var self = this, target = self._parentPage ? self._parentPage.parent() : self.element.parent(); self._modal = $( "<div class='" + self.options.classes.modal + "'></div>" ) .on( "mousedown", function() { self.close(); }) .appendTo( target ); }, _getPage: function() { var page = this._openedPage || this._parentPage || $( "." + $.mobile.activePageClass ); return page; }, _getWrapper: function() { var wrapper = this._page().find( "." + this.options.classes.pageWrapper ); if ( wrapper.length === 0 ) { wrapper = this._page().children( ".ui-header:not(.ui-header-fixed), .ui-content:not(.ui-popup), .ui-footer:not(.ui-footer-fixed)" ) .wrapAll( "<div class='" + this.options.classes.pageWrapper + "'></div>" ) .parent(); } this._wrapper = wrapper; }, _getFixedToolbars: function() { var extFixedToolbars = $( "body" ).children( ".ui-header-fixed, .ui-footer-fixed" ), intFixedToolbars = this._page().find( ".ui-header-fixed, .ui-footer-fixed" ), fixedToolbars = extFixedToolbars.add( intFixedToolbars ).addClass( this.options.classes.pageFixedToolbar ); return fixedToolbars; }, _getPosDisplayClasses: function( prefix ) { return prefix + "-position-" + this.options.position + " " + prefix + "-display-" + this.options.display; }, _getPanelClasses: function() { var panelClasses = this.options.classes.panel + " " + this._getPosDisplayClasses( this.options.classes.panel ) + " " + this.options.classes.panelClosed + " " + "ui-body-" + ( this.options.theme ? this.options.theme : "inherit" ); if ( !!this.options.positionFixed ) { panelClasses += " " + this.options.classes.panelFixed; } return panelClasses; }, _addPanelClasses: function() { this.element.addClass( this._getPanelClasses() ); }, _handleCloseClickAndEatEvent: function( event ) { if ( !event.isDefaultPrevented() ) { event.preventDefault(); this.close(); return false; } }, _handleCloseClick: function( event ) { if ( !event.isDefaultPrevented() ) { this.close(); } }, _bindCloseEvents: function() { this._on( this._closeLink, { "click": "_handleCloseClick" }); this._on({ "click a:jqmData(ajax='false')": "_handleCloseClick" }); }, _positionPanel: function( scrollToTop ) { var self = this, panelInnerHeight = self._panelInner.outerHeight(), expand = panelInnerHeight > $.mobile.getScreenHeight(); if ( expand || !self.options.positionFixed ) { if ( expand ) { self._unfixPanel(); $.mobile.resetActivePageHeight( panelInnerHeight ); } if ( scrollToTop ) { this.window[ 0 ].scrollTo( 0, $.mobile.defaultHomeScroll ); } } else { self._fixPanel(); } }, _bindFixListener: function() { this._on( $( window ), { "throttledresize": "_positionPanel" }); }, _unbindFixListener: function() { this._off( $( window ), "throttledresize" ); }, _unfixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.removeClass( this.options.classes.panelFixed ); } }, _fixPanel: function() { if ( !!this.options.positionFixed && $.support.fixedPosition ) { this.element.addClass( this.options.classes.panelFixed ); } }, _bindUpdateLayout: function() { var self = this; self.element.on( "updatelayout", function(/* e */) { if ( self._open ) { self._positionPanel(); } }); }, _bindLinkListeners: function() { this._on( "body", { "click a": "_handleClick" }); }, _handleClick: function( e ) { var link, panelId = this.element.attr( "id" ); if ( e.currentTarget.href.split( "#" )[ 1 ] === panelId && panelId !== undefined ) { e.preventDefault(); link = $( e.target ); if ( link.hasClass( "ui-btn" ) ) { link.addClass( $.mobile.activeBtnClass ); this.element.one( "panelopen panelclose", function() { link.removeClass( $.mobile.activeBtnClass ); }); } this.toggle(); return false; } }, _bindSwipeEvents: function() { var self = this, area = self._modal ? self.element.add( self._modal ) : self.element; // on swipe, close the panel if ( !!self.options.swipeClose ) { if ( self.options.position === "left" ) { area.on( "swipeleft.panel", function(/* e */) { self.close(); }); } else { area.on( "swiperight.panel", function(/* e */) { self.close(); }); } } }, _bindPageEvents: function() { var self = this; this.document // Close the panel if another panel on the page opens .on( "panelbeforeopen", function( e ) { if ( self._open && e.target !== self.element[ 0 ] ) { self.close(); } }) // On escape, close? might need to have a target check too... .on( "keyup.panel", function( e ) { if ( e.keyCode === 27 && self._open ) { self.close(); } }); if ( !this._parentPage && this.options.display !== "overlay" ) { this._on( this.document, { "pageshow": "_getWrapper" }); } // Clean up open panels after page hide if ( self._parentPage ) { this.document.on( "pagehide", ":jqmData(role='page')", function() { if ( self._open ) { self.close( true ); } }); } else { this.document.on( "pagebeforehide", function() { if ( self._open ) { self.close( true ); } }); } }, // state storage of open or closed _open: false, _pageContentOpenClasses: null, _modalOpenClasses: null, open: function( immediate ) { if ( !this._open ) { var self = this, o = self.options, _openPanel = function() { self.document.off( "panelclose" ); self._page().jqmData( "panel", "open" ); if ( $.support.cssTransform3d && !!o.animate && o.display !== "overlay" ) { self._wrapper.addClass( o.classes.animate ); self._fixedToolbars().addClass( o.classes.animate ); } if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.animationComplete( complete, "transition" ); } else { setTimeout( complete, 0 ); } if ( o.theme && o.display !== "overlay" ) { self._page().parent() .addClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } self.element .removeClass( o.classes.panelClosed ) .addClass( o.classes.panelOpen ); self._positionPanel( true ); self._pageContentOpenClasses = self._getPosDisplayClasses( o.classes.pageContentPrefix ); if ( o.display !== "overlay" ) { self._page().parent().addClass( o.classes.pageContainer ); self._wrapper.addClass( self._pageContentOpenClasses ); self._fixedToolbars().addClass( self._pageContentOpenClasses ); } self._modalOpenClasses = self._getPosDisplayClasses( o.classes.modal ) + " " + o.classes.modalOpen; if ( self._modal ) { self._modal .addClass( self._modalOpenClasses ) .height( Math.max( self._modal.height(), self.document.height() ) ); } }, complete = function() { if ( o.display !== "overlay" ) { self._wrapper.addClass( o.classes.pageContentPrefix + "-open" ); self._fixedToolbars().addClass( o.classes.pageContentPrefix + "-open" ); } self._bindFixListener(); self._trigger( "open" ); self._openedPage = self._page(); }; self._trigger( "beforeopen" ); if ( self._page().jqmData( "panel" ) === "open" ) { self.document.on( "panelclose", function() { _openPanel(); }); } else { _openPanel(); } self._open = true; } }, close: function( immediate ) { if ( this._open ) { var self = this, o = this.options, _closePanel = function() { self.element.removeClass( o.classes.panelOpen ); if ( o.display !== "overlay" ) { self._wrapper.removeClass( self._pageContentOpenClasses ); self._fixedToolbars().removeClass( self._pageContentOpenClasses ); } if ( !immediate && $.support.cssTransform3d && !!o.animate ) { self.element.animationComplete( complete, "transition" ); } else { setTimeout( complete, 0 ); } if ( self._modal ) { self._modal.removeClass( self._modalOpenClasses ); } }, complete = function() { if ( o.theme && o.display !== "overlay" ) { self._page().parent().removeClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } self.element.addClass( o.classes.panelClosed ); if ( o.display !== "overlay" ) { self._page().parent().removeClass( o.classes.pageContainer ); self._wrapper.removeClass( o.classes.pageContentPrefix + "-open" ); self._fixedToolbars().removeClass( o.classes.pageContentPrefix + "-open" ); } if ( $.support.cssTransform3d && !!o.animate && o.display !== "overlay" ) { self._wrapper.removeClass( o.classes.animate ); self._fixedToolbars().removeClass( o.classes.animate ); } self._fixPanel(); self._unbindFixListener(); $.mobile.resetActivePageHeight(); self._page().jqmRemoveData( "panel" ); self._trigger( "close" ); self._openedPage = null; }; self._trigger( "beforeclose" ); _closePanel(); self._open = false; } }, toggle: function() { this[ this._open ? "close" : "open" ](); }, _destroy: function() { var otherPanels, o = this.options, multiplePanels = ( $( "body > :mobile-panel" ).length + $.mobile.activePage.find( ":mobile-panel" ).length ) > 1; if ( o.display !== "overlay" ) { // remove the wrapper if not in use by another panel otherPanels = $( "body > :mobile-panel" ).add( $.mobile.activePage.find( ":mobile-panel" ) ); if ( otherPanels.not( ".ui-panel-display-overlay" ).not( this.element ).length === 0 ) { this._wrapper.children().unwrap(); } if ( this._open ) { this._fixedToolbars().removeClass( o.classes.pageContentPrefix + "-open" ); if ( $.support.cssTransform3d && !!o.animate ) { this._fixedToolbars().removeClass( o.classes.animate ); } this._page().parent().removeClass( o.classes.pageContainer ); if ( o.theme ) { this._page().parent().removeClass( o.classes.pageContainer + "-themed " + o.classes.pageContainer + "-" + o.theme ); } } } if ( !multiplePanels ) { this.document.off( "panelopen panelclose" ); } if ( this._open ) { this._page().jqmRemoveData( "panel" ); } this._panelInner.children().unwrap(); this.element .removeClass( [ this._getPanelClasses(), o.classes.panelOpen, o.classes.animate ].join( " " ) ) .off( "swipeleft.panel swiperight.panel" ) .off( "panelbeforeopen" ) .off( "panelhide" ) .off( "keyup.panel" ) .off( "updatelayout" ); if ( this._modal ) { this._modal.remove(); } } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", { options: { classes: { table: "ui-table" }, enhanced: false }, _create: function() { if ( !this.options.enhanced ) { this.element.addClass( this.options.classes.table ); } // extend here, assign on refresh > _setHeaders $.extend( this, { // Expose headers and allHeaders properties on the widget // headers references the THs within the first TR in the table headers: undefined, // allHeaders references headers, plus all THs in the thead, which may // include several rows, or not allHeaders: undefined }); this._refresh( true ); }, _setHeaders: function() { var trs = this.element.find( "thead tr" ); this.headers = this.element.find( "tr:eq(0)" ).children(); this.allHeaders = this.headers.add( trs.children() ); }, refresh: function() { this._refresh(); }, rebuild: $.noop, _refresh: function( /* create */ ) { var table = this.element, trs = table.find( "thead tr" ); // updating headers on refresh (fixes #5880) this._setHeaders(); // Iterate over the trs trs.each( function() { var columnCount = 0; // Iterate over the children of the tr $( this ).children().each( function() { var span = parseInt( this.getAttribute( "colspan" ), 10 ), selector = ":nth-child(" + ( columnCount + 1 ) + ")", j; this.setAttribute( "data-" + $.mobile.ns + "colstart", columnCount + 1 ); if ( span ) { for( j = 0; j < span - 1; j++ ) { columnCount++; selector += ", :nth-child(" + ( columnCount + 1 ) + ")"; } } // Store "cells" data on header as a reference to all cells in the // same column as this TH $( this ).jqmData( "cells", table.find( "tr" ).not( trs.eq( 0 ) ).not( this ).children( selector ) ); columnCount++; }); }); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.table, { options: { mode: "columntoggle", columnBtnTheme: null, columnPopupTheme: null, columnBtnText: "Columns...", classes: $.extend( $.mobile.table.prototype.options.classes, { popup: "ui-table-columntoggle-popup", columnBtn: "ui-table-columntoggle-btn", priorityPrefix: "ui-table-priority-", columnToggleTable: "ui-table-columntoggle" }) }, _create: function() { this._super(); if ( this.options.mode !== "columntoggle" ) { return; } $.extend( this, { _menu: null }); if ( this.options.enhanced ) { this._menu = $( this.document[ 0 ].getElementById( this._id() + "-popup" ) ).children().first(); this._addToggles( this._menu, true ); } else { this._menu = this._enhanceColToggle(); this.element.addClass( this.options.classes.columnToggleTable ); } this._setupEvents(); this._setToggleState(); }, _id: function() { return ( this.element.attr( "id" ) || ( this.widgetName + this.uuid ) ); }, _setupEvents: function() { //NOTE: inputs are bound in bindToggles, // so it can be called on refresh, too // update column toggles on resize this._on( this.window, { throttledresize: "_setToggleState" }); this._on( this._menu, { "change input": "_menuInputChange" }); }, _addToggles: function( menu, keep ) { var inputs, checkboxIndex = 0, opts = this.options, container = menu.controlgroup( "container" ); // allow update of menu on refresh (fixes #5880) if ( keep ) { inputs = menu.find( "input" ); } else { container.empty(); } // create the hide/show toggles this.headers.not( "td" ).each( function() { var header = $( this ), priority = $.mobile.getAttribute( this, "priority" ), cells = header.add( header.jqmData( "cells" ) ); if ( priority ) { cells.addClass( opts.classes.priorityPrefix + priority ); ( keep ? inputs.eq( checkboxIndex++ ) : $("<label><input type='checkbox' checked />" + ( header.children( "abbr" ).first().attr( "title" ) || header.text() ) + "</label>" ) .appendTo( container ) .children( 0 ) .checkboxradio( { theme: opts.columnPopupTheme }) ) .jqmData( "cells", cells ); } }); // set bindings here if ( !keep ) { menu.controlgroup( "refresh" ); } }, _menuInputChange: function( evt ) { var input = $( evt.target ), checked = input[ 0 ].checked; input.jqmData( "cells" ) .toggleClass( "ui-table-cell-hidden", !checked ) .toggleClass( "ui-table-cell-visible", checked ); if ( input[ 0 ].getAttribute( "locked" ) ) { input.removeAttr( "locked" ); this._unlockCells( input.jqmData( "cells" ) ); } else { input.attr( "locked", true ); } }, _unlockCells: function( cells ) { // allow hide/show via CSS only = remove all toggle-locks cells.removeClass( "ui-table-cell-hidden ui-table-cell-visible"); }, _enhanceColToggle: function() { var id , menuButton, popup, menu, table = this.element, opts = this.options, ns = $.mobile.ns, fragment = this.document[ 0 ].createDocumentFragment(); id = this._id() + "-popup"; menuButton = $( "<a href='#" + id + "' " + "class='" + opts.classes.columnBtn + " ui-btn " + "ui-btn-" + ( opts.columnBtnTheme || "a" ) + " ui-corner-all ui-shadow ui-mini' " + "data-" + ns + "rel='popup'>" + opts.columnBtnText + "</a>" ); popup = $( "<div class='" + opts.classes.popup + "' id='" + id + "'></div>" ); menu = $( "<fieldset></fieldset>" ).controlgroup(); // set extension here, send "false" to trigger build/rebuild this._addToggles( menu, false ); menu.appendTo( popup ); fragment.appendChild( popup[ 0 ] ); fragment.appendChild( menuButton[ 0 ] ); table.before( fragment ); popup.popup(); return menu; }, rebuild: function() { this._super(); if ( this.options.mode === "columntoggle" ) { // NOTE: rebuild passes "false", while refresh passes "undefined" // both refresh the table, but inside addToggles, !false will be true, // so a rebuild call can be indentified this._refresh( false ); } }, _refresh: function( create ) { this._super( create ); if ( !create && this.options.mode === "columntoggle" ) { // columns not being replaced must be cleared from input toggle-locks this._unlockCells( this.element.find( ".ui-table-cell-hidden, " + ".ui-table-cell-visible" ) ); // update columntoggles and cells this._addToggles( this._menu, create ); // check/uncheck this._setToggleState(); } }, _setToggleState: function() { this._menu.find( "input" ).each( function() { var checkbox = $( this ); this.checked = checkbox.jqmData( "cells" ).eq( 0 ).css( "display" ) === "table-cell"; checkbox.checkboxradio( "refresh" ); }); }, _destroy: function() { this._super(); } }); })( jQuery ); (function( $, undefined ) { $.widget( "mobile.table", $.mobile.table, { options: { mode: "reflow", classes: $.extend( $.mobile.table.prototype.options.classes, { reflowTable: "ui-table-reflow", cellLabels: "ui-table-cell-label" }) }, _create: function() { this._super(); // If it's not reflow mode, return here. if ( this.options.mode !== "reflow" ) { return; } if ( !this.options.enhanced ) { this.element.addClass( this.options.classes.reflowTable ); this._updateReflow(); } }, rebuild: function() { this._super(); if ( this.options.mode === "reflow" ) { this._refresh( false ); } }, _refresh: function( create ) { this._super( create ); if ( !create && this.options.mode === "reflow" ) { this._updateReflow( ); } }, _updateReflow: function() { var table = this, opts = this.options; // get headers in reverse order so that top-level headers are appended last $( table.allHeaders.get().reverse() ).each( function() { var cells = $( this ).jqmData( "cells" ), colstart = $.mobile.getAttribute( this, "colstart" ), hierarchyClass = cells.not( this ).filter( "thead th" ).length && " ui-table-cell-label-top", text = $( this ).text(), iteration, filter; if ( text !== "" ) { if ( hierarchyClass ) { iteration = parseInt( this.getAttribute( "colspan" ), 10 ); filter = ""; if ( iteration ) { filter = "td:nth-child("+ iteration +"n + " + ( colstart ) +")"; } table._addLabels( cells.filter( filter ), opts.classes.cellLabels + hierarchyClass, text ); } else { table._addLabels( cells, opts.classes.cellLabels, text ); } } }); }, _addLabels: function( cells, label, text ) { // .not fixes #6006 cells.not( ":has(b." + label + ")" ).prepend( "<b class='" + label + "'>" + text + "</b>" ); } }); })( jQuery ); (function( $, undefined ) { // TODO rename filterCallback/deprecate and default to the item itself as the first argument var defaultFilterCallback = function( index, searchValue ) { return ( ( "" + ( $.mobile.getAttribute( this, "filtertext" ) || $( this ).text() ) ) .toLowerCase().indexOf( searchValue ) === -1 ); }; $.widget( "mobile.filterable", { initSelector: ":jqmData(filter='true')", options: { filterReveal: false, filterCallback: defaultFilterCallback, enhanced: false, input: null, children: "> li, > option, > optgroup option, > tbody tr, > .ui-controlgroup-controls > .ui-btn, > .ui-controlgroup-controls > .ui-checkbox, > .ui-controlgroup-controls > .ui-radio" }, _create: function() { var opts = this.options; $.extend( this, { _search: null, _timer: 0 }); this._setInput( opts.input ); if ( !opts.enhanced ) { this._filterItems( ( ( this._search && this._search.val() ) || "" ).toLowerCase() ); } }, _onKeyUp: function() { var val, lastval, search = this._search; if ( search ) { val = search.val().toLowerCase(), lastval = $.mobile.getAttribute( search[ 0 ], "lastval" ) + ""; if ( lastval && lastval === val ) { // Execute the handler only once per value change return; } if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } this._timer = this._delay( function() { this._trigger( "beforefilter", null, { input: search } ); // Change val as lastval for next execution search[ 0 ].setAttribute( "data-" + $.mobile.ns + "lastval", val ); this._filterItems( val ); this._timer = 0; }, 250 ); } }, _getFilterableItems: function() { var elem = this.element, children = this.options.children, items = !children ? { length: 0 }: $.isFunction( children ) ? children(): children.nodeName ? $( children ): children.jquery ? children: this.element.find( children ); if ( items.length === 0 ) { items = elem.children(); } return items; }, _filterItems: function( val ) { var idx, callback, length, dst, show = [], hide = [], opts = this.options, filterItems = this._getFilterableItems(); if ( val != null ) { callback = opts.filterCallback || defaultFilterCallback; length = filterItems.length; // Partition the items into those to be hidden and those to be shown for ( idx = 0 ; idx < length ; idx++ ) { dst = ( callback.call( filterItems[ idx ], idx, val ) ) ? hide : show; dst.push( filterItems[ idx ] ); } } // If nothing is hidden, then the decision whether to hide or show the items // is based on the "filterReveal" option. if ( hide.length === 0 ) { filterItems[ opts.filterReveal ? "addClass" : "removeClass" ]( "ui-screen-hidden" ); } else { $( hide ).addClass( "ui-screen-hidden" ); $( show ).removeClass( "ui-screen-hidden" ); } this._refreshChildWidget(); this._trigger( "filter", null, { items: filterItems }); }, // The Default implementation of _refreshChildWidget attempts to call // refresh on collapsibleset, controlgroup, selectmenu, or listview _refreshChildWidget: function() { var widget, idx, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ]; for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widget = recognizedWidgets[ idx ]; if ( $.mobile[ widget ] ) { widget = this.element.data( "mobile-" + widget ); if ( widget && $.isFunction( widget.refresh ) ) { widget.refresh(); } } } }, // TODO: When the input is not internal, do not even store it in this._search _setInput: function ( selector ) { var search = this._search; // Stop a pending filter operation if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } if ( search ) { this._off( search, "keyup change input" ); search = null; } if ( selector ) { search = selector.jquery ? selector: selector.nodeName ? $( selector ): this.document.find( selector ); this._on( search, { keyup: "_onKeyUp", change: "_onKeyUp", input: "_onKeyUp" }); } this._search = search; }, _setOptions: function( options ) { var refilter = !( ( options.filterReveal === undefined ) && ( options.filterCallback === undefined ) && ( options.children === undefined ) ); this._super( options ); if ( options.input !== undefined ) { this._setInput( options.input ); refilter = true; } if ( refilter ) { this.refresh(); } }, _destroy: function() { var opts = this.options, items = this._getFilterableItems(); if ( opts.enhanced ) { items.toggleClass( "ui-screen-hidden", opts.filterReveal ); } else { items.removeClass( "ui-screen-hidden" ); } }, refresh: function() { if ( this._timer ) { window.clearTimeout( this._timer ); this._timer = 0; } this._filterItems( ( ( this._search && this._search.val() ) || "" ).toLowerCase() ); } }); })( jQuery ); (function( $, undefined ) { // Create a function that will replace the _setOptions function of a widget, // and will pass the options on to the input of the filterable. var replaceSetOptions = function( self, orig ) { return function( options ) { orig.call( this, options ); self._syncTextInputOptions( options ); }; }, rDividerListItem = /(^|\s)ui-li-divider(\s|$)/, origDefaultFilterCallback = $.mobile.filterable.prototype.options.filterCallback; // Override the default filter callback with one that does not hide list dividers $.mobile.filterable.prototype.options.filterCallback = function( index, searchValue ) { return !this.className.match( rDividerListItem ) && origDefaultFilterCallback.call( this, index, searchValue ); }; $.widget( "mobile.filterable", $.mobile.filterable, { options: { filterPlaceholder: "Filter items...", filterTheme: null }, _create: function() { var idx, widgetName, elem = this.element, recognizedWidgets = [ "collapsibleset", "selectmenu", "controlgroup", "listview" ], createHandlers = {}; this._super(); $.extend( this, { _widget: null }); for ( idx = recognizedWidgets.length - 1 ; idx > -1 ; idx-- ) { widgetName = recognizedWidgets[ idx ]; if ( $.mobile[ widgetName ] ) { if ( this._setWidget( elem.data( "mobile-" + widgetName ) ) ) { break; } else { createHandlers[ widgetName + "create" ] = "_handleCreate"; } } } if ( !this._widget ) { this._on( elem, createHandlers ); } }, _handleCreate: function( evt ) { this._setWidget( this.element.data( "mobile-" + evt.type.substring( 0, evt.type.length - 6 ) ) ); }, _trigger: function( type, event, data ) { if ( this._widget && this._widget.widgetFullName === "mobile-listview" && type === "beforefilter" ) { // Also trigger listviewbeforefilter if this widget is also a listview this._widget._trigger( "beforefilter", event, data ); } this._super( type, event, data ); }, _setWidget: function( widget ) { if ( !this._widget && widget ) { this._widget = widget; this._widget._setOptions = replaceSetOptions( this, this._widget._setOptions ); } if ( !!this._widget ) { this._syncTextInputOptions( this._widget.options ); if ( this._widget.widgetName === "listview" ) { this._widget.options.hideDividers = true; this._widget.element.listview( "refresh" ); } } return !!this._widget; }, _isSearchInternal: function() { return ( this._search && this._search.jqmData( "ui-filterable-" + this.uuid + "-internal" ) ); }, _setInput: function( selector ) { var opts = this.options, updatePlaceholder = true, textinputOpts = {}; if ( !selector ) { if ( this._isSearchInternal() ) { // Ignore the call to set a new input if the selector goes to falsy and // the current textinput is already of the internally generated variety. return; } else { // Generating a new textinput widget. No need to set the placeholder // further down the function. updatePlaceholder = false; selector = $( "<input " + "data-" + $.mobile.ns + "type='search' " + "placeholder='" + opts.filterPlaceholder + "'></input>" ) .jqmData( "ui-filterable-" + this.uuid + "-internal", true ); $( "<form class='ui-filterable'></form>" ) .append( selector ) .submit( function( evt ) { evt.preventDefault(); selector.blur(); }) .insertBefore( this.element ); if ( $.mobile.textinput ) { if ( this.options.filterTheme != null ) { textinputOpts[ "theme" ] = opts.filterTheme; } selector.textinput( textinputOpts ); } } } this._super( selector ); if ( this._isSearchInternal() && updatePlaceholder ) { this._search.attr( "placeholder", this.options.filterPlaceholder ); } }, _setOptions: function( options ) { var ret = this._super( options ); // Need to set the filterPlaceholder after having established the search input if ( options.filterPlaceholder !== undefined ) { if ( this._isSearchInternal() ) { this._search.attr( "placeholder", options.filterPlaceholder ); } } if ( options.filterTheme !== undefined && this._search && $.mobile.textinput ) { this._search.textinput( "option", "theme", options.filterTheme ); } return ret; }, _destroy: function() { if ( this._isSearchInternal() ) { this._search.remove(); } this._super(); }, _syncTextInputOptions: function( options ) { var idx, textinputOptions = {}; // We only sync options if the filterable's textinput is of the internally // generated variety, rather than one specified by the user. if ( this._isSearchInternal() && $.mobile.textinput ) { // Apply only the options understood by textinput for ( idx in $.mobile.textinput.prototype.options ) { if ( options[ idx ] !== undefined ) { if ( idx === "theme" && this.options.filterTheme != null ) { textinputOptions[ idx ] = this.options.filterTheme; } else { textinputOptions[ idx ] = options[ idx ]; } } } this._search.textinput( "option", textinputOptions ); } } }); })( jQuery ); /*! * jQuery UI Tabs fadf2b312a05040436451c64bbfaf4814bc62c56 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/tabs/ * * Depends: * jquery.ui.core.js * jquery.ui.widget.js */ (function( $, undefined ) { var tabId = 0, rhash = /#.*$/; function getNextTabId() { return ++tabId; } function isLocal( anchor ) { return anchor.hash.length > 1 && decodeURIComponent( anchor.href.replace( rhash, "" ) ) === decodeURIComponent( location.href.replace( rhash, "" ) ); } $.widget( "ui.tabs", { version: "fadf2b312a05040436451c64bbfaf4814bc62c56", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _tabId: function( tab ) { return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-expanded": "false", "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( isLocal( anchor ) ) { selector = anchor.hash; panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { panelId = that._tabId( tab ); selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": selector.substring( 1 ), "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = { click: function( event ) { event.preventDefault(); } }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); eventData.oldTab.attr( "aria-selected", "false" ); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr({ "aria-expanded": "true", "aria-hidden": "false" }); eventData.newTab.attr({ "aria-selected": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); })( jQuery ); (function( $, undefined ) { })( jQuery ); (function( $, window ) { $.mobile.iosorientationfixEnabled = true; // This fix addresses an iOS bug, so return early if the UA claims it's something else. var ua = navigator.userAgent, zoom, evt, x, y, z, aig; if ( !( /iPhone|iPad|iPod/.test( navigator.platform ) && /OS [1-5]_[0-9_]* like Mac OS X/i.test( ua ) && ua.indexOf( "AppleWebKit" ) > -1 ) ) { $.mobile.iosorientationfixEnabled = false; return; } zoom = $.mobile.zoom; function checkTilt( e ) { evt = e.originalEvent; aig = evt.accelerationIncludingGravity; x = Math.abs( aig.x ); y = Math.abs( aig.y ); z = Math.abs( aig.z ); // If portrait orientation and in one of the danger zones if ( !window.orientation && ( x > 7 || ( ( z > 6 && y < 8 || z < 8 && y > 6 ) && x > 5 ) ) ) { if ( zoom.enabled ) { zoom.disable(); } } else if ( !zoom.enabled ) { zoom.enable(); } } $.mobile.document.on( "mobileinit", function() { if ( $.mobile.iosorientationfixEnabled ) { $.mobile.window .bind( "orientationchange.iosorientationfix", zoom.enable ) .bind( "devicemotion.iosorientationfix", checkTilt ); } }); }( jQuery, this )); (function( $, window, undefined ) { var $html = $( "html" ), $window = $.mobile.window; //remove initial build class (only present on first pageshow) function hideRenderingClass() { $html.removeClass( "ui-mobile-rendering" ); } // trigger mobileinit event - useful hook for configuring $.mobile settings before they're used $( window.document ).trigger( "mobileinit" ); // support conditions // if device support condition(s) aren't met, leave things as they are -> a basic, usable experience, // otherwise, proceed with the enhancements if ( !$.mobile.gradeA() ) { return; } // override ajaxEnabled on platforms that have known conflicts with hash history updates // or generally work better browsing in regular http for full page refreshes (BB5, Opera Mini) if ( $.mobile.ajaxBlacklist ) { $.mobile.ajaxEnabled = false; } // Add mobile, initial load "rendering" classes to docEl $html.addClass( "ui-mobile ui-mobile-rendering" ); // This is a fallback. If anything goes wrong (JS errors, etc), or events don't fire, // this ensures the rendering class is removed after 5 seconds, so content is visible and accessible setTimeout( hideRenderingClass, 5000 ); $.extend( $.mobile, { // find and enhance the pages in the dom and transition to the first page. initializePage: function() { // find present pages var path = $.mobile.path, $pages = $( ":jqmData(role='page'), :jqmData(role='dialog')" ), hash = path.stripHash( path.stripQueryParams(path.parseLocation().hash) ), hashPage = document.getElementById( hash ); // if no pages are found, create one with body's inner html if ( !$pages.length ) { $pages = $( "body" ).wrapInner( "<div data-" + $.mobile.ns + "role='page'></div>" ).children( 0 ); } // add dialogs, set data-url attrs $pages.each(function() { var $this = $( this ); // unless the data url is already set set it to the pathname if ( !$this[ 0 ].getAttribute( "data-" + $.mobile.ns + "url" ) ) { $this.attr( "data-" + $.mobile.ns + "url", $this.attr( "id" ) || location.pathname + location.search ); } }); // define first page in dom case one backs out to the directory root (not always the first page visited, but defined as fallback) $.mobile.firstPage = $pages.first(); // define page container $.mobile.pageContainer = $.mobile.firstPage .parent() .addClass( "ui-mobile-viewport" ) .pagecontainer(); // initialize navigation events now, after mobileinit has occurred and the page container // has been created but before the rest of the library is alerted to that fact $.mobile.navreadyDeferred.resolve(); // alert listeners that the pagecontainer has been determined for binding // to events triggered on it $window.trigger( "pagecontainercreate" ); // cue page loading message $.mobile.loading( "show" ); //remove initial build class (only present on first pageshow) hideRenderingClass(); // if hashchange listening is disabled, there's no hash deeplink, // the hash is not valid (contains more than one # or does not start with #) // or there is no page with that hash, change to the first page in the DOM // Remember, however, that the hash can also be a path! if ( ! ( $.mobile.hashListeningEnabled && $.mobile.path.isHashValid( location.hash ) && ( $( hashPage ).is( ":jqmData(role='page')" ) || $.mobile.path.isPath( hash ) || hash === $.mobile.dialogHashKey ) ) ) { // Store the initial destination if ( $.mobile.path.isHashValid( location.hash ) ) { $.mobile.navigate.history.initialDst = hash.replace( "#", "" ); } // make sure to set initial popstate state if it exists // so that navigation back to the initial page works properly if ( $.event.special.navigate.isPushStateEnabled() ) { $.mobile.navigate.navigator.squash( path.parseLocation().href ); } $.mobile.changePage( $.mobile.firstPage, { transition: "none", reverse: true, changeHash: false, fromHashChange: true }); } else { // trigger hashchange or navigate to squash and record the correct // history entry for an initial hash path if ( !$.event.special.navigate.isPushStateEnabled() ) { $window.trigger( "hashchange", [true] ); } else { // TODO figure out how to simplify this interaction with the initial history entry // at the bottom js/navigate/navigate.js $.mobile.navigate.history.stack = []; $.mobile.navigate( $.mobile.path.isPath( location.hash ) ? location.hash : location.href ); } } } }); $(function() { //Run inlineSVG support test $.support.inlineSVG(); // check which scrollTop value should be used by scrolling to 1 immediately at domready // then check what the scroll top is. Android will report 0... others 1 // note that this initial scroll won't hide the address bar. It's just for the check. // hide iOS browser chrome on load if hideUrlBar is true this is to try and do it as soon as possible if ( $.mobile.hideUrlBar ) { window.scrollTo( 0, 1 ); } // if defaultHomeScroll hasn't been set yet, see if scrollTop is 1 // it should be 1 in most browsers, but android treats 1 as 0 (for hiding addr bar) // so if it's 1, use 0 from now on $.mobile.defaultHomeScroll = ( !$.support.scrollTop || $.mobile.window.scrollTop() === 1 ) ? 0 : 1; //dom-ready inits if ( $.mobile.autoInitializePage ) { $.mobile.initializePage(); } // window load event // hide iOS browser chrome on load if hideUrlBar is true this is as fall back incase we were too early before if ( $.mobile.hideUrlBar ) { $window.load( $.mobile.silentScroll ); } if ( !$.support.cssPointerEvents ) { // IE and Opera don't support CSS pointer-events: none that we use to disable link-based buttons // by adding the 'ui-disabled' class to them. Using a JavaScript workaround for those browser. // https://github.com/jquery/jquery-mobile/issues/3558 // DEPRECATED as of 1.4.0 - remove ui-disabled after 1.4.0 release // only ui-state-disabled should be present thereafter $.mobile.document.delegate( ".ui-state-disabled,.ui-disabled", "vclick", function( e ) { e.preventDefault(); e.stopImmediatePropagation(); } ); } }); }( jQuery, this )); }));
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("droppable"); $(_2).bind("_dragenter",function(e,_3){ $.data(_2,"droppable").options.onDragEnter.apply(_2,[e,_3]); }); $(_2).bind("_dragleave",function(e,_4){ $.data(_2,"droppable").options.onDragLeave.apply(_2,[e,_4]); }); $(_2).bind("_dragover",function(e,_5){ $.data(_2,"droppable").options.onDragOver.apply(_2,[e,_5]); }); $(_2).bind("_drop",function(e,_6){ $.data(_2,"droppable").options.onDrop.apply(_2,[e,_6]); }); }; $.fn.droppable=function(_7,_8){ if(typeof _7=="string"){ return $.fn.droppable.methods[_7](this,_8); } _7=_7||{}; return this.each(function(){ var _9=$.data(this,"droppable"); if(_9){ $.extend(_9.options,_7); }else{ _1(this); $.data(this,"droppable",{options:$.extend({},$.fn.droppable.defaults,$.fn.droppable.parseOptions(this),_7)}); } }); }; $.fn.droppable.methods={options:function(jq){ return $.data(jq[0],"droppable").options; },enable:function(jq){ return jq.each(function(){ $(this).droppable({disabled:false}); }); },disable:function(jq){ return jq.each(function(){ $(this).droppable({disabled:true}); }); }}; $.fn.droppable.parseOptions=function(_a){ var t=$(_a); return $.extend({},$.parser.parseOptions(_a,["accept"]),{disabled:(t.attr("disabled")?true:undefined)}); }; $.fn.droppable.defaults={accept:null,disabled:false,onDragEnter:function(e,_b){ },onDragOver:function(e,_c){ },onDragLeave:function(e,_d){ },onDrop:function(e,_e){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"calendar").options; var t=$(_2); _3.fit?$.extend(_3,t._fit()):t._fit(false); var _4=t.find(".calendar-header"); t._outerWidth(_3.width); t._outerHeight(_3.height); t.find(".calendar-body")._outerHeight(t.height()-_4._outerHeight()); }; function _5(_6){ $(_6).addClass("calendar").html("<div class=\"calendar-header\">"+"<div class=\"calendar-prevmonth\"></div>"+"<div class=\"calendar-nextmonth\"></div>"+"<div class=\"calendar-prevyear\"></div>"+"<div class=\"calendar-nextyear\"></div>"+"<div class=\"calendar-title\">"+"<span>Aprial 2010</span>"+"</div>"+"</div>"+"<div class=\"calendar-body\">"+"<div class=\"calendar-menu\">"+"<div class=\"calendar-menu-year-inner\">"+"<span class=\"calendar-menu-prev\"></span>"+"<span><input class=\"calendar-menu-year\" type=\"text\"></input></span>"+"<span class=\"calendar-menu-next\"></span>"+"</div>"+"<div class=\"calendar-menu-month-inner\">"+"</div>"+"</div>"+"</div>"); $(_6).find(".calendar-title span").hover(function(){ $(this).addClass("calendar-menu-hover"); },function(){ $(this).removeClass("calendar-menu-hover"); }).click(function(){ var _7=$(_6).find(".calendar-menu"); if(_7.is(":visible")){ _7.hide(); }else{ _14(_6); } }); $(".calendar-prevmonth,.calendar-nextmonth,.calendar-prevyear,.calendar-nextyear",_6).hover(function(){ $(this).addClass("calendar-nav-hover"); },function(){ $(this).removeClass("calendar-nav-hover"); }); $(_6).find(".calendar-nextmonth").click(function(){ _9(_6,1); }); $(_6).find(".calendar-prevmonth").click(function(){ _9(_6,-1); }); $(_6).find(".calendar-nextyear").click(function(){ _f(_6,1); }); $(_6).find(".calendar-prevyear").click(function(){ _f(_6,-1); }); $(_6).bind("_resize",function(){ var _8=$.data(_6,"calendar").options; if(_8.fit==true){ _1(_6); } return false; }); }; function _9(_a,_b){ var _c=$.data(_a,"calendar").options; _c.month+=_b; if(_c.month>12){ _c.year++; _c.month=1; }else{ if(_c.month<1){ _c.year--; _c.month=12; } } _d(_a); var _e=$(_a).find(".calendar-menu-month-inner"); _e.find("td.calendar-selected").removeClass("calendar-selected"); _e.find("td:eq("+(_c.month-1)+")").addClass("calendar-selected"); }; function _f(_10,_11){ var _12=$.data(_10,"calendar").options; _12.year+=_11; _d(_10); var _13=$(_10).find(".calendar-menu-year"); _13.val(_12.year); }; function _14(_15){ var _16=$.data(_15,"calendar").options; $(_15).find(".calendar-menu").show(); if($(_15).find(".calendar-menu-month-inner").is(":empty")){ $(_15).find(".calendar-menu-month-inner").empty(); var t=$("<table></table>").appendTo($(_15).find(".calendar-menu-month-inner")); var idx=0; for(var i=0;i<3;i++){ var tr=$("<tr></tr>").appendTo(t); for(var j=0;j<4;j++){ $("<td class=\"calendar-menu-month\"></td>").html(_16.months[idx++]).attr("abbr",idx).appendTo(tr); } } $(_15).find(".calendar-menu-prev,.calendar-menu-next").hover(function(){ $(this).addClass("calendar-menu-hover"); },function(){ $(this).removeClass("calendar-menu-hover"); }); $(_15).find(".calendar-menu-next").click(function(){ var y=$(_15).find(".calendar-menu-year"); if(!isNaN(y.val())){ y.val(parseInt(y.val())+1); } }); $(_15).find(".calendar-menu-prev").click(function(){ var y=$(_15).find(".calendar-menu-year"); if(!isNaN(y.val())){ y.val(parseInt(y.val()-1)); } }); $(_15).find(".calendar-menu-year").keypress(function(e){ if(e.keyCode==13){ _17(); } }); $(_15).find(".calendar-menu-month").hover(function(){ $(this).addClass("calendar-menu-hover"); },function(){ $(this).removeClass("calendar-menu-hover"); }).click(function(){ var _18=$(_15).find(".calendar-menu"); _18.find(".calendar-selected").removeClass("calendar-selected"); $(this).addClass("calendar-selected"); _17(); }); } function _17(){ var _19=$(_15).find(".calendar-menu"); var _1a=_19.find(".calendar-menu-year").val(); var _1b=_19.find(".calendar-selected").attr("abbr"); if(!isNaN(_1a)){ _16.year=parseInt(_1a); _16.month=parseInt(_1b); _d(_15); } _19.hide(); }; var _1c=$(_15).find(".calendar-body"); var _1d=$(_15).find(".calendar-menu"); var _1e=_1d.find(".calendar-menu-year-inner"); var _1f=_1d.find(".calendar-menu-month-inner"); _1e.find("input").val(_16.year).focus(); _1f.find("td.calendar-selected").removeClass("calendar-selected"); _1f.find("td:eq("+(_16.month-1)+")").addClass("calendar-selected"); _1d._outerWidth(_1c._outerWidth()); _1d._outerHeight(_1c._outerHeight()); _1f._outerHeight(_1d.height()-_1e._outerHeight()); }; function _20(_21,_22,_23){ var _24=$.data(_21,"calendar").options; var _25=[]; var _26=new Date(_22,_23,0).getDate(); for(var i=1;i<=_26;i++){ _25.push([_22,_23,i]); } var _27=[],_28=[]; var _29=-1; while(_25.length>0){ var _2a=_25.shift(); _28.push(_2a); var day=new Date(_2a[0],_2a[1]-1,_2a[2]).getDay(); if(_29==day){ day=0; }else{ if(day==(_24.firstDay==0?7:_24.firstDay)-1){ _27.push(_28); _28=[]; } } _29=day; } if(_28.length){ _27.push(_28); } var _2b=_27[0]; if(_2b.length<7){ while(_2b.length<7){ var _2c=_2b[0]; var _2a=new Date(_2c[0],_2c[1]-1,_2c[2]-1); _2b.unshift([_2a.getFullYear(),_2a.getMonth()+1,_2a.getDate()]); } }else{ var _2c=_2b[0]; var _28=[]; for(var i=1;i<=7;i++){ var _2a=new Date(_2c[0],_2c[1]-1,_2c[2]-i); _28.unshift([_2a.getFullYear(),_2a.getMonth()+1,_2a.getDate()]); } _27.unshift(_28); } var _2d=_27[_27.length-1]; while(_2d.length<7){ var _2e=_2d[_2d.length-1]; var _2a=new Date(_2e[0],_2e[1]-1,_2e[2]+1); _2d.push([_2a.getFullYear(),_2a.getMonth()+1,_2a.getDate()]); } if(_27.length<6){ var _2e=_2d[_2d.length-1]; var _28=[]; for(var i=1;i<=7;i++){ var _2a=new Date(_2e[0],_2e[1]-1,_2e[2]+i); _28.push([_2a.getFullYear(),_2a.getMonth()+1,_2a.getDate()]); } _27.push(_28); } return _27; }; function _d(_2f){ var _30=$.data(_2f,"calendar").options; $(_2f).find(".calendar-title span").html(_30.months[_30.month-1]+" "+_30.year); var _31=$(_2f).find("div.calendar-body"); _31.find(">table").remove(); var t=$("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><thead></thead><tbody></tbody></table>").prependTo(_31); var tr=$("<tr></tr>").appendTo(t.find("thead")); for(var i=_30.firstDay;i<_30.weeks.length;i++){ tr.append("<th>"+_30.weeks[i]+"</th>"); } for(var i=0;i<_30.firstDay;i++){ tr.append("<th>"+_30.weeks[i]+"</th>"); } var _32=_20(_2f,_30.year,_30.month); for(var i=0;i<_32.length;i++){ var _33=_32[i]; var tr=$("<tr></tr>").appendTo(t.find("tbody")); for(var j=0;j<_33.length;j++){ var day=_33[j]; $("<td class=\"calendar-day calendar-other-month\"></td>").attr("abbr",day[0]+","+day[1]+","+day[2]).html(day[2]).appendTo(tr); } } t.find("td[abbr^=\""+_30.year+","+_30.month+"\"]").removeClass("calendar-other-month"); var now=new Date(); var _34=now.getFullYear()+","+(now.getMonth()+1)+","+now.getDate(); t.find("td[abbr=\""+_34+"\"]").addClass("calendar-today"); if(_30.current){ t.find(".calendar-selected").removeClass("calendar-selected"); var _35=_30.current.getFullYear()+","+(_30.current.getMonth()+1)+","+_30.current.getDate(); t.find("td[abbr=\""+_35+"\"]").addClass("calendar-selected"); } var _36=6-_30.firstDay; var _37=_36+1; if(_36>=7){ _36-=7; } if(_37>=7){ _37-=7; } t.find("tr").find("td:eq("+_36+")").addClass("calendar-saturday"); t.find("tr").find("td:eq("+_37+")").addClass("calendar-sunday"); t.find("td").hover(function(){ $(this).addClass("calendar-hover"); },function(){ $(this).removeClass("calendar-hover"); }).click(function(){ t.find(".calendar-selected").removeClass("calendar-selected"); $(this).addClass("calendar-selected"); var _38=$(this).attr("abbr").split(","); _30.current=new Date(_38[0],parseInt(_38[1])-1,_38[2]); _30.onSelect.call(_2f,_30.current); }); }; $.fn.calendar=function(_39,_3a){ if(typeof _39=="string"){ return $.fn.calendar.methods[_39](this,_3a); } _39=_39||{}; return this.each(function(){ var _3b=$.data(this,"calendar"); if(_3b){ $.extend(_3b.options,_39); }else{ _3b=$.data(this,"calendar",{options:$.extend({},$.fn.calendar.defaults,$.fn.calendar.parseOptions(this),_39)}); _5(this); } if(_3b.options.border==false){ $(this).addClass("calendar-noborder"); } _1(this); _d(this); $(this).find("div.calendar-menu").hide(); }); }; $.fn.calendar.methods={options:function(jq){ return $.data(jq[0],"calendar").options; },resize:function(jq){ return jq.each(function(){ _1(this); }); },moveTo:function(jq,_3c){ return jq.each(function(){ $(this).calendar({year:_3c.getFullYear(),month:_3c.getMonth()+1,current:_3c}); }); }}; $.fn.calendar.parseOptions=function(_3d){ var t=$(_3d); return $.extend({},$.parser.parseOptions(_3d,["width","height",{firstDay:"number",fit:"boolean",border:"boolean"}])); }; $.fn.calendar.defaults={width:180,height:180,fit:false,border:true,firstDay:0,weeks:["S","M","T","W","T","F","S"],months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],year:new Date().getFullYear(),month:new Date().getMonth()+1,current:new Date(),onSelect:function(_3e){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$("<div class=\"slider\">"+"<div class=\"slider-inner\">"+"<a href=\"javascript:void(0)\" class=\"slider-handle\"></a>"+"<span class=\"slider-tip\"></span>"+"</div>"+"<div class=\"slider-rule\"></div>"+"<div class=\"slider-rulelabel\"></div>"+"<div style=\"clear:both\"></div>"+"<input type=\"hidden\" class=\"slider-value\">"+"</div>").insertAfter(_2); var t=$(_2); t.addClass("slider-f").hide(); var _4=t.attr("name"); if(_4){ _3.find("input.slider-value").attr("name",_4); t.removeAttr("name").attr("sliderName",_4); } return _3; }; function _5(_6,_7){ var _8=$.data(_6,"slider"); var _9=_8.options; var _a=_8.slider; if(_7){ if(_7.width){ _9.width=_7.width; } if(_7.height){ _9.height=_7.height; } } if(_9.mode=="h"){ _a.css("height",""); _a.children("div").css("height",""); if(!isNaN(_9.width)){ _a.width(_9.width); } }else{ _a.css("width",""); _a.children("div").css("width",""); if(!isNaN(_9.height)){ _a.height(_9.height); _a.find("div.slider-rule").height(_9.height); _a.find("div.slider-rulelabel").height(_9.height); _a.find("div.slider-inner")._outerHeight(_9.height); } } _b(_6); }; function _c(_d){ var _e=$.data(_d,"slider"); var _f=_e.options; var _10=_e.slider; var aa=_f.mode=="h"?_f.rule:_f.rule.slice(0).reverse(); if(_f.reversed){ aa=aa.slice(0).reverse(); } _11(aa); function _11(aa){ var _12=_10.find("div.slider-rule"); var _13=_10.find("div.slider-rulelabel"); _12.empty(); _13.empty(); for(var i=0;i<aa.length;i++){ var _14=i*100/(aa.length-1)+"%"; var _15=$("<span></span>").appendTo(_12); _15.css((_f.mode=="h"?"left":"top"),_14); if(aa[i]!="|"){ _15=$("<span></span>").appendTo(_13); _15.html(aa[i]); if(_f.mode=="h"){ _15.css({left:_14,marginLeft:-Math.round(_15.outerWidth()/2)}); }else{ _15.css({top:_14,marginTop:-Math.round(_15.outerHeight()/2)}); } } } }; }; function _16(_17){ var _18=$.data(_17,"slider"); var _19=_18.options; var _1a=_18.slider; _1a.removeClass("slider-h slider-v slider-disabled"); _1a.addClass(_19.mode=="h"?"slider-h":"slider-v"); _1a.addClass(_19.disabled?"slider-disabled":""); _1a.find("a.slider-handle").draggable({axis:_19.mode,cursor:"pointer",disabled:_19.disabled,onDrag:function(e){ var _1b=e.data.left; var _1c=_1a.width(); if(_19.mode!="h"){ _1b=e.data.top; _1c=_1a.height(); } if(_1b<0||_1b>_1c){ return false; }else{ var _1d=_32(_17,_1b); _1e(_1d); return false; } },onBeforeDrag:function(){ _18.isDragging=true; },onStartDrag:function(){ _19.onSlideStart.call(_17,_19.value); },onStopDrag:function(e){ var _1f=_32(_17,(_19.mode=="h"?e.data.left:e.data.top)); _1e(_1f); _19.onSlideEnd.call(_17,_19.value); _19.onComplete.call(_17,_19.value); _18.isDragging=false; }}); _1a.find("div.slider-inner").unbind(".slider").bind("mousedown.slider",function(e){ if(_18.isDragging){ return; } var pos=$(this).offset(); var _20=_32(_17,(_19.mode=="h"?(e.pageX-pos.left):(e.pageY-pos.top))); _1e(_20); _19.onComplete.call(_17,_19.value); }); function _1e(_21){ var s=Math.abs(_21%_19.step); if(s<_19.step/2){ _21-=s; }else{ _21=_21-s+_19.step; } _22(_17,_21); }; }; function _22(_23,_24){ var _25=$.data(_23,"slider"); var _26=_25.options; var _27=_25.slider; var _28=_26.value; if(_24<_26.min){ _24=_26.min; } if(_24>_26.max){ _24=_26.max; } _26.value=_24; $(_23).val(_24); _27.find("input.slider-value").val(_24); var pos=_29(_23,_24); var tip=_27.find(".slider-tip"); if(_26.showTip){ tip.show(); tip.html(_26.tipFormatter.call(_23,_26.value)); }else{ tip.hide(); } if(_26.mode=="h"){ var _2a="left:"+pos+"px;"; _27.find(".slider-handle").attr("style",_2a); tip.attr("style",_2a+"margin-left:"+(-Math.round(tip.outerWidth()/2))+"px"); }else{ var _2a="top:"+pos+"px;"; _27.find(".slider-handle").attr("style",_2a); tip.attr("style",_2a+"margin-left:"+(-Math.round(tip.outerWidth()))+"px"); } if(_28!=_24){ _26.onChange.call(_23,_24,_28); } }; function _b(_2b){ var _2c=$.data(_2b,"slider").options; var fn=_2c.onChange; _2c.onChange=function(){ }; _22(_2b,_2c.value); _2c.onChange=fn; }; function _29(_2d,_2e){ var _2f=$.data(_2d,"slider"); var _30=_2f.options; var _31=_2f.slider; if(_30.mode=="h"){ var pos=(_2e-_30.min)/(_30.max-_30.min)*_31.width(); if(_30.reversed){ pos=_31.width()-pos; } }else{ var pos=_31.height()-(_2e-_30.min)/(_30.max-_30.min)*_31.height(); if(_30.reversed){ pos=_31.height()-pos; } } return pos.toFixed(0); }; function _32(_33,pos){ var _34=$.data(_33,"slider"); var _35=_34.options; var _36=_34.slider; if(_35.mode=="h"){ var _37=_35.min+(_35.max-_35.min)*(pos/_36.width()); }else{ var _37=_35.min+(_35.max-_35.min)*((_36.height()-pos)/_36.height()); } return _35.reversed?_35.max-_37.toFixed(0):_37.toFixed(0); }; $.fn.slider=function(_38,_39){ if(typeof _38=="string"){ return $.fn.slider.methods[_38](this,_39); } _38=_38||{}; return this.each(function(){ var _3a=$.data(this,"slider"); if(_3a){ $.extend(_3a.options,_38); }else{ _3a=$.data(this,"slider",{options:$.extend({},$.fn.slider.defaults,$.fn.slider.parseOptions(this),_38),slider:_1(this)}); $(this).removeAttr("disabled"); } var _3b=_3a.options; _3b.min=parseFloat(_3b.min); _3b.max=parseFloat(_3b.max); _3b.value=parseFloat(_3b.value); _3b.step=parseFloat(_3b.step); _3b.originalValue=_3b.value; _16(this); _c(this); _5(this); }); }; $.fn.slider.methods={options:function(jq){ return $.data(jq[0],"slider").options; },destroy:function(jq){ return jq.each(function(){ $.data(this,"slider").slider.remove(); $(this).remove(); }); },resize:function(jq,_3c){ return jq.each(function(){ _5(this,_3c); }); },getValue:function(jq){ return jq.slider("options").value; },setValue:function(jq,_3d){ return jq.each(function(){ _22(this,_3d); }); },clear:function(jq){ return jq.each(function(){ var _3e=$(this).slider("options"); _22(this,_3e.min); }); },reset:function(jq){ return jq.each(function(){ var _3f=$(this).slider("options"); _22(this,_3f.originalValue); }); },enable:function(jq){ return jq.each(function(){ $.data(this,"slider").options.disabled=false; _16(this); }); },disable:function(jq){ return jq.each(function(){ $.data(this,"slider").options.disabled=true; _16(this); }); }}; $.fn.slider.parseOptions=function(_40){ var t=$(_40); return $.extend({},$.parser.parseOptions(_40,["width","height","mode",{reversed:"boolean",showTip:"boolean",min:"number",max:"number",step:"number"}]),{value:(t.val()||undefined),disabled:(t.attr("disabled")?true:undefined),rule:(t.attr("rule")?eval(t.attr("rule")):undefined)}); }; $.fn.slider.defaults={width:"auto",height:"auto",mode:"h",reversed:false,showTip:false,disabled:false,value:0,min:0,max:100,step:1,rule:[],tipFormatter:function(_41){ return _41; },onChange:function(_42,_43){ },onSlideStart:function(_44){ },onSlideEnd:function(_45){ },onComplete:function(_46){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2,_3){ var _4=$.data(_2,"combo"); var _5=_4.options; var _6=_4.combo; var _7=_4.panel; if(_3){ _5.width=_3; } if(isNaN(_5.width)){ var c=$(_2).clone(); c.css("visibility","hidden"); c.appendTo("body"); _5.width=c.outerWidth(); c.remove(); } _6.appendTo("body"); var _8=_6.find("input.combo-text"); var _9=_6.find(".combo-arrow"); var _a=_5.hasDownArrow?_9._outerWidth():0; _6._outerWidth(_5.width)._outerHeight(_5.height); _8._outerWidth(_6.width()-_a); _8.css({height:_6.height()+"px",lineHeight:_6.height()+"px"}); _9._outerHeight(_6.height()); _7.panel("resize",{width:(_5.panelWidth?_5.panelWidth:_6.outerWidth()),height:_5.panelHeight}); _6.insertAfter(_2); }; function _b(_c){ $(_c).addClass("combo-f").hide(); var _d=$("<span class=\"combo\">"+"<input type=\"text\" class=\"combo-text\" autocomplete=\"off\">"+"<span><span class=\"combo-arrow\"></span></span>"+"<input type=\"hidden\" class=\"combo-value\">"+"</span>").insertAfter(_c); var _e=$("<div class=\"combo-panel\"></div>").appendTo("body"); _e.panel({doSize:false,closed:true,cls:"combo-p",style:{position:"absolute",zIndex:10},onOpen:function(){ $(this).panel("resize"); },onClose:function(){ var _f=$.data(_c,"combo"); if(_f){ _f.options.onHidePanel.call(_c); } }}); var _10=$(_c).attr("name"); if(_10){ _d.find("input.combo-value").attr("name",_10); $(_c).removeAttr("name").attr("comboName",_10); } return {combo:_d,panel:_e}; }; function _11(_12){ var _13=$.data(_12,"combo"); var _14=_13.options; var _15=_13.combo; if(_14.hasDownArrow){ _15.find(".combo-arrow").show(); }else{ _15.find(".combo-arrow").hide(); } _16(_12,_14.disabled); _17(_12,_14.readonly); }; function _18(_19){ var _1a=$.data(_19,"combo"); var _1b=_1a.combo.find("input.combo-text"); _1b.validatebox("destroy"); _1a.panel.panel("destroy"); _1a.combo.remove(); $(_19).remove(); }; function _1c(_1d){ $(_1d).find(".combo-f").each(function(){ var p=$(this).combo("panel"); if(p.is(":visible")){ p.panel("close"); } }); }; function _1e(_1f){ var _20=$.data(_1f,"combo"); var _21=_20.options; var _22=_20.panel; var _23=_20.combo; var _24=_23.find(".combo-text"); var _25=_23.find(".combo-arrow"); $(document).unbind(".combo").bind("mousedown.combo",function(e){ var p=$(e.target).closest("span.combo,div.combo-p"); if(p.length){ _1c(p); return; } $("body>div.combo-p>div.combo-panel:visible").panel("close"); }); _24.unbind(".combo"); _25.unbind(".combo"); if(!_21.disabled&&!_21.readonly){ _24.bind("click.combo",function(e){ if(!_21.editable){ _26.call(this); }else{ var p=$(this).closest("div.combo-panel"); $("div.combo-panel:visible").not(_22).not(p).panel("close"); } }).bind("keydown.combo",function(e){ switch(e.keyCode){ case 38: _21.keyHandler.up.call(_1f,e); break; case 40: _21.keyHandler.down.call(_1f,e); break; case 37: _21.keyHandler.left.call(_1f,e); break; case 39: _21.keyHandler.right.call(_1f,e); break; case 13: e.preventDefault(); _21.keyHandler.enter.call(_1f,e); return false; case 9: case 27: _27(_1f); break; default: if(_21.editable){ if(_20.timer){ clearTimeout(_20.timer); } _20.timer=setTimeout(function(){ var q=_24.val(); if(_20.previousValue!=q){ _20.previousValue=q; $(_1f).combo("showPanel"); _21.keyHandler.query.call(_1f,_24.val(),e); $(_1f).combo("validate"); } },_21.delay); } } }); _25.bind("click.combo",function(){ _26.call(this); }).bind("mouseenter.combo",function(){ $(this).addClass("combo-arrow-hover"); }).bind("mouseleave.combo",function(){ $(this).removeClass("combo-arrow-hover"); }); } function _26(){ if(_22.is(":visible")){ _1c(_22); _27(_1f); }else{ var p=$(this).closest("div.combo-panel"); $("div.combo-panel:visible").not(_22).not(p).panel("close"); $(_1f).combo("showPanel"); } _24.focus(); }; }; function _28(_29){ var _2a=$.data(_29,"combo").options; var _2b=$.data(_29,"combo").combo; var _2c=$.data(_29,"combo").panel; if($.fn.window){ _2c.panel("panel").css("z-index",$.fn.window.defaults.zIndex++); } _2c.panel("move",{left:_2b.offset().left,top:_2d()}); if(_2c.panel("options").closed){ _2c.panel("open"); _2a.onShowPanel.call(_29); } (function(){ if(_2c.is(":visible")){ _2c.panel("move",{left:_2e(),top:_2d()}); setTimeout(arguments.callee,200); } })(); function _2e(){ var _2f=_2b.offset().left; if(_2f+_2c._outerWidth()>$(window)._outerWidth()+$(document).scrollLeft()){ _2f=$(window)._outerWidth()+$(document).scrollLeft()-_2c._outerWidth(); } if(_2f<0){ _2f=0; } return _2f; }; function _2d(){ var top=_2b.offset().top+_2b._outerHeight(); if(top+_2c._outerHeight()>$(window)._outerHeight()+$(document).scrollTop()){ top=_2b.offset().top-_2c._outerHeight(); } if(top<$(document).scrollTop()){ top=_2b.offset().top+_2b._outerHeight(); } return top; }; }; function _27(_30){ var _31=$.data(_30,"combo").panel; _31.panel("close"); }; function _32(_33){ var _34=$.data(_33,"combo").options; var _35=$(_33).combo("textbox"); _35.validatebox($.extend({},_34,{deltaX:(_34.hasDownArrow?_34.deltaX:(_34.deltaX>0?1:-1))})); }; function _16(_36,_37){ var _38=$.data(_36,"combo"); var _39=_38.options; var _3a=_38.combo; if(_37){ _39.disabled=true; $(_36).attr("disabled",true); _3a.find(".combo-value").attr("disabled",true); _3a.find(".combo-text").attr("disabled",true); }else{ _39.disabled=false; $(_36).removeAttr("disabled"); _3a.find(".combo-value").removeAttr("disabled"); _3a.find(".combo-text").removeAttr("disabled"); } }; function _17(_3b,_3c){ var _3d=$.data(_3b,"combo"); var _3e=_3d.options; _3e.readonly=_3c==undefined?true:_3c; var _3f=_3e.readonly?true:(!_3e.editable); _3d.combo.find(".combo-text").attr("readonly",_3f).css("cursor",_3f?"pointer":""); }; function _40(_41){ var _42=$.data(_41,"combo"); var _43=_42.options; var _44=_42.combo; if(_43.multiple){ _44.find("input.combo-value").remove(); }else{ _44.find("input.combo-value").val(""); } _44.find("input.combo-text").val(""); }; function _45(_46){ var _47=$.data(_46,"combo").combo; return _47.find("input.combo-text").val(); }; function _48(_49,_4a){ var _4b=$.data(_49,"combo"); var _4c=_4b.combo.find("input.combo-text"); if(_4c.val()!=_4a){ _4c.val(_4a); $(_49).combo("validate"); _4b.previousValue=_4a; } }; function _4d(_4e){ var _4f=[]; var _50=$.data(_4e,"combo").combo; _50.find("input.combo-value").each(function(){ _4f.push($(this).val()); }); return _4f; }; function _51(_52,_53){ var _54=$.data(_52,"combo").options; var _55=_4d(_52); var _56=$.data(_52,"combo").combo; _56.find("input.combo-value").remove(); var _57=$(_52).attr("comboName"); for(var i=0;i<_53.length;i++){ var _58=$("<input type=\"hidden\" class=\"combo-value\">").appendTo(_56); if(_57){ _58.attr("name",_57); } _58.val(_53[i]); } var tmp=[]; for(var i=0;i<_55.length;i++){ tmp[i]=_55[i]; } var aa=[]; for(var i=0;i<_53.length;i++){ for(var j=0;j<tmp.length;j++){ if(_53[i]==tmp[j]){ aa.push(_53[i]); tmp.splice(j,1); break; } } } if(aa.length!=_53.length||_53.length!=_55.length){ if(_54.multiple){ _54.onChange.call(_52,_53,_55); }else{ _54.onChange.call(_52,_53[0],_55[0]); } } }; function _59(_5a){ var _5b=_4d(_5a); return _5b[0]; }; function _5c(_5d,_5e){ _51(_5d,[_5e]); }; function _5f(_60){ var _61=$.data(_60,"combo").options; var fn=_61.onChange; _61.onChange=function(){ }; if(_61.multiple){ if(_61.value){ if(typeof _61.value=="object"){ _51(_60,_61.value); }else{ _5c(_60,_61.value); } }else{ _51(_60,[]); } _61.originalValue=_4d(_60); }else{ _5c(_60,_61.value); _61.originalValue=_61.value; } _61.onChange=fn; }; $.fn.combo=function(_62,_63){ if(typeof _62=="string"){ var _64=$.fn.combo.methods[_62]; if(_64){ return _64(this,_63); }else{ return this.each(function(){ var _65=$(this).combo("textbox"); _65.validatebox(_62,_63); }); } } _62=_62||{}; return this.each(function(){ var _66=$.data(this,"combo"); if(_66){ $.extend(_66.options,_62); }else{ var r=_b(this); _66=$.data(this,"combo",{options:$.extend({},$.fn.combo.defaults,$.fn.combo.parseOptions(this),_62),combo:r.combo,panel:r.panel,previousValue:null}); $(this).removeAttr("disabled"); } _11(this); _1(this); _1e(this); _32(this); _5f(this); }); }; $.fn.combo.methods={options:function(jq){ return $.data(jq[0],"combo").options; },panel:function(jq){ return $.data(jq[0],"combo").panel; },textbox:function(jq){ return $.data(jq[0],"combo").combo.find("input.combo-text"); },destroy:function(jq){ return jq.each(function(){ _18(this); }); },resize:function(jq,_67){ return jq.each(function(){ _1(this,_67); }); },showPanel:function(jq){ return jq.each(function(){ _28(this); }); },hidePanel:function(jq){ return jq.each(function(){ _27(this); }); },disable:function(jq){ return jq.each(function(){ _16(this,true); _1e(this); }); },enable:function(jq){ return jq.each(function(){ _16(this,false); _1e(this); }); },readonly:function(jq,_68){ return jq.each(function(){ _17(this,_68); _1e(this); }); },isValid:function(jq){ var _69=$.data(jq[0],"combo").combo.find("input.combo-text"); return _69.validatebox("isValid"); },clear:function(jq){ return jq.each(function(){ _40(this); }); },reset:function(jq){ return jq.each(function(){ var _6a=$.data(this,"combo").options; if(_6a.multiple){ $(this).combo("setValues",_6a.originalValue); }else{ $(this).combo("setValue",_6a.originalValue); } }); },getText:function(jq){ return _45(jq[0]); },setText:function(jq,_6b){ return jq.each(function(){ _48(this,_6b); }); },getValues:function(jq){ return _4d(jq[0]); },setValues:function(jq,_6c){ return jq.each(function(){ _51(this,_6c); }); },getValue:function(jq){ return _59(jq[0]); },setValue:function(jq,_6d){ return jq.each(function(){ _5c(this,_6d); }); }}; $.fn.combo.parseOptions=function(_6e){ var t=$(_6e); return $.extend({},$.fn.validatebox.parseOptions(_6e),$.parser.parseOptions(_6e,["width","height","separator",{panelWidth:"number",editable:"boolean",hasDownArrow:"boolean",delay:"number",selectOnNavigation:"boolean"}]),{panelHeight:(t.attr("panelHeight")=="auto"?"auto":parseInt(t.attr("panelHeight"))||undefined),multiple:(t.attr("multiple")?true:undefined),disabled:(t.attr("disabled")?true:undefined),readonly:(t.attr("readonly")?true:undefined),value:(t.val()||undefined)}); }; $.fn.combo.defaults=$.extend({},$.fn.validatebox.defaults,{width:"auto",height:22,panelWidth:null,panelHeight:200,multiple:false,selectOnNavigation:true,separator:",",editable:true,disabled:false,readonly:false,hasDownArrow:true,value:"",delay:200,deltaX:19,keyHandler:{up:function(e){ },down:function(e){ },left:function(e){ },right:function(e){ },enter:function(e){ },query:function(q,e){ }},onShowPanel:function(){ },onHidePanel:function(){ },onChange:function(_6f,_70){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var cp=document.createElement("div"); while(_2.firstChild){ cp.appendChild(_2.firstChild); } _2.appendChild(cp); var _3=$(cp); _3.attr("style",$(_2).attr("style")); $(_2).removeAttr("style").css("overflow","hidden"); _3.panel({border:false,doSize:false,bodyCls:"dialog-content"}); return _3; }; function _4(_5){ var _6=$.data(_5,"dialog").options; var _7=$.data(_5,"dialog").contentPanel; if(_6.toolbar){ if($.isArray(_6.toolbar)){ $(_5).find("div.dialog-toolbar").remove(); var _8=$("<div class=\"dialog-toolbar\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(_5); var tr=_8.find("tr"); for(var i=0;i<_6.toolbar.length;i++){ var _9=_6.toolbar[i]; if(_9=="-"){ $("<td><div class=\"dialog-tool-separator\"></div></td>").appendTo(tr); }else{ var td=$("<td></td>").appendTo(tr); var _a=$("<a href=\"javascript:void(0)\"></a>").appendTo(td); _a[0].onclick=eval(_9.handler||function(){ }); _a.linkbutton($.extend({},_9,{plain:true})); } } }else{ $(_6.toolbar).addClass("dialog-toolbar").prependTo(_5); $(_6.toolbar).show(); } }else{ $(_5).find("div.dialog-toolbar").remove(); } if(_6.buttons){ if($.isArray(_6.buttons)){ $(_5).find("div.dialog-button").remove(); var _b=$("<div class=\"dialog-button\"></div>").appendTo(_5); for(var i=0;i<_6.buttons.length;i++){ var p=_6.buttons[i]; var _c=$("<a href=\"javascript:void(0)\"></a>").appendTo(_b); if(p.handler){ _c[0].onclick=p.handler; } _c.linkbutton(p); } }else{ $(_6.buttons).addClass("dialog-button").appendTo(_5); $(_6.buttons).show(); } }else{ $(_5).find("div.dialog-button").remove(); } var _d=_6.href; var _e=_6.content; _6.href=null; _6.content=null; _7.panel({closed:_6.closed,cache:_6.cache,href:_d,content:_e,onLoad:function(){ if(_6.height=="auto"){ $(_5).window("resize"); } _6.onLoad.apply(_5,arguments); }}); $(_5).window($.extend({},_6,{onOpen:function(){ if(_7.panel("options").closed){ _7.panel("open"); } if(_6.onOpen){ _6.onOpen.call(_5); } },onResize:function(_f,_10){ var _11=$(_5); _7.panel("panel").show(); _7.panel("resize",{width:_11.width(),height:(_10=="auto")?"auto":_11.height()-_11.children("div.dialog-toolbar")._outerHeight()-_11.children("div.dialog-button")._outerHeight()}); if(_6.onResize){ _6.onResize.call(_5,_f,_10); } }})); _6.href=_d; _6.content=_e; }; function _12(_13,_14){ var _15=$.data(_13,"dialog").contentPanel; _15.panel("refresh",_14); }; $.fn.dialog=function(_16,_17){ if(typeof _16=="string"){ var _18=$.fn.dialog.methods[_16]; if(_18){ return _18(this,_17); }else{ return this.window(_16,_17); } } _16=_16||{}; return this.each(function(){ var _19=$.data(this,"dialog"); if(_19){ $.extend(_19.options,_16); }else{ $.data(this,"dialog",{options:$.extend({},$.fn.dialog.defaults,$.fn.dialog.parseOptions(this),_16),contentPanel:_1(this)}); } _4(this); }); }; $.fn.dialog.methods={options:function(jq){ var _1a=$.data(jq[0],"dialog").options; var _1b=jq.panel("options"); $.extend(_1a,{closed:_1b.closed,collapsed:_1b.collapsed,minimized:_1b.minimized,maximized:_1b.maximized}); var _1c=$.data(jq[0],"dialog").contentPanel; return _1a; },dialog:function(jq){ return jq.window("window"); },refresh:function(jq,_1d){ return jq.each(function(){ _12(this,_1d); }); }}; $.fn.dialog.parseOptions=function(_1e){ return $.extend({},$.fn.window.parseOptions(_1e),$.parser.parseOptions(_1e,["toolbar","buttons"])); }; $.fn.dialog.defaults=$.extend({},$.fn.window.defaults,{title:"New Dialog",collapsible:false,minimizable:false,maximizable:false,resizable:false,toolbar:null,buttons:null}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ $.fn._remove=function(){ return this.each(function(){ $(this).remove(); try{ this.outerHTML=""; } catch(err){ } }); }; function _1(_2){ _2._remove(); }; function _3(_4,_5){ var _6=$.data(_4,"panel").options; var _7=$.data(_4,"panel").panel; var _8=_7.children("div.panel-header"); var _9=_7.children("div.panel-body"); if(_5){ $.extend(_6,{width:_5.width,height:_5.height,left:_5.left,top:_5.top}); } _6.fit?$.extend(_6,_7._fit()):_7._fit(false); _7.css({left:_6.left,top:_6.top}); if(!isNaN(_6.width)){ _7._outerWidth(_6.width); }else{ _7.width("auto"); } _8.add(_9)._outerWidth(_7.width()); if(!isNaN(_6.height)){ _7._outerHeight(_6.height); _9._outerHeight(_7.height()-_8._outerHeight()); }else{ _9.height("auto"); } _7.css("height",""); _6.onResize.apply(_4,[_6.width,_6.height]); $(_4).find(">div,>form>div").triggerHandler("_resize"); }; function _a(_b,_c){ var _d=$.data(_b,"panel").options; var _e=$.data(_b,"panel").panel; if(_c){ if(_c.left!=null){ _d.left=_c.left; } if(_c.top!=null){ _d.top=_c.top; } } _e.css({left:_d.left,top:_d.top}); _d.onMove.apply(_b,[_d.left,_d.top]); }; function _f(_10){ $(_10).addClass("panel-body"); var _11=$("<div class=\"panel\"></div>").insertBefore(_10); _11[0].appendChild(_10); _11.bind("_resize",function(){ var _12=$.data(_10,"panel").options; if(_12.fit==true){ _3(_10); } return false; }); return _11; }; function _13(_14){ var _15=$.data(_14,"panel").options; var _16=$.data(_14,"panel").panel; if(_15.tools&&typeof _15.tools=="string"){ _16.find(">div.panel-header>div.panel-tool .panel-tool-a").appendTo(_15.tools); } _1(_16.children("div.panel-header")); if(_15.title&&!_15.noheader){ var _17=$("<div class=\"panel-header\"><div class=\"panel-title\">"+_15.title+"</div></div>").prependTo(_16); if(_15.iconCls){ _17.find(".panel-title").addClass("panel-with-icon"); $("<div class=\"panel-icon\"></div>").addClass(_15.iconCls).appendTo(_17); } var _18=$("<div class=\"panel-tool\"></div>").appendTo(_17); _18.bind("click",function(e){ e.stopPropagation(); }); if(_15.tools){ if($.isArray(_15.tools)){ for(var i=0;i<_15.tools.length;i++){ var t=$("<a href=\"javascript:void(0)\"></a>").addClass(_15.tools[i].iconCls).appendTo(_18); if(_15.tools[i].handler){ t.bind("click",eval(_15.tools[i].handler)); } } }else{ $(_15.tools).children().each(function(){ $(this).addClass($(this).attr("iconCls")).addClass("panel-tool-a").appendTo(_18); }); } } if(_15.collapsible){ $("<a class=\"panel-tool-collapse\" href=\"javascript:void(0)\"></a>").appendTo(_18).bind("click",function(){ if(_15.collapsed==true){ _3c(_14,true); }else{ _2c(_14,true); } return false; }); } if(_15.minimizable){ $("<a class=\"panel-tool-min\" href=\"javascript:void(0)\"></a>").appendTo(_18).bind("click",function(){ _47(_14); return false; }); } if(_15.maximizable){ $("<a class=\"panel-tool-max\" href=\"javascript:void(0)\"></a>").appendTo(_18).bind("click",function(){ if(_15.maximized==true){ _4b(_14); }else{ _2b(_14); } return false; }); } if(_15.closable){ $("<a class=\"panel-tool-close\" href=\"javascript:void(0)\"></a>").appendTo(_18).bind("click",function(){ _19(_14); return false; }); } _16.children("div.panel-body").removeClass("panel-body-noheader"); }else{ _16.children("div.panel-body").addClass("panel-body-noheader"); } }; function _1a(_1b){ var _1c=$.data(_1b,"panel"); var _1d=_1c.options; if(_1d.href){ if(!_1c.isLoaded||!_1d.cache){ if(_1d.onBeforeLoad.call(_1b)==false){ return; } _1c.isLoaded=false; _1e(_1b); if(_1d.loadingMessage){ $(_1b).html($("<div class=\"panel-loading\"></div>").html(_1d.loadingMessage)); } $.ajax({url:_1d.href,cache:false,dataType:"html",success:function(_1f){ _20(_1d.extractor.call(_1b,_1f)); _1d.onLoad.apply(_1b,arguments); _1c.isLoaded=true; }}); } }else{ if(_1d.content){ if(!_1c.isLoaded){ _1e(_1b); _20(_1d.content); _1c.isLoaded=true; } } } function _20(_21){ $(_1b).html(_21); if($.parser){ $.parser.parse($(_1b)); } }; }; function _1e(_22){ var t=$(_22); t.find(".combo-f").each(function(){ $(this).combo("destroy"); }); t.find(".m-btn").each(function(){ $(this).menubutton("destroy"); }); t.find(".s-btn").each(function(){ $(this).splitbutton("destroy"); }); t.find(".tooltip-f").each(function(){ $(this).tooltip("destroy"); }); }; function _23(_24){ $(_24).find("div.panel:visible,div.accordion:visible,div.tabs-container:visible,div.layout:visible").each(function(){ $(this).triggerHandler("_resize",[true]); }); }; function _25(_26,_27){ var _28=$.data(_26,"panel").options; var _29=$.data(_26,"panel").panel; if(_27!=true){ if(_28.onBeforeOpen.call(_26)==false){ return; } } _29.show(); _28.closed=false; _28.minimized=false; var _2a=_29.children("div.panel-header").find("a.panel-tool-restore"); if(_2a.length){ _28.maximized=true; } _28.onOpen.call(_26); if(_28.maximized==true){ _28.maximized=false; _2b(_26); } if(_28.collapsed==true){ _28.collapsed=false; _2c(_26); } if(!_28.collapsed){ _1a(_26); _23(_26); } }; function _19(_2d,_2e){ var _2f=$.data(_2d,"panel").options; var _30=$.data(_2d,"panel").panel; if(_2e!=true){ if(_2f.onBeforeClose.call(_2d)==false){ return; } } _30._fit(false); _30.hide(); _2f.closed=true; _2f.onClose.call(_2d); }; function _31(_32,_33){ var _34=$.data(_32,"panel").options; var _35=$.data(_32,"panel").panel; if(_33!=true){ if(_34.onBeforeDestroy.call(_32)==false){ return; } } _1e(_32); _1(_35); _34.onDestroy.call(_32); }; function _2c(_36,_37){ var _38=$.data(_36,"panel").options; var _39=$.data(_36,"panel").panel; var _3a=_39.children("div.panel-body"); var _3b=_39.children("div.panel-header").find("a.panel-tool-collapse"); if(_38.collapsed==true){ return; } _3a.stop(true,true); if(_38.onBeforeCollapse.call(_36)==false){ return; } _3b.addClass("panel-tool-expand"); if(_37==true){ _3a.slideUp("normal",function(){ _38.collapsed=true; _38.onCollapse.call(_36); }); }else{ _3a.hide(); _38.collapsed=true; _38.onCollapse.call(_36); } }; function _3c(_3d,_3e){ var _3f=$.data(_3d,"panel").options; var _40=$.data(_3d,"panel").panel; var _41=_40.children("div.panel-body"); var _42=_40.children("div.panel-header").find("a.panel-tool-collapse"); if(_3f.collapsed==false){ return; } _41.stop(true,true); if(_3f.onBeforeExpand.call(_3d)==false){ return; } _42.removeClass("panel-tool-expand"); if(_3e==true){ _41.slideDown("normal",function(){ _3f.collapsed=false; _3f.onExpand.call(_3d); _1a(_3d); _23(_3d); }); }else{ _41.show(); _3f.collapsed=false; _3f.onExpand.call(_3d); _1a(_3d); _23(_3d); } }; function _2b(_43){ var _44=$.data(_43,"panel").options; var _45=$.data(_43,"panel").panel; var _46=_45.children("div.panel-header").find("a.panel-tool-max"); if(_44.maximized==true){ return; } _46.addClass("panel-tool-restore"); if(!$.data(_43,"panel").original){ $.data(_43,"panel").original={width:_44.width,height:_44.height,left:_44.left,top:_44.top,fit:_44.fit}; } _44.left=0; _44.top=0; _44.fit=true; _3(_43); _44.minimized=false; _44.maximized=true; _44.onMaximize.call(_43); }; function _47(_48){ var _49=$.data(_48,"panel").options; var _4a=$.data(_48,"panel").panel; _4a._fit(false); _4a.hide(); _49.minimized=true; _49.maximized=false; _49.onMinimize.call(_48); }; function _4b(_4c){ var _4d=$.data(_4c,"panel").options; var _4e=$.data(_4c,"panel").panel; var _4f=_4e.children("div.panel-header").find("a.panel-tool-max"); if(_4d.maximized==false){ return; } _4e.show(); _4f.removeClass("panel-tool-restore"); $.extend(_4d,$.data(_4c,"panel").original); _3(_4c); _4d.minimized=false; _4d.maximized=false; $.data(_4c,"panel").original=null; _4d.onRestore.call(_4c); }; function _50(_51){ var _52=$.data(_51,"panel").options; var _53=$.data(_51,"panel").panel; var _54=$(_51).panel("header"); var _55=$(_51).panel("body"); _53.css(_52.style); _53.addClass(_52.cls); if(_52.border){ _54.removeClass("panel-header-noborder"); _55.removeClass("panel-body-noborder"); }else{ _54.addClass("panel-header-noborder"); _55.addClass("panel-body-noborder"); } _54.addClass(_52.headerCls); _55.addClass(_52.bodyCls); if(_52.id){ $(_51).attr("id",_52.id); }else{ $(_51).attr("id",""); } }; function _56(_57,_58){ $.data(_57,"panel").options.title=_58; $(_57).panel("header").find("div.panel-title").html(_58); }; var TO=false; var _59=true; $(window).unbind(".panel").bind("resize.panel",function(){ if(!_59){ return; } if(TO!==false){ clearTimeout(TO); } TO=setTimeout(function(){ _59=false; var _5a=$("body.layout"); if(_5a.length){ _5a.layout("resize"); }else{ $("body").children("div.panel,div.accordion,div.tabs-container,div.layout").triggerHandler("_resize"); } _59=true; TO=false; },200); }); $.fn.panel=function(_5b,_5c){ if(typeof _5b=="string"){ return $.fn.panel.methods[_5b](this,_5c); } _5b=_5b||{}; return this.each(function(){ var _5d=$.data(this,"panel"); var _5e; if(_5d){ _5e=$.extend(_5d.options,_5b); _5d.isLoaded=false; }else{ _5e=$.extend({},$.fn.panel.defaults,$.fn.panel.parseOptions(this),_5b); $(this).attr("title",""); _5d=$.data(this,"panel",{options:_5e,panel:_f(this),isLoaded:false}); } _13(this); _50(this); if(_5e.doSize==true){ _5d.panel.css("display","block"); _3(this); } if(_5e.closed==true||_5e.minimized==true){ _5d.panel.hide(); }else{ _25(this); } }); }; $.fn.panel.methods={options:function(jq){ return $.data(jq[0],"panel").options; },panel:function(jq){ return $.data(jq[0],"panel").panel; },header:function(jq){ return $.data(jq[0],"panel").panel.find(">div.panel-header"); },body:function(jq){ return $.data(jq[0],"panel").panel.find(">div.panel-body"); },setTitle:function(jq,_5f){ return jq.each(function(){ _56(this,_5f); }); },open:function(jq,_60){ return jq.each(function(){ _25(this,_60); }); },close:function(jq,_61){ return jq.each(function(){ _19(this,_61); }); },destroy:function(jq,_62){ return jq.each(function(){ _31(this,_62); }); },refresh:function(jq,_63){ return jq.each(function(){ $.data(this,"panel").isLoaded=false; if(_63){ $.data(this,"panel").options.href=_63; } _1a(this); }); },resize:function(jq,_64){ return jq.each(function(){ _3(this,_64); }); },move:function(jq,_65){ return jq.each(function(){ _a(this,_65); }); },maximize:function(jq){ return jq.each(function(){ _2b(this); }); },minimize:function(jq){ return jq.each(function(){ _47(this); }); },restore:function(jq){ return jq.each(function(){ _4b(this); }); },collapse:function(jq,_66){ return jq.each(function(){ _2c(this,_66); }); },expand:function(jq,_67){ return jq.each(function(){ _3c(this,_67); }); }}; $.fn.panel.parseOptions=function(_68){ var t=$(_68); return $.extend({},$.parser.parseOptions(_68,["id","width","height","left","top","title","iconCls","cls","headerCls","bodyCls","tools","href",{cache:"boolean",fit:"boolean",border:"boolean",noheader:"boolean"},{collapsible:"boolean",minimizable:"boolean",maximizable:"boolean"},{closable:"boolean",collapsed:"boolean",minimized:"boolean",maximized:"boolean",closed:"boolean"}]),{loadingMessage:(t.attr("loadingMessage")!=undefined?t.attr("loadingMessage"):undefined)}); }; $.fn.panel.defaults={id:null,title:null,iconCls:null,width:"auto",height:"auto",left:null,top:null,cls:null,headerCls:null,bodyCls:null,style:{},href:null,cache:true,fit:false,border:true,doSize:true,noheader:false,content:null,collapsible:false,minimizable:false,maximizable:false,closable:false,collapsed:false,minimized:false,maximized:false,closed:false,tools:null,href:null,loadingMessage:"Loading...",extractor:function(_69){ var _6a=/<body[^>]*>((.|[\n\r])*)<\/body>/im; var _6b=_6a.exec(_69); if(_6b){ return _6b[1]; }else{ return _69; } },onBeforeLoad:function(){ },onLoad:function(){ },onBeforeOpen:function(){ },onOpen:function(){ },onBeforeClose:function(){ },onClose:function(){ },onBeforeDestroy:function(){ },onDestroy:function(){ },onResize:function(_6c,_6d){ },onMove:function(_6e,top){ },onMaximize:function(){ },onRestore:function(){ },onMinimize:function(){ },onBeforeCollapse:function(){ },onBeforeExpand:function(){ },onCollapse:function(){ },onExpand:function(){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("tooltip-f"); }; function _3(_4){ var _5=$.data(_4,"tooltip").options; $(_4).unbind(".tooltip").bind(_5.showEvent+".tooltip",function(e){ _10(_4,e); }).bind(_5.hideEvent+".tooltip",function(e){ _17(_4,e); }).bind("mousemove.tooltip",function(e){ if(_5.trackMouse){ _5.trackMouseX=e.pageX; _5.trackMouseY=e.pageY; _6(_4); } }); }; function _7(_8){ var _9=$.data(_8,"tooltip"); if(_9.showTimer){ clearTimeout(_9.showTimer); _9.showTimer=null; } if(_9.hideTimer){ clearTimeout(_9.hideTimer); _9.hideTimer=null; } }; function _6(_a){ var _b=$.data(_a,"tooltip"); if(!_b||!_b.tip){ return; } var _c=_b.options; var _d=_b.tip; if(_c.trackMouse){ t=$(); var _e=_c.trackMouseX+_c.deltaX; var _f=_c.trackMouseY+_c.deltaY; }else{ var t=$(_a); var _e=t.offset().left+_c.deltaX; var _f=t.offset().top+_c.deltaY; } switch(_c.position){ case "right": _e+=t._outerWidth()+12+(_c.trackMouse?12:0); _f-=(_d._outerHeight()-t._outerHeight())/2; break; case "left": _e-=_d._outerWidth()+12+(_c.trackMouse?12:0); _f-=(_d._outerHeight()-t._outerHeight())/2; break; case "top": _e-=(_d._outerWidth()-t._outerWidth())/2; _f-=_d._outerHeight()+12+(_c.trackMouse?12:0); break; case "bottom": _e-=(_d._outerWidth()-t._outerWidth())/2; _f+=t._outerHeight()+12+(_c.trackMouse?12:0); break; } if(!$(_a).is(":visible")){ _e=-100000; _f=-100000; } _d.css({left:_e,top:_f,zIndex:(_c.zIndex!=undefined?_c.zIndex:($.fn.window?$.fn.window.defaults.zIndex++:""))}); _c.onPosition.call(_a,_e,_f); }; function _10(_11,e){ var _12=$.data(_11,"tooltip"); var _13=_12.options; var tip=_12.tip; if(!tip){ tip=$("<div tabindex=\"-1\" class=\"tooltip\">"+"<div class=\"tooltip-content\"></div>"+"<div class=\"tooltip-arrow-outer\"></div>"+"<div class=\"tooltip-arrow\"></div>"+"</div>").appendTo("body"); _12.tip=tip; _14(_11); } tip.removeClass("tooltip-top tooltip-bottom tooltip-left tooltip-right").addClass("tooltip-"+_13.position); _7(_11); _12.showTimer=setTimeout(function(){ _6(_11); tip.show(); _13.onShow.call(_11,e); var _15=tip.children(".tooltip-arrow-outer"); var _16=tip.children(".tooltip-arrow"); var bc="border-"+_13.position+"-color"; _15.add(_16).css({borderTopColor:"",borderBottomColor:"",borderLeftColor:"",borderRightColor:""}); _15.css(bc,tip.css(bc)); _16.css(bc,tip.css("backgroundColor")); },_13.showDelay); }; function _17(_18,e){ var _19=$.data(_18,"tooltip"); if(_19&&_19.tip){ _7(_18); _19.hideTimer=setTimeout(function(){ _19.tip.hide(); _19.options.onHide.call(_18,e); },_19.options.hideDelay); } }; function _14(_1a,_1b){ var _1c=$.data(_1a,"tooltip"); var _1d=_1c.options; if(_1b){ _1d.content=_1b; } if(!_1c.tip){ return; } var cc=typeof _1d.content=="function"?_1d.content.call(_1a):_1d.content; _1c.tip.children(".tooltip-content").html(cc); _1d.onUpdate.call(_1a,cc); }; function _1e(_1f){ var _20=$.data(_1f,"tooltip"); if(_20){ _7(_1f); var _21=_20.options; if(_20.tip){ _20.tip.remove(); } if(_21._title){ $(_1f).attr("title",_21._title); } $.removeData(_1f,"tooltip"); $(_1f).unbind(".tooltip").removeClass("tooltip-f"); _21.onDestroy.call(_1f); } }; $.fn.tooltip=function(_22,_23){ if(typeof _22=="string"){ return $.fn.tooltip.methods[_22](this,_23); } _22=_22||{}; return this.each(function(){ var _24=$.data(this,"tooltip"); if(_24){ $.extend(_24.options,_22); }else{ $.data(this,"tooltip",{options:$.extend({},$.fn.tooltip.defaults,$.fn.tooltip.parseOptions(this),_22)}); _1(this); } _3(this); _14(this); }); }; $.fn.tooltip.methods={options:function(jq){ return $.data(jq[0],"tooltip").options; },tip:function(jq){ return $.data(jq[0],"tooltip").tip; },arrow:function(jq){ return jq.tooltip("tip").children(".tooltip-arrow-outer,.tooltip-arrow"); },show:function(jq,e){ return jq.each(function(){ _10(this,e); }); },hide:function(jq,e){ return jq.each(function(){ _17(this,e); }); },update:function(jq,_25){ return jq.each(function(){ _14(this,_25); }); },reposition:function(jq){ return jq.each(function(){ _6(this); }); },destroy:function(jq){ return jq.each(function(){ _1e(this); }); }}; $.fn.tooltip.parseOptions=function(_26){ var t=$(_26); var _27=$.extend({},$.parser.parseOptions(_26,["position","showEvent","hideEvent","content",{deltaX:"number",deltaY:"number",showDelay:"number",hideDelay:"number"}]),{_title:t.attr("title")}); t.attr("title",""); if(!_27.content){ _27.content=_27._title; } return _27; }; $.fn.tooltip.defaults={position:"bottom",content:null,trackMouse:false,deltaX:0,deltaY:0,showEvent:"mouseenter",hideEvent:"mouseleave",showDelay:200,hideDelay:100,onShow:function(e){ },onHide:function(e){ },onUpdate:function(_28){ },onPosition:function(_29,top){ },onDestroy:function(){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("numberspinner-f"); var _3=$.data(_2,"numberspinner").options; $(_2).spinner(_3).numberbox(_3); }; function _4(_5,_6){ var _7=$.data(_5,"numberspinner").options; var v=parseFloat($(_5).numberbox("getValue")||_7.value)||0; if(_6==true){ v-=_7.increment; }else{ v+=_7.increment; } $(_5).numberbox("setValue",v); }; $.fn.numberspinner=function(_8,_9){ if(typeof _8=="string"){ var _a=$.fn.numberspinner.methods[_8]; if(_a){ return _a(this,_9); }else{ return this.spinner(_8,_9); } } _8=_8||{}; return this.each(function(){ var _b=$.data(this,"numberspinner"); if(_b){ $.extend(_b.options,_8); }else{ $.data(this,"numberspinner",{options:$.extend({},$.fn.numberspinner.defaults,$.fn.numberspinner.parseOptions(this),_8)}); } _1(this); }); }; $.fn.numberspinner.methods={options:function(jq){ var _c=$.data(jq[0],"numberspinner").options; return $.extend(_c,{value:jq.numberbox("getValue"),originalValue:jq.numberbox("options").originalValue}); },setValue:function(jq,_d){ return jq.each(function(){ $(this).numberbox("setValue",_d); }); },getValue:function(jq){ return jq.numberbox("getValue"); },clear:function(jq){ return jq.each(function(){ $(this).spinner("clear"); $(this).numberbox("clear"); }); },reset:function(jq){ return jq.each(function(){ var _e=$(this).numberspinner("options"); $(this).numberspinner("setValue",_e.originalValue); }); }}; $.fn.numberspinner.parseOptions=function(_f){ return $.extend({},$.fn.spinner.parseOptions(_f),$.fn.numberbox.parseOptions(_f),{}); }; $.fn.numberspinner.defaults=$.extend({},$.fn.spinner.defaults,$.fn.numberbox.defaults,{spin:function(_10){ _4(this,_10); }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"tabs").options; if(_3.tabPosition=="left"||_3.tabPosition=="right"||!_3.showHeader){ return; } var _4=$(_2).children("div.tabs-header"); var _5=_4.children("div.tabs-tool"); var _6=_4.children("div.tabs-scroller-left"); var _7=_4.children("div.tabs-scroller-right"); var _8=_4.children("div.tabs-wrap"); var _9=_4.outerHeight(); if(_3.plain){ _9-=_9-_4.height(); } _5._outerHeight(_9); var _a=0; $("ul.tabs li",_4).each(function(){ _a+=$(this).outerWidth(true); }); var _b=_4.width()-_5._outerWidth(); if(_a>_b){ _6.add(_7).show()._outerHeight(_9); if(_3.toolPosition=="left"){ _5.css({left:_6.outerWidth(),right:""}); _8.css({marginLeft:_6.outerWidth()+_5._outerWidth(),marginRight:_7._outerWidth(),width:_b-_6.outerWidth()-_7.outerWidth()}); }else{ _5.css({left:"",right:_7.outerWidth()}); _8.css({marginLeft:_6.outerWidth(),marginRight:_7.outerWidth()+_5._outerWidth(),width:_b-_6.outerWidth()-_7.outerWidth()}); } }else{ _6.add(_7).hide(); if(_3.toolPosition=="left"){ _5.css({left:0,right:""}); _8.css({marginLeft:_5._outerWidth(),marginRight:0,width:_b}); }else{ _5.css({left:"",right:0}); _8.css({marginLeft:0,marginRight:_5._outerWidth(),width:_b}); } } }; function _c(_d){ var _e=$.data(_d,"tabs").options; var _f=$(_d).children("div.tabs-header"); if(_e.tools){ if(typeof _e.tools=="string"){ $(_e.tools).addClass("tabs-tool").appendTo(_f); $(_e.tools).show(); }else{ _f.children("div.tabs-tool").remove(); var _10=$("<div class=\"tabs-tool\"><table cellspacing=\"0\" cellpadding=\"0\" style=\"height:100%\"><tr></tr></table></div>").appendTo(_f); var tr=_10.find("tr"); for(var i=0;i<_e.tools.length;i++){ var td=$("<td></td>").appendTo(tr); var _11=$("<a href=\"javascript:void(0);\"></a>").appendTo(td); _11[0].onclick=eval(_e.tools[i].handler||function(){ }); _11.linkbutton($.extend({},_e.tools[i],{plain:true})); } } }else{ _f.children("div.tabs-tool").remove(); } }; function _12(_13){ var _14=$.data(_13,"tabs"); var _15=_14.options; var cc=$(_13); _15.fit?$.extend(_15,cc._fit()):cc._fit(false); cc.width(_15.width).height(_15.height); var _16=$(_13).children("div.tabs-header"); var _17=$(_13).children("div.tabs-panels"); var _18=_16.find("div.tabs-wrap"); var ul=_18.find(".tabs"); for(var i=0;i<_14.tabs.length;i++){ var _19=_14.tabs[i].panel("options"); var p_t=_19.tab.find("a.tabs-inner"); var _1a=parseInt(_19.tabWidth||_15.tabWidth)||undefined; if(_1a){ p_t._outerWidth(_1a); }else{ p_t.css("width",""); } p_t._outerHeight(_15.tabHeight); p_t.css("lineHeight",p_t.height()+"px"); } if(_15.tabPosition=="left"||_15.tabPosition=="right"){ _16._outerWidth(_15.showHeader?_15.headerWidth:0); _17._outerWidth(cc.width()-_16.outerWidth()); _16.add(_17)._outerHeight(_15.height); _18._outerWidth(_16.width()); ul._outerWidth(_18.width()).css("height",""); }else{ var lrt=_16.children("div.tabs-scroller-left,div.tabs-scroller-right,div.tabs-tool"); _16._outerWidth(_15.width).css("height",""); if(_15.showHeader){ _16.css("background-color",""); _18.css("height",""); lrt.show(); }else{ _16.css("background-color","transparent"); _16._outerHeight(0); _18._outerHeight(0); lrt.hide(); } ul._outerHeight(_15.tabHeight).css("width",""); _1(_13); var _1b=_15.height; if(!isNaN(_1b)){ _17._outerHeight(_1b-_16.outerHeight()); }else{ _17.height("auto"); } var _1a=_15.width; if(!isNaN(_1a)){ _17._outerWidth(_1a); }else{ _17.width("auto"); } } }; function _1c(_1d){ var _1e=$.data(_1d,"tabs").options; var tab=_1f(_1d); if(tab){ var _20=$(_1d).children("div.tabs-panels"); var _21=_1e.width=="auto"?"auto":_20.width(); var _22=_1e.height=="auto"?"auto":_20.height(); tab.panel("resize",{width:_21,height:_22}); } }; function _23(_24){ var _25=$.data(_24,"tabs").tabs; var cc=$(_24); cc.addClass("tabs-container"); var pp=$("<div class=\"tabs-panels\"></div>").insertBefore(cc); cc.children("div").each(function(){ pp[0].appendChild(this); }); cc[0].appendChild(pp[0]); $("<div class=\"tabs-header\">"+"<div class=\"tabs-scroller-left\"></div>"+"<div class=\"tabs-scroller-right\"></div>"+"<div class=\"tabs-wrap\">"+"<ul class=\"tabs\"></ul>"+"</div>"+"</div>").prependTo(_24); cc.children("div.tabs-panels").children("div").each(function(i){ var _26=$.extend({},$.parser.parseOptions(this),{selected:($(this).attr("selected")?true:undefined)}); var pp=$(this); _25.push(pp); _36(_24,pp,_26); }); cc.children("div.tabs-header").find(".tabs-scroller-left, .tabs-scroller-right").hover(function(){ $(this).addClass("tabs-scroller-over"); },function(){ $(this).removeClass("tabs-scroller-over"); }); cc.bind("_resize",function(e,_27){ var _28=$.data(_24,"tabs").options; if(_28.fit==true||_27){ _12(_24); _1c(_24); } return false; }); }; function _29(_2a){ var _2b=$.data(_2a,"tabs"); var _2c=_2b.options; $(_2a).children("div.tabs-header").unbind().bind("click",function(e){ if($(e.target).hasClass("tabs-scroller-left")){ $(_2a).tabs("scrollBy",-_2c.scrollIncrement); }else{ if($(e.target).hasClass("tabs-scroller-right")){ $(_2a).tabs("scrollBy",_2c.scrollIncrement); }else{ var li=$(e.target).closest("li"); if(li.hasClass("tabs-disabled")){ return; } var a=$(e.target).closest("a.tabs-close"); if(a.length){ _4c(_2a,_2d(li)); }else{ if(li.length){ var _2e=_2d(li); var _2f=_2b.tabs[_2e].panel("options"); if(_2f.collapsible){ _2f.closed?_41(_2a,_2e):_6b(_2a,_2e); }else{ _41(_2a,_2e); } } } } } }).bind("contextmenu",function(e){ var li=$(e.target).closest("li"); if(li.hasClass("tabs-disabled")){ return; } if(li.length){ _2c.onContextMenu.call(_2a,e,li.find("span.tabs-title").html(),_2d(li)); } }); function _2d(li){ var _30=0; li.parent().children("li").each(function(i){ if(li[0]==this){ _30=i; return false; } }); return _30; }; }; function _31(_32){ var _33=$.data(_32,"tabs").options; var _34=$(_32).children("div.tabs-header"); var _35=$(_32).children("div.tabs-panels"); _34.removeClass("tabs-header-top tabs-header-bottom tabs-header-left tabs-header-right"); _35.removeClass("tabs-panels-top tabs-panels-bottom tabs-panels-left tabs-panels-right"); if(_33.tabPosition=="top"){ _34.insertBefore(_35); }else{ if(_33.tabPosition=="bottom"){ _34.insertAfter(_35); _34.addClass("tabs-header-bottom"); _35.addClass("tabs-panels-top"); }else{ if(_33.tabPosition=="left"){ _34.addClass("tabs-header-left"); _35.addClass("tabs-panels-right"); }else{ if(_33.tabPosition=="right"){ _34.addClass("tabs-header-right"); _35.addClass("tabs-panels-left"); } } } } if(_33.plain==true){ _34.addClass("tabs-header-plain"); }else{ _34.removeClass("tabs-header-plain"); } if(_33.border==true){ _34.removeClass("tabs-header-noborder"); _35.removeClass("tabs-panels-noborder"); }else{ _34.addClass("tabs-header-noborder"); _35.addClass("tabs-panels-noborder"); } }; function _36(_37,pp,_38){ var _39=$.data(_37,"tabs"); _38=_38||{}; pp.panel($.extend({},_38,{border:false,noheader:true,closed:true,doSize:false,iconCls:(_38.icon?_38.icon:undefined),onLoad:function(){ if(_38.onLoad){ _38.onLoad.call(this,arguments); } _39.options.onLoad.call(_37,$(this)); }})); var _3a=pp.panel("options"); var _3b=$(_37).children("div.tabs-header").find("ul.tabs"); _3a.tab=$("<li></li>").appendTo(_3b); _3a.tab.append("<a href=\"javascript:void(0)\" class=\"tabs-inner\">"+"<span class=\"tabs-title\"></span>"+"<span class=\"tabs-icon\"></span>"+"</a>"); $(_37).tabs("update",{tab:pp,options:_3a}); }; function _3c(_3d,_3e){ var _3f=$.data(_3d,"tabs").options; var _40=$.data(_3d,"tabs").tabs; if(_3e.selected==undefined){ _3e.selected=true; } var pp=$("<div></div>").appendTo($(_3d).children("div.tabs-panels")); _40.push(pp); _36(_3d,pp,_3e); _3f.onAdd.call(_3d,_3e.title,_40.length-1); _12(_3d); if(_3e.selected){ _41(_3d,_40.length-1); } }; function _42(_43,_44){ var _45=$.data(_43,"tabs").selectHis; var pp=_44.tab; var _46=pp.panel("options").title; pp.panel($.extend({},_44.options,{iconCls:(_44.options.icon?_44.options.icon:undefined)})); var _47=pp.panel("options"); var tab=_47.tab; var _48=tab.find("span.tabs-title"); var _49=tab.find("span.tabs-icon"); _48.html(_47.title); _49.attr("class","tabs-icon"); tab.find("a.tabs-close").remove(); if(_47.closable){ _48.addClass("tabs-closable"); $("<a href=\"javascript:void(0)\" class=\"tabs-close\"></a>").appendTo(tab); }else{ _48.removeClass("tabs-closable"); } if(_47.iconCls){ _48.addClass("tabs-with-icon"); _49.addClass(_47.iconCls); }else{ _48.removeClass("tabs-with-icon"); } if(_46!=_47.title){ for(var i=0;i<_45.length;i++){ if(_45[i]==_46){ _45[i]=_47.title; } } } tab.find("span.tabs-p-tool").remove(); if(_47.tools){ var _4a=$("<span class=\"tabs-p-tool\"></span>").insertAfter(tab.find("a.tabs-inner")); if($.isArray(_47.tools)){ for(var i=0;i<_47.tools.length;i++){ var t=$("<a href=\"javascript:void(0)\"></a>").appendTo(_4a); t.addClass(_47.tools[i].iconCls); if(_47.tools[i].handler){ t.bind("click",{handler:_47.tools[i].handler},function(e){ if($(this).parents("li").hasClass("tabs-disabled")){ return; } e.data.handler.call(this); }); } } }else{ $(_47.tools).children().appendTo(_4a); } var pr=_4a.children().length*12; if(_47.closable){ pr+=8; }else{ pr-=3; _4a.css("right","5px"); } _48.css("padding-right",pr+"px"); } _12(_43); $.data(_43,"tabs").options.onUpdate.call(_43,_47.title,_4b(_43,pp)); }; function _4c(_4d,_4e){ var _4f=$.data(_4d,"tabs").options; var _50=$.data(_4d,"tabs").tabs; var _51=$.data(_4d,"tabs").selectHis; if(!_52(_4d,_4e)){ return; } var tab=_53(_4d,_4e); var _54=tab.panel("options").title; var _55=_4b(_4d,tab); if(_4f.onBeforeClose.call(_4d,_54,_55)==false){ return; } var tab=_53(_4d,_4e,true); tab.panel("options").tab.remove(); tab.panel("destroy"); _4f.onClose.call(_4d,_54,_55); _12(_4d); for(var i=0;i<_51.length;i++){ if(_51[i]==_54){ _51.splice(i,1); i--; } } var _56=_51.pop(); if(_56){ _41(_4d,_56); }else{ if(_50.length){ _41(_4d,0); } } }; function _53(_57,_58,_59){ var _5a=$.data(_57,"tabs").tabs; if(typeof _58=="number"){ if(_58<0||_58>=_5a.length){ return null; }else{ var tab=_5a[_58]; if(_59){ _5a.splice(_58,1); } return tab; } } for(var i=0;i<_5a.length;i++){ var tab=_5a[i]; if(tab.panel("options").title==_58){ if(_59){ _5a.splice(i,1); } return tab; } } return null; }; function _4b(_5b,tab){ var _5c=$.data(_5b,"tabs").tabs; for(var i=0;i<_5c.length;i++){ if(_5c[i][0]==$(tab)[0]){ return i; } } return -1; }; function _1f(_5d){ var _5e=$.data(_5d,"tabs").tabs; for(var i=0;i<_5e.length;i++){ var tab=_5e[i]; if(tab.panel("options").closed==false){ return tab; } } return null; }; function _5f(_60){ var _61=$.data(_60,"tabs"); var _62=_61.tabs; for(var i=0;i<_62.length;i++){ if(_62[i].panel("options").selected){ _41(_60,i); return; } } _41(_60,_61.options.selected); }; function _41(_63,_64){ var _65=$.data(_63,"tabs"); var _66=_65.options; var _67=_65.tabs; var _68=_65.selectHis; if(_67.length==0){ return; } var _69=_53(_63,_64); if(!_69){ return; } var _6a=_1f(_63); if(_6a){ if(_69[0]==_6a[0]){ return; } _6b(_63,_4b(_63,_6a)); if(!_6a.panel("options").closed){ return; } } _69.panel("open"); var _6c=_69.panel("options").title; _68.push(_6c); var tab=_69.panel("options").tab; tab.addClass("tabs-selected"); var _6d=$(_63).find(">div.tabs-header>div.tabs-wrap"); var _6e=tab.position().left; var _6f=_6e+tab.outerWidth(); if(_6e<0||_6f>_6d.width()){ var _70=_6e-(_6d.width()-tab.width())/2; $(_63).tabs("scrollBy",_70); }else{ $(_63).tabs("scrollBy",0); } _1c(_63); _66.onSelect.call(_63,_6c,_4b(_63,_69)); }; function _6b(_71,_72){ var _73=$.data(_71,"tabs"); var p=_53(_71,_72); if(p){ var _74=p.panel("options"); if(!_74.closed){ p.panel("close"); if(_74.closed){ _74.tab.removeClass("tabs-selected"); _73.options.onUnselect.call(_71,_74.title,_4b(_71,p)); } } } }; function _52(_75,_76){ return _53(_75,_76)!=null; }; function _77(_78,_79){ var _7a=$.data(_78,"tabs").options; _7a.showHeader=_79; $(_78).tabs("resize"); }; $.fn.tabs=function(_7b,_7c){ if(typeof _7b=="string"){ return $.fn.tabs.methods[_7b](this,_7c); } _7b=_7b||{}; return this.each(function(){ var _7d=$.data(this,"tabs"); var _7e; if(_7d){ _7e=$.extend(_7d.options,_7b); _7d.options=_7e; }else{ $.data(this,"tabs",{options:$.extend({},$.fn.tabs.defaults,$.fn.tabs.parseOptions(this),_7b),tabs:[],selectHis:[]}); _23(this); } _c(this); _31(this); _12(this); _29(this); _5f(this); }); }; $.fn.tabs.methods={options:function(jq){ var cc=jq[0]; var _7f=$.data(cc,"tabs").options; var s=_1f(cc); _7f.selected=s?_4b(cc,s):-1; return _7f; },tabs:function(jq){ return $.data(jq[0],"tabs").tabs; },resize:function(jq){ return jq.each(function(){ _12(this); _1c(this); }); },add:function(jq,_80){ return jq.each(function(){ _3c(this,_80); }); },close:function(jq,_81){ return jq.each(function(){ _4c(this,_81); }); },getTab:function(jq,_82){ return _53(jq[0],_82); },getTabIndex:function(jq,tab){ return _4b(jq[0],tab); },getSelected:function(jq){ return _1f(jq[0]); },select:function(jq,_83){ return jq.each(function(){ _41(this,_83); }); },unselect:function(jq,_84){ return jq.each(function(){ _6b(this,_84); }); },exists:function(jq,_85){ return _52(jq[0],_85); },update:function(jq,_86){ return jq.each(function(){ _42(this,_86); }); },enableTab:function(jq,_87){ return jq.each(function(){ $(this).tabs("getTab",_87).panel("options").tab.removeClass("tabs-disabled"); }); },disableTab:function(jq,_88){ return jq.each(function(){ $(this).tabs("getTab",_88).panel("options").tab.addClass("tabs-disabled"); }); },showHeader:function(jq){ return jq.each(function(){ _77(this,true); }); },hideHeader:function(jq){ return jq.each(function(){ _77(this,false); }); },scrollBy:function(jq,_89){ return jq.each(function(){ var _8a=$(this).tabs("options"); var _8b=$(this).find(">div.tabs-header>div.tabs-wrap"); var pos=Math.min(_8b._scrollLeft()+_89,_8c()); _8b.animate({scrollLeft:pos},_8a.scrollDuration); function _8c(){ var w=0; var ul=_8b.children("ul"); ul.children("li").each(function(){ w+=$(this).outerWidth(true); }); return w-_8b.width()+(ul.outerWidth()-ul.width()); }; }); }}; $.fn.tabs.parseOptions=function(_8d){ return $.extend({},$.parser.parseOptions(_8d,["width","height","tools","toolPosition","tabPosition",{fit:"boolean",border:"boolean",plain:"boolean",headerWidth:"number",tabWidth:"number",tabHeight:"number",selected:"number",showHeader:"boolean"}])); }; $.fn.tabs.defaults={width:"auto",height:"auto",headerWidth:150,tabWidth:"auto",tabHeight:27,selected:0,showHeader:true,plain:false,fit:false,border:true,tools:null,toolPosition:"right",tabPosition:"top",scrollIncrement:100,scrollDuration:400,onLoad:function(_8e){ },onSelect:function(_8f,_90){ },onUnselect:function(_91,_92){ },onBeforeClose:function(_93,_94){ },onClose:function(_95,_96){ },onAdd:function(_97,_98){ },onUpdate:function(_99,_9a){ },onContextMenu:function(e,_9b,_9c){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2,_3){ var _4=$.data(_2,"window").options; if(_3){ $.extend(_4,_3); } $(_2).panel("resize",_4); }; function _5(_6,_7){ var _8=$.data(_6,"window"); if(_7){ if(_7.left!=null){ _8.options.left=_7.left; } if(_7.top!=null){ _8.options.top=_7.top; } } $(_6).panel("move",_8.options); if(_8.shadow){ _8.shadow.css({left:_8.options.left,top:_8.options.top}); } }; function _9(_a,_b){ var _c=$.data(_a,"window"); var _d=_c.options; var _e=_d.width; if(isNaN(_e)){ _e=_c.window._outerWidth(); } if(_d.inline){ var _f=_c.window.parent(); _d.left=(_f.width()-_e)/2+_f.scrollLeft(); }else{ _d.left=($(window)._outerWidth()-_e)/2+$(document).scrollLeft(); } if(_b){ _5(_a); } }; function _10(_11,_12){ var _13=$.data(_11,"window"); var _14=_13.options; var _15=_14.height; if(isNaN(_15)){ _15=_13.window._outerHeight(); } if(_14.inline){ var _16=_13.window.parent(); _14.top=(_16.height()-_15)/2+_16.scrollTop(); }else{ _14.top=($(window)._outerHeight()-_15)/2+$(document).scrollTop(); } if(_12){ _5(_11); } }; function _17(_18){ var _19=$.data(_18,"window"); var win=$(_18).panel($.extend({},_19.options,{border:false,doSize:true,closed:true,cls:"window",headerCls:"window-header",bodyCls:"window-body "+(_19.options.noheader?"window-body-noheader":""),onBeforeDestroy:function(){ if(_19.options.onBeforeDestroy.call(_18)==false){ return false; } if(_19.shadow){ _19.shadow.remove(); } if(_19.mask){ _19.mask.remove(); } },onClose:function(){ if(_19.shadow){ _19.shadow.hide(); } if(_19.mask){ _19.mask.hide(); } _19.options.onClose.call(_18); },onOpen:function(){ if(_19.mask){ _19.mask.css({display:"block",zIndex:$.fn.window.defaults.zIndex++}); } if(_19.shadow){ _19.shadow.css({display:"block",zIndex:$.fn.window.defaults.zIndex++,left:_19.options.left,top:_19.options.top,width:_19.window._outerWidth(),height:_19.window._outerHeight()}); } _19.window.css("z-index",$.fn.window.defaults.zIndex++); _19.options.onOpen.call(_18); },onResize:function(_1a,_1b){ var _1c=$(this).panel("options"); $.extend(_19.options,{width:_1c.width,height:_1c.height,left:_1c.left,top:_1c.top}); if(_19.shadow){ _19.shadow.css({left:_19.options.left,top:_19.options.top,width:_19.window._outerWidth(),height:_19.window._outerHeight()}); } _19.options.onResize.call(_18,_1a,_1b); },onMinimize:function(){ if(_19.shadow){ _19.shadow.hide(); } if(_19.mask){ _19.mask.hide(); } _19.options.onMinimize.call(_18); },onBeforeCollapse:function(){ if(_19.options.onBeforeCollapse.call(_18)==false){ return false; } if(_19.shadow){ _19.shadow.hide(); } },onExpand:function(){ if(_19.shadow){ _19.shadow.show(); } _19.options.onExpand.call(_18); }})); _19.window=win.panel("panel"); if(_19.mask){ _19.mask.remove(); } if(_19.options.modal==true){ _19.mask=$("<div class=\"window-mask\"></div>").insertAfter(_19.window); _19.mask.css({width:(_19.options.inline?_19.mask.parent().width():_1d().width),height:(_19.options.inline?_19.mask.parent().height():_1d().height),display:"none"}); } if(_19.shadow){ _19.shadow.remove(); } if(_19.options.shadow==true){ _19.shadow=$("<div class=\"window-shadow\"></div>").insertAfter(_19.window); _19.shadow.css({display:"none"}); } if(_19.options.left==null){ _9(_18); } if(_19.options.top==null){ _10(_18); } _5(_18); if(_19.options.closed==false){ win.window("open"); } }; function _1e(_1f){ var _20=$.data(_1f,"window"); _20.window.draggable({handle:">div.panel-header>div.panel-title",disabled:_20.options.draggable==false,onStartDrag:function(e){ if(_20.mask){ _20.mask.css("z-index",$.fn.window.defaults.zIndex++); } if(_20.shadow){ _20.shadow.css("z-index",$.fn.window.defaults.zIndex++); } _20.window.css("z-index",$.fn.window.defaults.zIndex++); if(!_20.proxy){ _20.proxy=$("<div class=\"window-proxy\"></div>").insertAfter(_20.window); } _20.proxy.css({display:"none",zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top}); _20.proxy._outerWidth(_20.window._outerWidth()); _20.proxy._outerHeight(_20.window._outerHeight()); setTimeout(function(){ if(_20.proxy){ _20.proxy.show(); } },500); },onDrag:function(e){ _20.proxy.css({display:"block",left:e.data.left,top:e.data.top}); return false; },onStopDrag:function(e){ _20.options.left=e.data.left; _20.options.top=e.data.top; $(_1f).window("move"); _20.proxy.remove(); _20.proxy=null; }}); _20.window.resizable({disabled:_20.options.resizable==false,onStartResize:function(e){ _20.pmask=$("<div class=\"window-proxy-mask\"></div>").insertAfter(_20.window); _20.pmask.css({zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top,width:_20.window._outerWidth(),height:_20.window._outerHeight()}); if(!_20.proxy){ _20.proxy=$("<div class=\"window-proxy\"></div>").insertAfter(_20.window); } _20.proxy.css({zIndex:$.fn.window.defaults.zIndex++,left:e.data.left,top:e.data.top}); _20.proxy._outerWidth(e.data.width); _20.proxy._outerHeight(e.data.height); },onResize:function(e){ _20.proxy.css({left:e.data.left,top:e.data.top}); _20.proxy._outerWidth(e.data.width); _20.proxy._outerHeight(e.data.height); return false; },onStopResize:function(e){ $.extend(_20.options,{left:e.data.left,top:e.data.top,width:e.data.width,height:e.data.height}); _1(_1f); _20.pmask.remove(); _20.pmask=null; _20.proxy.remove(); _20.proxy=null; }}); }; function _1d(){ if(document.compatMode=="BackCompat"){ return {width:Math.max(document.body.scrollWidth,document.body.clientWidth),height:Math.max(document.body.scrollHeight,document.body.clientHeight)}; }else{ return {width:Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth),height:Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight)}; } }; $(window).resize(function(){ $("body>div.window-mask").css({width:$(window)._outerWidth(),height:$(window)._outerHeight()}); setTimeout(function(){ $("body>div.window-mask").css({width:_1d().width,height:_1d().height}); },50); }); $.fn.window=function(_21,_22){ if(typeof _21=="string"){ var _23=$.fn.window.methods[_21]; if(_23){ return _23(this,_22); }else{ return this.panel(_21,_22); } } _21=_21||{}; return this.each(function(){ var _24=$.data(this,"window"); if(_24){ $.extend(_24.options,_21); }else{ _24=$.data(this,"window",{options:$.extend({},$.fn.window.defaults,$.fn.window.parseOptions(this),_21)}); if(!_24.options.inline){ document.body.appendChild(this); } } _17(this); _1e(this); }); }; $.fn.window.methods={options:function(jq){ var _25=jq.panel("options"); var _26=$.data(jq[0],"window").options; return $.extend(_26,{closed:_25.closed,collapsed:_25.collapsed,minimized:_25.minimized,maximized:_25.maximized}); },window:function(jq){ return $.data(jq[0],"window").window; },resize:function(jq,_27){ return jq.each(function(){ _1(this,_27); }); },move:function(jq,_28){ return jq.each(function(){ _5(this,_28); }); },hcenter:function(jq){ return jq.each(function(){ _9(this,true); }); },vcenter:function(jq){ return jq.each(function(){ _10(this,true); }); },center:function(jq){ return jq.each(function(){ _9(this); _10(this); _5(this); }); }}; $.fn.window.parseOptions=function(_29){ return $.extend({},$.fn.panel.parseOptions(_29),$.parser.parseOptions(_29,[{draggable:"boolean",resizable:"boolean",shadow:"boolean",modal:"boolean",inline:"boolean"}])); }; $.fn.window.defaults=$.extend({},$.fn.panel.defaults,{zIndex:9000,draggable:true,resizable:true,shadow:true,modal:false,inline:false,title:"New Window",collapsible:true,minimizable:true,maximizable:true,closable:true,closed:false}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2,_3,_4,_5){ var _6=$.data(_2,"combobox"); var _7=_6.options; if(_5){ return _8(_6.groups,_4,_3); }else{ return _8(_6.data,(_4?_4:_6.options.valueField),_3); } function _8(_9,_a,_b){ for(var i=0;i<_9.length;i++){ var _c=_9[i]; if(_c[_a]==_b){ return _c; } } return null; }; }; function _d(_e,_f){ var _10=$(_e).combo("panel"); var row=_1(_e,_f); if(row){ var _11=$("#"+row.domId); if(_11.position().top<=0){ var h=_10.scrollTop()+_11.position().top; _10.scrollTop(h); }else{ if(_11.position().top+_11.outerHeight()>_10.height()){ var h=_10.scrollTop()+_11.position().top+_11.outerHeight()-_10.height(); _10.scrollTop(h); } } } }; function nav(_12,dir){ var _13=$.data(_12,"combobox").options; var _14=$(_12).combobox("panel"); var _15=_14.children("div.combobox-item-hover"); if(!_15.length){ _15=_14.children("div.combobox-item-selected"); } _15.removeClass("combobox-item-hover"); var _16="div.combobox-item:visible:not(.combobox-item-disabled):first"; var _17="div.combobox-item:visible:not(.combobox-item-disabled):last"; if(!_15.length){ _15=_14.children(dir=="next"?_16:_17); }else{ if(dir=="next"){ _15=_15.nextAll(_16); if(!_15.length){ _15=_14.children(_16); } }else{ _15=_15.prevAll(_16); if(!_15.length){ _15=_14.children(_17); } } } if(_15.length){ _15.addClass("combobox-item-hover"); var row=_1(_12,_15.attr("id"),"domId"); if(row){ _d(_12,row[_13.valueField]); if(_13.selectOnNavigation){ _18(_12,row[_13.valueField]); } } } }; function _18(_19,_1a){ var _1b=$.data(_19,"combobox").options; var _1c=$(_19).combo("getValues"); if($.inArray(_1a+"",_1c)==-1){ if(_1b.multiple){ _1c.push(_1a); }else{ _1c=[_1a]; } _1d(_19,_1c); _1b.onSelect.call(_19,_1(_19,_1a)); } }; function _1e(_1f,_20){ var _21=$.data(_1f,"combobox").options; var _22=$(_1f).combo("getValues"); var _23=$.inArray(_20+"",_22); if(_23>=0){ _22.splice(_23,1); _1d(_1f,_22); _21.onUnselect.call(_1f,_1(_1f,_20)); } }; function _1d(_24,_25,_26){ var _27=$.data(_24,"combobox").options; var _28=$(_24).combo("panel"); _28.find("div.combobox-item-selected").removeClass("combobox-item-selected"); var vv=[],ss=[]; for(var i=0;i<_25.length;i++){ var v=_25[i]; var s=v; var row=_1(_24,v); if(row){ s=row[_27.textField]; $("#"+row.domId).addClass("combobox-item-selected"); } vv.push(v); ss.push(s); } $(_24).combo("setValues",vv); if(!_26){ $(_24).combo("setText",ss.join(_27.separator)); } }; var _29=1; function _2a(_2b,_2c,_2d){ var _2e=$.data(_2b,"combobox"); var _2f=_2e.options; _2e.data=_2f.loadFilter.call(_2b,_2c); _2e.groups=[]; _2c=_2e.data; var _30=$(_2b).combobox("getValues"); var dd=[]; var _31=undefined; for(var i=0;i<_2c.length;i++){ var row=_2c[i]; var v=row[_2f.valueField]+""; var s=row[_2f.textField]; var g=row[_2f.groupField]; if(g){ if(_31!=g){ _31=g; var _32={value:g,domId:("_easyui_combobox_"+_29++)}; _2e.groups.push(_32); dd.push("<div id=\""+_32.domId+"\" class=\"combobox-group\">"); dd.push(_2f.groupFormatter?_2f.groupFormatter.call(_2b,g):g); dd.push("</div>"); } }else{ _31=undefined; } var cls="combobox-item"+(row.disabled?" combobox-item-disabled":"")+(g?" combobox-gitem":""); row.domId="_easyui_combobox_"+_29++; dd.push("<div id=\""+row.domId+"\" class=\""+cls+"\">"); dd.push(_2f.formatter?_2f.formatter.call(_2b,row):s); dd.push("</div>"); if(row["selected"]&&$.inArray(v,_30)==-1){ _30.push(v); } } $(_2b).combo("panel").html(dd.join("")); if(_2f.multiple){ _1d(_2b,_30,_2d); }else{ _1d(_2b,_30.length?[_30[_30.length-1]]:[],_2d); } _2f.onLoadSuccess.call(_2b,_2c); }; function _33(_34,url,_35,_36){ var _37=$.data(_34,"combobox").options; if(url){ _37.url=url; } _35=_35||{}; if(_37.onBeforeLoad.call(_34,_35)==false){ return; } _37.loader.call(_34,_35,function(_38){ _2a(_34,_38,_36); },function(){ _37.onLoadError.apply(this,arguments); }); }; function _39(_3a,q){ var _3b=$.data(_3a,"combobox"); var _3c=_3b.options; if(_3c.multiple&&!q){ _1d(_3a,[],true); }else{ _1d(_3a,[q],true); } if(_3c.mode=="remote"){ _33(_3a,null,{q:q},true); }else{ var _3d=$(_3a).combo("panel"); _3d.find("div.combobox-item,div.combobox-group").hide(); var _3e=_3b.data; var _3f=undefined; for(var i=0;i<_3e.length;i++){ var row=_3e[i]; if(_3c.filter.call(_3a,q,row)){ var v=row[_3c.valueField]; var s=row[_3c.textField]; var g=row[_3c.groupField]; var _40=$("#"+row.domId).show(); if(s.toLowerCase()==q.toLowerCase()){ _1d(_3a,[v]); _40.addClass("combobox-item-selected"); } if(_3c.groupField&&_3f!=g){ var _41=_1(_3a,g,"value",true); if(_41){ $("#"+_41.domId).show(); } _3f=g; } } } } }; function _42(_43){ var t=$(_43); var _44=t.combobox("options"); var _45=t.combobox("panel"); var _46=_45.children("div.combobox-item-hover"); if(!_46.length){ _46=_45.children("div.combobox-item-selected"); } if(!_46.length){ return; } var row=_1(_43,_46.attr("id"),"domId"); if(!row){ return; } var _47=row[_44.valueField]; if(_44.multiple){ if(_46.hasClass("combobox-item-selected")){ t.combobox("unselect",_47); }else{ t.combobox("select",_47); } }else{ t.combobox("select",_47); t.combobox("hidePanel"); } var vv=[]; var _48=t.combobox("getValues"); for(var i=0;i<_48.length;i++){ if(_1(_43,_48[i])){ vv.push(_48[i]); } } t.combobox("setValues",vv); }; function _49(_4a){ var _4b=$.data(_4a,"combobox").options; $(_4a).addClass("combobox-f"); $(_4a).combo($.extend({},_4b,{onShowPanel:function(){ $(_4a).combo("panel").find("div.combobox-item,div.combobox-group").show(); _d(_4a,$(_4a).combobox("getValue")); _4b.onShowPanel.call(_4a); }})); $(_4a).combo("panel").unbind().bind("mouseover",function(e){ $(this).children("div.combobox-item-hover").removeClass("combobox-item-hover"); var _4c=$(e.target).closest("div.combobox-item"); if(!_4c.hasClass("combobox-item-disabled")){ _4c.addClass("combobox-item-hover"); } e.stopPropagation(); }).bind("mouseout",function(e){ $(e.target).closest("div.combobox-item").removeClass("combobox-item-hover"); e.stopPropagation(); }).bind("click",function(e){ var _4d=$(e.target).closest("div.combobox-item"); if(!_4d.length||_4d.hasClass("combobox-item-disabled")){ return; } var row=_1(_4a,_4d.attr("id"),"domId"); if(!row){ return; } var _4e=row[_4b.valueField]; if(_4b.multiple){ if(_4d.hasClass("combobox-item-selected")){ _1e(_4a,_4e); }else{ _18(_4a,_4e); } }else{ _18(_4a,_4e); $(_4a).combo("hidePanel"); } e.stopPropagation(); }); }; $.fn.combobox=function(_4f,_50){ if(typeof _4f=="string"){ var _51=$.fn.combobox.methods[_4f]; if(_51){ return _51(this,_50); }else{ return this.combo(_4f,_50); } } _4f=_4f||{}; return this.each(function(){ var _52=$.data(this,"combobox"); if(_52){ $.extend(_52.options,_4f); _49(this); }else{ _52=$.data(this,"combobox",{options:$.extend({},$.fn.combobox.defaults,$.fn.combobox.parseOptions(this),_4f),data:[]}); _49(this); var _53=$.fn.combobox.parseData(this); if(_53.length){ _2a(this,_53); } } if(_52.options.data){ _2a(this,_52.options.data); } _33(this); }); }; $.fn.combobox.methods={options:function(jq){ var _54=jq.combo("options"); return $.extend($.data(jq[0],"combobox").options,{originalValue:_54.originalValue,disabled:_54.disabled,readonly:_54.readonly}); },getData:function(jq){ return $.data(jq[0],"combobox").data; },setValues:function(jq,_55){ return jq.each(function(){ _1d(this,_55); }); },setValue:function(jq,_56){ return jq.each(function(){ _1d(this,[_56]); }); },clear:function(jq){ return jq.each(function(){ $(this).combo("clear"); var _57=$(this).combo("panel"); _57.find("div.combobox-item-selected").removeClass("combobox-item-selected"); }); },reset:function(jq){ return jq.each(function(){ var _58=$(this).combobox("options"); if(_58.multiple){ $(this).combobox("setValues",_58.originalValue); }else{ $(this).combobox("setValue",_58.originalValue); } }); },loadData:function(jq,_59){ return jq.each(function(){ _2a(this,_59); }); },reload:function(jq,url){ return jq.each(function(){ _33(this,url); }); },select:function(jq,_5a){ return jq.each(function(){ _18(this,_5a); }); },unselect:function(jq,_5b){ return jq.each(function(){ _1e(this,_5b); }); }}; $.fn.combobox.parseOptions=function(_5c){ var t=$(_5c); return $.extend({},$.fn.combo.parseOptions(_5c),$.parser.parseOptions(_5c,["valueField","textField","groupField","mode","method","url"])); }; $.fn.combobox.parseData=function(_5d){ var _5e=[]; var _5f=$(_5d).combobox("options"); $(_5d).children().each(function(){ if(this.tagName.toLowerCase()=="optgroup"){ var _60=$(this).attr("label"); $(this).children().each(function(){ _61(this,_60); }); }else{ _61(this); } }); return _5e; function _61(el,_62){ var t=$(el); var row={}; row[_5f.valueField]=t.attr("value")!=undefined?t.attr("value"):t.html(); row[_5f.textField]=t.html(); row["selected"]=t.is(":selected"); row["disabled"]=t.is(":disabled"); if(_62){ _5f.groupField=_5f.groupField||"group"; row[_5f.groupField]=_62; } _5e.push(row); }; }; $.fn.combobox.defaults=$.extend({},$.fn.combo.defaults,{valueField:"value",textField:"text",groupField:null,groupFormatter:function(_63){ return _63; },mode:"local",method:"post",url:null,data:null,keyHandler:{up:function(e){ nav(this,"prev"); e.preventDefault(); },down:function(e){ nav(this,"next"); e.preventDefault(); },left:function(e){ },right:function(e){ },enter:function(e){ _42(this); },query:function(q,e){ _39(this,q); }},filter:function(q,row){ var _64=$(this).combobox("options"); return row[_64.textField].toLowerCase().indexOf(q.toLowerCase())==0; },formatter:function(row){ var _65=$(this).combobox("options"); return row[_65.textField]; },loader:function(_66,_67,_68){ var _69=$(this).combobox("options"); if(!_69.url){ return false; } $.ajax({type:_69.method,url:_69.url,data:_66,dataType:"json",success:function(_6a){ _67(_6a); },error:function(){ _68.apply(this,arguments); }}); },loadFilter:function(_6b){ return _6b; },onBeforeLoad:function(_6c){ },onLoadSuccess:function(){ },onLoadError:function(){ },onSelect:function(_6d){ },onUnselect:function(_6e){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("numberbox-f"); var v=$("<input type=\"hidden\">").insertAfter(_2); var _3=$(_2).attr("name"); if(_3){ v.attr("name",_3); $(_2).removeAttr("name").attr("numberboxName",_3); } return v; }; function _4(_5){ var _6=$.data(_5,"numberbox").options; var fn=_6.onChange; _6.onChange=function(){ }; _7(_5,_6.parser.call(_5,_6.value)); _6.onChange=fn; _6.originalValue=_8(_5); }; function _8(_9){ return $.data(_9,"numberbox").field.val(); }; function _7(_a,_b){ var _c=$.data(_a,"numberbox"); var _d=_c.options; var _e=_8(_a); _b=_d.parser.call(_a,_b); _d.value=_b; _c.field.val(_b); $(_a).val(_d.formatter.call(_a,_b)); if(_e!=_b){ _d.onChange.call(_a,_b,_e); } }; function _f(_10){ var _11=$.data(_10,"numberbox").options; $(_10).unbind(".numberbox").bind("keypress.numberbox",function(e){ return _11.filter.call(_10,e); }).bind("blur.numberbox",function(){ _7(_10,$(this).val()); $(this).val(_11.formatter.call(_10,_8(_10))); }).bind("focus.numberbox",function(){ var vv=_8(_10); if(vv!=_11.parser.call(_10,$(this).val())){ $(this).val(_11.formatter.call(_10,vv)); } }); }; function _12(_13){ if($.fn.validatebox){ var _14=$.data(_13,"numberbox").options; $(_13).validatebox(_14); } }; function _15(_16,_17){ var _18=$.data(_16,"numberbox").options; if(_17){ _18.disabled=true; $(_16).attr("disabled",true); }else{ _18.disabled=false; $(_16).removeAttr("disabled"); } }; $.fn.numberbox=function(_19,_1a){ if(typeof _19=="string"){ var _1b=$.fn.numberbox.methods[_19]; if(_1b){ return _1b(this,_1a); }else{ return this.validatebox(_19,_1a); } } _19=_19||{}; return this.each(function(){ var _1c=$.data(this,"numberbox"); if(_1c){ $.extend(_1c.options,_19); }else{ _1c=$.data(this,"numberbox",{options:$.extend({},$.fn.numberbox.defaults,$.fn.numberbox.parseOptions(this),_19),field:_1(this)}); $(this).removeAttr("disabled"); $(this).css({imeMode:"disabled"}); } _15(this,_1c.options.disabled); _f(this); _12(this); _4(this); }); }; $.fn.numberbox.methods={options:function(jq){ return $.data(jq[0],"numberbox").options; },destroy:function(jq){ return jq.each(function(){ $.data(this,"numberbox").field.remove(); $(this).validatebox("destroy"); $(this).remove(); }); },disable:function(jq){ return jq.each(function(){ _15(this,true); }); },enable:function(jq){ return jq.each(function(){ _15(this,false); }); },fix:function(jq){ return jq.each(function(){ _7(this,$(this).val()); }); },setValue:function(jq,_1d){ return jq.each(function(){ _7(this,_1d); }); },getValue:function(jq){ return _8(jq[0]); },clear:function(jq){ return jq.each(function(){ var _1e=$.data(this,"numberbox"); _1e.field.val(""); $(this).val(""); }); },reset:function(jq){ return jq.each(function(){ var _1f=$(this).numberbox("options"); $(this).numberbox("setValue",_1f.originalValue); }); }}; $.fn.numberbox.parseOptions=function(_20){ var t=$(_20); return $.extend({},$.fn.validatebox.parseOptions(_20),$.parser.parseOptions(_20,["decimalSeparator","groupSeparator","suffix",{min:"number",max:"number",precision:"number"}]),{prefix:(t.attr("prefix")?t.attr("prefix"):undefined),disabled:(t.attr("disabled")?true:undefined),value:(t.val()||undefined)}); }; $.fn.numberbox.defaults=$.extend({},$.fn.validatebox.defaults,{disabled:false,value:"",min:null,max:null,precision:0,decimalSeparator:".",groupSeparator:"",prefix:"",suffix:"",filter:function(e){ var _21=$(this).numberbox("options"); if(e.which==45){ return ($(this).val().indexOf("-")==-1?true:false); } var c=String.fromCharCode(e.which); if(c==_21.decimalSeparator){ return ($(this).val().indexOf(c)==-1?true:false); }else{ if(c==_21.groupSeparator){ return true; }else{ if((e.which>=48&&e.which<=57&&e.ctrlKey==false&&e.shiftKey==false)||e.which==0||e.which==8){ return true; }else{ if(e.ctrlKey==true&&(e.which==99||e.which==118)){ return true; }else{ return false; } } } } },formatter:function(_22){ if(!_22){ return _22; } _22=_22+""; var _23=$(this).numberbox("options"); var s1=_22,s2=""; var _24=_22.indexOf("."); if(_24>=0){ s1=_22.substring(0,_24); s2=_22.substring(_24+1,_22.length); } if(_23.groupSeparator){ var p=/(\d+)(\d{3})/; while(p.test(s1)){ s1=s1.replace(p,"$1"+_23.groupSeparator+"$2"); } } if(s2){ return _23.prefix+s1+_23.decimalSeparator+s2+_23.suffix; }else{ return _23.prefix+s1+_23.suffix; } },parser:function(s){ s=s+""; var _25=$(this).numberbox("options"); if(parseFloat(s)!=s){ if(_25.prefix){ s=$.trim(s.replace(new RegExp("\\"+$.trim(_25.prefix),"g"),"")); } if(_25.suffix){ s=$.trim(s.replace(new RegExp("\\"+$.trim(_25.suffix),"g"),"")); } if(_25.groupSeparator){ s=$.trim(s.replace(new RegExp("\\"+_25.groupSeparator,"g"),"")); } if(_25.decimalSeparator){ s=$.trim(s.replace(new RegExp("\\"+_25.decimalSeparator,"g"),".")); } s=s.replace(/\s/g,""); } var val=parseFloat(s).toFixed(_25.precision); if(isNaN(val)){ val=""; }else{ if(typeof (_25.min)=="number"&&val<_25.min){ val=_25.min.toFixed(_25.precision); }else{ if(typeof (_25.max)=="number"&&val>_25.max){ val=_25.max.toFixed(_25.precision); } } } return val; },onChange:function(_26,_27){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(e){ var _2=$.data(e.data.target,"draggable"); var _3=_2.options; var _4=_2.proxy; var _5=e.data; var _6=_5.startLeft+e.pageX-_5.startX; var _7=_5.startTop+e.pageY-_5.startY; if(_4){ if(_4.parent()[0]==document.body){ if(_3.deltaX!=null&&_3.deltaX!=undefined){ _6=e.pageX+_3.deltaX; }else{ _6=e.pageX-e.data.offsetWidth; } if(_3.deltaY!=null&&_3.deltaY!=undefined){ _7=e.pageY+_3.deltaY; }else{ _7=e.pageY-e.data.offsetHeight; } }else{ if(_3.deltaX!=null&&_3.deltaX!=undefined){ _6+=e.data.offsetWidth+_3.deltaX; } if(_3.deltaY!=null&&_3.deltaY!=undefined){ _7+=e.data.offsetHeight+_3.deltaY; } } } if(e.data.parent!=document.body){ _6+=$(e.data.parent).scrollLeft(); _7+=$(e.data.parent).scrollTop(); } if(_3.axis=="h"){ _5.left=_6; }else{ if(_3.axis=="v"){ _5.top=_7; }else{ _5.left=_6; _5.top=_7; } } }; function _8(e){ var _9=$.data(e.data.target,"draggable"); var _a=_9.options; var _b=_9.proxy; if(!_b){ _b=$(e.data.target); } _b.css({left:e.data.left,top:e.data.top}); $("body").css("cursor",_a.cursor); }; function _c(e){ $.fn.draggable.isDragging=true; var _d=$.data(e.data.target,"draggable"); var _e=_d.options; var _f=$(".droppable").filter(function(){ return e.data.target!=this; }).filter(function(){ var _10=$.data(this,"droppable").options.accept; if(_10){ return $(_10).filter(function(){ return this==e.data.target; }).length>0; }else{ return true; } }); _d.droppables=_f; var _11=_d.proxy; if(!_11){ if(_e.proxy){ if(_e.proxy=="clone"){ _11=$(e.data.target).clone().insertAfter(e.data.target); }else{ _11=_e.proxy.call(e.data.target,e.data.target); } _d.proxy=_11; }else{ _11=$(e.data.target); } } _11.css("position","absolute"); _1(e); _8(e); _e.onStartDrag.call(e.data.target,e); return false; }; function _12(e){ var _13=$.data(e.data.target,"draggable"); _1(e); if(_13.options.onDrag.call(e.data.target,e)!=false){ _8(e); } var _14=e.data.target; _13.droppables.each(function(){ var _15=$(this); if(_15.droppable("options").disabled){ return; } var p2=_15.offset(); if(e.pageX>p2.left&&e.pageX<p2.left+_15.outerWidth()&&e.pageY>p2.top&&e.pageY<p2.top+_15.outerHeight()){ if(!this.entered){ $(this).trigger("_dragenter",[_14]); this.entered=true; } $(this).trigger("_dragover",[_14]); }else{ if(this.entered){ $(this).trigger("_dragleave",[_14]); this.entered=false; } } }); return false; }; function _16(e){ $.fn.draggable.isDragging=false; _12(e); var _17=$.data(e.data.target,"draggable"); var _18=_17.proxy; var _19=_17.options; if(_19.revert){ if(_1a()==true){ $(e.data.target).css({position:e.data.startPosition,left:e.data.startLeft,top:e.data.startTop}); }else{ if(_18){ var _1b,top; if(_18.parent()[0]==document.body){ _1b=e.data.startX-e.data.offsetWidth; top=e.data.startY-e.data.offsetHeight; }else{ _1b=e.data.startLeft; top=e.data.startTop; } _18.animate({left:_1b,top:top},function(){ _1c(); }); }else{ $(e.data.target).animate({left:e.data.startLeft,top:e.data.startTop},function(){ $(e.data.target).css("position",e.data.startPosition); }); } } }else{ $(e.data.target).css({position:"absolute",left:e.data.left,top:e.data.top}); _1a(); } _19.onStopDrag.call(e.data.target,e); $(document).unbind(".draggable"); setTimeout(function(){ $("body").css("cursor",""); },100); function _1c(){ if(_18){ _18.remove(); } _17.proxy=null; }; function _1a(){ var _1d=false; _17.droppables.each(function(){ var _1e=$(this); if(_1e.droppable("options").disabled){ return; } var p2=_1e.offset(); if(e.pageX>p2.left&&e.pageX<p2.left+_1e.outerWidth()&&e.pageY>p2.top&&e.pageY<p2.top+_1e.outerHeight()){ if(_19.revert){ $(e.data.target).css({position:e.data.startPosition,left:e.data.startLeft,top:e.data.startTop}); } $(this).trigger("_drop",[e.data.target]); _1c(); _1d=true; this.entered=false; return false; } }); if(!_1d&&!_19.revert){ _1c(); } return _1d; }; return false; }; $.fn.draggable=function(_1f,_20){ if(typeof _1f=="string"){ return $.fn.draggable.methods[_1f](this,_20); } return this.each(function(){ var _21; var _22=$.data(this,"draggable"); if(_22){ _22.handle.unbind(".draggable"); _21=$.extend(_22.options,_1f); }else{ _21=$.extend({},$.fn.draggable.defaults,$.fn.draggable.parseOptions(this),_1f||{}); } var _23=_21.handle?(typeof _21.handle=="string"?$(_21.handle,this):_21.handle):$(this); $.data(this,"draggable",{options:_21,handle:_23}); if(_21.disabled){ $(this).css("cursor",""); return; } _23.unbind(".draggable").bind("mousemove.draggable",{target:this},function(e){ if($.fn.draggable.isDragging){ return; } var _24=$.data(e.data.target,"draggable").options; if(_25(e)){ $(this).css("cursor",_24.cursor); }else{ $(this).css("cursor",""); } }).bind("mouseleave.draggable",{target:this},function(e){ $(this).css("cursor",""); }).bind("mousedown.draggable",{target:this},function(e){ if(_25(e)==false){ return; } $(this).css("cursor",""); var _26=$(e.data.target).position(); var _27=$(e.data.target).offset(); var _28={startPosition:$(e.data.target).css("position"),startLeft:_26.left,startTop:_26.top,left:_26.left,top:_26.top,startX:e.pageX,startY:e.pageY,offsetWidth:(e.pageX-_27.left),offsetHeight:(e.pageY-_27.top),target:e.data.target,parent:$(e.data.target).parent()[0]}; $.extend(e.data,_28); var _29=$.data(e.data.target,"draggable").options; if(_29.onBeforeDrag.call(e.data.target,e)==false){ return; } $(document).bind("mousedown.draggable",e.data,_c); $(document).bind("mousemove.draggable",e.data,_12); $(document).bind("mouseup.draggable",e.data,_16); }); function _25(e){ var _2a=$.data(e.data.target,"draggable"); var _2b=_2a.handle; var _2c=$(_2b).offset(); var _2d=$(_2b).outerWidth(); var _2e=$(_2b).outerHeight(); var t=e.pageY-_2c.top; var r=_2c.left+_2d-e.pageX; var b=_2c.top+_2e-e.pageY; var l=e.pageX-_2c.left; return Math.min(t,r,b,l)>_2a.options.edge; }; }); }; $.fn.draggable.methods={options:function(jq){ return $.data(jq[0],"draggable").options; },proxy:function(jq){ return $.data(jq[0],"draggable").proxy; },enable:function(jq){ return jq.each(function(){ $(this).draggable({disabled:false}); }); },disable:function(jq){ return jq.each(function(){ $(this).draggable({disabled:true}); }); }}; $.fn.draggable.parseOptions=function(_2f){ var t=$(_2f); return $.extend({},$.parser.parseOptions(_2f,["cursor","handle","axis",{"revert":"boolean","deltaX":"number","deltaY":"number","edge":"number"}]),{disabled:(t.attr("disabled")?true:undefined)}); }; $.fn.draggable.defaults={proxy:null,revert:false,cursor:"move",deltaX:null,deltaY:null,handle:null,disabled:false,edge:0,axis:null,onBeforeDrag:function(e){ },onStartDrag:function(e){ },onDrag:function(e){ },onStopDrag:function(e){ }}; $.fn.draggable.isDragging=false; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"linkbutton").options; var t=$(_2); t.addClass("l-btn").removeClass("l-btn-plain l-btn-selected l-btn-plain-selected"); if(_3.plain){ t.addClass("l-btn-plain"); } if(_3.selected){ t.addClass(_3.plain?"l-btn-selected l-btn-plain-selected":"l-btn-selected"); } t.attr("group",_3.group||""); t.attr("id",_3.id||""); t.html("<span class=\"l-btn-left\">"+"<span class=\"l-btn-text\"></span>"+"</span>"); if(_3.text){ t.find(".l-btn-text").html(_3.text); if(_3.iconCls){ t.find(".l-btn-text").addClass(_3.iconCls).addClass(_3.iconAlign=="left"?"l-btn-icon-left":"l-btn-icon-right"); } }else{ t.find(".l-btn-text").html("<span class=\"l-btn-empty\">&nbsp;</span>"); if(_3.iconCls){ t.find(".l-btn-empty").addClass(_3.iconCls); } } t.unbind(".linkbutton").bind("focus.linkbutton",function(){ if(!_3.disabled){ $(this).find(".l-btn-text").addClass("l-btn-focus"); } }).bind("blur.linkbutton",function(){ $(this).find(".l-btn-text").removeClass("l-btn-focus"); }); if(_3.toggle&&!_3.disabled){ t.bind("click.linkbutton",function(){ if(_3.selected){ $(this).linkbutton("unselect"); }else{ $(this).linkbutton("select"); } }); } _4(_2,_3.selected); _5(_2,_3.disabled); }; function _4(_6,_7){ var _8=$.data(_6,"linkbutton").options; if(_7){ if(_8.group){ $("a.l-btn[group=\""+_8.group+"\"]").each(function(){ var o=$(this).linkbutton("options"); if(o.toggle){ $(this).removeClass("l-btn-selected l-btn-plain-selected"); o.selected=false; } }); } $(_6).addClass(_8.plain?"l-btn-selected l-btn-plain-selected":"l-btn-selected"); _8.selected=true; }else{ if(!_8.group){ $(_6).removeClass("l-btn-selected l-btn-plain-selected"); _8.selected=false; } } }; function _5(_9,_a){ var _b=$.data(_9,"linkbutton"); var _c=_b.options; $(_9).removeClass("l-btn-disabled l-btn-plain-disabled"); if(_a){ _c.disabled=true; var _d=$(_9).attr("href"); if(_d){ _b.href=_d; $(_9).attr("href","javascript:void(0)"); } if(_9.onclick){ _b.onclick=_9.onclick; _9.onclick=null; } _c.plain?$(_9).addClass("l-btn-disabled l-btn-plain-disabled"):$(_9).addClass("l-btn-disabled"); }else{ _c.disabled=false; if(_b.href){ $(_9).attr("href",_b.href); } if(_b.onclick){ _9.onclick=_b.onclick; } } }; $.fn.linkbutton=function(_e,_f){ if(typeof _e=="string"){ return $.fn.linkbutton.methods[_e](this,_f); } _e=_e||{}; return this.each(function(){ var _10=$.data(this,"linkbutton"); if(_10){ $.extend(_10.options,_e); }else{ $.data(this,"linkbutton",{options:$.extend({},$.fn.linkbutton.defaults,$.fn.linkbutton.parseOptions(this),_e)}); $(this).removeAttr("disabled"); } _1(this); }); }; $.fn.linkbutton.methods={options:function(jq){ return $.data(jq[0],"linkbutton").options; },enable:function(jq){ return jq.each(function(){ _5(this,false); }); },disable:function(jq){ return jq.each(function(){ _5(this,true); }); },select:function(jq){ return jq.each(function(){ _4(this,true); }); },unselect:function(jq){ return jq.each(function(){ _4(this,false); }); }}; $.fn.linkbutton.parseOptions=function(_11){ var t=$(_11); return $.extend({},$.parser.parseOptions(_11,["id","iconCls","iconAlign","group",{plain:"boolean",toggle:"boolean",selected:"boolean"}]),{disabled:(t.attr("disabled")?true:undefined),text:$.trim(t.html()),iconCls:(t.attr("icon")||t.attr("iconCls"))}); }; $.fn.linkbutton.defaults={id:null,disabled:false,toggle:false,selected:false,group:null,plain:false,text:"",iconCls:null,iconAlign:"left"}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("progressbar"); $(_2).html("<div class=\"progressbar-text\"></div><div class=\"progressbar-value\"><div class=\"progressbar-text\"></div></div>"); return $(_2); }; function _3(_4,_5){ var _6=$.data(_4,"progressbar").options; var _7=$.data(_4,"progressbar").bar; if(_5){ _6.width=_5; } _7._outerWidth(_6.width)._outerHeight(_6.height); _7.find("div.progressbar-text").width(_7.width()); _7.find("div.progressbar-text,div.progressbar-value").css({height:_7.height()+"px",lineHeight:_7.height()+"px"}); }; $.fn.progressbar=function(_8,_9){ if(typeof _8=="string"){ var _a=$.fn.progressbar.methods[_8]; if(_a){ return _a(this,_9); } } _8=_8||{}; return this.each(function(){ var _b=$.data(this,"progressbar"); if(_b){ $.extend(_b.options,_8); }else{ _b=$.data(this,"progressbar",{options:$.extend({},$.fn.progressbar.defaults,$.fn.progressbar.parseOptions(this),_8),bar:_1(this)}); } $(this).progressbar("setValue",_b.options.value); _3(this); }); }; $.fn.progressbar.methods={options:function(jq){ return $.data(jq[0],"progressbar").options; },resize:function(jq,_c){ return jq.each(function(){ _3(this,_c); }); },getValue:function(jq){ return $.data(jq[0],"progressbar").options.value; },setValue:function(jq,_d){ if(_d<0){ _d=0; } if(_d>100){ _d=100; } return jq.each(function(){ var _e=$.data(this,"progressbar").options; var _f=_e.text.replace(/{value}/,_d); var _10=_e.value; _e.value=_d; $(this).find("div.progressbar-value").width(_d+"%"); $(this).find("div.progressbar-text").html(_f); if(_10!=_d){ _e.onChange.call(this,_d,_10); } }); }}; $.fn.progressbar.parseOptions=function(_11){ return $.extend({},$.parser.parseOptions(_11,["width","height","text",{value:"number"}])); }; $.fn.progressbar.defaults={width:"auto",height:22,value:0,text:"{value}%",onChange:function(_12,_13){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(el,_2,_3,_4){ var _5=$(el).window("window"); if(!_5){ return; } switch(_2){ case null: _5.show(); break; case "slide": _5.slideDown(_3); break; case "fade": _5.fadeIn(_3); break; case "show": _5.show(_3); break; } var _6=null; if(_4>0){ _6=setTimeout(function(){ _7(el,_2,_3); },_4); } _5.hover(function(){ if(_6){ clearTimeout(_6); } },function(){ if(_4>0){ _6=setTimeout(function(){ _7(el,_2,_3); },_4); } }); }; function _7(el,_8,_9){ if(el.locked==true){ return; } el.locked=true; var _a=$(el).window("window"); if(!_a){ return; } switch(_8){ case null: _a.hide(); break; case "slide": _a.slideUp(_9); break; case "fade": _a.fadeOut(_9); break; case "show": _a.hide(_9); break; } setTimeout(function(){ $(el).window("destroy"); },_9); }; function _b(_c){ var _d=$.extend({},$.fn.window.defaults,{collapsible:false,minimizable:false,maximizable:false,shadow:false,draggable:false,resizable:false,closed:true,style:{left:"",top:"",right:0,zIndex:$.fn.window.defaults.zIndex++,bottom:-document.body.scrollTop-document.documentElement.scrollTop},onBeforeOpen:function(){ _1(this,_d.showType,_d.showSpeed,_d.timeout); return false; },onBeforeClose:function(){ _7(this,_d.showType,_d.showSpeed); return false; }},{title:"",width:250,height:100,showType:"slide",showSpeed:600,msg:"",timeout:4000},_c); _d.style.zIndex=$.fn.window.defaults.zIndex++; var _e=$("<div class=\"messager-body\"></div>").html(_d.msg).appendTo("body"); _e.window(_d); _e.window("window").css(_d.style); _e.window("open"); return _e; }; function _f(_10,_11,_12){ var win=$("<div class=\"messager-body\"></div>").appendTo("body"); win.append(_11); if(_12){ var tb=$("<div class=\"messager-button\"></div>").appendTo(win); for(var _13 in _12){ $("<a></a>").attr("href","javascript:void(0)").text(_13).css("margin-left",10).bind("click",eval(_12[_13])).appendTo(tb).linkbutton(); } } win.window({title:_10,noheader:(_10?false:true),width:300,height:"auto",modal:true,collapsible:false,minimizable:false,maximizable:false,resizable:false,onClose:function(){ setTimeout(function(){ win.window("destroy"); },100); }}); win.window("window").addClass("messager-window"); win.children("div.messager-button").children("a:first").focus(); return win; }; $.messager={show:function(_14){ return _b(_14); },alert:function(_15,msg,_16,fn){ var _17="<div>"+msg+"</div>"; switch(_16){ case "error": _17="<div class=\"messager-icon messager-error\"></div>"+_17; break; case "info": _17="<div class=\"messager-icon messager-info\"></div>"+_17; break; case "question": _17="<div class=\"messager-icon messager-question\"></div>"+_17; break; case "warning": _17="<div class=\"messager-icon messager-warning\"></div>"+_17; break; } _17+="<div style=\"clear:both;\"/>"; var _18={}; _18[$.messager.defaults.ok]=function(){ win.window("close"); if(fn){ fn(); return false; } }; var win=_f(_15,_17,_18); return win; },confirm:function(_19,msg,fn){ var _1a="<div class=\"messager-icon messager-question\"></div>"+"<div>"+msg+"</div>"+"<div style=\"clear:both;\"/>"; var _1b={}; _1b[$.messager.defaults.ok]=function(){ win.window("close"); if(fn){ fn(true); return false; } }; _1b[$.messager.defaults.cancel]=function(){ win.window("close"); if(fn){ fn(false); return false; } }; var win=_f(_19,_1a,_1b); return win; },prompt:function(_1c,msg,fn){ var _1d="<div class=\"messager-icon messager-question\"></div>"+"<div>"+msg+"</div>"+"<br/>"+"<div style=\"clear:both;\"/>"+"<div><input class=\"messager-input\" type=\"text\"/></div>"; var _1e={}; _1e[$.messager.defaults.ok]=function(){ win.window("close"); if(fn){ fn($(".messager-input",win).val()); return false; } }; _1e[$.messager.defaults.cancel]=function(){ win.window("close"); if(fn){ fn(); return false; } }; var win=_f(_1c,_1d,_1e); win.children("input.messager-input").focus(); return win; },progress:function(_1f){ var _20={bar:function(){ return $("body>div.messager-window").find("div.messager-p-bar"); },close:function(){ var win=$("body>div.messager-window>div.messager-body:has(div.messager-progress)"); if(win.length){ win.window("close"); } }}; if(typeof _1f=="string"){ var _21=_20[_1f]; return _21(); } var _22=$.extend({title:"",msg:"",text:undefined,interval:300},_1f||{}); var _23="<div class=\"messager-progress\"><div class=\"messager-p-msg\"></div><div class=\"messager-p-bar\"></div></div>"; var win=_f(_22.title,_23,null); win.find("div.messager-p-msg").html(_22.msg); var bar=win.find("div.messager-p-bar"); bar.progressbar({text:_22.text}); win.window({closable:false,onClose:function(){ if(this.timer){ clearInterval(this.timer); } $(this).window("destroy"); }}); if(_22.interval){ win[0].timer=setInterval(function(){ var v=bar.progressbar("getValue"); v+=10; if(v>100){ v=0; } bar.progressbar("setValue",v); },_22.interval); } return win; }}; $.messager.defaults={ok:"Ok",cancel:"Cancel"}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ var _1=false; function _2(_3){ var _4=$.data(_3,"layout"); var _5=_4.options; var _6=_4.panels; var cc=$(_3); if(_3.tagName=="BODY"){ cc._fit(); }else{ _5.fit?cc.css(cc._fit()):cc._fit(false); } var _7={top:0,left:0,width:cc.width(),height:cc.height()}; _8(_9(_6.expandNorth)?_6.expandNorth:_6.north,"n"); _8(_9(_6.expandSouth)?_6.expandSouth:_6.south,"s"); _a(_9(_6.expandEast)?_6.expandEast:_6.east,"e"); _a(_9(_6.expandWest)?_6.expandWest:_6.west,"w"); _6.center.panel("resize",_7); function _b(pp){ var _c=pp.panel("options"); return Math.min(Math.max(_c.height,_c.minHeight),_c.maxHeight); }; function _d(pp){ var _e=pp.panel("options"); return Math.min(Math.max(_e.width,_e.minWidth),_e.maxWidth); }; function _8(pp,_f){ if(!pp.length){ return; } var _10=pp.panel("options"); var _11=_b(pp); pp.panel("resize",{width:cc.width(),height:_11,left:0,top:(_f=="n"?0:cc.height()-_11)}); _7.height-=_11; if(_f=="n"){ _7.top+=_11; if(!_10.split&&_10.border){ _7.top--; } } if(!_10.split&&_10.border){ _7.height++; } }; function _a(pp,_12){ if(!pp.length){ return; } var _13=pp.panel("options"); var _14=_d(pp); pp.panel("resize",{width:_14,height:_7.height,left:(_12=="e"?cc.width()-_14:0),top:_7.top}); _7.width-=_14; if(_12=="w"){ _7.left+=_14; if(!_13.split&&_13.border){ _7.left--; } } if(!_13.split&&_13.border){ _7.width++; } }; }; function _15(_16){ var cc=$(_16); cc.addClass("layout"); function _17(cc){ cc.children("div").each(function(){ var _18=$.fn.layout.parsePanelOptions(this); if("north,south,east,west,center".indexOf(_18.region)>=0){ _1b(_16,_18,this); } }); }; cc.children("form").length?_17(cc.children("form")):_17(cc); cc.append("<div class=\"layout-split-proxy-h\"></div><div class=\"layout-split-proxy-v\"></div>"); cc.bind("_resize",function(e,_19){ var _1a=$.data(_16,"layout").options; if(_1a.fit==true||_19){ _2(_16); } return false; }); }; function _1b(_1c,_1d,el){ _1d.region=_1d.region||"center"; var _1e=$.data(_1c,"layout").panels; var cc=$(_1c); var dir=_1d.region; if(_1e[dir].length){ return; } var pp=$(el); if(!pp.length){ pp=$("<div></div>").appendTo(cc); } var _1f=$.extend({},$.fn.layout.paneldefaults,{width:(pp.length?parseInt(pp[0].style.width)||pp.outerWidth():"auto"),height:(pp.length?parseInt(pp[0].style.height)||pp.outerHeight():"auto"),doSize:false,collapsible:true,cls:("layout-panel layout-panel-"+dir),bodyCls:"layout-body",onOpen:function(){ var _20=$(this).panel("header").children("div.panel-tool"); _20.children("a.panel-tool-collapse").hide(); var _21={north:"up",south:"down",east:"right",west:"left"}; if(!_21[dir]){ return; } var _22="layout-button-"+_21[dir]; var t=_20.children("a."+_22); if(!t.length){ t=$("<a href=\"javascript:void(0)\"></a>").addClass(_22).appendTo(_20); t.bind("click",{dir:dir},function(e){ _2f(_1c,e.data.dir); return false; }); } $(this).panel("options").collapsible?t.show():t.hide(); }},_1d); pp.panel(_1f); _1e[dir]=pp; if(pp.panel("options").split){ var _23=pp.panel("panel"); _23.addClass("layout-split-"+dir); var _24=""; if(dir=="north"){ _24="s"; } if(dir=="south"){ _24="n"; } if(dir=="east"){ _24="w"; } if(dir=="west"){ _24="e"; } _23.resizable($.extend({},{handles:_24,onStartResize:function(e){ _1=true; if(dir=="north"||dir=="south"){ var _25=$(">div.layout-split-proxy-v",_1c); }else{ var _25=$(">div.layout-split-proxy-h",_1c); } var top=0,_26=0,_27=0,_28=0; var pos={display:"block"}; if(dir=="north"){ pos.top=parseInt(_23.css("top"))+_23.outerHeight()-_25.height(); pos.left=parseInt(_23.css("left")); pos.width=_23.outerWidth(); pos.height=_25.height(); }else{ if(dir=="south"){ pos.top=parseInt(_23.css("top")); pos.left=parseInt(_23.css("left")); pos.width=_23.outerWidth(); pos.height=_25.height(); }else{ if(dir=="east"){ pos.top=parseInt(_23.css("top"))||0; pos.left=parseInt(_23.css("left"))||0; pos.width=_25.width(); pos.height=_23.outerHeight(); }else{ if(dir=="west"){ pos.top=parseInt(_23.css("top"))||0; pos.left=_23.outerWidth()-_25.width(); pos.width=_25.width(); pos.height=_23.outerHeight(); } } } } _25.css(pos); $("<div class=\"layout-mask\"></div>").css({left:0,top:0,width:cc.width(),height:cc.height()}).appendTo(cc); },onResize:function(e){ if(dir=="north"||dir=="south"){ var _29=$(">div.layout-split-proxy-v",_1c); _29.css("top",e.pageY-$(_1c).offset().top-_29.height()/2); }else{ var _29=$(">div.layout-split-proxy-h",_1c); _29.css("left",e.pageX-$(_1c).offset().left-_29.width()/2); } return false; },onStopResize:function(e){ cc.children("div.layout-split-proxy-v,div.layout-split-proxy-h").hide(); pp.panel("resize",e.data); _2(_1c); _1=false; cc.find(">div.layout-mask").remove(); }},_1d)); } }; function _2a(_2b,_2c){ var _2d=$.data(_2b,"layout").panels; if(_2d[_2c].length){ _2d[_2c].panel("destroy"); _2d[_2c]=$(); var _2e="expand"+_2c.substring(0,1).toUpperCase()+_2c.substring(1); if(_2d[_2e]){ _2d[_2e].panel("destroy"); _2d[_2e]=undefined; } } }; function _2f(_30,_31,_32){ if(_32==undefined){ _32="normal"; } var _33=$.data(_30,"layout").panels; var p=_33[_31]; var _34=p.panel("options"); if(_34.onBeforeCollapse.call(p)==false){ return; } var _35="expand"+_31.substring(0,1).toUpperCase()+_31.substring(1); if(!_33[_35]){ _33[_35]=_36(_31); _33[_35].panel("panel").bind("click",function(){ var _37=_38(); p.panel("expand",false).panel("open").panel("resize",_37.collapse); p.panel("panel").animate(_37.expand,function(){ $(this).unbind(".layout").bind("mouseleave.layout",{region:_31},function(e){ if(_1==true){ return; } _2f(_30,e.data.region); }); }); return false; }); } var _39=_38(); if(!_9(_33[_35])){ _33.center.panel("resize",_39.resizeC); } p.panel("panel").animate(_39.collapse,_32,function(){ p.panel("collapse",false).panel("close"); _33[_35].panel("open").panel("resize",_39.expandP); $(this).unbind(".layout"); }); function _36(dir){ var _3a; if(dir=="east"){ _3a="layout-button-left"; }else{ if(dir=="west"){ _3a="layout-button-right"; }else{ if(dir=="north"){ _3a="layout-button-down"; }else{ if(dir=="south"){ _3a="layout-button-up"; } } } } var p=$("<div></div>").appendTo(_30); p.panel($.extend({},$.fn.layout.paneldefaults,{cls:("layout-expand layout-expand-"+dir),title:"&nbsp;",closed:true,doSize:false,tools:[{iconCls:_3a,handler:function(){ _3c(_30,_31); return false; }}]})); p.panel("panel").hover(function(){ $(this).addClass("layout-expand-over"); },function(){ $(this).removeClass("layout-expand-over"); }); return p; }; function _38(){ var cc=$(_30); var _3b=_33.center.panel("options"); if(_31=="east"){ var ww=_3b.width+_34.width-28; if(_34.split||!_34.border){ ww++; } return {resizeC:{width:ww},expand:{left:cc.width()-_34.width},expandP:{top:_3b.top,left:cc.width()-28,width:28,height:_3b.height},collapse:{left:cc.width(),top:_3b.top,height:_3b.height}}; }else{ if(_31=="west"){ var ww=_3b.width+_34.width-28; if(_34.split||!_34.border){ ww++; } return {resizeC:{width:ww,left:28-1},expand:{left:0},expandP:{left:0,top:_3b.top,width:28,height:_3b.height},collapse:{left:-_34.width,top:_3b.top,height:_3b.height}}; }else{ if(_31=="north"){ var hh=_3b.height; if(!_9(_33.expandNorth)){ hh+=_34.height-28+((_34.split||!_34.border)?1:0); } _33.east.add(_33.west).add(_33.expandEast).add(_33.expandWest).panel("resize",{top:28-1,height:hh}); return {resizeC:{top:28-1,height:hh},expand:{top:0},expandP:{top:0,left:0,width:cc.width(),height:28},collapse:{top:-_34.height,width:cc.width()}}; }else{ if(_31=="south"){ var hh=_3b.height; if(!_9(_33.expandSouth)){ hh+=_34.height-28+((_34.split||!_34.border)?1:0); } _33.east.add(_33.west).add(_33.expandEast).add(_33.expandWest).panel("resize",{height:hh}); return {resizeC:{height:hh},expand:{top:cc.height()-_34.height},expandP:{top:cc.height()-28,left:0,width:cc.width(),height:28},collapse:{top:cc.height(),width:cc.width()}}; } } } } }; }; function _3c(_3d,_3e){ var _3f=$.data(_3d,"layout").panels; var p=_3f[_3e]; var _40=p.panel("options"); if(_40.onBeforeExpand.call(p)==false){ return; } var _41=_42(); var _43="expand"+_3e.substring(0,1).toUpperCase()+_3e.substring(1); if(_3f[_43]){ _3f[_43].panel("close"); p.panel("panel").stop(true,true); p.panel("expand",false).panel("open").panel("resize",_41.collapse); p.panel("panel").animate(_41.expand,function(){ _2(_3d); }); } function _42(){ var cc=$(_3d); var _44=_3f.center.panel("options"); if(_3e=="east"&&_3f.expandEast){ return {collapse:{left:cc.width(),top:_44.top,height:_44.height},expand:{left:cc.width()-_3f["east"].panel("options").width}}; }else{ if(_3e=="west"&&_3f.expandWest){ return {collapse:{left:-_3f["west"].panel("options").width,top:_44.top,height:_44.height},expand:{left:0}}; }else{ if(_3e=="north"&&_3f.expandNorth){ return {collapse:{top:-_3f["north"].panel("options").height,width:cc.width()},expand:{top:0}}; }else{ if(_3e=="south"&&_3f.expandSouth){ return {collapse:{top:cc.height(),width:cc.width()},expand:{top:cc.height()-_3f["south"].panel("options").height}}; } } } } }; }; function _9(pp){ if(!pp){ return false; } if(pp.length){ return pp.panel("panel").is(":visible"); }else{ return false; } }; function _45(_46){ var _47=$.data(_46,"layout").panels; if(_47.east.length&&_47.east.panel("options").collapsed){ _2f(_46,"east",0); } if(_47.west.length&&_47.west.panel("options").collapsed){ _2f(_46,"west",0); } if(_47.north.length&&_47.north.panel("options").collapsed){ _2f(_46,"north",0); } if(_47.south.length&&_47.south.panel("options").collapsed){ _2f(_46,"south",0); } }; $.fn.layout=function(_48,_49){ if(typeof _48=="string"){ return $.fn.layout.methods[_48](this,_49); } _48=_48||{}; return this.each(function(){ var _4a=$.data(this,"layout"); if(_4a){ $.extend(_4a.options,_48); }else{ var _4b=$.extend({},$.fn.layout.defaults,$.fn.layout.parseOptions(this),_48); $.data(this,"layout",{options:_4b,panels:{center:$(),north:$(),south:$(),east:$(),west:$()}}); _15(this); } _2(this); _45(this); }); }; $.fn.layout.methods={resize:function(jq){ return jq.each(function(){ _2(this); }); },panel:function(jq,_4c){ return $.data(jq[0],"layout").panels[_4c]; },collapse:function(jq,_4d){ return jq.each(function(){ _2f(this,_4d); }); },expand:function(jq,_4e){ return jq.each(function(){ _3c(this,_4e); }); },add:function(jq,_4f){ return jq.each(function(){ _1b(this,_4f); _2(this); if($(this).layout("panel",_4f.region).panel("options").collapsed){ _2f(this,_4f.region,0); } }); },remove:function(jq,_50){ return jq.each(function(){ _2a(this,_50); _2(this); }); }}; $.fn.layout.parseOptions=function(_51){ return $.extend({},$.parser.parseOptions(_51,[{fit:"boolean"}])); }; $.fn.layout.defaults={fit:false}; $.fn.layout.parsePanelOptions=function(_52){ var t=$(_52); return $.extend({},$.fn.panel.parseOptions(_52),$.parser.parseOptions(_52,["region",{split:"boolean",minWidth:"number",minHeight:"number",maxWidth:"number",maxHeight:"number"}])); }; $.fn.layout.paneldefaults=$.extend({},$.fn.panel.defaults,{region:null,split:false,minWidth:10,minHeight:10,maxWidth:10000,maxHeight:10000}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("validatebox-text"); }; function _3(_4){ var _5=$.data(_4,"validatebox"); _5.validating=false; if(_5.timer){ clearTimeout(_5.timer); } $(_4).tooltip("destroy"); $(_4).unbind(); $(_4).remove(); }; function _6(_7){ var _8=$(_7); var _9=$.data(_7,"validatebox"); _8.unbind(".validatebox"); if(_9.options.novalidate){ return; } _8.bind("focus.validatebox",function(){ _9.validating=true; _9.value=undefined; (function(){ if(_9.validating){ if(_9.value!=_8.val()){ _9.value=_8.val(); if(_9.timer){ clearTimeout(_9.timer); } _9.timer=setTimeout(function(){ $(_7).validatebox("validate"); },_9.options.delay); }else{ _f(_7); } setTimeout(arguments.callee,200); } })(); }).bind("blur.validatebox",function(){ if(_9.timer){ clearTimeout(_9.timer); _9.timer=undefined; } _9.validating=false; _a(_7); }).bind("mouseenter.validatebox",function(){ if(_8.hasClass("validatebox-invalid")){ _b(_7); } }).bind("mouseleave.validatebox",function(){ if(!_9.validating){ _a(_7); } }); }; function _b(_c){ var _d=$.data(_c,"validatebox"); var _e=_d.options; $(_c).tooltip($.extend({},_e.tipOptions,{content:_d.message,position:_e.tipPosition,deltaX:_e.deltaX})).tooltip("show"); _d.tip=true; }; function _f(_10){ var _11=$.data(_10,"validatebox"); if(_11&&_11.tip){ $(_10).tooltip("reposition"); } }; function _a(_12){ var _13=$.data(_12,"validatebox"); _13.tip=false; $(_12).tooltip("hide"); }; function _14(_15){ var _16=$.data(_15,"validatebox"); var _17=_16.options; var box=$(_15); var _18=box.val(); function _19(msg){ _16.message=msg; }; function _1a(_1b){ var _1c=/([a-zA-Z_]+)(.*)/.exec(_1b); var _1d=_17.rules[_1c[1]]; if(_1d&&_18){ var _1e=eval(_1c[2]); if(!_1d["validator"](_18,_1e)){ box.addClass("validatebox-invalid"); var _1f=_1d["message"]; if(_1e){ for(var i=0;i<_1e.length;i++){ _1f=_1f.replace(new RegExp("\\{"+i+"\\}","g"),_1e[i]); } } _19(_17.invalidMessage||_1f); if(_16.validating){ _b(_15); } return false; } } return true; }; box.removeClass("validatebox-invalid"); _a(_15); if(_17.novalidate||box.is(":disabled")){ return true; } if(_17.required){ if(_18==""){ box.addClass("validatebox-invalid"); _19(_17.missingMessage); if(_16.validating){ _b(_15); } return false; } } if(_17.validType){ if(typeof _17.validType=="string"){ if(!_1a(_17.validType)){ return false; } }else{ for(var i=0;i<_17.validType.length;i++){ if(!_1a(_17.validType[i])){ return false; } } } } return true; }; function _20(_21,_22){ var _23=$.data(_21,"validatebox").options; if(_22!=undefined){ _23.novalidate=_22; } if(_23.novalidate){ $(_21).removeClass("validatebox-invalid"); _a(_21); } _6(_21); }; $.fn.validatebox=function(_24,_25){ if(typeof _24=="string"){ return $.fn.validatebox.methods[_24](this,_25); } _24=_24||{}; return this.each(function(){ var _26=$.data(this,"validatebox"); if(_26){ $.extend(_26.options,_24); }else{ _1(this); $.data(this,"validatebox",{options:$.extend({},$.fn.validatebox.defaults,$.fn.validatebox.parseOptions(this),_24)}); } _20(this); _14(this); }); }; $.fn.validatebox.methods={options:function(jq){ return $.data(jq[0],"validatebox").options; },destroy:function(jq){ return jq.each(function(){ _3(this); }); },validate:function(jq){ return jq.each(function(){ _14(this); }); },isValid:function(jq){ return _14(jq[0]); },enableValidation:function(jq){ return jq.each(function(){ _20(this,false); }); },disableValidation:function(jq){ return jq.each(function(){ _20(this,true); }); }}; $.fn.validatebox.parseOptions=function(_27){ var t=$(_27); return $.extend({},$.parser.parseOptions(_27,["validType","missingMessage","invalidMessage","tipPosition",{delay:"number",deltaX:"number"}]),{required:(t.attr("required")?true:undefined),novalidate:(t.attr("novalidate")!=undefined?true:undefined)}); }; $.fn.validatebox.defaults={required:false,validType:null,delay:200,missingMessage:"This field is required.",invalidMessage:null,tipPosition:"right",deltaX:0,novalidate:false,tipOptions:{showEvent:"none",hideEvent:"none",showDelay:0,hideDelay:0,zIndex:"",onShow:function(){ $(this).tooltip("tip").css({color:"#000",borderColor:"#CC9933",backgroundColor:"#FFFFCC"}); },onHide:function(){ $(this).tooltip("destroy"); }},rules:{email:{validator:function(_28){ return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(_28); },message:"Please enter a valid email address."},url:{validator:function(_29){ return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(_29); },message:"Please enter a valid URL."},length:{validator:function(_2a,_2b){ var len=$.trim(_2a).length; return len>=_2b[0]&&len<=_2b[1]; },message:"Please enter a value between {0} and {1}."},remote:{validator:function(_2c,_2d){ var _2e={}; _2e[_2d[1]]=_2c; var _2f=$.ajax({url:_2d[0],dataType:"json",data:_2e,async:false,cache:false,type:"post"}).responseText; return _2f=="true"; },message:"Please fix this field."}}}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"menubutton").options; var _4=$(_2); _4.removeClass(_3.cls.btn1+" "+_3.cls.btn2).addClass("m-btn"); _4.linkbutton($.extend({},_3,{text:_3.text+"<span class=\""+_3.cls.arrow+"\">&nbsp;</span>"})); if(_3.menu){ $(_3.menu).menu(); var _5=$(_3.menu).menu("options"); var _6=_5.onShow; var _7=_5.onHide; $.extend(_5,{onShow:function(){ var _8=$(this).menu("options"); var _9=$(_8.alignTo); var _a=_9.menubutton("options"); _9.addClass((_a.plain==true)?_a.cls.btn2:_a.cls.btn1); _6.call(this); },onHide:function(){ var _b=$(this).menu("options"); var _c=$(_b.alignTo); var _d=_c.menubutton("options"); _c.removeClass((_d.plain==true)?_d.cls.btn2:_d.cls.btn1); _7.call(this); }}); } _e(_2,_3.disabled); }; function _e(_f,_10){ var _11=$.data(_f,"menubutton").options; _11.disabled=_10; var btn=$(_f); var t=btn.find("."+_11.cls.trigger); if(!t.length){ t=btn; } t.unbind(".menubutton"); if(_10){ btn.linkbutton("disable"); }else{ btn.linkbutton("enable"); var _12=null; t.bind("click.menubutton",function(){ _13(_f); return false; }).bind("mouseenter.menubutton",function(){ _12=setTimeout(function(){ _13(_f); },_11.duration); return false; }).bind("mouseleave.menubutton",function(){ if(_12){ clearTimeout(_12); } }); } }; function _13(_14){ var _15=$.data(_14,"menubutton").options; if(_15.disabled||!_15.menu){ return; } $("body>div.menu-top").menu("hide"); var btn=$(_14); var mm=$(_15.menu); if(mm.length){ mm.menu("options").alignTo=btn; mm.menu("show",{alignTo:btn}); } btn.blur(); }; $.fn.menubutton=function(_16,_17){ if(typeof _16=="string"){ var _18=$.fn.menubutton.methods[_16]; if(_18){ return _18(this,_17); }else{ return this.linkbutton(_16,_17); } } _16=_16||{}; return this.each(function(){ var _19=$.data(this,"menubutton"); if(_19){ $.extend(_19.options,_16); }else{ $.data(this,"menubutton",{options:$.extend({},$.fn.menubutton.defaults,$.fn.menubutton.parseOptions(this),_16)}); $(this).removeAttr("disabled"); } _1(this); }); }; $.fn.menubutton.methods={options:function(jq){ var _1a=jq.linkbutton("options"); var _1b=$.data(jq[0],"menubutton").options; _1b.toggle=_1a.toggle; _1b.selected=_1a.selected; return _1b; },enable:function(jq){ return jq.each(function(){ _e(this,false); }); },disable:function(jq){ return jq.each(function(){ _e(this,true); }); },destroy:function(jq){ return jq.each(function(){ var _1c=$(this).menubutton("options"); if(_1c.menu){ $(_1c.menu).menu("destroy"); } $(this).remove(); }); }}; $.fn.menubutton.parseOptions=function(_1d){ var t=$(_1d); return $.extend({},$.fn.linkbutton.parseOptions(_1d),$.parser.parseOptions(_1d,["menu",{plain:"boolean",duration:"number"}])); }; $.fn.menubutton.defaults=$.extend({},$.fn.linkbutton.defaults,{plain:true,menu:null,duration:100,cls:{btn1:"m-btn-active",btn2:"m-btn-plain-active",arrow:"m-btn-downarrow",trigger:"m-btn"}}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"pagination"); var _4=_3.options; var bb=_3.bb={}; var _5=$(_2).addClass("pagination").html("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr></tr></table>"); var tr=_5.find("tr"); var aa=$.extend([],_4.layout); if(!_4.showPageList){ _6(aa,"list"); } if(!_4.showRefresh){ _6(aa,"refresh"); } if(aa[0]=="sep"){ aa.shift(); } if(aa[aa.length-1]=="sep"){ aa.pop(); } for(var _7=0;_7<aa.length;_7++){ var _8=aa[_7]; if(_8=="list"){ var ps=$("<select class=\"pagination-page-list\"></select>"); ps.bind("change",function(){ _4.pageSize=parseInt($(this).val()); _4.onChangePageSize.call(_2,_4.pageSize); _10(_2,_4.pageNumber); }); for(var i=0;i<_4.pageList.length;i++){ $("<option></option>").text(_4.pageList[i]).appendTo(ps); } $("<td></td>").append(ps).appendTo(tr); }else{ if(_8=="sep"){ $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); }else{ if(_8=="first"){ bb.first=_9("first"); }else{ if(_8=="prev"){ bb.prev=_9("prev"); }else{ if(_8=="next"){ bb.next=_9("next"); }else{ if(_8=="last"){ bb.last=_9("last"); }else{ if(_8=="manual"){ $("<span style=\"padding-left:6px;\"></span>").html(_4.beforePageText).appendTo(tr).wrap("<td></td>"); bb.num=$("<input class=\"pagination-num\" type=\"text\" value=\"1\" size=\"2\">").appendTo(tr).wrap("<td></td>"); bb.num.unbind(".pagination").bind("keydown.pagination",function(e){ if(e.keyCode==13){ var _a=parseInt($(this).val())||1; _10(_2,_a); return false; } }); bb.after=$("<span style=\"padding-right:6px;\"></span>").appendTo(tr).wrap("<td></td>"); }else{ if(_8=="refresh"){ bb.refresh=_9("refresh"); }else{ if(_8=="links"){ $("<td class=\"pagination-links\"></td>").appendTo(tr); } } } } } } } } } } if(_4.buttons){ $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); if($.isArray(_4.buttons)){ for(var i=0;i<_4.buttons.length;i++){ var _b=_4.buttons[i]; if(_b=="-"){ $("<td><div class=\"pagination-btn-separator\"></div></td>").appendTo(tr); }else{ var td=$("<td></td>").appendTo(tr); var a=$("<a href=\"javascript:void(0)\"></a>").appendTo(td); a[0].onclick=eval(_b.handler||function(){ }); a.linkbutton($.extend({},_b,{plain:true})); } } }else{ var td=$("<td></td>").appendTo(tr); $(_4.buttons).appendTo(td).show(); } } $("<div class=\"pagination-info\"></div>").appendTo(_5); $("<div style=\"clear:both;\"></div>").appendTo(_5); function _9(_c){ var _d=_4.nav[_c]; var a=$("<a href=\"javascript:void(0)\"></a>").appendTo(tr); a.wrap("<td></td>"); a.linkbutton({iconCls:_d.iconCls,plain:true}).unbind(".pagination").bind("click.pagination",function(){ _d.handler.call(_2); }); return a; }; function _6(aa,_e){ var _f=$.inArray(_e,aa); if(_f>=0){ aa.splice(_f,1); } return aa; }; }; function _10(_11,_12){ var _13=$.data(_11,"pagination").options; _14(_11,{pageNumber:_12}); _13.onSelectPage.call(_11,_13.pageNumber,_13.pageSize); }; function _14(_15,_16){ var _17=$.data(_15,"pagination"); var _18=_17.options; var bb=_17.bb; $.extend(_18,_16||{}); var ps=$(_15).find("select.pagination-page-list"); if(ps.length){ ps.val(_18.pageSize+""); _18.pageSize=parseInt(ps.val()); } var _19=Math.ceil(_18.total/_18.pageSize)||1; if(_18.pageNumber<1){ _18.pageNumber=1; } if(_18.pageNumber>_19){ _18.pageNumber=_19; } if(bb.num){ bb.num.val(_18.pageNumber); } if(bb.after){ bb.after.html(_18.afterPageText.replace(/{pages}/,_19)); } var td=$(_15).find("td.pagination-links"); if(td.length){ td.empty(); var _1a=_18.pageNumber-Math.floor(_18.links/2); if(_1a<1){ _1a=1; } var _1b=_1a+_18.links-1; if(_1b>_19){ _1b=_19; } _1a=_1b-_18.links+1; if(_1a<1){ _1a=1; } for(var i=_1a;i<=_1b;i++){ var a=$("<a class=\"pagination-link\" href=\"javascript:void(0)\"></a>").appendTo(td); a.linkbutton({plain:true,text:i}); if(i==_18.pageNumber){ a.linkbutton("select"); }else{ a.unbind(".pagination").bind("click.pagination",{pageNumber:i},function(e){ _10(_15,e.data.pageNumber); }); } } } var _1c=_18.displayMsg; _1c=_1c.replace(/{from}/,_18.total==0?0:_18.pageSize*(_18.pageNumber-1)+1); _1c=_1c.replace(/{to}/,Math.min(_18.pageSize*(_18.pageNumber),_18.total)); _1c=_1c.replace(/{total}/,_18.total); $(_15).find("div.pagination-info").html(_1c); if(bb.first){ bb.first.linkbutton({disabled:(_18.pageNumber==1)}); } if(bb.prev){ bb.prev.linkbutton({disabled:(_18.pageNumber==1)}); } if(bb.next){ bb.next.linkbutton({disabled:(_18.pageNumber==_19)}); } if(bb.last){ bb.last.linkbutton({disabled:(_18.pageNumber==_19)}); } _1d(_15,_18.loading); }; function _1d(_1e,_1f){ var _20=$.data(_1e,"pagination"); var _21=_20.options; _21.loading=_1f; if(_21.showRefresh&&_20.bb.refresh){ _20.bb.refresh.linkbutton({iconCls:(_21.loading?"pagination-loading":"pagination-load")}); } }; $.fn.pagination=function(_22,_23){ if(typeof _22=="string"){ return $.fn.pagination.methods[_22](this,_23); } _22=_22||{}; return this.each(function(){ var _24; var _25=$.data(this,"pagination"); if(_25){ _24=$.extend(_25.options,_22); }else{ _24=$.extend({},$.fn.pagination.defaults,$.fn.pagination.parseOptions(this),_22); $.data(this,"pagination",{options:_24}); } _1(this); _14(this); }); }; $.fn.pagination.methods={options:function(jq){ return $.data(jq[0],"pagination").options; },loading:function(jq){ return jq.each(function(){ _1d(this,true); }); },loaded:function(jq){ return jq.each(function(){ _1d(this,false); }); },refresh:function(jq,_26){ return jq.each(function(){ _14(this,_26); }); },select:function(jq,_27){ return jq.each(function(){ _10(this,_27); }); }}; $.fn.pagination.parseOptions=function(_28){ var t=$(_28); return $.extend({},$.parser.parseOptions(_28,[{total:"number",pageSize:"number",pageNumber:"number",links:"number"},{loading:"boolean",showPageList:"boolean",showRefresh:"boolean"}]),{pageList:(t.attr("pageList")?eval(t.attr("pageList")):undefined)}); }; $.fn.pagination.defaults={total:1,pageSize:10,pageNumber:1,pageList:[10,20,30,50],loading:false,buttons:null,showPageList:true,showRefresh:true,links:10,layout:["list","sep","first","prev","sep","manual","sep","next","last","sep","refresh"],onSelectPage:function(_29,_2a){ },onBeforeRefresh:function(_2b,_2c){ },onRefresh:function(_2d,_2e){ },onChangePageSize:function(_2f){ },beforePageText:"Page",afterPageText:"of {pages}",displayMsg:"Displaying {from} to {to} of {total} items",nav:{first:{iconCls:"pagination-first",handler:function(){ var _30=$(this).pagination("options"); if(_30.pageNumber>1){ $(this).pagination("select",1); } }},prev:{iconCls:"pagination-prev",handler:function(){ var _31=$(this).pagination("options"); if(_31.pageNumber>1){ $(this).pagination("select",_31.pageNumber-1); } }},next:{iconCls:"pagination-next",handler:function(){ var _32=$(this).pagination("options"); var _33=Math.ceil(_32.total/_32.pageSize); if(_32.pageNumber<_33){ $(this).pagination("select",_32.pageNumber+1); } }},last:{iconCls:"pagination-last",handler:function(){ var _34=$(this).pagination("options"); var _35=Math.ceil(_34.total/_34.pageSize); if(_34.pageNumber<_35){ $(this).pagination("select",_35); } }},refresh:{iconCls:"pagination-refresh",handler:function(){ var _36=$(this).pagination("options"); if(_36.onBeforeRefresh.call(this,_36.pageNumber,_36.pageSize)!=false){ $(this).pagination("select",_36.pageNumber); _36.onRefresh.call(this,_36.pageNumber,_36.pageSize); } }}}}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"timespinner").options; $(_2).addClass("timespinner-f"); $(_2).spinner(_3); $(_2).unbind(".timespinner"); $(_2).bind("click.timespinner",function(){ var _4=0; if(this.selectionStart!=null){ _4=this.selectionStart; }else{ if(this.createTextRange){ var _5=_2.createTextRange(); var s=document.selection.createRange(); s.setEndPoint("StartToStart",_5); _4=s.text.length; } } if(_4>=0&&_4<=2){ _3.highlight=0; }else{ if(_4>=3&&_4<=5){ _3.highlight=1; }else{ if(_4>=6&&_4<=8){ _3.highlight=2; } } } _7(_2); }).bind("blur.timespinner",function(){ _6(_2); }); }; function _7(_8){ var _9=$.data(_8,"timespinner").options; var _a=0,_b=0; if(_9.highlight==0){ _a=0; _b=2; }else{ if(_9.highlight==1){ _a=3; _b=5; }else{ if(_9.highlight==2){ _a=6; _b=8; } } } if(_8.selectionStart!=null){ _8.setSelectionRange(_a,_b); }else{ if(_8.createTextRange){ var _c=_8.createTextRange(); _c.collapse(); _c.moveEnd("character",_b); _c.moveStart("character",_a); _c.select(); } } $(_8).focus(); }; function _d(_e,_f){ var _10=$.data(_e,"timespinner").options; if(!_f){ return null; } var vv=_f.split(_10.separator); for(var i=0;i<vv.length;i++){ if(isNaN(vv[i])){ return null; } } while(vv.length<3){ vv.push(0); } return new Date(1900,0,0,vv[0],vv[1],vv[2]); }; function _6(_11){ var _12=$.data(_11,"timespinner").options; var _13=$(_11).val(); var _14=_d(_11,_13); if(!_14){ _12.value=""; $(_11).val(""); return; } var _15=_d(_11,_12.min); var _16=_d(_11,_12.max); if(_15&&_15>_14){ _14=_15; } if(_16&&_16<_14){ _14=_16; } var tt=[_17(_14.getHours()),_17(_14.getMinutes())]; if(_12.showSeconds){ tt.push(_17(_14.getSeconds())); } var val=tt.join(_12.separator); _12.value=val; $(_11).val(val); function _17(_18){ return (_18<10?"0":"")+_18; }; }; function _19(_1a,_1b){ var _1c=$.data(_1a,"timespinner").options; var val=$(_1a).val(); if(val==""){ val=[0,0,0].join(_1c.separator); } var vv=val.split(_1c.separator); for(var i=0;i<vv.length;i++){ vv[i]=parseInt(vv[i],10); } if(_1b==true){ vv[_1c.highlight]-=_1c.increment; }else{ vv[_1c.highlight]+=_1c.increment; } $(_1a).val(vv.join(_1c.separator)); _6(_1a); _7(_1a); }; $.fn.timespinner=function(_1d,_1e){ if(typeof _1d=="string"){ var _1f=$.fn.timespinner.methods[_1d]; if(_1f){ return _1f(this,_1e); }else{ return this.spinner(_1d,_1e); } } _1d=_1d||{}; return this.each(function(){ var _20=$.data(this,"timespinner"); if(_20){ $.extend(_20.options,_1d); }else{ $.data(this,"timespinner",{options:$.extend({},$.fn.timespinner.defaults,$.fn.timespinner.parseOptions(this),_1d)}); _1(this); } }); }; $.fn.timespinner.methods={options:function(jq){ var _21=$.data(jq[0],"timespinner").options; return $.extend(_21,{value:jq.val(),originalValue:jq.spinner("options").originalValue}); },setValue:function(jq,_22){ return jq.each(function(){ $(this).val(_22); _6(this); }); },getHours:function(jq){ var _23=$.data(jq[0],"timespinner").options; var vv=jq.val().split(_23.separator); return parseInt(vv[0],10); },getMinutes:function(jq){ var _24=$.data(jq[0],"timespinner").options; var vv=jq.val().split(_24.separator); return parseInt(vv[1],10); },getSeconds:function(jq){ var _25=$.data(jq[0],"timespinner").options; var vv=jq.val().split(_25.separator); return parseInt(vv[2],10)||0; }}; $.fn.timespinner.parseOptions=function(_26){ return $.extend({},$.fn.spinner.parseOptions(_26),$.parser.parseOptions(_26,["separator",{showSeconds:"boolean",highlight:"number"}])); }; $.fn.timespinner.defaults=$.extend({},$.fn.spinner.defaults,{separator:":",showSeconds:false,highlight:0,spin:function(_27){ _19(this,_27); }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"treegrid"); var _4=_3.options; $(_2).datagrid($.extend({},_4,{url:null,data:null,loader:function(){ return false; },onBeforeLoad:function(){ return false; },onLoadSuccess:function(){ },onResizeColumn:function(_5,_6){ _20(_2); _4.onResizeColumn.call(_2,_5,_6); },onSortColumn:function(_7,_8){ _4.sortName=_7; _4.sortOrder=_8; if(_4.remoteSort){ _1f(_2); }else{ var _9=$(_2).treegrid("getData"); _39(_2,0,_9); } _4.onSortColumn.call(_2,_7,_8); },onBeforeEdit:function(_a,_b){ if(_4.onBeforeEdit.call(_2,_b)==false){ return false; } },onAfterEdit:function(_c,_d,_e){ _4.onAfterEdit.call(_2,_d,_e); },onCancelEdit:function(_f,row){ _4.onCancelEdit.call(_2,row); },onSelect:function(_10){ _4.onSelect.call(_2,_41(_2,_10)); },onUnselect:function(_11){ _4.onUnselect.call(_2,_41(_2,_11)); },onSelectAll:function(){ _4.onSelectAll.call(_2,$.data(_2,"treegrid").data); },onUnselectAll:function(){ _4.onUnselectAll.call(_2,$.data(_2,"treegrid").data); },onCheck:function(_12){ _4.onCheck.call(_2,_41(_2,_12)); },onUncheck:function(_13){ _4.onUncheck.call(_2,_41(_2,_13)); },onCheckAll:function(){ _4.onCheckAll.call(_2,$.data(_2,"treegrid").data); },onUncheckAll:function(){ _4.onUncheckAll.call(_2,$.data(_2,"treegrid").data); },onClickRow:function(_14){ _4.onClickRow.call(_2,_41(_2,_14)); },onDblClickRow:function(_15){ _4.onDblClickRow.call(_2,_41(_2,_15)); },onClickCell:function(_16,_17){ _4.onClickCell.call(_2,_17,_41(_2,_16)); },onDblClickCell:function(_18,_19){ _4.onDblClickCell.call(_2,_19,_41(_2,_18)); },onRowContextMenu:function(e,_1a){ _4.onContextMenu.call(_2,e,_41(_2,_1a)); }})); if(!_4.columns){ var _1b=$.data(_2,"datagrid").options; _4.columns=_1b.columns; _4.frozenColumns=_1b.frozenColumns; } _3.dc=$.data(_2,"datagrid").dc; if(_4.pagination){ var _1c=$(_2).datagrid("getPager"); _1c.pagination({pageNumber:_4.pageNumber,pageSize:_4.pageSize,pageList:_4.pageList,onSelectPage:function(_1d,_1e){ _4.pageNumber=_1d; _4.pageSize=_1e; _1f(_2); }}); _4.pageSize=_1c.pagination("options").pageSize; } }; function _20(_21,_22){ var _23=$.data(_21,"datagrid").options; var dc=$.data(_21,"datagrid").dc; if(!dc.body1.is(":empty")&&(!_23.nowrap||_23.autoRowHeight)){ if(_22!=undefined){ var _24=_25(_21,_22); for(var i=0;i<_24.length;i++){ _26(_24[i][_23.idField]); } } } $(_21).datagrid("fixRowHeight",_22); function _26(_27){ var tr1=_23.finder.getTr(_21,_27,"body",1); var tr2=_23.finder.getTr(_21,_27,"body",2); tr1.css("height",""); tr2.css("height",""); var _28=Math.max(tr1.height(),tr2.height()); tr1.css("height",_28); tr2.css("height",_28); }; }; function _29(_2a){ var dc=$.data(_2a,"datagrid").dc; var _2b=$.data(_2a,"treegrid").options; if(!_2b.rownumbers){ return; } dc.body1.find("div.datagrid-cell-rownumber").each(function(i){ $(this).html(i+1); }); }; function _2c(_2d){ var dc=$.data(_2d,"datagrid").dc; var _2e=dc.body1.add(dc.body2); var _2f=($.data(_2e[0],"events")||$._data(_2e[0],"events")).click[0].handler; dc.body1.add(dc.body2).bind("mouseover",function(e){ var tt=$(e.target); var tr=tt.closest("tr.datagrid-row"); if(!tr.length){ return; } if(tt.hasClass("tree-hit")){ tt.hasClass("tree-expanded")?tt.addClass("tree-expanded-hover"):tt.addClass("tree-collapsed-hover"); } e.stopPropagation(); }).bind("mouseout",function(e){ var tt=$(e.target); var tr=tt.closest("tr.datagrid-row"); if(!tr.length){ return; } if(tt.hasClass("tree-hit")){ tt.hasClass("tree-expanded")?tt.removeClass("tree-expanded-hover"):tt.removeClass("tree-collapsed-hover"); } e.stopPropagation(); }).unbind("click").bind("click",function(e){ var tt=$(e.target); var tr=tt.closest("tr.datagrid-row"); if(!tr.length){ return; } if(tt.hasClass("tree-hit")){ _30(_2d,tr.attr("node-id")); }else{ _2f(e); } e.stopPropagation(); }); }; function _31(_32,_33){ var _34=$.data(_32,"treegrid").options; var tr1=_34.finder.getTr(_32,_33,"body",1); var tr2=_34.finder.getTr(_32,_33,"body",2); var _35=$(_32).datagrid("getColumnFields",true).length+(_34.rownumbers?1:0); var _36=$(_32).datagrid("getColumnFields",false).length; _37(tr1,_35); _37(tr2,_36); function _37(tr,_38){ $("<tr class=\"treegrid-tr-tree\">"+"<td style=\"border:0px\" colspan=\""+_38+"\">"+"<div></div>"+"</td>"+"</tr>").insertAfter(tr); }; }; function _39(_3a,_3b,_3c,_3d){ var _3e=$.data(_3a,"treegrid"); var _3f=_3e.options; var dc=_3e.dc; _3c=_3f.loadFilter.call(_3a,_3c,_3b); var _40=_41(_3a,_3b); if(_40){ var _42=_3f.finder.getTr(_3a,_3b,"body",1); var _43=_3f.finder.getTr(_3a,_3b,"body",2); var cc1=_42.next("tr.treegrid-tr-tree").children("td").children("div"); var cc2=_43.next("tr.treegrid-tr-tree").children("td").children("div"); if(!_3d){ _40.children=[]; } }else{ var cc1=dc.body1; var cc2=dc.body2; if(!_3d){ _3e.data=[]; } } if(!_3d){ cc1.empty(); cc2.empty(); } if(_3f.view.onBeforeRender){ _3f.view.onBeforeRender.call(_3f.view,_3a,_3b,_3c); } _3f.view.render.call(_3f.view,_3a,cc1,true); _3f.view.render.call(_3f.view,_3a,cc2,false); if(_3f.showFooter){ _3f.view.renderFooter.call(_3f.view,_3a,dc.footer1,true); _3f.view.renderFooter.call(_3f.view,_3a,dc.footer2,false); } if(_3f.view.onAfterRender){ _3f.view.onAfterRender.call(_3f.view,_3a); } _3f.onLoadSuccess.call(_3a,_40,_3c); if(!_3b&&_3f.pagination){ var _44=$.data(_3a,"treegrid").total; var _45=$(_3a).datagrid("getPager"); if(_45.pagination("options").total!=_44){ _45.pagination({total:_44}); } } _20(_3a); _29(_3a); $(_3a).treegrid("autoSizeColumn"); }; function _1f(_46,_47,_48,_49,_4a){ var _4b=$.data(_46,"treegrid").options; var _4c=$(_46).datagrid("getPanel").find("div.datagrid-body"); if(_48){ _4b.queryParams=_48; } var _4d=$.extend({},_4b.queryParams); if(_4b.pagination){ $.extend(_4d,{page:_4b.pageNumber,rows:_4b.pageSize}); } if(_4b.sortName){ $.extend(_4d,{sort:_4b.sortName,order:_4b.sortOrder}); } var row=_41(_46,_47); if(_4b.onBeforeLoad.call(_46,row,_4d)==false){ return; } var _4e=_4c.find("tr[node-id=\""+_47+"\"] span.tree-folder"); _4e.addClass("tree-loading"); $(_46).treegrid("loading"); var _4f=_4b.loader.call(_46,_4d,function(_50){ _4e.removeClass("tree-loading"); $(_46).treegrid("loaded"); _39(_46,_47,_50,_49); if(_4a){ _4a(); } },function(){ _4e.removeClass("tree-loading"); $(_46).treegrid("loaded"); _4b.onLoadError.apply(_46,arguments); if(_4a){ _4a(); } }); if(_4f==false){ _4e.removeClass("tree-loading"); $(_46).treegrid("loaded"); } }; function _51(_52){ var _53=_54(_52); if(_53.length){ return _53[0]; }else{ return null; } }; function _54(_55){ return $.data(_55,"treegrid").data; }; function _56(_57,_58){ var row=_41(_57,_58); if(row._parentId){ return _41(_57,row._parentId); }else{ return null; } }; function _25(_59,_5a){ var _5b=$.data(_59,"treegrid").options; var _5c=$(_59).datagrid("getPanel").find("div.datagrid-view2 div.datagrid-body"); var _5d=[]; if(_5a){ _5e(_5a); }else{ var _5f=_54(_59); for(var i=0;i<_5f.length;i++){ _5d.push(_5f[i]); _5e(_5f[i][_5b.idField]); } } function _5e(_60){ var _61=_41(_59,_60); if(_61&&_61.children){ for(var i=0,len=_61.children.length;i<len;i++){ var _62=_61.children[i]; _5d.push(_62); _5e(_62[_5b.idField]); } } }; return _5d; }; function _63(_64){ var _65=_66(_64); if(_65.length){ return _65[0]; }else{ return null; } }; function _66(_67){ var _68=[]; var _69=$(_67).datagrid("getPanel"); _69.find("div.datagrid-view2 div.datagrid-body tr.datagrid-row-selected").each(function(){ var id=$(this).attr("node-id"); _68.push(_41(_67,id)); }); return _68; }; function _6a(_6b,_6c){ if(!_6c){ return 0; } var _6d=$.data(_6b,"treegrid").options; var _6e=$(_6b).datagrid("getPanel").children("div.datagrid-view"); var _6f=_6e.find("div.datagrid-body tr[node-id=\""+_6c+"\"]").children("td[field=\""+_6d.treeField+"\"]"); return _6f.find("span.tree-indent,span.tree-hit").length; }; function _41(_70,_71){ var _72=$.data(_70,"treegrid").options; var _73=$.data(_70,"treegrid").data; var cc=[_73]; while(cc.length){ var c=cc.shift(); for(var i=0;i<c.length;i++){ var _74=c[i]; if(_74[_72.idField]==_71){ return _74; }else{ if(_74["children"]){ cc.push(_74["children"]); } } } } return null; }; function _75(_76,_77){ var _78=$.data(_76,"treegrid").options; var row=_41(_76,_77); var tr=_78.finder.getTr(_76,_77); var hit=tr.find("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-collapsed")){ return; } if(_78.onBeforeCollapse.call(_76,row)==false){ return; } hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); hit.next().removeClass("tree-folder-open"); row.state="closed"; tr=tr.next("tr.treegrid-tr-tree"); var cc=tr.children("td").children("div"); if(_78.animate){ cc.slideUp("normal",function(){ $(_76).treegrid("autoSizeColumn"); _20(_76,_77); _78.onCollapse.call(_76,row); }); }else{ cc.hide(); $(_76).treegrid("autoSizeColumn"); _20(_76,_77); _78.onCollapse.call(_76,row); } }; function _79(_7a,_7b){ var _7c=$.data(_7a,"treegrid").options; var tr=_7c.finder.getTr(_7a,_7b); var hit=tr.find("span.tree-hit"); var row=_41(_7a,_7b); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ return; } if(_7c.onBeforeExpand.call(_7a,row)==false){ return; } hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded"); hit.next().addClass("tree-folder-open"); var _7d=tr.next("tr.treegrid-tr-tree"); if(_7d.length){ var cc=_7d.children("td").children("div"); _7e(cc); }else{ _31(_7a,row[_7c.idField]); var _7d=tr.next("tr.treegrid-tr-tree"); var cc=_7d.children("td").children("div"); cc.hide(); var _7f=$.extend({},_7c.queryParams||{}); _7f.id=row[_7c.idField]; _1f(_7a,row[_7c.idField],_7f,true,function(){ if(cc.is(":empty")){ _7d.remove(); }else{ _7e(cc); } }); } function _7e(cc){ row.state="open"; if(_7c.animate){ cc.slideDown("normal",function(){ $(_7a).treegrid("autoSizeColumn"); _20(_7a,_7b); _7c.onExpand.call(_7a,row); }); }else{ cc.show(); $(_7a).treegrid("autoSizeColumn"); _20(_7a,_7b); _7c.onExpand.call(_7a,row); } }; }; function _30(_80,_81){ var _82=$.data(_80,"treegrid").options; var tr=_82.finder.getTr(_80,_81); var hit=tr.find("span.tree-hit"); if(hit.hasClass("tree-expanded")){ _75(_80,_81); }else{ _79(_80,_81); } }; function _83(_84,_85){ var _86=$.data(_84,"treegrid").options; var _87=_25(_84,_85); if(_85){ _87.unshift(_41(_84,_85)); } for(var i=0;i<_87.length;i++){ _75(_84,_87[i][_86.idField]); } }; function _88(_89,_8a){ var _8b=$.data(_89,"treegrid").options; var _8c=_25(_89,_8a); if(_8a){ _8c.unshift(_41(_89,_8a)); } for(var i=0;i<_8c.length;i++){ _79(_89,_8c[i][_8b.idField]); } }; function _8d(_8e,_8f){ var _90=$.data(_8e,"treegrid").options; var ids=[]; var p=_56(_8e,_8f); while(p){ var id=p[_90.idField]; ids.unshift(id); p=_56(_8e,id); } for(var i=0;i<ids.length;i++){ _79(_8e,ids[i]); } }; function _91(_92,_93){ var _94=$.data(_92,"treegrid").options; if(_93.parent){ var tr=_94.finder.getTr(_92,_93.parent); if(tr.next("tr.treegrid-tr-tree").length==0){ _31(_92,_93.parent); } var _95=tr.children("td[field=\""+_94.treeField+"\"]").children("div.datagrid-cell"); var _96=_95.children("span.tree-icon"); if(_96.hasClass("tree-file")){ _96.removeClass("tree-file").addClass("tree-folder tree-folder-open"); var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_96); if(hit.prev().length){ hit.prev().remove(); } } } _39(_92,_93.parent,_93.data,true); }; function _97(_98,_99){ var ref=_99.before||_99.after; var _9a=$.data(_98,"treegrid").options; var _9b=_56(_98,ref); _91(_98,{parent:(_9b?_9b[_9a.idField]:null),data:[_99.data]}); _9c(true); _9c(false); _29(_98); function _9c(_9d){ var _9e=_9d?1:2; var tr=_9a.finder.getTr(_98,_99.data[_9a.idField],"body",_9e); var _9f=tr.closest("table.datagrid-btable"); tr=tr.parent().children(); var _a0=_9a.finder.getTr(_98,ref,"body",_9e); if(_99.before){ tr.insertBefore(_a0); }else{ var sub=_a0.next("tr.treegrid-tr-tree"); tr.insertAfter(sub.length?sub:_a0); } _9f.remove(); }; }; function _a1(_a2,_a3){ var _a4=$.data(_a2,"treegrid").options; var tr=_a4.finder.getTr(_a2,_a3); tr.next("tr.treegrid-tr-tree").remove(); tr.remove(); var _a5=del(_a3); if(_a5){ if(_a5.children.length==0){ tr=_a4.finder.getTr(_a2,_a5[_a4.idField]); tr.next("tr.treegrid-tr-tree").remove(); var _a6=tr.children("td[field=\""+_a4.treeField+"\"]").children("div.datagrid-cell"); _a6.find(".tree-icon").removeClass("tree-folder").addClass("tree-file"); _a6.find(".tree-hit").remove(); $("<span class=\"tree-indent\"></span>").prependTo(_a6); } } _29(_a2); function del(id){ var cc; var _a7=_56(_a2,_a3); if(_a7){ cc=_a7.children; }else{ cc=$(_a2).treegrid("getData"); } for(var i=0;i<cc.length;i++){ if(cc[i][_a4.idField]==id){ cc.splice(i,1); break; } } return _a7; }; }; $.fn.treegrid=function(_a8,_a9){ if(typeof _a8=="string"){ var _aa=$.fn.treegrid.methods[_a8]; if(_aa){ return _aa(this,_a9); }else{ return this.datagrid(_a8,_a9); } } _a8=_a8||{}; return this.each(function(){ var _ab=$.data(this,"treegrid"); if(_ab){ $.extend(_ab.options,_a8); }else{ _ab=$.data(this,"treegrid",{options:$.extend({},$.fn.treegrid.defaults,$.fn.treegrid.parseOptions(this),_a8),data:[]}); } _1(this); if(_ab.options.data){ $(this).treegrid("loadData",_ab.options.data); } _1f(this); _2c(this); }); }; $.fn.treegrid.methods={options:function(jq){ return $.data(jq[0],"treegrid").options; },resize:function(jq,_ac){ return jq.each(function(){ $(this).datagrid("resize",_ac); }); },fixRowHeight:function(jq,_ad){ return jq.each(function(){ _20(this,_ad); }); },loadData:function(jq,_ae){ return jq.each(function(){ _39(this,_ae.parent,_ae); }); },load:function(jq,_af){ return jq.each(function(){ $(this).treegrid("options").pageNumber=1; $(this).treegrid("getPager").pagination({pageNumber:1}); $(this).treegrid("reload",_af); }); },reload:function(jq,id){ return jq.each(function(){ var _b0=$(this).treegrid("options"); var _b1={}; if(typeof id=="object"){ _b1=id; }else{ _b1=$.extend({},_b0.queryParams); _b1.id=id; } if(_b1.id){ var _b2=$(this).treegrid("find",_b1.id); if(_b2.children){ _b2.children.splice(0,_b2.children.length); } _b0.queryParams=_b1; var tr=_b0.finder.getTr(this,_b1.id); tr.next("tr.treegrid-tr-tree").remove(); tr.find("span.tree-hit").removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); _79(this,_b1.id); }else{ _1f(this,null,_b1); } }); },reloadFooter:function(jq,_b3){ return jq.each(function(){ var _b4=$.data(this,"treegrid").options; var dc=$.data(this,"datagrid").dc; if(_b3){ $.data(this,"treegrid").footer=_b3; } if(_b4.showFooter){ _b4.view.renderFooter.call(_b4.view,this,dc.footer1,true); _b4.view.renderFooter.call(_b4.view,this,dc.footer2,false); if(_b4.view.onAfterRender){ _b4.view.onAfterRender.call(_b4.view,this); } $(this).treegrid("fixRowHeight"); } }); },getData:function(jq){ return $.data(jq[0],"treegrid").data; },getFooterRows:function(jq){ return $.data(jq[0],"treegrid").footer; },getRoot:function(jq){ return _51(jq[0]); },getRoots:function(jq){ return _54(jq[0]); },getParent:function(jq,id){ return _56(jq[0],id); },getChildren:function(jq,id){ return _25(jq[0],id); },getSelected:function(jq){ return _63(jq[0]); },getSelections:function(jq){ return _66(jq[0]); },getLevel:function(jq,id){ return _6a(jq[0],id); },find:function(jq,id){ return _41(jq[0],id); },isLeaf:function(jq,id){ var _b5=$.data(jq[0],"treegrid").options; var tr=_b5.finder.getTr(jq[0],id); var hit=tr.find("span.tree-hit"); return hit.length==0; },select:function(jq,id){ return jq.each(function(){ $(this).datagrid("selectRow",id); }); },unselect:function(jq,id){ return jq.each(function(){ $(this).datagrid("unselectRow",id); }); },collapse:function(jq,id){ return jq.each(function(){ _75(this,id); }); },expand:function(jq,id){ return jq.each(function(){ _79(this,id); }); },toggle:function(jq,id){ return jq.each(function(){ _30(this,id); }); },collapseAll:function(jq,id){ return jq.each(function(){ _83(this,id); }); },expandAll:function(jq,id){ return jq.each(function(){ _88(this,id); }); },expandTo:function(jq,id){ return jq.each(function(){ _8d(this,id); }); },append:function(jq,_b6){ return jq.each(function(){ _91(this,_b6); }); },insert:function(jq,_b7){ return jq.each(function(){ _97(this,_b7); }); },remove:function(jq,id){ return jq.each(function(){ _a1(this,id); }); },pop:function(jq,id){ var row=jq.treegrid("find",id); jq.treegrid("remove",id); return row; },refresh:function(jq,id){ return jq.each(function(){ var _b8=$.data(this,"treegrid").options; _b8.view.refreshRow.call(_b8.view,this,id); }); },update:function(jq,_b9){ return jq.each(function(){ var _ba=$.data(this,"treegrid").options; _ba.view.updateRow.call(_ba.view,this,_b9.id,_b9.row); }); },beginEdit:function(jq,id){ return jq.each(function(){ $(this).datagrid("beginEdit",id); $(this).treegrid("fixRowHeight",id); }); },endEdit:function(jq,id){ return jq.each(function(){ $(this).datagrid("endEdit",id); }); },cancelEdit:function(jq,id){ return jq.each(function(){ $(this).datagrid("cancelEdit",id); }); }}; $.fn.treegrid.parseOptions=function(_bb){ return $.extend({},$.fn.datagrid.parseOptions(_bb),$.parser.parseOptions(_bb,["treeField",{animate:"boolean"}])); }; var _bc=$.extend({},$.fn.datagrid.defaults.view,{render:function(_bd,_be,_bf){ var _c0=$.data(_bd,"treegrid").options; var _c1=$(_bd).datagrid("getColumnFields",_bf); var _c2=$.data(_bd,"datagrid").rowIdPrefix; if(_bf){ if(!(_c0.rownumbers||(_c0.frozenColumns&&_c0.frozenColumns.length))){ return; } } var _c3=0; var _c4=this; var _c5=_c6(_bf,this.treeLevel,this.treeNodes); $(_be).append(_c5.join("")); function _c6(_c7,_c8,_c9){ var _ca=["<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<_c9.length;i++){ var row=_c9[i]; if(row.state!="open"&&row.state!="closed"){ row.state="open"; } var css=_c0.rowStyler?_c0.rowStyler.call(_bd,row):""; var _cb=""; var _cc=""; if(typeof css=="string"){ _cc=css; }else{ if(css){ _cb=css["class"]||""; _cc=css["style"]||""; } } var cls="class=\"datagrid-row "+(_c3++%2&&_c0.striped?"datagrid-row-alt ":" ")+_cb+"\""; var _cd=_cc?"style=\""+_cc+"\"":""; var _ce=_c2+"-"+(_c7?1:2)+"-"+row[_c0.idField]; _ca.push("<tr id=\""+_ce+"\" node-id=\""+row[_c0.idField]+"\" "+cls+" "+_cd+">"); _ca=_ca.concat(_c4.renderRow.call(_c4,_bd,_c1,_c7,_c8,row)); _ca.push("</tr>"); if(row.children&&row.children.length){ var tt=_c6(_c7,_c8+1,row.children); var v=row.state=="closed"?"none":"block"; _ca.push("<tr class=\"treegrid-tr-tree\"><td style=\"border:0px\" colspan="+(_c1.length+(_c0.rownumbers?1:0))+"><div style=\"display:"+v+"\">"); _ca=_ca.concat(tt); _ca.push("</div></td></tr>"); } } _ca.push("</tbody></table>"); return _ca; }; },renderFooter:function(_cf,_d0,_d1){ var _d2=$.data(_cf,"treegrid").options; var _d3=$.data(_cf,"treegrid").footer||[]; var _d4=$(_cf).datagrid("getColumnFields",_d1); var _d5=["<table class=\"datagrid-ftable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<_d3.length;i++){ var row=_d3[i]; row[_d2.idField]=row[_d2.idField]||("foot-row-id"+i); _d5.push("<tr class=\"datagrid-row\" node-id=\""+row[_d2.idField]+"\">"); _d5.push(this.renderRow.call(this,_cf,_d4,_d1,0,row)); _d5.push("</tr>"); } _d5.push("</tbody></table>"); $(_d0).html(_d5.join("")); },renderRow:function(_d6,_d7,_d8,_d9,row){ var _da=$.data(_d6,"treegrid").options; var cc=[]; if(_d8&&_da.rownumbers){ cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">0</div></td>"); } for(var i=0;i<_d7.length;i++){ var _db=_d7[i]; var col=$(_d6).datagrid("getColumnOption",_db); if(col){ var css=col.styler?(col.styler(row[_db],row)||""):""; var _dc=""; var _dd=""; if(typeof css=="string"){ _dd=css; }else{ if(cc){ _dc=css["class"]||""; _dd=css["style"]||""; } } var cls=_dc?"class=\""+_dc+"\"":""; var _de=col.hidden?"style=\"display:none;"+_dd+"\"":(_dd?"style=\""+_dd+"\"":""); cc.push("<td field=\""+_db+"\" "+cls+" "+_de+">"); if(col.checkbox){ var _de=""; }else{ var _de=_dd; if(col.align){ _de+=";text-align:"+col.align+";"; } if(!_da.nowrap){ _de+=";white-space:normal;height:auto;"; }else{ if(_da.autoRowHeight){ _de+=";height:auto;"; } } } cc.push("<div style=\""+_de+"\" "); if(col.checkbox){ cc.push("class=\"datagrid-cell-check "); }else{ cc.push("class=\"datagrid-cell "+col.cellClass); } cc.push("\">"); if(col.checkbox){ if(row.checked){ cc.push("<input type=\"checkbox\" checked=\"checked\""); }else{ cc.push("<input type=\"checkbox\""); } cc.push(" name=\""+_db+"\" value=\""+(row[_db]!=undefined?row[_db]:"")+"\"/>"); }else{ var val=null; if(col.formatter){ val=col.formatter(row[_db],row); }else{ val=row[_db]; } if(_db==_da.treeField){ for(var j=0;j<_d9;j++){ cc.push("<span class=\"tree-indent\"></span>"); } if(row.state=="closed"){ cc.push("<span class=\"tree-hit tree-collapsed\"></span>"); cc.push("<span class=\"tree-icon tree-folder "+(row.iconCls?row.iconCls:"")+"\"></span>"); }else{ if(row.children&&row.children.length){ cc.push("<span class=\"tree-hit tree-expanded\"></span>"); cc.push("<span class=\"tree-icon tree-folder tree-folder-open "+(row.iconCls?row.iconCls:"")+"\"></span>"); }else{ cc.push("<span class=\"tree-indent\"></span>"); cc.push("<span class=\"tree-icon tree-file "+(row.iconCls?row.iconCls:"")+"\"></span>"); } } cc.push("<span class=\"tree-title\">"+val+"</span>"); }else{ cc.push(val); } } cc.push("</div>"); cc.push("</td>"); } } return cc.join(""); },refreshRow:function(_df,id){ this.updateRow.call(this,_df,id,{}); },updateRow:function(_e0,id,row){ var _e1=$.data(_e0,"treegrid").options; var _e2=$(_e0).treegrid("find",id); $.extend(_e2,row); var _e3=$(_e0).treegrid("getLevel",id)-1; var _e4=_e1.rowStyler?_e1.rowStyler.call(_e0,_e2):""; function _e5(_e6){ var _e7=$(_e0).treegrid("getColumnFields",_e6); var tr=_e1.finder.getTr(_e0,id,"body",(_e6?1:2)); var _e8=tr.find("div.datagrid-cell-rownumber").html(); var _e9=tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked"); tr.html(this.renderRow(_e0,_e7,_e6,_e3,_e2)); tr.attr("style",_e4||""); tr.find("div.datagrid-cell-rownumber").html(_e8); if(_e9){ tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true); } }; _e5.call(this,true); _e5.call(this,false); $(_e0).treegrid("fixRowHeight",id); },onBeforeRender:function(_ea,_eb,_ec){ if($.isArray(_eb)){ _ec={total:_eb.length,rows:_eb}; _eb=null; } if(!_ec){ return false; } var _ed=$.data(_ea,"treegrid"); var _ee=_ed.options; if(_ec.length==undefined){ if(_ec.footer){ _ed.footer=_ec.footer; } if(_ec.total){ _ed.total=_ec.total; } _ec=this.transfer(_ea,_eb,_ec.rows); }else{ function _ef(_f0,_f1){ for(var i=0;i<_f0.length;i++){ var row=_f0[i]; row._parentId=_f1; if(row.children&&row.children.length){ _ef(row.children,row[_ee.idField]); } } }; _ef(_ec,_eb); } var _f2=_41(_ea,_eb); if(_f2){ if(_f2.children){ _f2.children=_f2.children.concat(_ec); }else{ _f2.children=_ec; } }else{ _ed.data=_ed.data.concat(_ec); } this.sort(_ea,_ec); this.treeNodes=_ec; this.treeLevel=$(_ea).treegrid("getLevel",_eb); },sort:function(_f3,_f4){ var _f5=$.data(_f3,"treegrid").options; if(!_f5.remoteSort&&_f5.sortName){ var _f6=_f5.sortName.split(","); var _f7=_f5.sortOrder.split(","); _f8(_f4); } function _f8(_f9){ _f9.sort(function(r1,r2){ var r=0; for(var i=0;i<_f6.length;i++){ var sn=_f6[i]; var so=_f7[i]; var col=$(_f3).treegrid("getColumnOption",sn); var _fa=col.sorter||function(a,b){ return a==b?0:(a>b?1:-1); }; r=_fa(r1[sn],r2[sn])*(so=="asc"?1:-1); if(r!=0){ return r; } } return r; }); for(var i=0;i<_f9.length;i++){ var _fb=_f9[i].children; if(_fb&&_fb.length){ _f8(_fb); } } }; },transfer:function(_fc,_fd,_fe){ var _ff=$.data(_fc,"treegrid").options; var rows=[]; for(var i=0;i<_fe.length;i++){ rows.push(_fe[i]); } var _100=[]; for(var i=0;i<rows.length;i++){ var row=rows[i]; if(!_fd){ if(!row._parentId){ _100.push(row); rows.splice(i,1); i--; } }else{ if(row._parentId==_fd){ _100.push(row); rows.splice(i,1); i--; } } } var toDo=[]; for(var i=0;i<_100.length;i++){ toDo.push(_100[i]); } while(toDo.length){ var node=toDo.shift(); for(var i=0;i<rows.length;i++){ var row=rows[i]; if(row._parentId==node[_ff.idField]){ if(node.children){ node.children.push(row); }else{ node.children=[row]; } toDo.push(row); rows.splice(i,1); i--; } } } return _100; }}); $.fn.treegrid.defaults=$.extend({},$.fn.datagrid.defaults,{treeField:null,animate:false,singleSelect:true,view:_bc,loader:function(_101,_102,_103){ var opts=$(this).treegrid("options"); if(!opts.url){ return false; } $.ajax({type:opts.method,url:opts.url,data:_101,dataType:"json",success:function(data){ _102(data); },error:function(){ _103.apply(this,arguments); }}); },loadFilter:function(data,_104){ return data; },finder:{getTr:function(_105,id,type,_106){ type=type||"body"; _106=_106||0; var dc=$.data(_105,"datagrid").dc; if(_106==0){ var opts=$.data(_105,"treegrid").options; var tr1=opts.finder.getTr(_105,id,type,1); var tr2=opts.finder.getTr(_105,id,type,2); return tr1.add(tr2); }else{ if(type=="body"){ var tr=$("#"+$.data(_105,"datagrid").rowIdPrefix+"-"+_106+"-"+id); if(!tr.length){ tr=(_106==1?dc.body1:dc.body2).find("tr[node-id=\""+id+"\"]"); } return tr; }else{ if(type=="footer"){ return (_106==1?dc.footer1:dc.footer2).find("tr[node-id=\""+id+"\"]"); }else{ if(type=="selected"){ return (_106==1?dc.body1:dc.body2).find("tr.datagrid-row-selected"); }else{ if(type=="highlight"){ return (_106==1?dc.body1:dc.body2).find("tr.datagrid-row-over"); }else{ if(type=="checked"){ return (_106==1?dc.body1:dc.body2).find("tr.datagrid-row-checked"); }else{ if(type=="last"){ return (_106==1?dc.body1:dc.body2).find("tr:last[node-id]"); }else{ if(type=="allbody"){ return (_106==1?dc.body1:dc.body2).find("tr[node-id]"); }else{ if(type=="allfooter"){ return (_106==1?dc.footer1:dc.footer2).find("tr[node-id]"); } } } } } } } } } },getRow:function(_107,p){ var id=(typeof p=="object")?p.attr("node-id"):p; return $(_107).treegrid("find",id); }},onBeforeLoad:function(row,_108){ },onLoadSuccess:function(row,data){ },onLoadError:function(){ },onBeforeCollapse:function(row){ },onCollapse:function(row){ },onBeforeExpand:function(row){ },onExpand:function(row){ },onClickRow:function(row){ },onDblClickRow:function(row){ },onClickCell:function(_109,row){ },onDblClickCell:function(_10a,row){ },onContextMenu:function(e,row){ },onBeforeEdit:function(row){ },onAfterEdit:function(row,_10b){ },onCancelEdit:function(row){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"combogrid"); var _4=_3.options; var _5=_3.grid; $(_2).addClass("combogrid-f").combo(_4); var _6=$(_2).combo("panel"); if(!_5){ _5=$("<table></table>").appendTo(_6); _3.grid=_5; } _5.datagrid($.extend({},_4,{border:false,fit:true,singleSelect:(!_4.multiple),onLoadSuccess:function(_7){ var _8=$(_2).combo("getValues"); var _9=_4.onSelect; _4.onSelect=function(){ }; _1a(_2,_8,_3.remainText); _4.onSelect=_9; _4.onLoadSuccess.apply(_2,arguments); },onClickRow:_a,onSelect:function(_b,_c){ _d(); _4.onSelect.call(this,_b,_c); },onUnselect:function(_e,_f){ _d(); _4.onUnselect.call(this,_e,_f); },onSelectAll:function(_10){ _d(); _4.onSelectAll.call(this,_10); },onUnselectAll:function(_11){ if(_4.multiple){ _d(); } _4.onUnselectAll.call(this,_11); }})); function _a(_12,row){ _3.remainText=false; _d(); if(!_4.multiple){ $(_2).combo("hidePanel"); } _4.onClickRow.call(this,_12,row); }; function _d(){ var _13=_5.datagrid("getSelections"); var vv=[],ss=[]; for(var i=0;i<_13.length;i++){ vv.push(_13[i][_4.idField]); ss.push(_13[i][_4.textField]); } if(!_4.multiple){ $(_2).combo("setValues",(vv.length?vv:[""])); }else{ $(_2).combo("setValues",vv); } if(!_3.remainText){ $(_2).combo("setText",ss.join(_4.separator)); } }; }; function nav(_14,dir){ var _15=$.data(_14,"combogrid"); var _16=_15.options; var _17=_15.grid; var _18=_17.datagrid("getRows").length; if(!_18){ return; } var tr=_16.finder.getTr(_17[0],null,"highlight"); if(!tr.length){ tr=_16.finder.getTr(_17[0],null,"selected"); } var _19; if(!tr.length){ _19=(dir=="next"?0:_18-1); }else{ var _19=parseInt(tr.attr("datagrid-row-index")); _19+=(dir=="next"?1:-1); if(_19<0){ _19=_18-1; } if(_19>=_18){ _19=0; } } _17.datagrid("highlightRow",_19); if(_16.selectOnNavigation){ _15.remainText=false; _17.datagrid("selectRow",_19); } }; function _1a(_1b,_1c,_1d){ var _1e=$.data(_1b,"combogrid"); var _1f=_1e.options; var _20=_1e.grid; var _21=_20.datagrid("getRows"); var ss=[]; var _22=$(_1b).combo("getValues"); var _23=$(_1b).combo("options"); var _24=_23.onChange; _23.onChange=function(){ }; _20.datagrid("clearSelections"); for(var i=0;i<_1c.length;i++){ var _25=_20.datagrid("getRowIndex",_1c[i]); if(_25>=0){ _20.datagrid("selectRow",_25); ss.push(_21[_25][_1f.textField]); }else{ ss.push(_1c[i]); } } $(_1b).combo("setValues",_22); _23.onChange=_24; $(_1b).combo("setValues",_1c); if(!_1d){ var s=ss.join(_1f.separator); if($(_1b).combo("getText")!=s){ $(_1b).combo("setText",s); } } }; function _26(_27,q){ var _28=$.data(_27,"combogrid"); var _29=_28.options; var _2a=_28.grid; _28.remainText=true; if(_29.multiple&&!q){ _1a(_27,[],true); }else{ _1a(_27,[q],true); } if(_29.mode=="remote"){ _2a.datagrid("clearSelections"); _2a.datagrid("load",$.extend({},_29.queryParams,{q:q})); }else{ if(!q){ return; } var _2b=_2a.datagrid("getRows"); for(var i=0;i<_2b.length;i++){ if(_29.filter.call(_27,q,_2b[i])){ _2a.datagrid("clearSelections"); _2a.datagrid("selectRow",i); return; } } } }; function _2c(_2d){ var _2e=$.data(_2d,"combogrid"); var _2f=_2e.options; var _30=_2e.grid; var tr=_2f.finder.getTr(_30[0],null,"highlight"); if(!tr.length){ tr=_2f.finder.getTr(_30[0],null,"selected"); } if(!tr.length){ return; } _2e.remainText=false; var _31=parseInt(tr.attr("datagrid-row-index")); if(_2f.multiple){ if(tr.hasClass("datagrid-row-selected")){ _30.datagrid("unselectRow",_31); }else{ _30.datagrid("selectRow",_31); } }else{ _30.datagrid("selectRow",_31); $(_2d).combogrid("hidePanel"); } }; $.fn.combogrid=function(_32,_33){ if(typeof _32=="string"){ var _34=$.fn.combogrid.methods[_32]; if(_34){ return _34(this,_33); }else{ return this.combo(_32,_33); } } _32=_32||{}; return this.each(function(){ var _35=$.data(this,"combogrid"); if(_35){ $.extend(_35.options,_32); }else{ _35=$.data(this,"combogrid",{options:$.extend({},$.fn.combogrid.defaults,$.fn.combogrid.parseOptions(this),_32)}); } _1(this); }); }; $.fn.combogrid.methods={options:function(jq){ var _36=jq.combo("options"); return $.extend($.data(jq[0],"combogrid").options,{originalValue:_36.originalValue,disabled:_36.disabled,readonly:_36.readonly}); },grid:function(jq){ return $.data(jq[0],"combogrid").grid; },setValues:function(jq,_37){ return jq.each(function(){ _1a(this,_37); }); },setValue:function(jq,_38){ return jq.each(function(){ _1a(this,[_38]); }); },clear:function(jq){ return jq.each(function(){ $(this).combogrid("grid").datagrid("clearSelections"); $(this).combo("clear"); }); },reset:function(jq){ return jq.each(function(){ var _39=$(this).combogrid("options"); if(_39.multiple){ $(this).combogrid("setValues",_39.originalValue); }else{ $(this).combogrid("setValue",_39.originalValue); } }); }}; $.fn.combogrid.parseOptions=function(_3a){ var t=$(_3a); return $.extend({},$.fn.combo.parseOptions(_3a),$.fn.datagrid.parseOptions(_3a),$.parser.parseOptions(_3a,["idField","textField","mode"])); }; $.fn.combogrid.defaults=$.extend({},$.fn.combo.defaults,$.fn.datagrid.defaults,{loadMsg:null,idField:null,textField:null,mode:"local",keyHandler:{up:function(e){ nav(this,"prev"); e.preventDefault(); },down:function(e){ nav(this,"next"); e.preventDefault(); },left:function(e){ },right:function(e){ },enter:function(e){ _2c(this); },query:function(q,e){ _26(this,q); }},filter:function(q,row){ var _3b=$(this).combogrid("options"); return row[_3b.textField].indexOf(q)==0; }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$(_2); _3.addClass("tree"); return _3; }; function _4(_5){ var _6=$.data(_5,"tree").options; $(_5).unbind().bind("mouseover",function(e){ var tt=$(e.target); var _7=tt.closest("div.tree-node"); if(!_7.length){ return; } _7.addClass("tree-node-hover"); if(tt.hasClass("tree-hit")){ if(tt.hasClass("tree-expanded")){ tt.addClass("tree-expanded-hover"); }else{ tt.addClass("tree-collapsed-hover"); } } e.stopPropagation(); }).bind("mouseout",function(e){ var tt=$(e.target); var _8=tt.closest("div.tree-node"); if(!_8.length){ return; } _8.removeClass("tree-node-hover"); if(tt.hasClass("tree-hit")){ if(tt.hasClass("tree-expanded")){ tt.removeClass("tree-expanded-hover"); }else{ tt.removeClass("tree-collapsed-hover"); } } e.stopPropagation(); }).bind("click",function(e){ var tt=$(e.target); var _9=tt.closest("div.tree-node"); if(!_9.length){ return; } if(tt.hasClass("tree-hit")){ _7e(_5,_9[0]); return false; }else{ if(tt.hasClass("tree-checkbox")){ _32(_5,_9[0],!tt.hasClass("tree-checkbox1")); return false; }else{ _d6(_5,_9[0]); _6.onClick.call(_5,_c(_5,_9[0])); } } e.stopPropagation(); }).bind("dblclick",function(e){ var _a=$(e.target).closest("div.tree-node"); if(!_a.length){ return; } _d6(_5,_a[0]); _6.onDblClick.call(_5,_c(_5,_a[0])); e.stopPropagation(); }).bind("contextmenu",function(e){ var _b=$(e.target).closest("div.tree-node"); if(!_b.length){ return; } _6.onContextMenu.call(_5,e,_c(_5,_b[0])); e.stopPropagation(); }); }; function _d(_e){ var _f=$.data(_e,"tree").options; _f.dnd=false; var _10=$(_e).find("div.tree-node"); _10.draggable("disable"); _10.css("cursor","pointer"); }; function _11(_12){ var _13=$.data(_12,"tree"); var _14=_13.options; var _15=_13.tree; _13.disabledNodes=[]; _14.dnd=true; _15.find("div.tree-node").draggable({disabled:false,revert:true,cursor:"pointer",proxy:function(_16){ var p=$("<div class=\"tree-node-proxy\"></div>").appendTo("body"); p.html("<span class=\"tree-dnd-icon tree-dnd-no\">&nbsp;</span>"+$(_16).find(".tree-title").html()); p.hide(); return p; },deltaX:15,deltaY:15,onBeforeDrag:function(e){ if(_14.onBeforeDrag.call(_12,_c(_12,this))==false){ return false; } if($(e.target).hasClass("tree-hit")||$(e.target).hasClass("tree-checkbox")){ return false; } if(e.which!=1){ return false; } $(this).next("ul").find("div.tree-node").droppable({accept:"no-accept"}); var _17=$(this).find("span.tree-indent"); if(_17.length){ e.data.offsetWidth-=_17.length*_17.width(); } },onStartDrag:function(){ $(this).draggable("proxy").css({left:-10000,top:-10000}); _14.onStartDrag.call(_12,_c(_12,this)); var _18=_c(_12,this); if(_18.id==undefined){ _18.id="easyui_tree_node_id_temp"; _54(_12,_18); } _13.draggingNodeId=_18.id; },onDrag:function(e){ var x1=e.pageX,y1=e.pageY,x2=e.data.startX,y2=e.data.startY; var d=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); if(d>3){ $(this).draggable("proxy").show(); } this.pageY=e.pageY; },onStopDrag:function(){ $(this).next("ul").find("div.tree-node").droppable({accept:"div.tree-node"}); for(var i=0;i<_13.disabledNodes.length;i++){ $(_13.disabledNodes[i]).droppable("enable"); } _13.disabledNodes=[]; var _19=_c9(_12,_13.draggingNodeId); if(_19&&_19.id=="easyui_tree_node_id_temp"){ _19.id=""; _54(_12,_19); } _14.onStopDrag.call(_12,_19); }}).droppable({accept:"div.tree-node",onDragEnter:function(e,_1a){ if(_14.onDragEnter.call(_12,this,_c(_12,_1a))==false){ _1b(_1a,false); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); $(this).droppable("disable"); _13.disabledNodes.push(this); } },onDragOver:function(e,_1c){ if($(this).droppable("options").disabled){ return; } var _1d=_1c.pageY; var top=$(this).offset().top; var _1e=top+$(this).outerHeight(); _1b(_1c,true); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); if(_1d>top+(_1e-top)/2){ if(_1e-_1d<5){ $(this).addClass("tree-node-bottom"); }else{ $(this).addClass("tree-node-append"); } }else{ if(_1d-top<5){ $(this).addClass("tree-node-top"); }else{ $(this).addClass("tree-node-append"); } } if(_14.onDragOver.call(_12,this,_c(_12,_1c))==false){ _1b(_1c,false); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); $(this).droppable("disable"); _13.disabledNodes.push(this); } },onDragLeave:function(e,_1f){ _1b(_1f,false); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); _14.onDragLeave.call(_12,this,_c(_12,_1f)); },onDrop:function(e,_20){ var _21=this; var _22,_23; if($(this).hasClass("tree-node-append")){ _22=_24; _23="append"; }else{ _22=_25; _23=$(this).hasClass("tree-node-top")?"top":"bottom"; } if(_14.onBeforeDrop.call(_12,_21,_c2(_12,_20),_23)==false){ $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); return; } _22(_20,_21,_23); $(this).removeClass("tree-node-append tree-node-top tree-node-bottom"); }}); function _1b(_26,_27){ var _28=$(_26).draggable("proxy").find("span.tree-dnd-icon"); _28.removeClass("tree-dnd-yes tree-dnd-no").addClass(_27?"tree-dnd-yes":"tree-dnd-no"); }; function _24(_29,_2a){ if(_c(_12,_2a).state=="closed"){ _72(_12,_2a,function(){ _2b(); }); }else{ _2b(); } function _2b(){ var _2c=$(_12).tree("pop",_29); $(_12).tree("append",{parent:_2a,data:[_2c]}); _14.onDrop.call(_12,_2a,_2c,"append"); }; }; function _25(_2d,_2e,_2f){ var _30={}; if(_2f=="top"){ _30.before=_2e; }else{ _30.after=_2e; } var _31=$(_12).tree("pop",_2d); _30.data=_31; $(_12).tree("insert",_30); _14.onDrop.call(_12,_2e,_31,_2f); }; }; function _32(_33,_34,_35){ var _36=$.data(_33,"tree").options; if(!_36.checkbox){ return; } var _37=_c(_33,_34); if(_36.onBeforeCheck.call(_33,_37,_35)==false){ return; } var _38=$(_34); var ck=_38.find(".tree-checkbox"); ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_35){ ck.addClass("tree-checkbox1"); }else{ ck.addClass("tree-checkbox0"); } if(_36.cascadeCheck){ _39(_38); _3a(_38); } _36.onCheck.call(_33,_37,_35); function _3a(_3b){ var _3c=_3b.next().find(".tree-checkbox"); _3c.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_3b.find(".tree-checkbox").hasClass("tree-checkbox1")){ _3c.addClass("tree-checkbox1"); }else{ _3c.addClass("tree-checkbox0"); } }; function _39(_3d){ var _3e=_89(_33,_3d[0]); if(_3e){ var ck=$(_3e.target).find(".tree-checkbox"); ck.removeClass("tree-checkbox0 tree-checkbox1 tree-checkbox2"); if(_3f(_3d)){ ck.addClass("tree-checkbox1"); }else{ if(_40(_3d)){ ck.addClass("tree-checkbox0"); }else{ ck.addClass("tree-checkbox2"); } } _39($(_3e.target)); } function _3f(n){ var ck=n.find(".tree-checkbox"); if(ck.hasClass("tree-checkbox0")||ck.hasClass("tree-checkbox2")){ return false; } var b=true; n.parent().siblings().each(function(){ if(!$(this).children("div.tree-node").children(".tree-checkbox").hasClass("tree-checkbox1")){ b=false; } }); return b; }; function _40(n){ var ck=n.find(".tree-checkbox"); if(ck.hasClass("tree-checkbox1")||ck.hasClass("tree-checkbox2")){ return false; } var b=true; n.parent().siblings().each(function(){ if(!$(this).children("div.tree-node").children(".tree-checkbox").hasClass("tree-checkbox0")){ b=false; } }); return b; }; }; }; function _41(_42,_43){ var _44=$.data(_42,"tree").options; if(!_44.checkbox){ return; } var _45=$(_43); if(_46(_42,_43)){ var ck=_45.find(".tree-checkbox"); if(ck.length){ if(ck.hasClass("tree-checkbox1")){ _32(_42,_43,true); }else{ _32(_42,_43,false); } }else{ if(_44.onlyLeafCheck){ $("<span class=\"tree-checkbox tree-checkbox0\"></span>").insertBefore(_45.find(".tree-title")); } } }else{ var ck=_45.find(".tree-checkbox"); if(_44.onlyLeafCheck){ ck.remove(); }else{ if(ck.hasClass("tree-checkbox1")){ _32(_42,_43,true); }else{ if(ck.hasClass("tree-checkbox2")){ var _47=true; var _48=true; var _49=_4a(_42,_43); for(var i=0;i<_49.length;i++){ if(_49[i].checked){ _48=false; }else{ _47=false; } } if(_47){ _32(_42,_43,true); } if(_48){ _32(_42,_43,false); } } } } } }; function _4b(_4c,ul,_4d,_4e){ var _4f=$.data(_4c,"tree"); var _50=_4f.options; var _51=$(ul).prevAll("div.tree-node:first"); _4d=_50.loadFilter.call(_4c,_4d,_51[0]); var _52=_53(_4c,"domId",_51.attr("id")); if(!_4e){ _52?_52.children=_4d:_4f.data=_4d; $(ul).empty(); }else{ if(_52){ _52.children?_52.children=_52.children.concat(_4d):_52.children=_4d; }else{ _4f.data=_4f.data.concat(_4d); } } _50.view.render.call(_50.view,_4c,ul,_4d); if(_50.dnd){ _11(_4c); } if(_52){ _54(_4c,_52); } var _55=[]; var _56=[]; for(var i=0;i<_4d.length;i++){ var _57=_4d[i]; if(!_57.checked){ _55.push(_57); } } _58(_4d,function(_59){ if(_59.checked){ _56.push(_59); } }); if(_55.length){ _32(_4c,$("#"+_55[0].domId)[0],false); } for(var i=0;i<_56.length;i++){ _32(_4c,$("#"+_56[i].domId)[0],true); } setTimeout(function(){ _5a(_4c,_4c); },0); _50.onLoadSuccess.call(_4c,_52,_4d); }; function _5a(_5b,ul,_5c){ var _5d=$.data(_5b,"tree").options; if(_5d.lines){ $(_5b).addClass("tree-lines"); }else{ $(_5b).removeClass("tree-lines"); return; } if(!_5c){ _5c=true; $(_5b).find("span.tree-indent").removeClass("tree-line tree-join tree-joinbottom"); $(_5b).find("div.tree-node").removeClass("tree-node-last tree-root-first tree-root-one"); var _5e=$(_5b).tree("getRoots"); if(_5e.length>1){ $(_5e[0].target).addClass("tree-root-first"); }else{ if(_5e.length==1){ $(_5e[0].target).addClass("tree-root-one"); } } } $(ul).children("li").each(function(){ var _5f=$(this).children("div.tree-node"); var ul=_5f.next("ul"); if(ul.length){ if($(this).next().length){ _60(_5f); } _5a(_5b,ul,_5c); }else{ _61(_5f); } }); var _62=$(ul).children("li:last").children("div.tree-node").addClass("tree-node-last"); _62.children("span.tree-join").removeClass("tree-join").addClass("tree-joinbottom"); function _61(_63,_64){ var _65=_63.find("span.tree-icon"); _65.prev("span.tree-indent").addClass("tree-join"); }; function _60(_66){ var _67=_66.find("span.tree-indent, span.tree-hit").length; _66.next().find("div.tree-node").each(function(){ $(this).children("span:eq("+(_67-1)+")").addClass("tree-line"); }); }; }; function _68(_69,ul,_6a,_6b){ var _6c=$.data(_69,"tree").options; _6a=_6a||{}; var _6d=null; if(_69!=ul){ var _6e=$(ul).prev(); _6d=_c(_69,_6e[0]); } if(_6c.onBeforeLoad.call(_69,_6d,_6a)==false){ return; } var _6f=$(ul).prev().children("span.tree-folder"); _6f.addClass("tree-loading"); var _70=_6c.loader.call(_69,_6a,function(_71){ _6f.removeClass("tree-loading"); _4b(_69,ul,_71); if(_6b){ _6b(); } },function(){ _6f.removeClass("tree-loading"); _6c.onLoadError.apply(_69,arguments); if(_6b){ _6b(); } }); if(_70==false){ _6f.removeClass("tree-loading"); } }; function _72(_73,_74,_75){ var _76=$.data(_73,"tree").options; var hit=$(_74).children("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ return; } var _77=_c(_73,_74); if(_76.onBeforeExpand.call(_73,_77)==false){ return; } hit.removeClass("tree-collapsed tree-collapsed-hover").addClass("tree-expanded"); hit.next().addClass("tree-folder-open"); var ul=$(_74).next(); if(ul.length){ if(_76.animate){ ul.slideDown("normal",function(){ _77.state="open"; _76.onExpand.call(_73,_77); if(_75){ _75(); } }); }else{ ul.css("display","block"); _77.state="open"; _76.onExpand.call(_73,_77); if(_75){ _75(); } } }else{ var _78=$("<ul style=\"display:none\"></ul>").insertAfter(_74); _68(_73,_78[0],{id:_77.id},function(){ if(_78.is(":empty")){ _78.remove(); } if(_76.animate){ _78.slideDown("normal",function(){ _77.state="open"; _76.onExpand.call(_73,_77); if(_75){ _75(); } }); }else{ _78.css("display","block"); _77.state="open"; _76.onExpand.call(_73,_77); if(_75){ _75(); } } }); } }; function _79(_7a,_7b){ var _7c=$.data(_7a,"tree").options; var hit=$(_7b).children("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-collapsed")){ return; } var _7d=_c(_7a,_7b); if(_7c.onBeforeCollapse.call(_7a,_7d)==false){ return; } hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); hit.next().removeClass("tree-folder-open"); var ul=$(_7b).next(); if(_7c.animate){ ul.slideUp("normal",function(){ _7d.state="closed"; _7c.onCollapse.call(_7a,_7d); }); }else{ ul.css("display","none"); _7d.state="closed"; _7c.onCollapse.call(_7a,_7d); } }; function _7e(_7f,_80){ var hit=$(_80).children("span.tree-hit"); if(hit.length==0){ return; } if(hit.hasClass("tree-expanded")){ _79(_7f,_80); }else{ _72(_7f,_80); } }; function _81(_82,_83){ var _84=_4a(_82,_83); if(_83){ _84.unshift(_c(_82,_83)); } for(var i=0;i<_84.length;i++){ _72(_82,_84[i].target); } }; function _85(_86,_87){ var _88=[]; var p=_89(_86,_87); while(p){ _88.unshift(p); p=_89(_86,p.target); } for(var i=0;i<_88.length;i++){ _72(_86,_88[i].target); } }; function _8a(_8b,_8c){ var c=$(_8b).parent(); while(c[0].tagName!="BODY"&&c.css("overflow-y")!="auto"){ c=c.parent(); } var n=$(_8c); var _8d=n.offset().top; if(c[0].tagName!="BODY"){ var _8e=c.offset().top; if(_8d<_8e){ c.scrollTop(c.scrollTop()+_8d-_8e); }else{ if(_8d+n.outerHeight()>_8e+c.outerHeight()-18){ c.scrollTop(c.scrollTop()+_8d+n.outerHeight()-_8e-c.outerHeight()+18); } } }else{ c.scrollTop(_8d); } }; function _8f(_90,_91){ var _92=_4a(_90,_91); if(_91){ _92.unshift(_c(_90,_91)); } for(var i=0;i<_92.length;i++){ _79(_90,_92[i].target); } }; function _93(_94,_95){ var _96=$(_95.parent); var _97=_95.data; if(!_97){ return; } _97=$.isArray(_97)?_97:[_97]; if(!_97.length){ return; } var ul; if(_96.length==0){ ul=$(_94); }else{ if(_46(_94,_96[0])){ var _98=_96.find("span.tree-icon"); _98.removeClass("tree-file").addClass("tree-folder tree-folder-open"); var hit=$("<span class=\"tree-hit tree-expanded\"></span>").insertBefore(_98); if(hit.prev().length){ hit.prev().remove(); } } ul=_96.next(); if(!ul.length){ ul=$("<ul></ul>").insertAfter(_96); } } _4b(_94,ul[0],_97,true); _41(_94,ul.prev()); }; function _99(_9a,_9b){ var ref=_9b.before||_9b.after; var _9c=_89(_9a,ref); var _9d=_9b.data; if(!_9d){ return; } _9d=$.isArray(_9d)?_9d:[_9d]; if(!_9d.length){ return; } _93(_9a,{parent:(_9c?_9c.target:null),data:_9d}); var li=$(); for(var i=0;i<_9d.length;i++){ li=li.add($("#"+_9d[i].domId).parent()); } if(_9b.before){ li.insertBefore($(ref).parent()); }else{ li.insertAfter($(ref).parent()); } }; function _9e(_9f,_a0){ var _a1=del(_a0); $(_a0).parent().remove(); if(_a1){ if(!_a1.children||!_a1.children.length){ var _a2=$(_a1.target); _a2.find(".tree-icon").removeClass("tree-folder").addClass("tree-file"); _a2.find(".tree-hit").remove(); $("<span class=\"tree-indent\"></span>").prependTo(_a2); _a2.next().remove(); } _54(_9f,_a1); _41(_9f,_a1.target); } _5a(_9f,_9f); function del(_a3){ var id=$(_a3).attr("id"); var _a4=_89(_9f,_a3); var cc=_a4?_a4.children:$.data(_9f,"tree").data; for(var i=0;i<cc.length;i++){ if(cc[i].domId==id){ cc.splice(i,1); break; } } return _a4; }; }; function _54(_a5,_a6){ var _a7=$.data(_a5,"tree").options; var _a8=$(_a6.target); var _a9=_c(_a5,_a6.target); var _aa=_a9.checked; if(_a9.iconCls){ _a8.find(".tree-icon").removeClass(_a9.iconCls); } $.extend(_a9,_a6); _a8.find(".tree-title").html(_a7.formatter.call(_a5,_a9)); if(_a9.iconCls){ _a8.find(".tree-icon").addClass(_a9.iconCls); } if(_aa!=_a9.checked){ _32(_a5,_a6.target,_a9.checked); } }; function _ab(_ac){ var _ad=_ae(_ac); return _ad.length?_ad[0]:null; }; function _ae(_af){ var _b0=$.data(_af,"tree").data; for(var i=0;i<_b0.length;i++){ _b1(_b0[i]); } return _b0; }; function _4a(_b2,_b3){ var _b4=[]; var n=_c(_b2,_b3); var _b5=n?n.children:$.data(_b2,"tree").data; _58(_b5,function(_b6){ _b4.push(_b1(_b6)); }); return _b4; }; function _89(_b7,_b8){ var p=$(_b8).closest("ul").prevAll("div.tree-node:first"); return _c(_b7,p[0]); }; function _b9(_ba,_bb){ _bb=_bb||"checked"; if(!$.isArray(_bb)){ _bb=[_bb]; } var _bc=[]; for(var i=0;i<_bb.length;i++){ var s=_bb[i]; if(s=="checked"){ _bc.push("span.tree-checkbox1"); }else{ if(s=="unchecked"){ _bc.push("span.tree-checkbox0"); }else{ if(s=="indeterminate"){ _bc.push("span.tree-checkbox2"); } } } } var _bd=[]; $(_ba).find(_bc.join(",")).each(function(){ var _be=$(this).parent(); _bd.push(_c(_ba,_be[0])); }); return _bd; }; function _bf(_c0){ var _c1=$(_c0).find("div.tree-node-selected"); return _c1.length?_c(_c0,_c1[0]):null; }; function _c2(_c3,_c4){ var _c5=_c(_c3,_c4); if(_c5&&_c5.children){ _58(_c5.children,function(_c6){ _b1(_c6); }); } return _c5; }; function _c(_c7,_c8){ return _53(_c7,"domId",$(_c8).attr("id")); }; function _c9(_ca,id){ return _53(_ca,"id",id); }; function _53(_cb,_cc,_cd){ var _ce=$.data(_cb,"tree").data; var _cf=null; _58(_ce,function(_d0){ if(_d0[_cc]==_cd){ _cf=_b1(_d0); return false; } }); return _cf; }; function _b1(_d1){ var d=$("#"+_d1.domId); _d1.target=d[0]; _d1.checked=d.find(".tree-checkbox").hasClass("tree-checkbox1"); return _d1; }; function _58(_d2,_d3){ var _d4=[]; for(var i=0;i<_d2.length;i++){ _d4.push(_d2[i]); } while(_d4.length){ var _d5=_d4.shift(); if(_d3(_d5)==false){ return; } if(_d5.children){ for(var i=_d5.children.length-1;i>=0;i--){ _d4.unshift(_d5.children[i]); } } } }; function _d6(_d7,_d8){ var _d9=$.data(_d7,"tree").options; var _da=_c(_d7,_d8); if(_d9.onBeforeSelect.call(_d7,_da)==false){ return; } $(_d7).find("div.tree-node-selected").removeClass("tree-node-selected"); $(_d8).addClass("tree-node-selected"); _d9.onSelect.call(_d7,_da); }; function _46(_db,_dc){ return $(_dc).children("span.tree-hit").length==0; }; function _dd(_de,_df){ var _e0=$.data(_de,"tree").options; var _e1=_c(_de,_df); if(_e0.onBeforeEdit.call(_de,_e1)==false){ return; } $(_df).css("position","relative"); var nt=$(_df).find(".tree-title"); var _e2=nt.outerWidth(); nt.empty(); var _e3=$("<input class=\"tree-editor\">").appendTo(nt); _e3.val(_e1.text).focus(); _e3.width(_e2+20); _e3.height(document.compatMode=="CSS1Compat"?(18-(_e3.outerHeight()-_e3.height())):18); _e3.bind("click",function(e){ return false; }).bind("mousedown",function(e){ e.stopPropagation(); }).bind("mousemove",function(e){ e.stopPropagation(); }).bind("keydown",function(e){ if(e.keyCode==13){ _e4(_de,_df); return false; }else{ if(e.keyCode==27){ _ea(_de,_df); return false; } } }).bind("blur",function(e){ e.stopPropagation(); _e4(_de,_df); }); }; function _e4(_e5,_e6){ var _e7=$.data(_e5,"tree").options; $(_e6).css("position",""); var _e8=$(_e6).find("input.tree-editor"); var val=_e8.val(); _e8.remove(); var _e9=_c(_e5,_e6); _e9.text=val; _54(_e5,_e9); _e7.onAfterEdit.call(_e5,_e9); }; function _ea(_eb,_ec){ var _ed=$.data(_eb,"tree").options; $(_ec).css("position",""); $(_ec).find("input.tree-editor").remove(); var _ee=_c(_eb,_ec); _54(_eb,_ee); _ed.onCancelEdit.call(_eb,_ee); }; $.fn.tree=function(_ef,_f0){ if(typeof _ef=="string"){ return $.fn.tree.methods[_ef](this,_f0); } var _ef=_ef||{}; return this.each(function(){ var _f1=$.data(this,"tree"); var _f2; if(_f1){ _f2=$.extend(_f1.options,_ef); _f1.options=_f2; }else{ _f2=$.extend({},$.fn.tree.defaults,$.fn.tree.parseOptions(this),_ef); $.data(this,"tree",{options:_f2,tree:_1(this),data:[]}); var _f3=$.fn.tree.parseData(this); if(_f3.length){ _4b(this,this,_f3); } } _4(this); if(_f2.data){ _4b(this,this,_f2.data); } _68(this,this); }); }; $.fn.tree.methods={options:function(jq){ return $.data(jq[0],"tree").options; },loadData:function(jq,_f4){ return jq.each(function(){ _4b(this,this,_f4); }); },getNode:function(jq,_f5){ return _c(jq[0],_f5); },getData:function(jq,_f6){ return _c2(jq[0],_f6); },reload:function(jq,_f7){ return jq.each(function(){ if(_f7){ var _f8=$(_f7); var hit=_f8.children("span.tree-hit"); hit.removeClass("tree-expanded tree-expanded-hover").addClass("tree-collapsed"); _f8.next().remove(); _72(this,_f7); }else{ $(this).empty(); _68(this,this); } }); },getRoot:function(jq){ return _ab(jq[0]); },getRoots:function(jq){ return _ae(jq[0]); },getParent:function(jq,_f9){ return _89(jq[0],_f9); },getChildren:function(jq,_fa){ return _4a(jq[0],_fa); },getChecked:function(jq,_fb){ return _b9(jq[0],_fb); },getSelected:function(jq){ return _bf(jq[0]); },isLeaf:function(jq,_fc){ return _46(jq[0],_fc); },find:function(jq,id){ return _c9(jq[0],id); },select:function(jq,_fd){ return jq.each(function(){ _d6(this,_fd); }); },check:function(jq,_fe){ return jq.each(function(){ _32(this,_fe,true); }); },uncheck:function(jq,_ff){ return jq.each(function(){ _32(this,_ff,false); }); },collapse:function(jq,_100){ return jq.each(function(){ _79(this,_100); }); },expand:function(jq,_101){ return jq.each(function(){ _72(this,_101); }); },collapseAll:function(jq,_102){ return jq.each(function(){ _8f(this,_102); }); },expandAll:function(jq,_103){ return jq.each(function(){ _81(this,_103); }); },expandTo:function(jq,_104){ return jq.each(function(){ _85(this,_104); }); },scrollTo:function(jq,_105){ return jq.each(function(){ _8a(this,_105); }); },toggle:function(jq,_106){ return jq.each(function(){ _7e(this,_106); }); },append:function(jq,_107){ return jq.each(function(){ _93(this,_107); }); },insert:function(jq,_108){ return jq.each(function(){ _99(this,_108); }); },remove:function(jq,_109){ return jq.each(function(){ _9e(this,_109); }); },pop:function(jq,_10a){ var node=jq.tree("getData",_10a); jq.tree("remove",_10a); return node; },update:function(jq,_10b){ return jq.each(function(){ _54(this,_10b); }); },enableDnd:function(jq){ return jq.each(function(){ _11(this); }); },disableDnd:function(jq){ return jq.each(function(){ _d(this); }); },beginEdit:function(jq,_10c){ return jq.each(function(){ _dd(this,_10c); }); },endEdit:function(jq,_10d){ return jq.each(function(){ _e4(this,_10d); }); },cancelEdit:function(jq,_10e){ return jq.each(function(){ _ea(this,_10e); }); }}; $.fn.tree.parseOptions=function(_10f){ var t=$(_10f); return $.extend({},$.parser.parseOptions(_10f,["url","method",{checkbox:"boolean",cascadeCheck:"boolean",onlyLeafCheck:"boolean"},{animate:"boolean",lines:"boolean",dnd:"boolean"}])); }; $.fn.tree.parseData=function(_110){ var data=[]; _111(data,$(_110)); return data; function _111(aa,tree){ tree.children("li").each(function(){ var node=$(this); var item=$.extend({},$.parser.parseOptions(this,["id","iconCls","state"]),{checked:(node.attr("checked")?true:undefined)}); item.text=node.children("span").html(); if(!item.text){ item.text=node.html(); } var _112=node.children("ul"); if(_112.length){ item.children=[]; _111(item.children,_112); } aa.push(item); }); }; }; var _113=1; var _114={render:function(_115,ul,data){ var opts=$.data(_115,"tree").options; var _116=$(ul).prev("div.tree-node").find("span.tree-indent, span.tree-hit").length; var cc=_117(_116,data); $(ul).append(cc.join("")); function _117(_118,_119){ var cc=[]; for(var i=0;i<_119.length;i++){ var item=_119[i]; if(item.state!="open"&&item.state!="closed"){ item.state="open"; } item.domId="_easyui_tree_"+_113++; cc.push("<li>"); cc.push("<div id=\""+item.domId+"\" class=\"tree-node\">"); for(var j=0;j<_118;j++){ cc.push("<span class=\"tree-indent\"></span>"); } if(item.state=="closed"){ cc.push("<span class=\"tree-hit tree-collapsed\"></span>"); cc.push("<span class=\"tree-icon tree-folder "+(item.iconCls?item.iconCls:"")+"\"></span>"); }else{ if(item.children&&item.children.length){ cc.push("<span class=\"tree-hit tree-expanded\"></span>"); cc.push("<span class=\"tree-icon tree-folder tree-folder-open "+(item.iconCls?item.iconCls:"")+"\"></span>"); }else{ cc.push("<span class=\"tree-indent\"></span>"); cc.push("<span class=\"tree-icon tree-file "+(item.iconCls?item.iconCls:"")+"\"></span>"); } } if(opts.checkbox){ if((!opts.onlyLeafCheck)||(opts.onlyLeafCheck&&(!item.children||!item.children.length))){ cc.push("<span class=\"tree-checkbox tree-checkbox0\"></span>"); } } cc.push("<span class=\"tree-title\">"+opts.formatter.call(_115,item)+"</span>"); cc.push("</div>"); if(item.children&&item.children.length){ var tmp=_117(_118+1,item.children); cc.push("<ul style=\"display:"+(item.state=="closed"?"none":"block")+"\">"); cc=cc.concat(tmp); cc.push("</ul>"); } cc.push("</li>"); } return cc; }; }}; $.fn.tree.defaults={url:null,method:"post",animate:false,checkbox:false,cascadeCheck:true,onlyLeafCheck:false,lines:false,dnd:false,data:null,formatter:function(node){ return node.text; },loader:function(_11a,_11b,_11c){ var opts=$(this).tree("options"); if(!opts.url){ return false; } $.ajax({type:opts.method,url:opts.url,data:_11a,dataType:"json",success:function(data){ _11b(data); },error:function(){ _11c.apply(this,arguments); }}); },loadFilter:function(data,_11d){ return data; },view:_114,onBeforeLoad:function(node,_11e){ },onLoadSuccess:function(node,data){ },onLoadError:function(){ },onClick:function(node){ },onDblClick:function(node){ },onBeforeExpand:function(node){ },onExpand:function(node){ },onBeforeCollapse:function(node){ },onCollapse:function(node){ },onBeforeCheck:function(node,_11f){ },onCheck:function(node,_120){ },onBeforeSelect:function(node){ },onSelect:function(node){ },onContextMenu:function(e,node){ },onBeforeDrag:function(node){ },onStartDrag:function(node){ },onStopDrag:function(node){ },onDragEnter:function(_121,_122){ },onDragOver:function(_123,_124){ },onDragLeave:function(_125,_126){ },onBeforeDrop:function(_127,_128,_129){ },onDrop:function(_12a,_12b,_12c){ },onBeforeEdit:function(node){ },onAfterEdit:function(node){ },onCancelEdit:function(node){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"combotree").options; var _4=$.data(_2,"combotree").tree; $(_2).addClass("combotree-f"); $(_2).combo(_3); var _5=$(_2).combo("panel"); if(!_4){ _4=$("<ul></ul>").appendTo(_5); $.data(_2,"combotree").tree=_4; } _4.tree($.extend({},_3,{checkbox:_3.multiple,onLoadSuccess:function(_6,_7){ var _8=$(_2).combotree("getValues"); if(_3.multiple){ var _9=_4.tree("getChecked"); for(var i=0;i<_9.length;i++){ var id=_9[i].id; (function(){ for(var i=0;i<_8.length;i++){ if(id==_8[i]){ return; } } _8.push(id); })(); } } $(_2).combotree("setValues",_8); _3.onLoadSuccess.call(this,_6,_7); },onClick:function(_a){ _d(_2); $(_2).combo("hidePanel"); _3.onClick.call(this,_a); },onCheck:function(_b,_c){ _d(_2); _3.onCheck.call(this,_b,_c); }})); }; function _d(_e){ var _f=$.data(_e,"combotree").options; var _10=$.data(_e,"combotree").tree; var vv=[],ss=[]; if(_f.multiple){ var _11=_10.tree("getChecked"); for(var i=0;i<_11.length;i++){ vv.push(_11[i].id); ss.push(_11[i].text); } }else{ var _12=_10.tree("getSelected"); if(_12){ vv.push(_12.id); ss.push(_12.text); } } $(_e).combo("setValues",vv).combo("setText",ss.join(_f.separator)); }; function _13(_14,_15){ var _16=$.data(_14,"combotree").options; var _17=$.data(_14,"combotree").tree; _17.find("span.tree-checkbox").addClass("tree-checkbox0").removeClass("tree-checkbox1 tree-checkbox2"); var vv=[],ss=[]; for(var i=0;i<_15.length;i++){ var v=_15[i]; var s=v; var _18=_17.tree("find",v); if(_18){ s=_18.text; _17.tree("check",_18.target); _17.tree("select",_18.target); } vv.push(v); ss.push(s); } $(_14).combo("setValues",vv).combo("setText",ss.join(_16.separator)); }; $.fn.combotree=function(_19,_1a){ if(typeof _19=="string"){ var _1b=$.fn.combotree.methods[_19]; if(_1b){ return _1b(this,_1a); }else{ return this.combo(_19,_1a); } } _19=_19||{}; return this.each(function(){ var _1c=$.data(this,"combotree"); if(_1c){ $.extend(_1c.options,_19); }else{ $.data(this,"combotree",{options:$.extend({},$.fn.combotree.defaults,$.fn.combotree.parseOptions(this),_19)}); } _1(this); }); }; $.fn.combotree.methods={options:function(jq){ var _1d=jq.combo("options"); return $.extend($.data(jq[0],"combotree").options,{originalValue:_1d.originalValue,disabled:_1d.disabled,readonly:_1d.readonly}); },tree:function(jq){ return $.data(jq[0],"combotree").tree; },loadData:function(jq,_1e){ return jq.each(function(){ var _1f=$.data(this,"combotree").options; _1f.data=_1e; var _20=$.data(this,"combotree").tree; _20.tree("loadData",_1e); }); },reload:function(jq,url){ return jq.each(function(){ var _21=$.data(this,"combotree").options; var _22=$.data(this,"combotree").tree; if(url){ _21.url=url; } _22.tree({url:_21.url}); }); },setValues:function(jq,_23){ return jq.each(function(){ _13(this,_23); }); },setValue:function(jq,_24){ return jq.each(function(){ _13(this,[_24]); }); },clear:function(jq){ return jq.each(function(){ var _25=$.data(this,"combotree").tree; _25.find("div.tree-node-selected").removeClass("tree-node-selected"); var cc=_25.tree("getChecked"); for(var i=0;i<cc.length;i++){ _25.tree("uncheck",cc[i].target); } $(this).combo("clear"); }); },reset:function(jq){ return jq.each(function(){ var _26=$(this).combotree("options"); if(_26.multiple){ $(this).combotree("setValues",_26.originalValue); }else{ $(this).combotree("setValue",_26.originalValue); } }); }}; $.fn.combotree.parseOptions=function(_27){ return $.extend({},$.fn.combo.parseOptions(_27),$.fn.tree.parseOptions(_27)); }; $.fn.combotree.defaults=$.extend({},$.fn.combo.defaults,$.fn.tree.defaults,{editable:false}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ var _1=0; function _2(a,o){ for(var i=0,_3=a.length;i<_3;i++){ if(a[i]==o){ return i; } } return -1; }; function _4(a,o,id){ if(typeof o=="string"){ for(var i=0,_5=a.length;i<_5;i++){ if(a[i][o]==id){ a.splice(i,1); return; } } }else{ var _6=_2(a,o); if(_6!=-1){ a.splice(_6,1); } } }; function _7(a,o,r){ for(var i=0,_8=a.length;i<_8;i++){ if(a[i][o]==r[o]){ return; } } a.push(r); }; function _9(_a){ var cc=_a||$("head"); var _b=$.data(cc[0],"ss"); if(!_b){ _b=$.data(cc[0],"ss",{cache:{},dirty:[]}); } return {add:function(_c){ var ss=["<style type=\"text/css\">"]; for(var i=0;i<_c.length;i++){ _b.cache[_c[i][0]]={width:_c[i][1]}; } var _d=0; for(var s in _b.cache){ var _e=_b.cache[s]; _e.index=_d++; ss.push(s+"{width:"+_e.width+"}"); } ss.push("</style>"); $(ss.join("\n")).appendTo(cc); setTimeout(function(){ cc.children("style:not(:last)").remove(); },0); },getRule:function(_f){ var _10=cc.children("style:last")[0]; var _11=_10.styleSheet?_10.styleSheet:(_10.sheet||document.styleSheets[document.styleSheets.length-1]); var _12=_11.cssRules||_11.rules; return _12[_f]; },set:function(_13,_14){ var _15=_b.cache[_13]; if(_15){ _15.width=_14; var _16=this.getRule(_15.index); if(_16){ _16.style["width"]=_14; } } },remove:function(_17){ var tmp=[]; for(var s in _b.cache){ if(s.indexOf(_17)==-1){ tmp.push([s,_b.cache[s].width]); } } _b.cache={}; this.add(tmp); },dirty:function(_18){ if(_18){ _b.dirty.push(_18); } },clean:function(){ for(var i=0;i<_b.dirty.length;i++){ this.remove(_b.dirty[i]); } _b.dirty=[]; }}; }; function _19(_1a,_1b){ var _1c=$.data(_1a,"datagrid").options; var _1d=$.data(_1a,"datagrid").panel; if(_1b){ if(_1b.width){ _1c.width=_1b.width; } if(_1b.height){ _1c.height=_1b.height; } } if(_1c.fit==true){ var p=_1d.panel("panel").parent(); _1c.width=p.width(); _1c.height=p.height(); } _1d.panel("resize",{width:_1c.width,height:_1c.height}); }; function _1e(_1f){ var _20=$.data(_1f,"datagrid").options; var dc=$.data(_1f,"datagrid").dc; var _21=$.data(_1f,"datagrid").panel; var _22=_21.width(); var _23=_21.height(); var _24=dc.view; var _25=dc.view1; var _26=dc.view2; var _27=_25.children("div.datagrid-header"); var _28=_26.children("div.datagrid-header"); var _29=_27.find("table"); var _2a=_28.find("table"); _24.width(_22); var _2b=_27.children("div.datagrid-header-inner").show(); _25.width(_2b.find("table").width()); if(!_20.showHeader){ _2b.hide(); } _26.width(_22-_25._outerWidth()); _25.children("div.datagrid-header,div.datagrid-body,div.datagrid-footer").width(_25.width()); _26.children("div.datagrid-header,div.datagrid-body,div.datagrid-footer").width(_26.width()); var hh; _27.css("height",""); _28.css("height",""); _29.css("height",""); _2a.css("height",""); hh=Math.max(_29.height(),_2a.height()); _29.height(hh); _2a.height(hh); _27.add(_28)._outerHeight(hh); if(_20.height!="auto"){ var _2c=_23-_26.children("div.datagrid-header")._outerHeight()-_26.children("div.datagrid-footer")._outerHeight()-_21.children("div.datagrid-toolbar")._outerHeight(); _21.children("div.datagrid-pager").each(function(){ _2c-=$(this)._outerHeight(); }); dc.body1.add(dc.body2).children("table.datagrid-btable-frozen").css({position:"absolute",top:dc.header2._outerHeight()}); var _2d=dc.body2.children("table.datagrid-btable-frozen")._outerHeight(); _25.add(_26).children("div.datagrid-body").css({marginTop:_2d,height:(_2c-_2d)}); } _24.height(_26.height()); }; function _2e(_2f,_30,_31){ var _32=$.data(_2f,"datagrid").data.rows; var _33=$.data(_2f,"datagrid").options; var dc=$.data(_2f,"datagrid").dc; if(!dc.body1.is(":empty")&&(!_33.nowrap||_33.autoRowHeight||_31)){ if(_30!=undefined){ var tr1=_33.finder.getTr(_2f,_30,"body",1); var tr2=_33.finder.getTr(_2f,_30,"body",2); _34(tr1,tr2); }else{ var tr1=_33.finder.getTr(_2f,0,"allbody",1); var tr2=_33.finder.getTr(_2f,0,"allbody",2); _34(tr1,tr2); if(_33.showFooter){ var tr1=_33.finder.getTr(_2f,0,"allfooter",1); var tr2=_33.finder.getTr(_2f,0,"allfooter",2); _34(tr1,tr2); } } } _1e(_2f); if(_33.height=="auto"){ var _35=dc.body1.parent(); var _36=dc.body2; var _37=_38(_36); var _39=_37.height; if(_37.width>_36.width()){ _39+=18; } _35.height(_39); _36.height(_39); dc.view.height(dc.view2.height()); } dc.body2.triggerHandler("scroll"); function _34(_3a,_3b){ for(var i=0;i<_3b.length;i++){ var tr1=$(_3a[i]); var tr2=$(_3b[i]); tr1.css("height",""); tr2.css("height",""); var _3c=Math.max(tr1.height(),tr2.height()); tr1.css("height",_3c); tr2.css("height",_3c); } }; function _38(cc){ var _3d=0; var _3e=0; $(cc).children().each(function(){ var c=$(this); if(c.is(":visible")){ _3e+=c._outerHeight(); if(_3d<c._outerWidth()){ _3d=c._outerWidth(); } } }); return {width:_3d,height:_3e}; }; }; function _3f(_40,_41){ var _42=$.data(_40,"datagrid"); var _43=_42.options; var dc=_42.dc; if(!dc.body2.children("table.datagrid-btable-frozen").length){ dc.body1.add(dc.body2).prepend("<table class=\"datagrid-btable datagrid-btable-frozen\" cellspacing=\"0\" cellpadding=\"0\"></table>"); } _44(true); _44(false); _1e(_40); function _44(_45){ var _46=_45?1:2; var tr=_43.finder.getTr(_40,_41,"body",_46); (_45?dc.body1:dc.body2).children("table.datagrid-btable-frozen").append(tr); }; }; function _47(_48,_49){ function _4a(){ var _4b=[]; var _4c=[]; $(_48).children("thead").each(function(){ var opt=$.parser.parseOptions(this,[{frozen:"boolean"}]); $(this).find("tr").each(function(){ var _4d=[]; $(this).find("th").each(function(){ var th=$(this); var col=$.extend({},$.parser.parseOptions(this,["field","align","halign","order",{sortable:"boolean",checkbox:"boolean",resizable:"boolean",fixed:"boolean"},{rowspan:"number",colspan:"number",width:"number"}]),{title:(th.html()||undefined),hidden:(th.attr("hidden")?true:undefined),formatter:(th.attr("formatter")?eval(th.attr("formatter")):undefined),styler:(th.attr("styler")?eval(th.attr("styler")):undefined),sorter:(th.attr("sorter")?eval(th.attr("sorter")):undefined)}); if(th.attr("editor")){ var s=$.trim(th.attr("editor")); if(s.substr(0,1)=="{"){ col.editor=eval("("+s+")"); }else{ col.editor=s; } } _4d.push(col); }); opt.frozen?_4b.push(_4d):_4c.push(_4d); }); }); return [_4b,_4c]; }; var _4e=$("<div class=\"datagrid-wrap\">"+"<div class=\"datagrid-view\">"+"<div class=\"datagrid-view1\">"+"<div class=\"datagrid-header\">"+"<div class=\"datagrid-header-inner\"></div>"+"</div>"+"<div class=\"datagrid-body\">"+"<div class=\"datagrid-body-inner\"></div>"+"</div>"+"<div class=\"datagrid-footer\">"+"<div class=\"datagrid-footer-inner\"></div>"+"</div>"+"</div>"+"<div class=\"datagrid-view2\">"+"<div class=\"datagrid-header\">"+"<div class=\"datagrid-header-inner\"></div>"+"</div>"+"<div class=\"datagrid-body\"></div>"+"<div class=\"datagrid-footer\">"+"<div class=\"datagrid-footer-inner\"></div>"+"</div>"+"</div>"+"</div>"+"</div>").insertAfter(_48); _4e.panel({doSize:false}); _4e.panel("panel").addClass("datagrid").bind("_resize",function(e,_4f){ var _50=$.data(_48,"datagrid").options; if(_50.fit==true||_4f){ _19(_48); setTimeout(function(){ if($.data(_48,"datagrid")){ _51(_48); } },0); } return false; }); $(_48).hide().appendTo(_4e.children("div.datagrid-view")); var cc=_4a(); var _52=_4e.children("div.datagrid-view"); var _53=_52.children("div.datagrid-view1"); var _54=_52.children("div.datagrid-view2"); var _55=_4e.closest("div.datagrid-view"); if(!_55.length){ _55=_52; } var ss=_9(_55); return {panel:_4e,frozenColumns:cc[0],columns:cc[1],dc:{view:_52,view1:_53,view2:_54,header1:_53.children("div.datagrid-header").children("div.datagrid-header-inner"),header2:_54.children("div.datagrid-header").children("div.datagrid-header-inner"),body1:_53.children("div.datagrid-body").children("div.datagrid-body-inner"),body2:_54.children("div.datagrid-body"),footer1:_53.children("div.datagrid-footer").children("div.datagrid-footer-inner"),footer2:_54.children("div.datagrid-footer").children("div.datagrid-footer-inner")},ss:ss}; }; function _56(_57){ var _58=$.data(_57,"datagrid"); var _59=_58.options; var dc=_58.dc; var _5a=_58.panel; _5a.panel($.extend({},_59,{id:null,doSize:false,onResize:function(_5b,_5c){ setTimeout(function(){ if($.data(_57,"datagrid")){ _1e(_57); _8d(_57); _59.onResize.call(_5a,_5b,_5c); } },0); },onExpand:function(){ _2e(_57); _59.onExpand.call(_5a); }})); _58.rowIdPrefix="datagrid-row-r"+(++_1); _58.cellClassPrefix="datagrid-cell-c"+_1; _5d(dc.header1,_59.frozenColumns,true); _5d(dc.header2,_59.columns,false); _5e(); dc.header1.add(dc.header2).css("display",_59.showHeader?"block":"none"); dc.footer1.add(dc.footer2).css("display",_59.showFooter?"block":"none"); if(_59.toolbar){ if($.isArray(_59.toolbar)){ $("div.datagrid-toolbar",_5a).remove(); var tb=$("<div class=\"datagrid-toolbar\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(_5a); var tr=tb.find("tr"); for(var i=0;i<_59.toolbar.length;i++){ var btn=_59.toolbar[i]; if(btn=="-"){ $("<td><div class=\"datagrid-btn-separator\"></div></td>").appendTo(tr); }else{ var td=$("<td></td>").appendTo(tr); var _5f=$("<a href=\"javascript:void(0)\"></a>").appendTo(td); _5f[0].onclick=eval(btn.handler||function(){ }); _5f.linkbutton($.extend({},btn,{plain:true})); } } }else{ $(_59.toolbar).addClass("datagrid-toolbar").prependTo(_5a); $(_59.toolbar).show(); } }else{ $("div.datagrid-toolbar",_5a).remove(); } $("div.datagrid-pager",_5a).remove(); if(_59.pagination){ var _60=$("<div class=\"datagrid-pager\"></div>"); if(_59.pagePosition=="bottom"){ _60.appendTo(_5a); }else{ if(_59.pagePosition=="top"){ _60.addClass("datagrid-pager-top").prependTo(_5a); }else{ var _61=$("<div class=\"datagrid-pager datagrid-pager-top\"></div>").prependTo(_5a); _60.appendTo(_5a); _60=_60.add(_61); } } _60.pagination({total:(_59.pageNumber*_59.pageSize),pageNumber:_59.pageNumber,pageSize:_59.pageSize,pageList:_59.pageList,onSelectPage:function(_62,_63){ _59.pageNumber=_62; _59.pageSize=_63; _60.pagination("refresh",{pageNumber:_62,pageSize:_63}); _16b(_57); }}); _59.pageSize=_60.pagination("options").pageSize; } function _5d(_64,_65,_66){ if(!_65){ return; } $(_64).show(); $(_64).empty(); var _67=[]; var _68=[]; if(_59.sortName){ _67=_59.sortName.split(","); _68=_59.sortOrder.split(","); } var t=$("<table class=\"datagrid-htable\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tbody></tbody></table>").appendTo(_64); for(var i=0;i<_65.length;i++){ var tr=$("<tr class=\"datagrid-header-row\"></tr>").appendTo($("tbody",t)); var _69=_65[i]; for(var j=0;j<_69.length;j++){ var col=_69[j]; var _6a=""; if(col.rowspan){ _6a+="rowspan=\""+col.rowspan+"\" "; } if(col.colspan){ _6a+="colspan=\""+col.colspan+"\" "; } var td=$("<td "+_6a+"></td>").appendTo(tr); if(col.checkbox){ td.attr("field",col.field); $("<div class=\"datagrid-header-check\"></div>").html("<input type=\"checkbox\"/>").appendTo(td); }else{ if(col.field){ td.attr("field",col.field); td.append("<div class=\"datagrid-cell\"><span></span><span class=\"datagrid-sort-icon\"></span></div>"); $("span",td).html(col.title); $("span.datagrid-sort-icon",td).html("&nbsp;"); var _6b=td.find("div.datagrid-cell"); var pos=_2(_67,col.field); if(pos>=0){ _6b.addClass("datagrid-sort-"+_68[pos]); } if(col.resizable==false){ _6b.attr("resizable","false"); } if(col.width){ _6b._outerWidth(col.width); col.boxWidth=parseInt(_6b[0].style.width); }else{ col.auto=true; } _6b.css("text-align",(col.halign||col.align||"")); col.cellClass=_58.cellClassPrefix+"-"+col.field.replace(/[\.|\s]/g,"-"); _6b.addClass(col.cellClass).css("width",""); }else{ $("<div class=\"datagrid-cell-group\"></div>").html(col.title).appendTo(td); } } if(col.hidden){ td.hide(); } } } if(_66&&_59.rownumbers){ var td=$("<td rowspan=\""+_59.frozenColumns.length+"\"><div class=\"datagrid-header-rownumber\"></div></td>"); if($("tr",t).length==0){ td.wrap("<tr class=\"datagrid-header-row\"></tr>").parent().appendTo($("tbody",t)); }else{ td.prependTo($("tr:first",t)); } } }; function _5e(){ var _6c=[]; var _6d=_6e(_57,true).concat(_6e(_57)); for(var i=0;i<_6d.length;i++){ var col=_6f(_57,_6d[i]); if(col&&!col.checkbox){ _6c.push(["."+col.cellClass,col.boxWidth?col.boxWidth+"px":"auto"]); } } _58.ss.add(_6c); _58.ss.dirty(_58.cellSelectorPrefix); _58.cellSelectorPrefix="."+_58.cellClassPrefix; }; }; function _70(_71){ var _72=$.data(_71,"datagrid"); var _73=_72.panel; var _74=_72.options; var dc=_72.dc; var _75=dc.header1.add(dc.header2); _75.find("input[type=checkbox]").unbind(".datagrid").bind("click.datagrid",function(e){ if(_74.singleSelect&&_74.selectOnCheck){ return false; } if($(this).is(":checked")){ _106(_71); }else{ _10c(_71); } e.stopPropagation(); }); var _76=_75.find("div.datagrid-cell"); _76.closest("td").unbind(".datagrid").bind("mouseenter.datagrid",function(){ if(_72.resizing){ return; } $(this).addClass("datagrid-header-over"); }).bind("mouseleave.datagrid",function(){ $(this).removeClass("datagrid-header-over"); }).bind("contextmenu.datagrid",function(e){ var _77=$(this).attr("field"); _74.onHeaderContextMenu.call(_71,e,_77); }); _76.unbind(".datagrid").bind("click.datagrid",function(e){ var p1=$(this).offset().left+5; var p2=$(this).offset().left+$(this)._outerWidth()-5; if(e.pageX<p2&&e.pageX>p1){ var _78=$(this).parent().attr("field"); var col=_6f(_71,_78); if(!col.sortable||_72.resizing){ return; } var _79=[]; var _7a=[]; if(_74.sortName){ _79=_74.sortName.split(","); _7a=_74.sortOrder.split(","); } var pos=_2(_79,_78); var _7b=col.order||"asc"; if(pos>=0){ $(this).removeClass("datagrid-sort-asc datagrid-sort-desc"); var _7c=_7a[pos]=="asc"?"desc":"asc"; if(_74.multiSort&&_7c==_7b){ _79.splice(pos,1); _7a.splice(pos,1); }else{ _7a[pos]=_7c; $(this).addClass("datagrid-sort-"+_7c); } }else{ if(_74.multiSort){ _79.push(_78); _7a.push(_7b); }else{ _79=[_78]; _7a=[_7b]; _76.removeClass("datagrid-sort-asc datagrid-sort-desc"); } $(this).addClass("datagrid-sort-"+_7b); } _74.sortName=_79.join(","); _74.sortOrder=_7a.join(","); if(_74.remoteSort){ _16b(_71); }else{ var _7d=$.data(_71,"datagrid").data; _c6(_71,_7d); } _74.onSortColumn.call(_71,_74.sortName,_74.sortOrder); } }).bind("dblclick.datagrid",function(e){ var p1=$(this).offset().left+5; var p2=$(this).offset().left+$(this)._outerWidth()-5; var _7e=_74.resizeHandle=="right"?(e.pageX>p2):(_74.resizeHandle=="left"?(e.pageX<p1):(e.pageX<p1||e.pageX>p2)); if(_7e){ var _7f=$(this).parent().attr("field"); var col=_6f(_71,_7f); if(col.resizable==false){ return; } $(_71).datagrid("autoSizeColumn",_7f); col.auto=false; } }); var _80=_74.resizeHandle=="right"?"e":(_74.resizeHandle=="left"?"w":"e,w"); _76.each(function(){ $(this).resizable({handles:_80,disabled:($(this).attr("resizable")?$(this).attr("resizable")=="false":false),minWidth:25,onStartResize:function(e){ _72.resizing=true; _75.css("cursor",$("body").css("cursor")); if(!_72.proxy){ _72.proxy=$("<div class=\"datagrid-resize-proxy\"></div>").appendTo(dc.view); } _72.proxy.css({left:e.pageX-$(_73).offset().left-1,display:"none"}); setTimeout(function(){ if(_72.proxy){ _72.proxy.show(); } },500); },onResize:function(e){ _72.proxy.css({left:e.pageX-$(_73).offset().left-1,display:"block"}); return false; },onStopResize:function(e){ _75.css("cursor",""); $(this).css("height",""); $(this)._outerWidth($(this)._outerWidth()); var _81=$(this).parent().attr("field"); var col=_6f(_71,_81); col.width=$(this)._outerWidth(); col.boxWidth=parseInt(this.style.width); col.auto=undefined; $(this).css("width",""); _51(_71,_81); _72.proxy.remove(); _72.proxy=null; if($(this).parents("div:first.datagrid-header").parent().hasClass("datagrid-view1")){ _1e(_71); } _8d(_71); _74.onResizeColumn.call(_71,_81,col.width); setTimeout(function(){ _72.resizing=false; },0); }}); }); dc.body1.add(dc.body2).unbind().bind("mouseover",function(e){ if(_72.resizing){ return; } var tr=$(e.target).closest("tr.datagrid-row"); if(!_82(tr)){ return; } var _83=_84(tr); _eb(_71,_83); e.stopPropagation(); }).bind("mouseout",function(e){ var tr=$(e.target).closest("tr.datagrid-row"); if(!_82(tr)){ return; } var _85=_84(tr); _74.finder.getTr(_71,_85).removeClass("datagrid-row-over"); e.stopPropagation(); }).bind("click",function(e){ var tt=$(e.target); var tr=tt.closest("tr.datagrid-row"); if(!_82(tr)){ return; } var _86=_84(tr); if(tt.parent().hasClass("datagrid-cell-check")){ if(_74.singleSelect&&_74.selectOnCheck){ if(!_74.checkOnSelect){ _10c(_71,true); } _f8(_71,_86); }else{ if(tt.is(":checked")){ _f8(_71,_86); }else{ _100(_71,_86); } } }else{ var row=_74.finder.getRow(_71,_86); var td=tt.closest("td[field]",tr); if(td.length){ var _87=td.attr("field"); _74.onClickCell.call(_71,_86,_87,row[_87]); } if(_74.singleSelect==true){ _f0(_71,_86); }else{ if(tr.hasClass("datagrid-row-selected")){ _f9(_71,_86); }else{ _f0(_71,_86); } } _74.onClickRow.call(_71,_86,row); } e.stopPropagation(); }).bind("dblclick",function(e){ var tt=$(e.target); var tr=tt.closest("tr.datagrid-row"); if(!_82(tr)){ return; } var _88=_84(tr); var row=_74.finder.getRow(_71,_88); var td=tt.closest("td[field]",tr); if(td.length){ var _89=td.attr("field"); _74.onDblClickCell.call(_71,_88,_89,row[_89]); } _74.onDblClickRow.call(_71,_88,row); e.stopPropagation(); }).bind("contextmenu",function(e){ var tr=$(e.target).closest("tr.datagrid-row"); if(!_82(tr)){ return; } var _8a=_84(tr); var row=_74.finder.getRow(_71,_8a); _74.onRowContextMenu.call(_71,e,_8a,row); e.stopPropagation(); }); dc.body2.bind("scroll",function(){ var b1=dc.view1.children("div.datagrid-body"); b1.scrollTop($(this).scrollTop()); var c1=dc.body1.children(":first"); var c2=dc.body2.children(":first"); if(c1.length&&c2.length){ var _8b=c1.offset().top; var _8c=c2.offset().top; if(_8b!=_8c){ b1.scrollTop(b1.scrollTop()+_8b-_8c); } } dc.view2.children("div.datagrid-header,div.datagrid-footer")._scrollLeft($(this)._scrollLeft()); dc.body2.children("table.datagrid-btable-frozen").css("left",-$(this)._scrollLeft()); }); function _84(tr){ if(tr.attr("datagrid-row-index")){ return parseInt(tr.attr("datagrid-row-index")); }else{ return tr.attr("node-id"); } }; function _82(tr){ return tr.length&&tr.parent().length; }; }; function _8d(_8e){ var _8f=$.data(_8e,"datagrid"); var _90=_8f.options; var dc=_8f.dc; dc.body2.css("overflow-x",_90.fitColumns?"hidden":""); if(!_90.fitColumns){ return; } if(!_8f.leftWidth){ _8f.leftWidth=0; } var _91=dc.view2.children("div.datagrid-header"); var _92=0; var _93; var _94=_6e(_8e,false); for(var i=0;i<_94.length;i++){ var col=_6f(_8e,_94[i]); if(_95(col)){ _92+=col.width; _93=col; } } if(!_92){ return; } if(_93){ _96(_93,-_8f.leftWidth); } var _97=_91.children("div.datagrid-header-inner").show(); var _98=_91.width()-_91.find("table").width()-_90.scrollbarSize+_8f.leftWidth; var _99=_98/_92; if(!_90.showHeader){ _97.hide(); } for(var i=0;i<_94.length;i++){ var col=_6f(_8e,_94[i]); if(_95(col)){ var _9a=parseInt(col.width*_99); _96(col,_9a); _98-=_9a; } } _8f.leftWidth=_98; if(_93){ _96(_93,_8f.leftWidth); } _51(_8e); function _96(col,_9b){ col.width+=_9b; col.boxWidth+=_9b; }; function _95(col){ if(!col.hidden&&!col.checkbox&&!col.auto&&!col.fixed){ return true; } }; }; function _9c(_9d,_9e){ var _9f=$.data(_9d,"datagrid"); var _a0=_9f.options; var dc=_9f.dc; var tmp=$("<div class=\"datagrid-cell\" style=\"position:absolute;left:-9999px\"></div>").appendTo("body"); if(_9e){ _19(_9e); if(_a0.fitColumns){ _1e(_9d); _8d(_9d); } }else{ var _a1=false; var _a2=_6e(_9d,true).concat(_6e(_9d,false)); for(var i=0;i<_a2.length;i++){ var _9e=_a2[i]; var col=_6f(_9d,_9e); if(col.auto){ _19(_9e); _a1=true; } } if(_a1&&_a0.fitColumns){ _1e(_9d); _8d(_9d); } } tmp.remove(); function _19(_a3){ var _a4=dc.view.find("div.datagrid-header td[field=\""+_a3+"\"] div.datagrid-cell"); _a4.css("width",""); var col=$(_9d).datagrid("getColumnOption",_a3); col.width=undefined; col.boxWidth=undefined; col.auto=true; $(_9d).datagrid("fixColumnSize",_a3); var _a5=Math.max(_a6("header"),_a6("allbody"),_a6("allfooter")); _a4._outerWidth(_a5); col.width=_a5; col.boxWidth=parseInt(_a4[0].style.width); _a4.css("width",""); $(_9d).datagrid("fixColumnSize",_a3); _a0.onResizeColumn.call(_9d,_a3,col.width); function _a6(_a7){ var _a8=0; if(_a7=="header"){ _a8=_a9(_a4); }else{ _a0.finder.getTr(_9d,0,_a7).find("td[field=\""+_a3+"\"] div.datagrid-cell").each(function(){ var w=_a9($(this)); if(_a8<w){ _a8=w; } }); } return _a8; function _a9(_aa){ return _aa.is(":visible")?_aa._outerWidth():tmp.html(_aa.html())._outerWidth(); }; }; }; }; function _51(_ab,_ac){ var _ad=$.data(_ab,"datagrid"); var _ae=_ad.options; var dc=_ad.dc; var _af=dc.view.find("table.datagrid-btable,table.datagrid-ftable"); _af.css("table-layout","fixed"); if(_ac){ fix(_ac); }else{ var ff=_6e(_ab,true).concat(_6e(_ab,false)); for(var i=0;i<ff.length;i++){ fix(ff[i]); } } _af.css("table-layout","auto"); _b0(_ab); setTimeout(function(){ _2e(_ab); _b5(_ab); },0); function fix(_b1){ var col=_6f(_ab,_b1); if(!col.checkbox){ _ad.ss.set("."+col.cellClass,col.boxWidth?col.boxWidth+"px":"auto"); } }; }; function _b0(_b2){ var dc=$.data(_b2,"datagrid").dc; dc.body1.add(dc.body2).find("td.datagrid-td-merged").each(function(){ var td=$(this); var _b3=td.attr("colspan")||1; var _b4=_6f(_b2,td.attr("field")).width; for(var i=1;i<_b3;i++){ td=td.next(); _b4+=_6f(_b2,td.attr("field")).width+1; } $(this).children("div.datagrid-cell")._outerWidth(_b4); }); }; function _b5(_b6){ var dc=$.data(_b6,"datagrid").dc; dc.view.find("div.datagrid-editable").each(function(){ var _b7=$(this); var _b8=_b7.parent().attr("field"); var col=$(_b6).datagrid("getColumnOption",_b8); _b7._outerWidth(col.width); var ed=$.data(this,"datagrid.editor"); if(ed.actions.resize){ ed.actions.resize(ed.target,_b7.width()); } }); }; function _6f(_b9,_ba){ function _bb(_bc){ if(_bc){ for(var i=0;i<_bc.length;i++){ var cc=_bc[i]; for(var j=0;j<cc.length;j++){ var c=cc[j]; if(c.field==_ba){ return c; } } } } return null; }; var _bd=$.data(_b9,"datagrid").options; var col=_bb(_bd.columns); if(!col){ col=_bb(_bd.frozenColumns); } return col; }; function _6e(_be,_bf){ var _c0=$.data(_be,"datagrid").options; var _c1=(_bf==true)?(_c0.frozenColumns||[[]]):_c0.columns; if(_c1.length==0){ return []; } var _c2=[]; function _c3(_c4){ var c=0; var i=0; while(true){ if(_c2[i]==undefined){ if(c==_c4){ return i; } c++; } i++; } }; function _c5(r){ var ff=[]; var c=0; for(var i=0;i<_c1[r].length;i++){ var col=_c1[r][i]; if(col.field){ ff.push([c,col.field]); } c+=parseInt(col.colspan||"1"); } for(var i=0;i<ff.length;i++){ ff[i][0]=_c3(ff[i][0]); } for(var i=0;i<ff.length;i++){ var f=ff[i]; _c2[f[0]]=f[1]; } }; for(var i=0;i<_c1.length;i++){ _c5(i); } return _c2; }; function _c6(_c7,_c8){ var _c9=$.data(_c7,"datagrid"); var _ca=_c9.options; var dc=_c9.dc; _c8=_ca.loadFilter.call(_c7,_c8); _c8.total=parseInt(_c8.total); _c9.data=_c8; if(_c8.footer){ _c9.footer=_c8.footer; } if(!_ca.remoteSort&&_ca.sortName){ var _cb=_ca.sortName.split(","); var _cc=_ca.sortOrder.split(","); _c8.rows.sort(function(r1,r2){ var r=0; for(var i=0;i<_cb.length;i++){ var sn=_cb[i]; var so=_cc[i]; var col=_6f(_c7,sn); var _cd=col.sorter||function(a,b){ return a==b?0:(a>b?1:-1); }; r=_cd(r1[sn],r2[sn])*(so=="asc"?1:-1); if(r!=0){ return r; } } return r; }); } if(_ca.view.onBeforeRender){ _ca.view.onBeforeRender.call(_ca.view,_c7,_c8.rows); } _ca.view.render.call(_ca.view,_c7,dc.body2,false); _ca.view.render.call(_ca.view,_c7,dc.body1,true); if(_ca.showFooter){ _ca.view.renderFooter.call(_ca.view,_c7,dc.footer2,false); _ca.view.renderFooter.call(_ca.view,_c7,dc.footer1,true); } if(_ca.view.onAfterRender){ _ca.view.onAfterRender.call(_ca.view,_c7); } _c9.ss.clean(); _ca.onLoadSuccess.call(_c7,_c8); var _ce=$(_c7).datagrid("getPager"); if(_ce.length){ var _cf=_ce.pagination("options"); if(_cf.total!=_c8.total){ _ce.pagination("refresh",{total:_c8.total}); if(_ca.pageNumber!=_cf.pageNumber){ _ca.pageNumber=_cf.pageNumber; _16b(_c7); } } } _2e(_c7); dc.body2.triggerHandler("scroll"); _d0(); $(_c7).datagrid("autoSizeColumn"); function _d0(){ if(_ca.idField){ for(var i=0;i<_c8.rows.length;i++){ var row=_c8.rows[i]; if(_d1(_c9.selectedRows,row)){ _ca.finder.getTr(_c7,i).addClass("datagrid-row-selected"); } if(_d1(_c9.checkedRows,row)){ _ca.finder.getTr(_c7,i).find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true); } } } function _d1(a,r){ for(var i=0;i<a.length;i++){ if(a[i][_ca.idField]==r[_ca.idField]){ a[i]=r; return true; } } return false; }; }; }; function _d2(_d3,row){ var _d4=$.data(_d3,"datagrid"); var _d5=_d4.options; var _d6=_d4.data.rows; if(typeof row=="object"){ return _2(_d6,row); }else{ for(var i=0;i<_d6.length;i++){ if(_d6[i][_d5.idField]==row){ return i; } } return -1; } }; function _d7(_d8){ var _d9=$.data(_d8,"datagrid"); var _da=_d9.options; var _db=_d9.data; if(_da.idField){ return _d9.selectedRows; }else{ var _dc=[]; _da.finder.getTr(_d8,"","selected",2).each(function(){ var _dd=parseInt($(this).attr("datagrid-row-index")); _dc.push(_db.rows[_dd]); }); return _dc; } }; function _de(_df){ var _e0=$.data(_df,"datagrid"); var _e1=_e0.options; if(_e1.idField){ return _e0.checkedRows; }else{ var _e2=[]; _e1.finder.getTr(_df,"","checked",2).each(function(){ _e2.push(_e1.finder.getRow(_df,$(this))); }); return _e2; } }; function _e3(_e4,_e5){ var _e6=$.data(_e4,"datagrid"); var dc=_e6.dc; var _e7=_e6.options; var tr=_e7.finder.getTr(_e4,_e5); if(tr.length){ if(tr.closest("table").hasClass("datagrid-btable-frozen")){ return; } var _e8=dc.view2.children("div.datagrid-header")._outerHeight(); var _e9=dc.body2; var _ea=_e9.outerHeight(true)-_e9.outerHeight(); var top=tr.position().top-_e8-_ea; if(top<0){ _e9.scrollTop(_e9.scrollTop()+top); }else{ if(top+tr._outerHeight()>_e9.height()-18){ _e9.scrollTop(_e9.scrollTop()+top+tr._outerHeight()-_e9.height()+18); } } } }; function _eb(_ec,_ed){ var _ee=$.data(_ec,"datagrid"); var _ef=_ee.options; _ef.finder.getTr(_ec,_ee.highlightIndex).removeClass("datagrid-row-over"); _ef.finder.getTr(_ec,_ed).addClass("datagrid-row-over"); _ee.highlightIndex=_ed; }; function _f0(_f1,_f2,_f3){ var _f4=$.data(_f1,"datagrid"); var dc=_f4.dc; var _f5=_f4.options; var _f6=_f4.selectedRows; if(_f5.singleSelect){ _f7(_f1); _f6.splice(0,_f6.length); } if(!_f3&&_f5.checkOnSelect){ _f8(_f1,_f2,true); } var row=_f5.finder.getRow(_f1,_f2); if(_f5.idField){ _7(_f6,_f5.idField,row); } _f5.finder.getTr(_f1,_f2).addClass("datagrid-row-selected"); _f5.onSelect.call(_f1,_f2,row); _e3(_f1,_f2); }; function _f9(_fa,_fb,_fc){ var _fd=$.data(_fa,"datagrid"); var dc=_fd.dc; var _fe=_fd.options; var _ff=$.data(_fa,"datagrid").selectedRows; if(!_fc&&_fe.checkOnSelect){ _100(_fa,_fb,true); } _fe.finder.getTr(_fa,_fb).removeClass("datagrid-row-selected"); var row=_fe.finder.getRow(_fa,_fb); if(_fe.idField){ _4(_ff,_fe.idField,row[_fe.idField]); } _fe.onUnselect.call(_fa,_fb,row); }; function _101(_102,_103){ var _104=$.data(_102,"datagrid"); var opts=_104.options; var rows=_104.data.rows; var _105=$.data(_102,"datagrid").selectedRows; if(!_103&&opts.checkOnSelect){ _106(_102,true); } opts.finder.getTr(_102,"","allbody").addClass("datagrid-row-selected"); if(opts.idField){ for(var _107=0;_107<rows.length;_107++){ _7(_105,opts.idField,rows[_107]); } } opts.onSelectAll.call(_102,rows); }; function _f7(_108,_109){ var _10a=$.data(_108,"datagrid"); var opts=_10a.options; var rows=_10a.data.rows; var _10b=$.data(_108,"datagrid").selectedRows; if(!_109&&opts.checkOnSelect){ _10c(_108,true); } opts.finder.getTr(_108,"","selected").removeClass("datagrid-row-selected"); if(opts.idField){ for(var _10d=0;_10d<rows.length;_10d++){ _4(_10b,opts.idField,rows[_10d][opts.idField]); } } opts.onUnselectAll.call(_108,rows); }; function _f8(_10e,_10f,_110){ var _111=$.data(_10e,"datagrid"); var opts=_111.options; if(!_110&&opts.selectOnCheck){ _f0(_10e,_10f,true); } var tr=opts.finder.getTr(_10e,_10f).addClass("datagrid-row-checked"); var ck=tr.find("div.datagrid-cell-check input[type=checkbox]"); ck._propAttr("checked",true); tr=opts.finder.getTr(_10e,"","checked",2); if(tr.length==_111.data.rows.length){ var dc=_111.dc; var _112=dc.header1.add(dc.header2); _112.find("input[type=checkbox]")._propAttr("checked",true); } var row=opts.finder.getRow(_10e,_10f); if(opts.idField){ _7(_111.checkedRows,opts.idField,row); } opts.onCheck.call(_10e,_10f,row); }; function _100(_113,_114,_115){ var _116=$.data(_113,"datagrid"); var opts=_116.options; if(!_115&&opts.selectOnCheck){ _f9(_113,_114,true); } var tr=opts.finder.getTr(_113,_114).removeClass("datagrid-row-checked"); var ck=tr.find("div.datagrid-cell-check input[type=checkbox]"); ck._propAttr("checked",false); var dc=_116.dc; var _117=dc.header1.add(dc.header2); _117.find("input[type=checkbox]")._propAttr("checked",false); var row=opts.finder.getRow(_113,_114); if(opts.idField){ _4(_116.checkedRows,opts.idField,row[opts.idField]); } opts.onUncheck.call(_113,_114,row); }; function _106(_118,_119){ var _11a=$.data(_118,"datagrid"); var opts=_11a.options; var rows=_11a.data.rows; if(!_119&&opts.selectOnCheck){ _101(_118,true); } var dc=_11a.dc; var hck=dc.header1.add(dc.header2).find("input[type=checkbox]"); var bck=opts.finder.getTr(_118,"","allbody").addClass("datagrid-row-checked").find("div.datagrid-cell-check input[type=checkbox]"); hck.add(bck)._propAttr("checked",true); if(opts.idField){ for(var i=0;i<rows.length;i++){ _7(_11a.checkedRows,opts.idField,rows[i]); } } opts.onCheckAll.call(_118,rows); }; function _10c(_11b,_11c){ var _11d=$.data(_11b,"datagrid"); var opts=_11d.options; var rows=_11d.data.rows; if(!_11c&&opts.selectOnCheck){ _f7(_11b,true); } var dc=_11d.dc; var hck=dc.header1.add(dc.header2).find("input[type=checkbox]"); var bck=opts.finder.getTr(_11b,"","checked").removeClass("datagrid-row-checked").find("div.datagrid-cell-check input[type=checkbox]"); hck.add(bck)._propAttr("checked",false); if(opts.idField){ for(var i=0;i<rows.length;i++){ _4(_11d.checkedRows,opts.idField,rows[i][opts.idField]); } } opts.onUncheckAll.call(_11b,rows); }; function _11e(_11f,_120){ var opts=$.data(_11f,"datagrid").options; var tr=opts.finder.getTr(_11f,_120); var row=opts.finder.getRow(_11f,_120); if(tr.hasClass("datagrid-row-editing")){ return; } if(opts.onBeforeEdit.call(_11f,_120,row)==false){ return; } tr.addClass("datagrid-row-editing"); _121(_11f,_120); _b5(_11f); tr.find("div.datagrid-editable").each(function(){ var _122=$(this).parent().attr("field"); var ed=$.data(this,"datagrid.editor"); ed.actions.setValue(ed.target,row[_122]); }); _123(_11f,_120); }; function _124(_125,_126,_127){ var opts=$.data(_125,"datagrid").options; var _128=$.data(_125,"datagrid").updatedRows; var _129=$.data(_125,"datagrid").insertedRows; var tr=opts.finder.getTr(_125,_126); var row=opts.finder.getRow(_125,_126); if(!tr.hasClass("datagrid-row-editing")){ return; } if(!_127){ if(!_123(_125,_126)){ return; } var _12a=false; var _12b={}; tr.find("div.datagrid-editable").each(function(){ var _12c=$(this).parent().attr("field"); var ed=$.data(this,"datagrid.editor"); var _12d=ed.actions.getValue(ed.target); if(row[_12c]!=_12d){ row[_12c]=_12d; _12a=true; _12b[_12c]=_12d; } }); if(_12a){ if(_2(_129,row)==-1){ if(_2(_128,row)==-1){ _128.push(row); } } } } tr.removeClass("datagrid-row-editing"); _12e(_125,_126); $(_125).datagrid("refreshRow",_126); if(!_127){ opts.onAfterEdit.call(_125,_126,row,_12b); }else{ opts.onCancelEdit.call(_125,_126,row); } }; function _12f(_130,_131){ var opts=$.data(_130,"datagrid").options; var tr=opts.finder.getTr(_130,_131); var _132=[]; tr.children("td").each(function(){ var cell=$(this).find("div.datagrid-editable"); if(cell.length){ var ed=$.data(cell[0],"datagrid.editor"); _132.push(ed); } }); return _132; }; function _133(_134,_135){ var _136=_12f(_134,_135.index!=undefined?_135.index:_135.id); for(var i=0;i<_136.length;i++){ if(_136[i].field==_135.field){ return _136[i]; } } return null; }; function _121(_137,_138){ var opts=$.data(_137,"datagrid").options; var tr=opts.finder.getTr(_137,_138); tr.children("td").each(function(){ var cell=$(this).find("div.datagrid-cell"); var _139=$(this).attr("field"); var col=_6f(_137,_139); if(col&&col.editor){ var _13a,_13b; if(typeof col.editor=="string"){ _13a=col.editor; }else{ _13a=col.editor.type; _13b=col.editor.options; } var _13c=opts.editors[_13a]; if(_13c){ var _13d=cell.html(); var _13e=cell._outerWidth(); cell.addClass("datagrid-editable"); cell._outerWidth(_13e); cell.html("<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\"><tr><td></td></tr></table>"); cell.children("table").bind("click dblclick contextmenu",function(e){ e.stopPropagation(); }); $.data(cell[0],"datagrid.editor",{actions:_13c,target:_13c.init(cell.find("td"),_13b),field:_139,type:_13a,oldHtml:_13d}); } } }); _2e(_137,_138,true); }; function _12e(_13f,_140){ var opts=$.data(_13f,"datagrid").options; var tr=opts.finder.getTr(_13f,_140); tr.children("td").each(function(){ var cell=$(this).find("div.datagrid-editable"); if(cell.length){ var ed=$.data(cell[0],"datagrid.editor"); if(ed.actions.destroy){ ed.actions.destroy(ed.target); } cell.html(ed.oldHtml); $.removeData(cell[0],"datagrid.editor"); cell.removeClass("datagrid-editable"); cell.css("width",""); } }); }; function _123(_141,_142){ var tr=$.data(_141,"datagrid").options.finder.getTr(_141,_142); if(!tr.hasClass("datagrid-row-editing")){ return true; } var vbox=tr.find(".validatebox-text"); vbox.validatebox("validate"); vbox.trigger("mouseleave"); var _143=tr.find(".validatebox-invalid"); return _143.length==0; }; function _144(_145,_146){ var _147=$.data(_145,"datagrid").insertedRows; var _148=$.data(_145,"datagrid").deletedRows; var _149=$.data(_145,"datagrid").updatedRows; if(!_146){ var rows=[]; rows=rows.concat(_147); rows=rows.concat(_148); rows=rows.concat(_149); return rows; }else{ if(_146=="inserted"){ return _147; }else{ if(_146=="deleted"){ return _148; }else{ if(_146=="updated"){ return _149; } } } } return []; }; function _14a(_14b,_14c){ var _14d=$.data(_14b,"datagrid"); var opts=_14d.options; var data=_14d.data; var _14e=_14d.insertedRows; var _14f=_14d.deletedRows; $(_14b).datagrid("cancelEdit",_14c); var row=data.rows[_14c]; if(_2(_14e,row)>=0){ _4(_14e,row); }else{ _14f.push(row); } _4(_14d.selectedRows,opts.idField,data.rows[_14c][opts.idField]); _4(_14d.checkedRows,opts.idField,data.rows[_14c][opts.idField]); opts.view.deleteRow.call(opts.view,_14b,_14c); if(opts.height=="auto"){ _2e(_14b); } $(_14b).datagrid("getPager").pagination("refresh",{total:data.total}); }; function _150(_151,_152){ var data=$.data(_151,"datagrid").data; var view=$.data(_151,"datagrid").options.view; var _153=$.data(_151,"datagrid").insertedRows; view.insertRow.call(view,_151,_152.index,_152.row); _153.push(_152.row); $(_151).datagrid("getPager").pagination("refresh",{total:data.total}); }; function _154(_155,row){ var data=$.data(_155,"datagrid").data; var view=$.data(_155,"datagrid").options.view; var _156=$.data(_155,"datagrid").insertedRows; view.insertRow.call(view,_155,null,row); _156.push(row); $(_155).datagrid("getPager").pagination("refresh",{total:data.total}); }; function _157(_158){ var _159=$.data(_158,"datagrid"); var data=_159.data; var rows=data.rows; var _15a=[]; for(var i=0;i<rows.length;i++){ _15a.push($.extend({},rows[i])); } _159.originalRows=_15a; _159.updatedRows=[]; _159.insertedRows=[]; _159.deletedRows=[]; }; function _15b(_15c){ var data=$.data(_15c,"datagrid").data; var ok=true; for(var i=0,len=data.rows.length;i<len;i++){ if(_123(_15c,i)){ _124(_15c,i,false); }else{ ok=false; } } if(ok){ _157(_15c); } }; function _15d(_15e){ var _15f=$.data(_15e,"datagrid"); var opts=_15f.options; var _160=_15f.originalRows; var _161=_15f.insertedRows; var _162=_15f.deletedRows; var _163=_15f.selectedRows; var _164=_15f.checkedRows; var data=_15f.data; function _165(a){ var ids=[]; for(var i=0;i<a.length;i++){ ids.push(a[i][opts.idField]); } return ids; }; function _166(ids,_167){ for(var i=0;i<ids.length;i++){ var _168=_d2(_15e,ids[i]); if(_168>=0){ (_167=="s"?_f0:_f8)(_15e,_168,true); } } }; for(var i=0;i<data.rows.length;i++){ _124(_15e,i,true); } var _169=_165(_163); var _16a=_165(_164); _163.splice(0,_163.length); _164.splice(0,_164.length); data.total+=_162.length-_161.length; data.rows=_160; _c6(_15e,data); _166(_169,"s"); _166(_16a,"c"); _157(_15e); }; function _16b(_16c,_16d){ var opts=$.data(_16c,"datagrid").options; if(_16d){ opts.queryParams=_16d; } var _16e=$.extend({},opts.queryParams); if(opts.pagination){ $.extend(_16e,{page:opts.pageNumber,rows:opts.pageSize}); } if(opts.sortName){ $.extend(_16e,{sort:opts.sortName,order:opts.sortOrder}); } if(opts.onBeforeLoad.call(_16c,_16e)==false){ return; } $(_16c).datagrid("loading"); setTimeout(function(){ _16f(); },0); function _16f(){ var _170=opts.loader.call(_16c,_16e,function(data){ setTimeout(function(){ $(_16c).datagrid("loaded"); },0); _c6(_16c,data); setTimeout(function(){ _157(_16c); },0); },function(){ setTimeout(function(){ $(_16c).datagrid("loaded"); },0); opts.onLoadError.apply(_16c,arguments); }); if(_170==false){ $(_16c).datagrid("loaded"); } }; }; function _171(_172,_173){ var opts=$.data(_172,"datagrid").options; _173.rowspan=_173.rowspan||1; _173.colspan=_173.colspan||1; if(_173.rowspan==1&&_173.colspan==1){ return; } var tr=opts.finder.getTr(_172,(_173.index!=undefined?_173.index:_173.id)); if(!tr.length){ return; } var row=opts.finder.getRow(_172,tr); var _174=row[_173.field]; var td=tr.find("td[field=\""+_173.field+"\"]"); td.attr("rowspan",_173.rowspan).attr("colspan",_173.colspan); td.addClass("datagrid-td-merged"); for(var i=1;i<_173.colspan;i++){ td=td.next(); td.hide(); row[td.attr("field")]=_174; } for(var i=1;i<_173.rowspan;i++){ tr=tr.next(); if(!tr.length){ break; } var row=opts.finder.getRow(_172,tr); var td=tr.find("td[field=\""+_173.field+"\"]").hide(); row[td.attr("field")]=_174; for(var j=1;j<_173.colspan;j++){ td=td.next(); td.hide(); row[td.attr("field")]=_174; } } _b0(_172); }; $.fn.datagrid=function(_175,_176){ if(typeof _175=="string"){ return $.fn.datagrid.methods[_175](this,_176); } _175=_175||{}; return this.each(function(){ var _177=$.data(this,"datagrid"); var opts; if(_177){ opts=$.extend(_177.options,_175); _177.options=opts; }else{ opts=$.extend({},$.extend({},$.fn.datagrid.defaults,{queryParams:{}}),$.fn.datagrid.parseOptions(this),_175); $(this).css("width","").css("height",""); var _178=_47(this,opts.rownumbers); if(!opts.columns){ opts.columns=_178.columns; } if(!opts.frozenColumns){ opts.frozenColumns=_178.frozenColumns; } opts.columns=$.extend(true,[],opts.columns); opts.frozenColumns=$.extend(true,[],opts.frozenColumns); opts.view=$.extend({},opts.view); $.data(this,"datagrid",{options:opts,panel:_178.panel,dc:_178.dc,ss:_178.ss,selectedRows:[],checkedRows:[],data:{total:0,rows:[]},originalRows:[],updatedRows:[],insertedRows:[],deletedRows:[]}); } _56(this); if(opts.data){ _c6(this,opts.data); _157(this); }else{ var data=$.fn.datagrid.parseData(this); if(data.total>0){ _c6(this,data); _157(this); } } _19(this); _16b(this); _70(this); }); }; var _179={text:{init:function(_17a,_17b){ var _17c=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_17a); return _17c; },getValue:function(_17d){ return $(_17d).val(); },setValue:function(_17e,_17f){ $(_17e).val(_17f); },resize:function(_180,_181){ $(_180)._outerWidth(_181)._outerHeight(22); }},textarea:{init:function(_182,_183){ var _184=$("<textarea class=\"datagrid-editable-input\"></textarea>").appendTo(_182); return _184; },getValue:function(_185){ return $(_185).val(); },setValue:function(_186,_187){ $(_186).val(_187); },resize:function(_188,_189){ $(_188)._outerWidth(_189); }},checkbox:{init:function(_18a,_18b){ var _18c=$("<input type=\"checkbox\">").appendTo(_18a); _18c.val(_18b.on); _18c.attr("offval",_18b.off); return _18c; },getValue:function(_18d){ if($(_18d).is(":checked")){ return $(_18d).val(); }else{ return $(_18d).attr("offval"); } },setValue:function(_18e,_18f){ var _190=false; if($(_18e).val()==_18f){ _190=true; } $(_18e)._propAttr("checked",_190); }},numberbox:{init:function(_191,_192){ var _193=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_191); _193.numberbox(_192); return _193; },destroy:function(_194){ $(_194).numberbox("destroy"); },getValue:function(_195){ $(_195).blur(); return $(_195).numberbox("getValue"); },setValue:function(_196,_197){ $(_196).numberbox("setValue",_197); },resize:function(_198,_199){ $(_198)._outerWidth(_199)._outerHeight(22); }},validatebox:{init:function(_19a,_19b){ var _19c=$("<input type=\"text\" class=\"datagrid-editable-input\">").appendTo(_19a); _19c.validatebox(_19b); return _19c; },destroy:function(_19d){ $(_19d).validatebox("destroy"); },getValue:function(_19e){ return $(_19e).val(); },setValue:function(_19f,_1a0){ $(_19f).val(_1a0); },resize:function(_1a1,_1a2){ $(_1a1)._outerWidth(_1a2)._outerHeight(22); }},datebox:{init:function(_1a3,_1a4){ var _1a5=$("<input type=\"text\">").appendTo(_1a3); _1a5.datebox(_1a4); return _1a5; },destroy:function(_1a6){ $(_1a6).datebox("destroy"); },getValue:function(_1a7){ return $(_1a7).datebox("getValue"); },setValue:function(_1a8,_1a9){ $(_1a8).datebox("setValue",_1a9); },resize:function(_1aa,_1ab){ $(_1aa).datebox("resize",_1ab); }},combobox:{init:function(_1ac,_1ad){ var _1ae=$("<input type=\"text\">").appendTo(_1ac); _1ae.combobox(_1ad||{}); return _1ae; },destroy:function(_1af){ $(_1af).combobox("destroy"); },getValue:function(_1b0){ var opts=$(_1b0).combobox("options"); if(opts.multiple){ return $(_1b0).combobox("getValues").join(opts.separator); }else{ return $(_1b0).combobox("getValue"); } },setValue:function(_1b1,_1b2){ var opts=$(_1b1).combobox("options"); if(opts.multiple){ if(_1b2){ $(_1b1).combobox("setValues",_1b2.split(opts.separator)); }else{ $(_1b1).combobox("clear"); } }else{ $(_1b1).combobox("setValue",_1b2); } },resize:function(_1b3,_1b4){ $(_1b3).combobox("resize",_1b4); }},combotree:{init:function(_1b5,_1b6){ var _1b7=$("<input type=\"text\">").appendTo(_1b5); _1b7.combotree(_1b6); return _1b7; },destroy:function(_1b8){ $(_1b8).combotree("destroy"); },getValue:function(_1b9){ return $(_1b9).combotree("getValue"); },setValue:function(_1ba,_1bb){ $(_1ba).combotree("setValue",_1bb); },resize:function(_1bc,_1bd){ $(_1bc).combotree("resize",_1bd); }}}; $.fn.datagrid.methods={options:function(jq){ var _1be=$.data(jq[0],"datagrid").options; var _1bf=$.data(jq[0],"datagrid").panel.panel("options"); var opts=$.extend(_1be,{width:_1bf.width,height:_1bf.height,closed:_1bf.closed,collapsed:_1bf.collapsed,minimized:_1bf.minimized,maximized:_1bf.maximized}); return opts; },getPanel:function(jq){ return $.data(jq[0],"datagrid").panel; },getPager:function(jq){ return $.data(jq[0],"datagrid").panel.children("div.datagrid-pager"); },getColumnFields:function(jq,_1c0){ return _6e(jq[0],_1c0); },getColumnOption:function(jq,_1c1){ return _6f(jq[0],_1c1); },resize:function(jq,_1c2){ return jq.each(function(){ _19(this,_1c2); }); },load:function(jq,_1c3){ return jq.each(function(){ var opts=$(this).datagrid("options"); opts.pageNumber=1; var _1c4=$(this).datagrid("getPager"); _1c4.pagination("refresh",{pageNumber:1}); _16b(this,_1c3); }); },reload:function(jq,_1c5){ return jq.each(function(){ _16b(this,_1c5); }); },reloadFooter:function(jq,_1c6){ return jq.each(function(){ var opts=$.data(this,"datagrid").options; var dc=$.data(this,"datagrid").dc; if(_1c6){ $.data(this,"datagrid").footer=_1c6; } if(opts.showFooter){ opts.view.renderFooter.call(opts.view,this,dc.footer2,false); opts.view.renderFooter.call(opts.view,this,dc.footer1,true); if(opts.view.onAfterRender){ opts.view.onAfterRender.call(opts.view,this); } $(this).datagrid("fixRowHeight"); } }); },loading:function(jq){ return jq.each(function(){ var opts=$.data(this,"datagrid").options; $(this).datagrid("getPager").pagination("loading"); if(opts.loadMsg){ var _1c7=$(this).datagrid("getPanel"); if(!_1c7.children("div.datagrid-mask").length){ $("<div class=\"datagrid-mask\" style=\"display:block\"></div>").appendTo(_1c7); var msg=$("<div class=\"datagrid-mask-msg\" style=\"display:block;left:50%\"></div>").html(opts.loadMsg).appendTo(_1c7); msg._outerHeight(40); msg.css({marginLeft:(-msg.outerWidth()/2),lineHeight:(msg.height()+"px")}); } } }); },loaded:function(jq){ return jq.each(function(){ $(this).datagrid("getPager").pagination("loaded"); var _1c8=$(this).datagrid("getPanel"); _1c8.children("div.datagrid-mask-msg").remove(); _1c8.children("div.datagrid-mask").remove(); }); },fitColumns:function(jq){ return jq.each(function(){ _8d(this); }); },fixColumnSize:function(jq,_1c9){ return jq.each(function(){ _51(this,_1c9); }); },fixRowHeight:function(jq,_1ca){ return jq.each(function(){ _2e(this,_1ca); }); },freezeRow:function(jq,_1cb){ return jq.each(function(){ _3f(this,_1cb); }); },autoSizeColumn:function(jq,_1cc){ return jq.each(function(){ _9c(this,_1cc); }); },loadData:function(jq,data){ return jq.each(function(){ _c6(this,data); _157(this); }); },getData:function(jq){ return $.data(jq[0],"datagrid").data; },getRows:function(jq){ return $.data(jq[0],"datagrid").data.rows; },getFooterRows:function(jq){ return $.data(jq[0],"datagrid").footer; },getRowIndex:function(jq,id){ return _d2(jq[0],id); },getChecked:function(jq){ return _de(jq[0]); },getSelected:function(jq){ var rows=_d7(jq[0]); return rows.length>0?rows[0]:null; },getSelections:function(jq){ return _d7(jq[0]); },clearSelections:function(jq){ return jq.each(function(){ var _1cd=$.data(this,"datagrid").selectedRows; _1cd.splice(0,_1cd.length); _f7(this); }); },clearChecked:function(jq){ return jq.each(function(){ var _1ce=$.data(this,"datagrid").checkedRows; _1ce.splice(0,_1ce.length); _10c(this); }); },scrollTo:function(jq,_1cf){ return jq.each(function(){ _e3(this,_1cf); }); },highlightRow:function(jq,_1d0){ return jq.each(function(){ _eb(this,_1d0); _e3(this,_1d0); }); },selectAll:function(jq){ return jq.each(function(){ _101(this); }); },unselectAll:function(jq){ return jq.each(function(){ _f7(this); }); },selectRow:function(jq,_1d1){ return jq.each(function(){ _f0(this,_1d1); }); },selectRecord:function(jq,id){ return jq.each(function(){ var opts=$.data(this,"datagrid").options; if(opts.idField){ var _1d2=_d2(this,id); if(_1d2>=0){ $(this).datagrid("selectRow",_1d2); } } }); },unselectRow:function(jq,_1d3){ return jq.each(function(){ _f9(this,_1d3); }); },checkRow:function(jq,_1d4){ return jq.each(function(){ _f8(this,_1d4); }); },uncheckRow:function(jq,_1d5){ return jq.each(function(){ _100(this,_1d5); }); },checkAll:function(jq){ return jq.each(function(){ _106(this); }); },uncheckAll:function(jq){ return jq.each(function(){ _10c(this); }); },beginEdit:function(jq,_1d6){ return jq.each(function(){ _11e(this,_1d6); }); },endEdit:function(jq,_1d7){ return jq.each(function(){ _124(this,_1d7,false); }); },cancelEdit:function(jq,_1d8){ return jq.each(function(){ _124(this,_1d8,true); }); },getEditors:function(jq,_1d9){ return _12f(jq[0],_1d9); },getEditor:function(jq,_1da){ return _133(jq[0],_1da); },refreshRow:function(jq,_1db){ return jq.each(function(){ var opts=$.data(this,"datagrid").options; opts.view.refreshRow.call(opts.view,this,_1db); }); },validateRow:function(jq,_1dc){ return _123(jq[0],_1dc); },updateRow:function(jq,_1dd){ return jq.each(function(){ var opts=$.data(this,"datagrid").options; opts.view.updateRow.call(opts.view,this,_1dd.index,_1dd.row); }); },appendRow:function(jq,row){ return jq.each(function(){ _154(this,row); }); },insertRow:function(jq,_1de){ return jq.each(function(){ _150(this,_1de); }); },deleteRow:function(jq,_1df){ return jq.each(function(){ _14a(this,_1df); }); },getChanges:function(jq,_1e0){ return _144(jq[0],_1e0); },acceptChanges:function(jq){ return jq.each(function(){ _15b(this); }); },rejectChanges:function(jq){ return jq.each(function(){ _15d(this); }); },mergeCells:function(jq,_1e1){ return jq.each(function(){ _171(this,_1e1); }); },showColumn:function(jq,_1e2){ return jq.each(function(){ var _1e3=$(this).datagrid("getPanel"); _1e3.find("td[field=\""+_1e2+"\"]").show(); $(this).datagrid("getColumnOption",_1e2).hidden=false; $(this).datagrid("fitColumns"); }); },hideColumn:function(jq,_1e4){ return jq.each(function(){ var _1e5=$(this).datagrid("getPanel"); _1e5.find("td[field=\""+_1e4+"\"]").hide(); $(this).datagrid("getColumnOption",_1e4).hidden=true; $(this).datagrid("fitColumns"); }); }}; $.fn.datagrid.parseOptions=function(_1e6){ var t=$(_1e6); return $.extend({},$.fn.panel.parseOptions(_1e6),$.parser.parseOptions(_1e6,["url","toolbar","idField","sortName","sortOrder","pagePosition","resizeHandle",{fitColumns:"boolean",autoRowHeight:"boolean",striped:"boolean",nowrap:"boolean"},{rownumbers:"boolean",singleSelect:"boolean",checkOnSelect:"boolean",selectOnCheck:"boolean"},{pagination:"boolean",pageSize:"number",pageNumber:"number"},{multiSort:"boolean",remoteSort:"boolean",showHeader:"boolean",showFooter:"boolean"},{scrollbarSize:"number"}]),{pageList:(t.attr("pageList")?eval(t.attr("pageList")):undefined),loadMsg:(t.attr("loadMsg")!=undefined?t.attr("loadMsg"):undefined),rowStyler:(t.attr("rowStyler")?eval(t.attr("rowStyler")):undefined)}); }; $.fn.datagrid.parseData=function(_1e7){ var t=$(_1e7); var data={total:0,rows:[]}; var _1e8=t.datagrid("getColumnFields",true).concat(t.datagrid("getColumnFields",false)); t.find("tbody tr").each(function(){ data.total++; var row={}; $.extend(row,$.parser.parseOptions(this,["iconCls","state"])); for(var i=0;i<_1e8.length;i++){ row[_1e8[i]]=$(this).find("td:eq("+i+")").html(); } data.rows.push(row); }); return data; }; var _1e9={render:function(_1ea,_1eb,_1ec){ var _1ed=$.data(_1ea,"datagrid"); var opts=_1ed.options; var rows=_1ed.data.rows; var _1ee=$(_1ea).datagrid("getColumnFields",_1ec); if(_1ec){ if(!(opts.rownumbers||(opts.frozenColumns&&opts.frozenColumns.length))){ return; } } var _1ef=["<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<rows.length;i++){ var css=opts.rowStyler?opts.rowStyler.call(_1ea,i,rows[i]):""; var _1f0=""; var _1f1=""; if(typeof css=="string"){ _1f1=css; }else{ if(css){ _1f0=css["class"]||""; _1f1=css["style"]||""; } } var cls="class=\"datagrid-row "+(i%2&&opts.striped?"datagrid-row-alt ":" ")+_1f0+"\""; var _1f2=_1f1?"style=\""+_1f1+"\"":""; var _1f3=_1ed.rowIdPrefix+"-"+(_1ec?1:2)+"-"+i; _1ef.push("<tr id=\""+_1f3+"\" datagrid-row-index=\""+i+"\" "+cls+" "+_1f2+">"); _1ef.push(this.renderRow.call(this,_1ea,_1ee,_1ec,i,rows[i])); _1ef.push("</tr>"); } _1ef.push("</tbody></table>"); $(_1eb).html(_1ef.join("")); },renderFooter:function(_1f4,_1f5,_1f6){ var opts=$.data(_1f4,"datagrid").options; var rows=$.data(_1f4,"datagrid").footer||[]; var _1f7=$(_1f4).datagrid("getColumnFields",_1f6); var _1f8=["<table class=\"datagrid-ftable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"]; for(var i=0;i<rows.length;i++){ _1f8.push("<tr class=\"datagrid-row\" datagrid-row-index=\""+i+"\">"); _1f8.push(this.renderRow.call(this,_1f4,_1f7,_1f6,i,rows[i])); _1f8.push("</tr>"); } _1f8.push("</tbody></table>"); $(_1f5).html(_1f8.join("")); },renderRow:function(_1f9,_1fa,_1fb,_1fc,_1fd){ var opts=$.data(_1f9,"datagrid").options; var cc=[]; if(_1fb&&opts.rownumbers){ var _1fe=_1fc+1; if(opts.pagination){ _1fe+=(opts.pageNumber-1)*opts.pageSize; } cc.push("<td class=\"datagrid-td-rownumber\"><div class=\"datagrid-cell-rownumber\">"+_1fe+"</div></td>"); } for(var i=0;i<_1fa.length;i++){ var _1ff=_1fa[i]; var col=$(_1f9).datagrid("getColumnOption",_1ff); if(col){ var _200=_1fd[_1ff]; var css=col.styler?(col.styler(_200,_1fd,_1fc)||""):""; var _201=""; var _202=""; if(typeof css=="string"){ _202=css; }else{ if(cc){ _201=css["class"]||""; _202=css["style"]||""; } } var cls=_201?"class=\""+_201+"\"":""; var _203=col.hidden?"style=\"display:none;"+_202+"\"":(_202?"style=\""+_202+"\"":""); cc.push("<td field=\""+_1ff+"\" "+cls+" "+_203+">"); if(col.checkbox){ var _203=""; }else{ var _203=_202; if(col.align){ _203+=";text-align:"+col.align+";"; } if(!opts.nowrap){ _203+=";white-space:normal;height:auto;"; }else{ if(opts.autoRowHeight){ _203+=";height:auto;"; } } } cc.push("<div style=\""+_203+"\" "); cc.push(col.checkbox?"class=\"datagrid-cell-check\"":"class=\"datagrid-cell "+col.cellClass+"\""); cc.push(">"); if(col.checkbox){ cc.push("<input type=\"checkbox\" name=\""+_1ff+"\" value=\""+(_200!=undefined?_200:"")+"\">"); }else{ if(col.formatter){ cc.push(col.formatter(_200,_1fd,_1fc)); }else{ cc.push(_200); } } cc.push("</div>"); cc.push("</td>"); } } return cc.join(""); },refreshRow:function(_204,_205){ this.updateRow.call(this,_204,_205,{}); },updateRow:function(_206,_207,row){ var opts=$.data(_206,"datagrid").options; var rows=$(_206).datagrid("getRows"); $.extend(rows[_207],row); var css=opts.rowStyler?opts.rowStyler.call(_206,_207,rows[_207]):""; var _208=""; var _209=""; if(typeof css=="string"){ _209=css; }else{ if(css){ _208=css["class"]||""; _209=css["style"]||""; } } var _208="datagrid-row "+(_207%2&&opts.striped?"datagrid-row-alt ":" ")+_208; function _20a(_20b){ var _20c=$(_206).datagrid("getColumnFields",_20b); var tr=opts.finder.getTr(_206,_207,"body",(_20b?1:2)); var _20d=tr.find("div.datagrid-cell-check input[type=checkbox]").is(":checked"); tr.html(this.renderRow.call(this,_206,_20c,_20b,_207,rows[_207])); tr.attr("style",_209).attr("class",tr.hasClass("datagrid-row-selected")?_208+" datagrid-row-selected":_208); if(_20d){ tr.find("div.datagrid-cell-check input[type=checkbox]")._propAttr("checked",true); } }; _20a.call(this,true); _20a.call(this,false); $(_206).datagrid("fixRowHeight",_207); },insertRow:function(_20e,_20f,row){ var _210=$.data(_20e,"datagrid"); var opts=_210.options; var dc=_210.dc; var data=_210.data; if(_20f==undefined||_20f==null){ _20f=data.rows.length; } if(_20f>data.rows.length){ _20f=data.rows.length; } function _211(_212){ var _213=_212?1:2; for(var i=data.rows.length-1;i>=_20f;i--){ var tr=opts.finder.getTr(_20e,i,"body",_213); tr.attr("datagrid-row-index",i+1); tr.attr("id",_210.rowIdPrefix+"-"+_213+"-"+(i+1)); if(_212&&opts.rownumbers){ var _214=i+2; if(opts.pagination){ _214+=(opts.pageNumber-1)*opts.pageSize; } tr.find("div.datagrid-cell-rownumber").html(_214); } if(opts.striped){ tr.removeClass("datagrid-row-alt").addClass((i+1)%2?"datagrid-row-alt":""); } } }; function _215(_216){ var _217=_216?1:2; var _218=$(_20e).datagrid("getColumnFields",_216); var _219=_210.rowIdPrefix+"-"+_217+"-"+_20f; var tr="<tr id=\""+_219+"\" class=\"datagrid-row\" datagrid-row-index=\""+_20f+"\"></tr>"; if(_20f>=data.rows.length){ if(data.rows.length){ opts.finder.getTr(_20e,"","last",_217).after(tr); }else{ var cc=_216?dc.body1:dc.body2; cc.html("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"+tr+"</tbody></table>"); } }else{ opts.finder.getTr(_20e,_20f+1,"body",_217).before(tr); } }; _211.call(this,true); _211.call(this,false); _215.call(this,true); _215.call(this,false); data.total+=1; data.rows.splice(_20f,0,row); this.refreshRow.call(this,_20e,_20f); },deleteRow:function(_21a,_21b){ var _21c=$.data(_21a,"datagrid"); var opts=_21c.options; var data=_21c.data; function _21d(_21e){ var _21f=_21e?1:2; for(var i=_21b+1;i<data.rows.length;i++){ var tr=opts.finder.getTr(_21a,i,"body",_21f); tr.attr("datagrid-row-index",i-1); tr.attr("id",_21c.rowIdPrefix+"-"+_21f+"-"+(i-1)); if(_21e&&opts.rownumbers){ var _220=i; if(opts.pagination){ _220+=(opts.pageNumber-1)*opts.pageSize; } tr.find("div.datagrid-cell-rownumber").html(_220); } if(opts.striped){ tr.removeClass("datagrid-row-alt").addClass((i-1)%2?"datagrid-row-alt":""); } } }; opts.finder.getTr(_21a,_21b).remove(); _21d.call(this,true); _21d.call(this,false); data.total-=1; data.rows.splice(_21b,1); },onBeforeRender:function(_221,rows){ },onAfterRender:function(_222){ var opts=$.data(_222,"datagrid").options; if(opts.showFooter){ var _223=$(_222).datagrid("getPanel").find("div.datagrid-footer"); _223.find("div.datagrid-cell-rownumber,div.datagrid-cell-check").css("visibility","hidden"); } }}; $.fn.datagrid.defaults=$.extend({},$.fn.panel.defaults,{frozenColumns:undefined,columns:undefined,fitColumns:false,resizeHandle:"right",autoRowHeight:true,toolbar:null,striped:false,method:"post",nowrap:true,idField:null,url:null,data:null,loadMsg:"Processing, please wait ...",rownumbers:false,singleSelect:false,selectOnCheck:true,checkOnSelect:true,pagination:false,pagePosition:"bottom",pageNumber:1,pageSize:10,pageList:[10,20,30,40,50],queryParams:{},sortName:null,sortOrder:"asc",multiSort:false,remoteSort:true,showHeader:true,showFooter:false,scrollbarSize:18,rowStyler:function(_224,_225){ },loader:function(_226,_227,_228){ var opts=$(this).datagrid("options"); if(!opts.url){ return false; } $.ajax({type:opts.method,url:opts.url,data:_226,dataType:"json",success:function(data){ _227(data); },error:function(){ _228.apply(this,arguments); }}); },loadFilter:function(data){ if(typeof data.length=="number"&&typeof data.splice=="function"){ return {total:data.length,rows:data}; }else{ return data; } },editors:_179,finder:{getTr:function(_229,_22a,type,_22b){ type=type||"body"; _22b=_22b||0; var _22c=$.data(_229,"datagrid"); var dc=_22c.dc; var opts=_22c.options; if(_22b==0){ var tr1=opts.finder.getTr(_229,_22a,type,1); var tr2=opts.finder.getTr(_229,_22a,type,2); return tr1.add(tr2); }else{ if(type=="body"){ var tr=$("#"+_22c.rowIdPrefix+"-"+_22b+"-"+_22a); if(!tr.length){ tr=(_22b==1?dc.body1:dc.body2).find(">table>tbody>tr[datagrid-row-index="+_22a+"]"); } return tr; }else{ if(type=="footer"){ return (_22b==1?dc.footer1:dc.footer2).find(">table>tbody>tr[datagrid-row-index="+_22a+"]"); }else{ if(type=="selected"){ return (_22b==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-selected"); }else{ if(type=="highlight"){ return (_22b==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-over"); }else{ if(type=="checked"){ return (_22b==1?dc.body1:dc.body2).find(">table>tbody>tr.datagrid-row-checked"); }else{ if(type=="last"){ return (_22b==1?dc.body1:dc.body2).find(">table>tbody>tr[datagrid-row-index]:last"); }else{ if(type=="allbody"){ return (_22b==1?dc.body1:dc.body2).find(">table>tbody>tr[datagrid-row-index]"); }else{ if(type=="allfooter"){ return (_22b==1?dc.footer1:dc.footer2).find(">table>tbody>tr[datagrid-row-index]"); } } } } } } } } } },getRow:function(_22d,p){ var _22e=(typeof p=="object")?p.attr("datagrid-row-index"):p; return $.data(_22d,"datagrid").data.rows[parseInt(_22e)]; }},view:_1e9,onBeforeLoad:function(_22f){ },onLoadSuccess:function(){ },onLoadError:function(){ },onClickRow:function(_230,_231){ },onDblClickRow:function(_232,_233){ },onClickCell:function(_234,_235,_236){ },onDblClickCell:function(_237,_238,_239){ },onSortColumn:function(sort,_23a){ },onResizeColumn:function(_23b,_23c){ },onSelect:function(_23d,_23e){ },onUnselect:function(_23f,_240){ },onSelectAll:function(rows){ },onUnselectAll:function(rows){ },onCheck:function(_241,_242){ },onUncheck:function(_243,_244){ },onCheckAll:function(rows){ },onUncheckAll:function(rows){ },onBeforeEdit:function(_245,_246){ },onAfterEdit:function(_247,_248,_249){ },onCancelEdit:function(_24a,_24b){ },onHeaderContextMenu:function(e,_24c){ },onRowContextMenu:function(e,_24d,_24e){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).appendTo("body"); $(_2).addClass("menu-top"); $(document).unbind(".menu").bind("mousedown.menu",function(e){ var _3=$("body>div.menu:visible"); var m=$(e.target).closest("div.menu",_3); if(m.length){ return; } $("body>div.menu-top:visible").menu("hide"); }); var _4=_5($(_2)); for(var i=0;i<_4.length;i++){ _6(_4[i]); } function _5(_7){ var _8=[]; _7.addClass("menu"); _8.push(_7); if(!_7.hasClass("menu-content")){ _7.children("div").each(function(){ var _9=$(this).children("div"); if(_9.length){ _9.insertAfter(_2); this.submenu=_9; var mm=_5(_9); _8=_8.concat(mm); } }); } return _8; }; function _6(_a){ var _b=$.parser.parseOptions(_a[0],["width"]).width; if(_a.hasClass("menu-content")){ _a[0].originalWidth=_b||_a._outerWidth(); }else{ _a[0].originalWidth=_b||0; _a.children("div").each(function(){ var _c=$(this); var _d=$.extend({},$.parser.parseOptions(this,["name","iconCls","href",{separator:"boolean"}]),{disabled:(_c.attr("disabled")?true:undefined)}); if(_d.separator){ _c.addClass("menu-sep"); } if(!_c.hasClass("menu-sep")){ _c[0].itemName=_d.name||""; _c[0].itemHref=_d.href||""; var _e=_c.addClass("menu-item").html(); _c.empty().append($("<div class=\"menu-text\"></div>").html(_e)); if(_d.iconCls){ $("<div class=\"menu-icon\"></div>").addClass(_d.iconCls).appendTo(_c); } if(_d.disabled){ _f(_2,_c[0],true); } if(_c[0].submenu){ $("<div class=\"menu-rightarrow\"></div>").appendTo(_c); } _10(_2,_c); } }); $("<div class=\"menu-line\"></div>").prependTo(_a); } _11(_2,_a); _a.hide(); _12(_2,_a); }; }; function _11(_13,_14){ var _15=$.data(_13,"menu").options; var _16=_14.attr("style"); _14.css({display:"block",left:-10000,height:"auto",overflow:"hidden"}); var _17=0; _14.find("div.menu-text").each(function(){ if(_17<$(this)._outerWidth()){ _17=$(this)._outerWidth(); } $(this).closest("div.menu-item")._outerHeight($(this)._outerHeight()+2); }); _17+=65; _14._outerWidth(Math.max((_14[0].originalWidth||0),_17,_15.minWidth)); _14.children("div.menu-line")._outerHeight(_14.outerHeight()); _14.attr("style",_16); }; function _12(_18,_19){ var _1a=$.data(_18,"menu"); _19.unbind(".menu").bind("mouseenter.menu",function(){ if(_1a.timer){ clearTimeout(_1a.timer); _1a.timer=null; } }).bind("mouseleave.menu",function(){ if(_1a.options.hideOnUnhover){ _1a.timer=setTimeout(function(){ _1b(_18); },100); } }); }; function _10(_1c,_1d){ if(!_1d.hasClass("menu-item")){ return; } _1d.unbind(".menu"); _1d.bind("click.menu",function(){ if($(this).hasClass("menu-item-disabled")){ return; } if(!this.submenu){ _1b(_1c); var _1e=$(this).attr("href"); if(_1e){ location.href=_1e; } } var _1f=$(_1c).menu("getItem",this); $.data(_1c,"menu").options.onClick.call(_1c,_1f); }).bind("mouseenter.menu",function(e){ _1d.siblings().each(function(){ if(this.submenu){ _22(this.submenu); } $(this).removeClass("menu-active"); }); _1d.addClass("menu-active"); if($(this).hasClass("menu-item-disabled")){ _1d.addClass("menu-active-disabled"); return; } var _20=_1d[0].submenu; if(_20){ $(_1c).menu("show",{menu:_20,parent:_1d}); } }).bind("mouseleave.menu",function(e){ _1d.removeClass("menu-active menu-active-disabled"); var _21=_1d[0].submenu; if(_21){ if(e.pageX>=parseInt(_21.css("left"))){ _1d.addClass("menu-active"); }else{ _22(_21); } }else{ _1d.removeClass("menu-active"); } }); }; function _1b(_23){ var _24=$.data(_23,"menu"); if(_24){ if($(_23).is(":visible")){ _22($(_23)); _24.options.onHide.call(_23); } } return false; }; function _25(_26,_27){ var _28,top; _27=_27||{}; var _29=$(_27.menu||_26); if(_29.hasClass("menu-top")){ var _2a=$.data(_26,"menu").options; $.extend(_2a,_27); _28=_2a.left; top=_2a.top; if(_2a.alignTo){ var at=$(_2a.alignTo); _28=at.offset().left; top=at.offset().top+at._outerHeight(); } if(_28+_29.outerWidth()>$(window)._outerWidth()+$(document)._scrollLeft()){ _28=$(window)._outerWidth()+$(document).scrollLeft()-_29.outerWidth()-5; } if(top+_29.outerHeight()>$(window)._outerHeight()+$(document).scrollTop()){ top=$(window)._outerHeight()+$(document).scrollTop()-_29.outerHeight()-5; } }else{ var _2b=_27.parent; _28=_2b.offset().left+_2b.outerWidth()-2; if(_28+_29.outerWidth()+5>$(window)._outerWidth()+$(document).scrollLeft()){ _28=_2b.offset().left-_29.outerWidth()+2; } var top=_2b.offset().top-3; if(top+_29.outerHeight()>$(window)._outerHeight()+$(document).scrollTop()){ top=$(window)._outerHeight()+$(document).scrollTop()-_29.outerHeight()-5; } } _29.css({left:_28,top:top}); _29.show(0,function(){ if(!_29[0].shadow){ _29[0].shadow=$("<div class=\"menu-shadow\"></div>").insertAfter(_29); } _29[0].shadow.css({display:"block",zIndex:$.fn.menu.defaults.zIndex++,left:_29.css("left"),top:_29.css("top"),width:_29.outerWidth(),height:_29.outerHeight()}); _29.css("z-index",$.fn.menu.defaults.zIndex++); if(_29.hasClass("menu-top")){ $.data(_29[0],"menu").options.onShow.call(_29[0]); } }); }; function _22(_2c){ if(!_2c){ return; } _2d(_2c); _2c.find("div.menu-item").each(function(){ if(this.submenu){ _22(this.submenu); } $(this).removeClass("menu-active"); }); function _2d(m){ m.stop(true,true); if(m[0].shadow){ m[0].shadow.hide(); } m.hide(); }; }; function _2e(_2f,_30){ var _31=null; var tmp=$("<div></div>"); function _32(_33){ _33.children("div.menu-item").each(function(){ var _34=$(_2f).menu("getItem",this); var s=tmp.empty().html(_34.text).text(); if(_30==$.trim(s)){ _31=_34; }else{ if(this.submenu&&!_31){ _32(this.submenu); } } }); }; _32($(_2f)); tmp.remove(); return _31; }; function _f(_35,_36,_37){ var t=$(_36); if(!t.hasClass("menu-item")){ return; } if(_37){ t.addClass("menu-item-disabled"); if(_36.onclick){ _36.onclick1=_36.onclick; _36.onclick=null; } }else{ t.removeClass("menu-item-disabled"); if(_36.onclick1){ _36.onclick=_36.onclick1; _36.onclick1=null; } } }; function _38(_39,_3a){ var _3b=$(_39); if(_3a.parent){ if(!_3a.parent.submenu){ var _3c=$("<div class=\"menu\"><div class=\"menu-line\"></div></div>").appendTo("body"); _3c.hide(); _3a.parent.submenu=_3c; $("<div class=\"menu-rightarrow\"></div>").appendTo(_3a.parent); } _3b=_3a.parent.submenu; } if(_3a.separator){ var _3d=$("<div class=\"menu-sep\"></div>").appendTo(_3b); }else{ var _3d=$("<div class=\"menu-item\"></div>").appendTo(_3b); $("<div class=\"menu-text\"></div>").html(_3a.text).appendTo(_3d); } if(_3a.iconCls){ $("<div class=\"menu-icon\"></div>").addClass(_3a.iconCls).appendTo(_3d); } if(_3a.id){ _3d.attr("id",_3a.id); } if(_3a.name){ _3d[0].itemName=_3a.name; } if(_3a.href){ _3d[0].itemHref=_3a.href; } if(_3a.onclick){ if(typeof _3a.onclick=="string"){ _3d.attr("onclick",_3a.onclick); }else{ _3d[0].onclick=eval(_3a.onclick); } } if(_3a.handler){ _3d[0].onclick=eval(_3a.handler); } if(_3a.disabled){ _f(_39,_3d[0],true); } _10(_39,_3d); _12(_39,_3b); _11(_39,_3b); }; function _3e(_3f,_40){ function _41(el){ if(el.submenu){ el.submenu.children("div.menu-item").each(function(){ _41(this); }); var _42=el.submenu[0].shadow; if(_42){ _42.remove(); } el.submenu.remove(); } $(el).remove(); }; _41(_40); }; function _43(_44){ $(_44).children("div.menu-item").each(function(){ _3e(_44,this); }); if(_44.shadow){ _44.shadow.remove(); } $(_44).remove(); }; $.fn.menu=function(_45,_46){ if(typeof _45=="string"){ return $.fn.menu.methods[_45](this,_46); } _45=_45||{}; return this.each(function(){ var _47=$.data(this,"menu"); if(_47){ $.extend(_47.options,_45); }else{ _47=$.data(this,"menu",{options:$.extend({},$.fn.menu.defaults,$.fn.menu.parseOptions(this),_45)}); _1(this); } $(this).css({left:_47.options.left,top:_47.options.top}); }); }; $.fn.menu.methods={options:function(jq){ return $.data(jq[0],"menu").options; },show:function(jq,pos){ return jq.each(function(){ _25(this,pos); }); },hide:function(jq){ return jq.each(function(){ _1b(this); }); },destroy:function(jq){ return jq.each(function(){ _43(this); }); },setText:function(jq,_48){ return jq.each(function(){ $(_48.target).children("div.menu-text").html(_48.text); }); },setIcon:function(jq,_49){ return jq.each(function(){ var _4a=$(this).menu("getItem",_49.target); if(_4a.iconCls){ $(_4a.target).children("div.menu-icon").removeClass(_4a.iconCls).addClass(_49.iconCls); }else{ $("<div class=\"menu-icon\"></div>").addClass(_49.iconCls).appendTo(_49.target); } }); },getItem:function(jq,_4b){ var t=$(_4b); var _4c={target:_4b,id:t.attr("id"),text:$.trim(t.children("div.menu-text").html()),disabled:t.hasClass("menu-item-disabled"),name:_4b.itemName,href:_4b.itemHref,onclick:_4b.onclick}; var _4d=t.children("div.menu-icon"); if(_4d.length){ var cc=[]; var aa=_4d.attr("class").split(" "); for(var i=0;i<aa.length;i++){ if(aa[i]!="menu-icon"){ cc.push(aa[i]); } } _4c.iconCls=cc.join(" "); } return _4c; },findItem:function(jq,_4e){ return _2e(jq[0],_4e); },appendItem:function(jq,_4f){ return jq.each(function(){ _38(this,_4f); }); },removeItem:function(jq,_50){ return jq.each(function(){ _3e(this,_50); }); },enableItem:function(jq,_51){ return jq.each(function(){ _f(this,_51,false); }); },disableItem:function(jq,_52){ return jq.each(function(){ _f(this,_52,true); }); }}; $.fn.menu.parseOptions=function(_53){ return $.extend({},$.parser.parseOptions(_53,["left","top",{minWidth:"number",hideOnUnhover:"boolean"}])); }; $.fn.menu.defaults={zIndex:110000,left:0,top:0,minWidth:120,hideOnUnhover:true,onShow:function(){ },onHide:function(){ },onClick:function(_54){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"splitbutton").options; $(_2).menubutton(_3); }; $.fn.splitbutton=function(_4,_5){ if(typeof _4=="string"){ var _6=$.fn.splitbutton.methods[_4]; if(_6){ return _6(this,_5); }else{ return this.menubutton(_4,_5); } } _4=_4||{}; return this.each(function(){ var _7=$.data(this,"splitbutton"); if(_7){ $.extend(_7.options,_4); }else{ $.data(this,"splitbutton",{options:$.extend({},$.fn.splitbutton.defaults,$.fn.splitbutton.parseOptions(this),_4)}); $(this).removeAttr("disabled"); } _1(this); }); }; $.fn.splitbutton.methods={options:function(jq){ var _8=jq.menubutton("options"); var _9=$.data(jq[0],"splitbutton").options; $.extend(_9,{disabled:_8.disabled,toggle:_8.toggle,selected:_8.selected}); return _9; }}; $.fn.splitbutton.parseOptions=function(_a){ var t=$(_a); return $.extend({},$.fn.linkbutton.parseOptions(_a),$.parser.parseOptions(_a,["menu",{plain:"boolean",duration:"number"}])); }; $.fn.splitbutton.defaults=$.extend({},$.fn.linkbutton.defaults,{plain:true,menu:null,duration:100,cls:{btn1:"s-btn-active",btn2:"s-btn-plain-active",arrow:"s-btn-downarrow",trigger:"s-btn-downarrow"}}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"datetimebox"); var _4=_3.options; $(_2).datebox($.extend({},_4,{onShowPanel:function(){ var _5=$(_2).datetimebox("getValue"); _8(_2,_5,true); _4.onShowPanel.call(_2); },formatter:$.fn.datebox.defaults.formatter,parser:$.fn.datebox.defaults.parser})); $(_2).removeClass("datebox-f").addClass("datetimebox-f"); $(_2).datebox("calendar").calendar({onSelect:function(_6){ _4.onSelect.call(_2,_6); }}); var _7=$(_2).datebox("panel"); if(!_3.spinner){ var p=$("<div style=\"padding:2px\"><input style=\"width:80px\"></div>").insertAfter(_7.children("div.datebox-calendar-inner")); _3.spinner=p.children("input"); } _3.spinner.timespinner({showSeconds:_4.showSeconds,separator:_4.timeSeparator}).unbind(".datetimebox").bind("mousedown.datetimebox",function(e){ e.stopPropagation(); }); _8(_2,_4.value); }; function _9(_a){ var c=$(_a).datetimebox("calendar"); var t=$(_a).datetimebox("spinner"); var _b=c.calendar("options").current; return new Date(_b.getFullYear(),_b.getMonth(),_b.getDate(),t.timespinner("getHours"),t.timespinner("getMinutes"),t.timespinner("getSeconds")); }; function _c(_d,q){ _8(_d,q,true); }; function _e(_f){ var _10=$.data(_f,"datetimebox").options; var _11=_9(_f); _8(_f,_10.formatter.call(_f,_11)); $(_f).combo("hidePanel"); }; function _8(_12,_13,_14){ var _15=$.data(_12,"datetimebox").options; $(_12).combo("setValue",_13); if(!_14){ if(_13){ var _16=_15.parser.call(_12,_13); $(_12).combo("setValue",_15.formatter.call(_12,_16)); $(_12).combo("setText",_15.formatter.call(_12,_16)); }else{ $(_12).combo("setText",_13); } } var _16=_15.parser.call(_12,_13); $(_12).datetimebox("calendar").calendar("moveTo",_16); $(_12).datetimebox("spinner").timespinner("setValue",_17(_16)); function _17(_18){ function _19(_1a){ return (_1a<10?"0":"")+_1a; }; var tt=[_19(_18.getHours()),_19(_18.getMinutes())]; if(_15.showSeconds){ tt.push(_19(_18.getSeconds())); } return tt.join($(_12).datetimebox("spinner").timespinner("options").separator); }; }; $.fn.datetimebox=function(_1b,_1c){ if(typeof _1b=="string"){ var _1d=$.fn.datetimebox.methods[_1b]; if(_1d){ return _1d(this,_1c); }else{ return this.datebox(_1b,_1c); } } _1b=_1b||{}; return this.each(function(){ var _1e=$.data(this,"datetimebox"); if(_1e){ $.extend(_1e.options,_1b); }else{ $.data(this,"datetimebox",{options:$.extend({},$.fn.datetimebox.defaults,$.fn.datetimebox.parseOptions(this),_1b)}); } _1(this); }); }; $.fn.datetimebox.methods={options:function(jq){ var _1f=jq.datebox("options"); return $.extend($.data(jq[0],"datetimebox").options,{originalValue:_1f.originalValue,disabled:_1f.disabled,readonly:_1f.readonly}); },spinner:function(jq){ return $.data(jq[0],"datetimebox").spinner; },setValue:function(jq,_20){ return jq.each(function(){ _8(this,_20); }); },reset:function(jq){ return jq.each(function(){ var _21=$(this).datetimebox("options"); $(this).datetimebox("setValue",_21.originalValue); }); }}; $.fn.datetimebox.parseOptions=function(_22){ var t=$(_22); return $.extend({},$.fn.datebox.parseOptions(_22),$.parser.parseOptions(_22,["timeSeparator",{showSeconds:"boolean"}])); }; $.fn.datetimebox.defaults=$.extend({},$.fn.datebox.defaults,{showSeconds:true,timeSeparator:":",keyHandler:{up:function(e){ },down:function(e){ },left:function(e){ },right:function(e){ },enter:function(e){ _e(this); },query:function(q,e){ _c(this,q); }},buttons:[{text:function(_23){ return $(_23).datetimebox("options").currentText; },handler:function(_24){ $(_24).datetimebox("calendar").calendar({year:new Date().getFullYear(),month:new Date().getMonth()+1,current:new Date()}); _e(_24); }},{text:function(_25){ return $(_25).datetimebox("options").okText; },handler:function(_26){ _e(_26); }},{text:function(_27){ return $(_27).datetimebox("options").closeText; },handler:function(_28){ $(this).closest("div.combo-panel").panel("close"); }}],formatter:function(_29){ var h=_29.getHours(); var M=_29.getMinutes(); var s=_29.getSeconds(); function _2a(_2b){ return (_2b<10?"0":"")+_2b; }; var _2c=$(this).datetimebox("spinner").timespinner("options").separator; var r=$.fn.datebox.defaults.formatter(_29)+" "+_2a(h)+_2c+_2a(M); if($(this).datetimebox("options").showSeconds){ r+=_2c+_2a(s); } return r; },parser:function(s){ if($.trim(s)==""){ return new Date(); } var dt=s.split(" "); var d=$.fn.datebox.defaults.parser(dt[0]); if(dt.length<2){ return d; } var _2d=$(this).datetimebox("spinner").timespinner("options").separator; var tt=dt[1].split(_2d); var _2e=parseInt(tt[0],10)||0; var _2f=parseInt(tt[1],10)||0; var _30=parseInt(tt[2],10)||0; return new Date(d.getFullYear(),d.getMonth(),d.getDate(),_2e,_2f,_30); }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$("<span class=\"spinner\">"+"<span class=\"spinner-arrow\">"+"<span class=\"spinner-arrow-up\"></span>"+"<span class=\"spinner-arrow-down\"></span>"+"</span>"+"</span>").insertAfter(_2); $(_2).addClass("spinner-text spinner-f").prependTo(_3); return _3; }; function _4(_5,_6){ var _7=$.data(_5,"spinner").options; var _8=$.data(_5,"spinner").spinner; if(_6){ _7.width=_6; } var _9=$("<div style=\"display:none\"></div>").insertBefore(_8); _8.appendTo("body"); if(isNaN(_7.width)){ _7.width=$(_5).outerWidth(); } var _a=_8.find(".spinner-arrow"); _8._outerWidth(_7.width)._outerHeight(_7.height); $(_5)._outerWidth(_8.width()-_a.outerWidth()); $(_5).css({height:_8.height()+"px",lineHeight:_8.height()+"px"}); _a._outerHeight(_8.height()); _a.find("span")._outerHeight(_a.height()/2); _8.insertAfter(_9); _9.remove(); }; function _b(_c){ var _d=$.data(_c,"spinner").options; var _e=$.data(_c,"spinner").spinner; _e.find(".spinner-arrow-up,.spinner-arrow-down").unbind(".spinner"); if(!_d.disabled){ _e.find(".spinner-arrow-up").bind("mouseenter.spinner",function(){ $(this).addClass("spinner-arrow-hover"); }).bind("mouseleave.spinner",function(){ $(this).removeClass("spinner-arrow-hover"); }).bind("click.spinner",function(){ _d.spin.call(_c,false); _d.onSpinUp.call(_c); $(_c).validatebox("validate"); }); _e.find(".spinner-arrow-down").bind("mouseenter.spinner",function(){ $(this).addClass("spinner-arrow-hover"); }).bind("mouseleave.spinner",function(){ $(this).removeClass("spinner-arrow-hover"); }).bind("click.spinner",function(){ _d.spin.call(_c,true); _d.onSpinDown.call(_c); $(_c).validatebox("validate"); }); } }; function _f(_10,_11){ var _12=$.data(_10,"spinner").options; if(_11){ _12.disabled=true; $(_10).attr("disabled",true); }else{ _12.disabled=false; $(_10).removeAttr("disabled"); } }; $.fn.spinner=function(_13,_14){ if(typeof _13=="string"){ var _15=$.fn.spinner.methods[_13]; if(_15){ return _15(this,_14); }else{ return this.validatebox(_13,_14); } } _13=_13||{}; return this.each(function(){ var _16=$.data(this,"spinner"); if(_16){ $.extend(_16.options,_13); }else{ _16=$.data(this,"spinner",{options:$.extend({},$.fn.spinner.defaults,$.fn.spinner.parseOptions(this),_13),spinner:_1(this)}); $(this).removeAttr("disabled"); } _16.options.originalValue=_16.options.value; $(this).val(_16.options.value); $(this).attr("readonly",!_16.options.editable); _f(this,_16.options.disabled); _4(this); $(this).validatebox(_16.options); _b(this); }); }; $.fn.spinner.methods={options:function(jq){ var _17=$.data(jq[0],"spinner").options; return $.extend(_17,{value:jq.val()}); },destroy:function(jq){ return jq.each(function(){ var _18=$.data(this,"spinner").spinner; $(this).validatebox("destroy"); _18.remove(); }); },resize:function(jq,_19){ return jq.each(function(){ _4(this,_19); }); },enable:function(jq){ return jq.each(function(){ _f(this,false); _b(this); }); },disable:function(jq){ return jq.each(function(){ _f(this,true); _b(this); }); },getValue:function(jq){ return jq.val(); },setValue:function(jq,_1a){ return jq.each(function(){ var _1b=$.data(this,"spinner").options; _1b.value=_1a; $(this).val(_1a); }); },clear:function(jq){ return jq.each(function(){ var _1c=$.data(this,"spinner").options; _1c.value=""; $(this).val(""); }); },reset:function(jq){ return jq.each(function(){ var _1d=$(this).spinner("options"); $(this).spinner("setValue",_1d.originalValue); }); }}; $.fn.spinner.parseOptions=function(_1e){ var t=$(_1e); return $.extend({},$.fn.validatebox.parseOptions(_1e),$.parser.parseOptions(_1e,["width","height","min","max",{increment:"number",editable:"boolean"}]),{value:(t.val()||undefined),disabled:(t.attr("disabled")?true:undefined)}); }; $.fn.spinner.defaults=$.extend({},$.fn.validatebox.defaults,{width:"auto",height:22,deltaX:19,value:"",min:null,max:null,increment:1,editable:true,disabled:false,spin:function(_1f){ },onSpinUp:function(){ },onSpinDown:function(){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"datebox"); var _4=_3.options; $(_2).addClass("datebox-f").combo($.extend({},_4,{onShowPanel:function(){ _5(); _10(_2,$(_2).datebox("getText")); _4.onShowPanel.call(_2); }})); $(_2).combo("textbox").parent().addClass("datebox"); if(!_3.calendar){ _6(); } function _6(){ var _7=$(_2).combo("panel").css("overflow","hidden"); var cc=$("<div class=\"datebox-calendar-inner\"></div>").appendTo(_7); if(_4.sharedCalendar){ _3.calendar=$(_4.sharedCalendar).appendTo(cc); if(!_3.calendar.hasClass("calendar")){ _3.calendar.calendar(); } }else{ _3.calendar=$("<div></div>").appendTo(cc).calendar(); } $.extend(_3.calendar.calendar("options"),{fit:true,border:false,onSelect:function(_8){ var _9=$(this.target).datebox("options"); _10(this.target,_9.formatter(_8)); $(this.target).combo("hidePanel"); _9.onSelect.call(_2,_8); }}); _10(_2,_4.value); var _a=$("<div class=\"datebox-button\"><table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%\"><tr></tr></table></div>").appendTo(_7); var tr=_a.find("tr"); for(var i=0;i<_4.buttons.length;i++){ var td=$("<td></td>").appendTo(tr); var _b=_4.buttons[i]; var t=$("<a href=\"javascript:void(0)\"></a>").html($.isFunction(_b.text)?_b.text(_2):_b.text).appendTo(td); t.bind("click",{target:_2,handler:_b.handler},function(e){ e.data.handler.call(this,e.data.target); }); } tr.find("td").css("width",(100/_4.buttons.length)+"%"); }; function _5(){ var _c=$(_2).combo("panel"); var cc=_c.children("div.datebox-calendar-inner"); _c.children()._outerWidth(_c.width()); _3.calendar.appendTo(cc); _3.calendar[0].target=_2; if(_4.panelHeight!="auto"){ var _d=_c.height(); _c.children().not(cc).each(function(){ _d-=$(this).outerHeight(); }); cc._outerHeight(_d); } _3.calendar.calendar("resize"); }; }; function _e(_f,q){ _10(_f,q); }; function _11(_12){ var _13=$.data(_12,"datebox"); var _14=_13.options; var _15=_14.formatter(_13.calendar.calendar("options").current); _10(_12,_15); $(_12).combo("hidePanel"); }; function _10(_16,_17){ var _18=$.data(_16,"datebox"); var _19=_18.options; $(_16).combo("setValue",_17).combo("setText",_17); _18.calendar.calendar("moveTo",_19.parser(_17)); }; $.fn.datebox=function(_1a,_1b){ if(typeof _1a=="string"){ var _1c=$.fn.datebox.methods[_1a]; if(_1c){ return _1c(this,_1b); }else{ return this.combo(_1a,_1b); } } _1a=_1a||{}; return this.each(function(){ var _1d=$.data(this,"datebox"); if(_1d){ $.extend(_1d.options,_1a); }else{ $.data(this,"datebox",{options:$.extend({},$.fn.datebox.defaults,$.fn.datebox.parseOptions(this),_1a)}); } _1(this); }); }; $.fn.datebox.methods={options:function(jq){ var _1e=jq.combo("options"); return $.extend($.data(jq[0],"datebox").options,{originalValue:_1e.originalValue,disabled:_1e.disabled,readonly:_1e.readonly}); },calendar:function(jq){ return $.data(jq[0],"datebox").calendar; },setValue:function(jq,_1f){ return jq.each(function(){ _10(this,_1f); }); },reset:function(jq){ return jq.each(function(){ var _20=$(this).datebox("options"); $(this).datebox("setValue",_20.originalValue); }); }}; $.fn.datebox.parseOptions=function(_21){ return $.extend({},$.fn.combo.parseOptions(_21),$.parser.parseOptions(_21,["sharedCalendar"])); }; $.fn.datebox.defaults=$.extend({},$.fn.combo.defaults,{panelWidth:180,panelHeight:"auto",sharedCalendar:null,keyHandler:{up:function(e){ },down:function(e){ },left:function(e){ },right:function(e){ },enter:function(e){ _11(this); },query:function(q,e){ _e(this,q); }},currentText:"Today",closeText:"Close",okText:"Ok",buttons:[{text:function(_22){ return $(_22).datebox("options").currentText; },handler:function(_23){ $(_23).datebox("calendar").calendar({year:new Date().getFullYear(),month:new Date().getMonth()+1,current:new Date()}); _11(_23); }},{text:function(_24){ return $(_24).datebox("options").closeText; },handler:function(_25){ $(this).closest("div.combo-panel").panel("close"); }}],formatter:function(_26){ var y=_26.getFullYear(); var m=_26.getMonth()+1; var d=_26.getDate(); return m+"/"+d+"/"+y; },parser:function(s){ var t=Date.parse(s); if(!isNaN(t)){ return new Date(t); }else{ return new Date(); } },onSelect:function(_27){ }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ $.parser={auto:true,onComplete:function(_1){ },plugins:["draggable","droppable","resizable","pagination","tooltip","linkbutton","menu","menubutton","splitbutton","progressbar","tree","combobox","combotree","combogrid","numberbox","validatebox","searchbox","numberspinner","timespinner","calendar","datebox","datetimebox","slider","layout","panel","datagrid","propertygrid","treegrid","tabs","accordion","window","dialog"],parse:function(_2){ var aa=[]; for(var i=0;i<$.parser.plugins.length;i++){ var _3=$.parser.plugins[i]; var r=$(".easyui-"+_3,_2); if(r.length){ if(r[_3]){ r[_3](); }else{ aa.push({name:_3,jq:r}); } } } if(aa.length&&window.easyloader){ var _4=[]; for(var i=0;i<aa.length;i++){ _4.push(aa[i].name); } easyloader.load(_4,function(){ for(var i=0;i<aa.length;i++){ var _5=aa[i].name; var jq=aa[i].jq; jq[_5](); } $.parser.onComplete.call($.parser,_2); }); }else{ $.parser.onComplete.call($.parser,_2); } },parseOptions:function(_6,_7){ var t=$(_6); var _8={}; var s=$.trim(t.attr("data-options")); if(s){ if(s.substring(0,1)!="{"){ s="{"+s+"}"; } _8=(new Function("return "+s))(); } if(_7){ var _9={}; for(var i=0;i<_7.length;i++){ var pp=_7[i]; if(typeof pp=="string"){ if(pp=="width"||pp=="height"||pp=="left"||pp=="top"){ _9[pp]=parseInt(_6.style[pp])||undefined; }else{ _9[pp]=t.attr(pp); } }else{ for(var _a in pp){ var _b=pp[_a]; if(_b=="boolean"){ _9[_a]=t.attr(_a)?(t.attr(_a)=="true"):undefined; }else{ if(_b=="number"){ _9[_a]=t.attr(_a)=="0"?0:parseFloat(t.attr(_a))||undefined; } } } } } $.extend(_8,_9); } return _8; }}; $(function(){ var d=$("<div style=\"position:absolute;top:-1000px;width:100px;height:100px;padding:5px\"></div>").appendTo("body"); d.width(100); $._boxModel=parseInt(d.width())==100; d.remove(); if(!window.easyloader&&$.parser.auto){ $.parser.parse(); } }); $.fn._outerWidth=function(_c){ if(_c==undefined){ if(this[0]==window){ return this.width()||document.body.clientWidth; } return this.outerWidth()||0; } return this.each(function(){ if($._boxModel){ $(this).width(_c-($(this).outerWidth()-$(this).width())); }else{ $(this).width(_c); } }); }; $.fn._outerHeight=function(_d){ if(_d==undefined){ if(this[0]==window){ return this.height()||document.body.clientHeight; } return this.outerHeight()||0; } return this.each(function(){ if($._boxModel){ $(this).height(_d-($(this).outerHeight()-$(this).height())); }else{ $(this).height(_d); } }); }; $.fn._scrollLeft=function(_e){ if(_e==undefined){ return this.scrollLeft(); }else{ return this.each(function(){ $(this).scrollLeft(_e); }); } }; $.fn._propAttr=$.fn.prop||$.fn.attr; $.fn._fit=function(_f){ _f=_f==undefined?true:_f; var t=this[0]; var p=(t.tagName=="BODY"?t:this.parent()[0]); var _10=p.fcount||0; if(_f){ if(!t.fitted){ t.fitted=true; p.fcount=_10+1; $(p).addClass("panel-noscroll"); if(p.tagName=="BODY"){ $("html").addClass("panel-fit"); } } }else{ if(t.fitted){ t.fitted=false; p.fcount=_10-1; if(p.fcount==0){ $(p).removeClass("panel-noscroll"); if(p.tagName=="BODY"){ $("html").removeClass("panel-fit"); } } } } return {width:$(p).width(),height:$(p).height()}; }; })(jQuery); (function($){ var _11=null; var _12=null; var _13=false; function _14(e){ if(e.touches.length!=1){ return; } if(!_13){ _13=true; dblClickTimer=setTimeout(function(){ _13=false; },500); }else{ clearTimeout(dblClickTimer); _13=false; _15(e,"dblclick"); } _11=setTimeout(function(){ _15(e,"contextmenu",3); },1000); _15(e,"mousedown"); if($.fn.draggable.isDragging||$.fn.resizable.isResizing){ e.preventDefault(); } }; function _16(e){ if(e.touches.length!=1){ return; } if(_11){ clearTimeout(_11); } _15(e,"mousemove"); if($.fn.draggable.isDragging||$.fn.resizable.isResizing){ e.preventDefault(); } }; function _17(e){ if(_11){ clearTimeout(_11); } _15(e,"mouseup"); if($.fn.draggable.isDragging||$.fn.resizable.isResizing){ e.preventDefault(); } }; function _15(e,_18,_19){ var _1a=new $.Event(_18); _1a.pageX=e.changedTouches[0].pageX; _1a.pageY=e.changedTouches[0].pageY; _1a.which=_19||1; $(e.target).trigger(_1a); }; if(document.addEventListener){ document.addEventListener("touchstart",_14,true); document.addEventListener("touchmove",_16,true); document.addEventListener("touchend",_17,true); } })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ var _1; function _2(_3){ var _4=$.data(_3,"propertygrid"); var _5=$.data(_3,"propertygrid").options; $(_3).datagrid($.extend({},_5,{cls:"propertygrid",view:(_5.showGroup?_5.groupView:_5.view),onClickRow:function(_6,_7){ if(_1!=this){ _a(_1); _1=this; } if(_5.editIndex!=_6&&_7.editor){ var _8=$(this).datagrid("getColumnOption","value"); _8.editor=_7.editor; _a(_1); $(this).datagrid("beginEdit",_6); $(this).datagrid("getEditors",_6)[0].target.focus(); _5.editIndex=_6; } _5.onClickRow.call(_3,_6,_7); },loadFilter:function(_9){ _a(this); return _5.loadFilter.call(this,_9); }})); $(document).unbind(".propertygrid").bind("mousedown.propertygrid",function(e){ var p=$(e.target).closest("div.datagrid-view,div.combo-panel"); if(p.length){ return; } _a(_1); _1=undefined; }); }; function _a(_b){ var t=$(_b); if(!t.length){ return; } var _c=$.data(_b,"propertygrid").options; var _d=_c.editIndex; if(_d==undefined){ return; } var ed=t.datagrid("getEditors",_d)[0]; if(ed){ ed.target.blur(); if(t.datagrid("validateRow",_d)){ t.datagrid("endEdit",_d); }else{ t.datagrid("cancelEdit",_d); } } _c.editIndex=undefined; }; $.fn.propertygrid=function(_e,_f){ if(typeof _e=="string"){ var _10=$.fn.propertygrid.methods[_e]; if(_10){ return _10(this,_f); }else{ return this.datagrid(_e,_f); } } _e=_e||{}; return this.each(function(){ var _11=$.data(this,"propertygrid"); if(_11){ $.extend(_11.options,_e); }else{ var _12=$.extend({},$.fn.propertygrid.defaults,$.fn.propertygrid.parseOptions(this),_e); _12.frozenColumns=$.extend(true,[],_12.frozenColumns); _12.columns=$.extend(true,[],_12.columns); $.data(this,"propertygrid",{options:_12}); } _2(this); }); }; $.fn.propertygrid.methods={options:function(jq){ return $.data(jq[0],"propertygrid").options; }}; $.fn.propertygrid.parseOptions=function(_13){ return $.extend({},$.fn.datagrid.parseOptions(_13),$.parser.parseOptions(_13,[{showGroup:"boolean"}])); }; var _14=$.extend({},$.fn.datagrid.defaults.view,{render:function(_15,_16,_17){ var _18=[]; var _19=this.groups; for(var i=0;i<_19.length;i++){ _18.push(this.renderGroup.call(this,_15,i,_19[i],_17)); } $(_16).html(_18.join("")); },renderGroup:function(_1a,_1b,_1c,_1d){ var _1e=$.data(_1a,"datagrid"); var _1f=_1e.options; var _20=$(_1a).datagrid("getColumnFields",_1d); var _21=[]; _21.push("<div class=\"datagrid-group\" group-index="+_1b+">"); _21.push("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" style=\"height:100%\"><tbody>"); _21.push("<tr>"); if((_1d&&(_1f.rownumbers||_1f.frozenColumns.length))||(!_1d&&!(_1f.rownumbers||_1f.frozenColumns.length))){ _21.push("<td style=\"border:0;text-align:center;width:25px\"><span class=\"datagrid-row-expander datagrid-row-collapse\" style=\"display:inline-block;width:16px;height:16px;cursor:pointer\">&nbsp;</span></td>"); } _21.push("<td style=\"border:0;\">"); if(!_1d){ _21.push("<span class=\"datagrid-group-title\">"); _21.push(_1f.groupFormatter.call(_1a,_1c.value,_1c.rows)); _21.push("</span>"); } _21.push("</td>"); _21.push("</tr>"); _21.push("</tbody></table>"); _21.push("</div>"); _21.push("<table class=\"datagrid-btable\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tbody>"); var _22=_1c.startIndex; for(var j=0;j<_1c.rows.length;j++){ var css=_1f.rowStyler?_1f.rowStyler.call(_1a,_22,_1c.rows[j]):""; var _23=""; var _24=""; if(typeof css=="string"){ _24=css; }else{ if(css){ _23=css["class"]||""; _24=css["style"]||""; } } var cls="class=\"datagrid-row "+(_22%2&&_1f.striped?"datagrid-row-alt ":" ")+_23+"\""; var _25=_24?"style=\""+_24+"\"":""; var _26=_1e.rowIdPrefix+"-"+(_1d?1:2)+"-"+_22; _21.push("<tr id=\""+_26+"\" datagrid-row-index=\""+_22+"\" "+cls+" "+_25+">"); _21.push(this.renderRow.call(this,_1a,_20,_1d,_22,_1c.rows[j])); _21.push("</tr>"); _22++; } _21.push("</tbody></table>"); return _21.join(""); },bindEvents:function(_27){ var _28=$.data(_27,"datagrid"); var dc=_28.dc; var _29=dc.body1.add(dc.body2); var _2a=($.data(_29[0],"events")||$._data(_29[0],"events")).click[0].handler; _29.unbind("click").bind("click",function(e){ var tt=$(e.target); var _2b=tt.closest("span.datagrid-row-expander"); if(_2b.length){ var _2c=_2b.closest("div.datagrid-group").attr("group-index"); if(_2b.hasClass("datagrid-row-collapse")){ $(_27).datagrid("collapseGroup",_2c); }else{ $(_27).datagrid("expandGroup",_2c); } }else{ _2a(e); } e.stopPropagation(); }); },onBeforeRender:function(_2d,_2e){ var _2f=$.data(_2d,"datagrid"); var _30=_2f.options; _31(); var _32=[]; for(var i=0;i<_2e.length;i++){ var row=_2e[i]; var _33=_34(row[_30.groupField]); if(!_33){ _33={value:row[_30.groupField],rows:[row]}; _32.push(_33); }else{ _33.rows.push(row); } } var _35=0; var _36=[]; for(var i=0;i<_32.length;i++){ var _33=_32[i]; _33.startIndex=_35; _35+=_33.rows.length; _36=_36.concat(_33.rows); } _2f.data.rows=_36; this.groups=_32; var _37=this; setTimeout(function(){ _37.bindEvents(_2d); },0); function _34(_38){ for(var i=0;i<_32.length;i++){ var _39=_32[i]; if(_39.value==_38){ return _39; } } return null; }; function _31(){ if(!$("#datagrid-group-style").length){ $("head").append("<style id=\"datagrid-group-style\">"+".datagrid-group{height:25px;overflow:hidden;font-weight:bold;border-bottom:1px solid #ccc;}"+"</style>"); } }; }}); $.extend($.fn.datagrid.methods,{expandGroup:function(jq,_3a){ return jq.each(function(){ var _3b=$.data(this,"datagrid").dc.view; var _3c=_3b.find(_3a!=undefined?"div.datagrid-group[group-index=\""+_3a+"\"]":"div.datagrid-group"); var _3d=_3c.find("span.datagrid-row-expander"); if(_3d.hasClass("datagrid-row-expand")){ _3d.removeClass("datagrid-row-expand").addClass("datagrid-row-collapse"); _3c.next("table").show(); } $(this).datagrid("fixRowHeight"); }); },collapseGroup:function(jq,_3e){ return jq.each(function(){ var _3f=$.data(this,"datagrid").dc.view; var _40=_3f.find(_3e!=undefined?"div.datagrid-group[group-index=\""+_3e+"\"]":"div.datagrid-group"); var _41=_40.find("span.datagrid-row-expander"); if(_41.hasClass("datagrid-row-collapse")){ _41.removeClass("datagrid-row-collapse").addClass("datagrid-row-expand"); _40.next("table").hide(); } $(this).datagrid("fixRowHeight"); }); }}); $.fn.propertygrid.defaults=$.extend({},$.fn.datagrid.defaults,{singleSelect:true,remoteSort:false,fitColumns:true,loadMsg:"",frozenColumns:[[{field:"f",width:16,resizable:false}]],columns:[[{field:"name",title:"Name",width:100,sortable:true},{field:"value",title:"Value",width:100,resizable:false}]],showGroup:false,groupView:_14,groupField:"group",groupFormatter:function(_42,_43){ return _42; }}); })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2,_3){ _3=_3||{}; var _4={}; if(_3.onSubmit){ if(_3.onSubmit.call(_2,_4)==false){ return; } } var _5=$(_2); if(_3.url){ _5.attr("action",_3.url); } var _6="easyui_frame_"+(new Date().getTime()); var _7=$("<iframe id="+_6+" name="+_6+"></iframe>").attr("src",window.ActiveXObject?"javascript:false":"about:blank").css({position:"absolute",top:-1000,left:-1000}); var t=_5.attr("target"),a=_5.attr("action"); _5.attr("target",_6); var _8=$(); try{ _7.appendTo("body"); _7.bind("load",cb); for(var n in _4){ var f=$("<input type=\"hidden\" name=\""+n+"\">").val(_4[n]).appendTo(_5); _8=_8.add(f); } _9(); _5[0].submit(); } finally{ _5.attr("action",a); t?_5.attr("target",t):_5.removeAttr("target"); _8.remove(); } function _9(){ var f=$("#"+_6); if(!f.length){ return; } try{ var s=f.contents()[0].readyState; if(s&&s.toLowerCase()=="uninitialized"){ setTimeout(_9,100); } } catch(e){ cb(); } }; var _a=10; function cb(){ var _b=$("#"+_6); if(!_b.length){ return; } _b.unbind(); var _c=""; try{ var _d=_b.contents().find("body"); _c=_d.html(); if(_c==""){ if(--_a){ setTimeout(cb,100); return; } } var ta=_d.find(">textarea"); if(ta.length){ _c=ta.val(); }else{ var _e=_d.find(">pre"); if(_e.length){ _c=_e.html(); } } } catch(e){ } if(_3.success){ _3.success(_c); } setTimeout(function(){ _b.unbind(); _b.remove(); },100); }; }; function _f(_10,_11){ if(!$.data(_10,"form")){ $.data(_10,"form",{options:$.extend({},$.fn.form.defaults)}); } var _12=$.data(_10,"form").options; if(typeof _11=="string"){ var _13={}; if(_12.onBeforeLoad.call(_10,_13)==false){ return; } $.ajax({url:_11,data:_13,dataType:"json",success:function(_14){ _15(_14); },error:function(){ _12.onLoadError.apply(_10,arguments); }}); }else{ _15(_11); } function _15(_16){ var _17=$(_10); for(var _18 in _16){ var val=_16[_18]; var rr=_19(_18,val); if(!rr.length){ var _1a=_1b(_18,val); if(!_1a){ $("input[name=\""+_18+"\"]",_17).val(val); $("textarea[name=\""+_18+"\"]",_17).val(val); $("select[name=\""+_18+"\"]",_17).val(val); } } _1c(_18,val); } _12.onLoadSuccess.call(_10,_16); _28(_10); }; function _19(_1d,val){ var rr=$(_10).find("input[name=\""+_1d+"\"][type=radio], input[name=\""+_1d+"\"][type=checkbox]"); rr._propAttr("checked",false); rr.each(function(){ var f=$(this); if(f.val()==String(val)||$.inArray(f.val(),$.isArray(val)?val:[val])>=0){ f._propAttr("checked",true); } }); return rr; }; function _1b(_1e,val){ var _1f=0; var pp=["numberbox","slider"]; for(var i=0;i<pp.length;i++){ var p=pp[i]; var f=$(_10).find("input["+p+"Name=\""+_1e+"\"]"); if(f.length){ f[p]("setValue",val); _1f+=f.length; } } return _1f; }; function _1c(_20,val){ var _21=$(_10); var cc=["combobox","combotree","combogrid","datetimebox","datebox","combo"]; var c=_21.find("[comboName=\""+_20+"\"]"); if(c.length){ for(var i=0;i<cc.length;i++){ var _22=cc[i]; if(c.hasClass(_22+"-f")){ if(c[_22]("options").multiple){ c[_22]("setValues",val); }else{ c[_22]("setValue",val); } return; } } } }; }; function _23(_24){ $("input,select,textarea",_24).each(function(){ var t=this.type,tag=this.tagName.toLowerCase(); if(t=="text"||t=="hidden"||t=="password"||tag=="textarea"){ this.value=""; }else{ if(t=="file"){ var _25=$(this); _25.after(_25.clone().val("")); _25.remove(); }else{ if(t=="checkbox"||t=="radio"){ this.checked=false; }else{ if(tag=="select"){ this.selectedIndex=-1; } } } } }); var t=$(_24); var _26=["combo","combobox","combotree","combogrid","slider"]; for(var i=0;i<_26.length;i++){ var _27=_26[i]; var r=t.find("."+_27+"-f"); if(r.length&&r[_27]){ r[_27]("clear"); } } _28(_24); }; function _29(_2a){ _2a.reset(); var t=$(_2a); var _2b=["combo","combobox","combotree","combogrid","datebox","datetimebox","spinner","timespinner","numberbox","numberspinner","slider"]; for(var i=0;i<_2b.length;i++){ var _2c=_2b[i]; var r=t.find("."+_2c+"-f"); if(r.length&&r[_2c]){ r[_2c]("reset"); } } _28(_2a); }; function _2d(_2e){ var _2f=$.data(_2e,"form").options; var _30=$(_2e); _30.unbind(".form").bind("submit.form",function(){ setTimeout(function(){ _1(_2e,_2f); },0); return false; }); }; function _28(_31){ if($.fn.validatebox){ var t=$(_31); t.find(".validatebox-text:not(:disabled)").validatebox("validate"); var _32=t.find(".validatebox-invalid"); _32.filter(":not(:disabled):first").focus(); return _32.length==0; } return true; }; function _33(_34,_35){ $(_34).find(".validatebox-text:not(:disabled)").validatebox(_35?"disableValidation":"enableValidation"); }; $.fn.form=function(_36,_37){ if(typeof _36=="string"){ return $.fn.form.methods[_36](this,_37); } _36=_36||{}; return this.each(function(){ if(!$.data(this,"form")){ $.data(this,"form",{options:$.extend({},$.fn.form.defaults,_36)}); } _2d(this); }); }; $.fn.form.methods={submit:function(jq,_38){ return jq.each(function(){ _1(this,$.extend({},$.fn.form.defaults,_38||{})); }); },load:function(jq,_39){ return jq.each(function(){ _f(this,_39); }); },clear:function(jq){ return jq.each(function(){ _23(this); }); },reset:function(jq){ return jq.each(function(){ _29(this); }); },validate:function(jq){ return _28(jq[0]); },disableValidation:function(jq){ return jq.each(function(){ _33(this,true); }); },enableValidation:function(jq){ return jq.each(function(){ _33(this,false); }); }}; $.fn.form.defaults={url:null,onSubmit:function(_3a){ return $(this).form("validate"); },success:function(_3b){ },onBeforeLoad:function(_3c){ },onLoadSuccess:function(_3d){ },onLoadError:function(){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ $(_2).addClass("searchbox-f").hide(); var _3=$("<span class=\"searchbox\"></span>").insertAfter(_2); var _4=$("<input type=\"text\" class=\"searchbox-text\">").appendTo(_3); $("<span><span class=\"searchbox-button\"></span></span>").appendTo(_3); var _5=$(_2).attr("name"); if(_5){ _4.attr("name",_5); $(_2).removeAttr("name").attr("searchboxName",_5); } return _3; }; function _6(_7,_8){ var _9=$.data(_7,"searchbox").options; var sb=$.data(_7,"searchbox").searchbox; if(_8){ _9.width=_8; } sb.appendTo("body"); if(isNaN(_9.width)){ _9.width=sb._outerWidth(); } var _a=sb.find("span.searchbox-button"); var _b=sb.find("a.searchbox-menu"); var _c=sb.find("input.searchbox-text"); sb._outerWidth(_9.width)._outerHeight(_9.height); _c._outerWidth(sb.width()-_b._outerWidth()-_a._outerWidth()); _c.css({height:sb.height()+"px",lineHeight:sb.height()+"px"}); _b._outerHeight(sb.height()); _a._outerHeight(sb.height()); var _d=_b.find("span.l-btn-left"); _d._outerHeight(sb.height()); _d.find("span.l-btn-text,span.m-btn-downarrow").css({height:_d.height()+"px",lineHeight:_d.height()+"px"}); sb.insertAfter(_7); }; function _e(_f){ var _10=$.data(_f,"searchbox"); var _11=_10.options; if(_11.menu){ _10.menu=$(_11.menu).menu({onClick:function(_12){ _13(_12); }}); var _14=_10.menu.children("div.menu-item:first"); _10.menu.children("div.menu-item").each(function(){ var _15=$.extend({},$.parser.parseOptions(this),{selected:($(this).attr("selected")?true:undefined)}); if(_15.selected){ _14=$(this); return false; } }); _14.triggerHandler("click"); }else{ _10.searchbox.find("a.searchbox-menu").remove(); _10.menu=null; } function _13(_16){ _10.searchbox.find("a.searchbox-menu").remove(); var mb=$("<a class=\"searchbox-menu\" href=\"javascript:void(0)\"></a>").html(_16.text); mb.prependTo(_10.searchbox).menubutton({menu:_10.menu,iconCls:_16.iconCls}); _10.searchbox.find("input.searchbox-text").attr("name",_16.name||_16.text); _6(_f); }; }; function _17(_18){ var _19=$.data(_18,"searchbox"); var _1a=_19.options; var _1b=_19.searchbox.find("input.searchbox-text"); var _1c=_19.searchbox.find(".searchbox-button"); _1b.unbind(".searchbox").bind("blur.searchbox",function(e){ _1a.value=$(this).val(); if(_1a.value==""){ $(this).val(_1a.prompt); $(this).addClass("searchbox-prompt"); }else{ $(this).removeClass("searchbox-prompt"); } }).bind("focus.searchbox",function(e){ if($(this).val()!=_1a.value){ $(this).val(_1a.value); } $(this).removeClass("searchbox-prompt"); }).bind("keydown.searchbox",function(e){ if(e.keyCode==13){ e.preventDefault(); _1a.value=$(this).val(); _1a.searcher.call(_18,_1a.value,_1b._propAttr("name")); return false; } }); _1c.unbind(".searchbox").bind("click.searchbox",function(){ _1a.searcher.call(_18,_1a.value,_1b._propAttr("name")); }).bind("mouseenter.searchbox",function(){ $(this).addClass("searchbox-button-hover"); }).bind("mouseleave.searchbox",function(){ $(this).removeClass("searchbox-button-hover"); }); }; function _1d(_1e){ var _1f=$.data(_1e,"searchbox"); var _20=_1f.options; var _21=_1f.searchbox.find("input.searchbox-text"); if(_20.value==""){ _21.val(_20.prompt); _21.addClass("searchbox-prompt"); }else{ _21.val(_20.value); _21.removeClass("searchbox-prompt"); } }; $.fn.searchbox=function(_22,_23){ if(typeof _22=="string"){ return $.fn.searchbox.methods[_22](this,_23); } _22=_22||{}; return this.each(function(){ var _24=$.data(this,"searchbox"); if(_24){ $.extend(_24.options,_22); }else{ _24=$.data(this,"searchbox",{options:$.extend({},$.fn.searchbox.defaults,$.fn.searchbox.parseOptions(this),_22),searchbox:_1(this)}); } _e(this); _1d(this); _17(this); _6(this); }); }; $.fn.searchbox.methods={options:function(jq){ return $.data(jq[0],"searchbox").options; },menu:function(jq){ return $.data(jq[0],"searchbox").menu; },textbox:function(jq){ return $.data(jq[0],"searchbox").searchbox.find("input.searchbox-text"); },getValue:function(jq){ return $.data(jq[0],"searchbox").options.value; },setValue:function(jq,_25){ return jq.each(function(){ $(this).searchbox("options").value=_25; $(this).searchbox("textbox").val(_25); $(this).searchbox("textbox").blur(); }); },getName:function(jq){ return $.data(jq[0],"searchbox").searchbox.find("input.searchbox-text").attr("name"); },selectName:function(jq,_26){ return jq.each(function(){ var _27=$.data(this,"searchbox").menu; if(_27){ _27.children("div.menu-item[name=\""+_26+"\"]").triggerHandler("click"); } }); },destroy:function(jq){ return jq.each(function(){ var _28=$(this).searchbox("menu"); if(_28){ _28.menu("destroy"); } $.data(this,"searchbox").searchbox.remove(); $(this).remove(); }); },resize:function(jq,_29){ return jq.each(function(){ _6(this,_29); }); }}; $.fn.searchbox.parseOptions=function(_2a){ var t=$(_2a); return $.extend({},$.parser.parseOptions(_2a,["width","height","prompt","menu"]),{value:t.val(),searcher:(t.attr("searcher")?eval(t.attr("searcher")):undefined)}); }; $.fn.searchbox.defaults={width:"auto",height:22,prompt:"",value:"",menu:null,searcher:function(_2b,_2c){ }}; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ $.fn.resizable=function(_1,_2){ if(typeof _1=="string"){ return $.fn.resizable.methods[_1](this,_2); } function _3(e){ var _4=e.data; var _5=$.data(_4.target,"resizable").options; if(_4.dir.indexOf("e")!=-1){ var _6=_4.startWidth+e.pageX-_4.startX; _6=Math.min(Math.max(_6,_5.minWidth),_5.maxWidth); _4.width=_6; } if(_4.dir.indexOf("s")!=-1){ var _7=_4.startHeight+e.pageY-_4.startY; _7=Math.min(Math.max(_7,_5.minHeight),_5.maxHeight); _4.height=_7; } if(_4.dir.indexOf("w")!=-1){ var _6=_4.startWidth-e.pageX+_4.startX; _6=Math.min(Math.max(_6,_5.minWidth),_5.maxWidth); _4.width=_6; _4.left=_4.startLeft+_4.startWidth-_4.width; } if(_4.dir.indexOf("n")!=-1){ var _7=_4.startHeight-e.pageY+_4.startY; _7=Math.min(Math.max(_7,_5.minHeight),_5.maxHeight); _4.height=_7; _4.top=_4.startTop+_4.startHeight-_4.height; } }; function _8(e){ var _9=e.data; var t=$(_9.target); t.css({left:_9.left,top:_9.top}); if(t.outerWidth()!=_9.width){ t._outerWidth(_9.width); } if(t.outerHeight()!=_9.height){ t._outerHeight(_9.height); } }; function _a(e){ $.fn.resizable.isResizing=true; $.data(e.data.target,"resizable").options.onStartResize.call(e.data.target,e); return false; }; function _b(e){ _3(e); if($.data(e.data.target,"resizable").options.onResize.call(e.data.target,e)!=false){ _8(e); } return false; }; function _c(e){ $.fn.resizable.isResizing=false; _3(e,true); _8(e); $.data(e.data.target,"resizable").options.onStopResize.call(e.data.target,e); $(document).unbind(".resizable"); $("body").css("cursor",""); return false; }; return this.each(function(){ var _d=null; var _e=$.data(this,"resizable"); if(_e){ $(this).unbind(".resizable"); _d=$.extend(_e.options,_1||{}); }else{ _d=$.extend({},$.fn.resizable.defaults,$.fn.resizable.parseOptions(this),_1||{}); $.data(this,"resizable",{options:_d}); } if(_d.disabled==true){ return; } $(this).bind("mousemove.resizable",{target:this},function(e){ if($.fn.resizable.isResizing){ return; } var _f=_10(e); if(_f==""){ $(e.data.target).css("cursor",""); }else{ $(e.data.target).css("cursor",_f+"-resize"); } }).bind("mouseleave.resizable",{target:this},function(e){ $(e.data.target).css("cursor",""); }).bind("mousedown.resizable",{target:this},function(e){ var dir=_10(e); if(dir==""){ return; } function _11(css){ var val=parseInt($(e.data.target).css(css)); if(isNaN(val)){ return 0; }else{ return val; } }; var _12={target:e.data.target,dir:dir,startLeft:_11("left"),startTop:_11("top"),left:_11("left"),top:_11("top"),startX:e.pageX,startY:e.pageY,startWidth:$(e.data.target).outerWidth(),startHeight:$(e.data.target).outerHeight(),width:$(e.data.target).outerWidth(),height:$(e.data.target).outerHeight(),deltaWidth:$(e.data.target).outerWidth()-$(e.data.target).width(),deltaHeight:$(e.data.target).outerHeight()-$(e.data.target).height()}; $(document).bind("mousedown.resizable",_12,_a); $(document).bind("mousemove.resizable",_12,_b); $(document).bind("mouseup.resizable",_12,_c); $("body").css("cursor",dir+"-resize"); }); function _10(e){ var tt=$(e.data.target); var dir=""; var _13=tt.offset(); var _14=tt.outerWidth(); var _15=tt.outerHeight(); var _16=_d.edge; if(e.pageY>_13.top&&e.pageY<_13.top+_16){ dir+="n"; }else{ if(e.pageY<_13.top+_15&&e.pageY>_13.top+_15-_16){ dir+="s"; } } if(e.pageX>_13.left&&e.pageX<_13.left+_16){ dir+="w"; }else{ if(e.pageX<_13.left+_14&&e.pageX>_13.left+_14-_16){ dir+="e"; } } var _17=_d.handles.split(","); for(var i=0;i<_17.length;i++){ var _18=_17[i].replace(/(^\s*)|(\s*$)/g,""); if(_18=="all"||_18==dir){ return dir; } } return ""; }; }); }; $.fn.resizable.methods={options:function(jq){ return $.data(jq[0],"resizable").options; },enable:function(jq){ return jq.each(function(){ $(this).resizable({disabled:false}); }); },disable:function(jq){ return jq.each(function(){ $(this).resizable({disabled:true}); }); }}; $.fn.resizable.parseOptions=function(_19){ var t=$(_19); return $.extend({},$.parser.parseOptions(_19,["handles",{minWidth:"number",minHeight:"number",maxWidth:"number",maxHeight:"number",edge:"number"}]),{disabled:(t.attr("disabled")?true:undefined)}); }; $.fn.resizable.defaults={disabled:false,handles:"n, e, s, w, ne, se, sw, nw, all",minWidth:10,minHeight:10,maxWidth:10000,maxHeight:10000,edge:5,onStartResize:function(e){ },onResize:function(e){ },onStopResize:function(e){ }}; $.fn.resizable.isResizing=false; })(jQuery);
JavaScript
/** * jQuery EasyUI 1.3.5 * * Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved. * * Licensed under the GPL or commercial licenses * To use it on other terms please contact us: info@jeasyui.com * http://www.gnu.org/licenses/gpl.txt * http://www.jeasyui.com/license_commercial.php * */ (function($){ function _1(_2){ var _3=$.data(_2,"accordion"); var _4=_3.options; var _5=_3.panels; var cc=$(_2); _4.fit?$.extend(_4,cc._fit()):cc._fit(false); if(!isNaN(_4.width)){ cc._outerWidth(_4.width); }else{ cc.css("width",""); } var _6=0; var _7="auto"; var _8=cc.find(">div.panel>div.accordion-header"); if(_8.length){ _6=$(_8[0]).css("height","")._outerHeight(); } if(!isNaN(_4.height)){ cc._outerHeight(_4.height); _7=cc.height()-_6*_8.length; }else{ cc.css("height",""); } _9(true,_7-_9(false)+1); function _9(_a,_b){ var _c=0; for(var i=0;i<_5.length;i++){ var p=_5[i]; var h=p.panel("header")._outerHeight(_6); if(p.panel("options").collapsible==_a){ var _d=isNaN(_b)?undefined:(_b+_6*h.length); p.panel("resize",{width:cc.width(),height:(_a?_d:undefined)}); _c+=p.panel("panel").outerHeight()-_6; } } return _c; }; }; function _e(_f,_10,_11,all){ var _12=$.data(_f,"accordion").panels; var pp=[]; for(var i=0;i<_12.length;i++){ var p=_12[i]; if(_10){ if(p.panel("options")[_10]==_11){ pp.push(p); } }else{ if(p[0]==$(_11)[0]){ return i; } } } if(_10){ return all?pp:(pp.length?pp[0]:null); }else{ return -1; } }; function _13(_14){ return _e(_14,"collapsed",false,true); }; function _15(_16){ var pp=_13(_16); return pp.length?pp[0]:null; }; function _17(_18,_19){ return _e(_18,null,_19); }; function _1a(_1b,_1c){ var _1d=$.data(_1b,"accordion").panels; if(typeof _1c=="number"){ if(_1c<0||_1c>=_1d.length){ return null; }else{ return _1d[_1c]; } } return _e(_1b,"title",_1c); }; function _1e(_1f){ var _20=$.data(_1f,"accordion").options; var cc=$(_1f); if(_20.border){ cc.removeClass("accordion-noborder"); }else{ cc.addClass("accordion-noborder"); } }; function _21(_22){ var _23=$.data(_22,"accordion"); var cc=$(_22); cc.addClass("accordion"); _23.panels=[]; cc.children("div").each(function(){ var _24=$.extend({},$.parser.parseOptions(this),{selected:($(this).attr("selected")?true:undefined)}); var pp=$(this); _23.panels.push(pp); _27(_22,pp,_24); }); cc.bind("_resize",function(e,_25){ var _26=$.data(_22,"accordion").options; if(_26.fit==true||_25){ _1(_22); } return false; }); }; function _27(_28,pp,_29){ var _2a=$.data(_28,"accordion").options; pp.panel($.extend({},{collapsible:true,minimizable:false,maximizable:false,closable:false,doSize:false,collapsed:true,headerCls:"accordion-header",bodyCls:"accordion-body"},_29,{onBeforeExpand:function(){ if(_29.onBeforeExpand){ if(_29.onBeforeExpand.call(this)==false){ return false; } } if(!_2a.multiple){ var all=$.grep(_13(_28),function(p){ return p.panel("options").collapsible; }); for(var i=0;i<all.length;i++){ _35(_28,_17(_28,all[i])); } } var _2b=$(this).panel("header"); _2b.addClass("accordion-header-selected"); _2b.find(".accordion-collapse").removeClass("accordion-expand"); },onExpand:function(){ if(_29.onExpand){ _29.onExpand.call(this); } _2a.onSelect.call(_28,$(this).panel("options").title,_17(_28,this)); },onBeforeCollapse:function(){ if(_29.onBeforeCollapse){ if(_29.onBeforeCollapse.call(this)==false){ return false; } } var _2c=$(this).panel("header"); _2c.removeClass("accordion-header-selected"); _2c.find(".accordion-collapse").addClass("accordion-expand"); },onCollapse:function(){ if(_29.onCollapse){ _29.onCollapse.call(this); } _2a.onUnselect.call(_28,$(this).panel("options").title,_17(_28,this)); }})); var _2d=pp.panel("header"); var _2e=_2d.children("div.panel-tool"); _2e.children("a.panel-tool-collapse").hide(); var t=$("<a href=\"javascript:void(0)\"></a>").addClass("accordion-collapse accordion-expand").appendTo(_2e); t.bind("click",function(){ var _2f=_17(_28,pp); if(pp.panel("options").collapsed){ _30(_28,_2f); }else{ _35(_28,_2f); } return false; }); pp.panel("options").collapsible?t.show():t.hide(); _2d.click(function(){ $(this).find("a.accordion-collapse:visible").triggerHandler("click"); return false; }); }; function _30(_31,_32){ var p=_1a(_31,_32); if(!p){ return; } _33(_31); var _34=$.data(_31,"accordion").options; p.panel("expand",_34.animate); }; function _35(_36,_37){ var p=_1a(_36,_37); if(!p){ return; } _33(_36); var _38=$.data(_36,"accordion").options; p.panel("collapse",_38.animate); }; function _39(_3a){ var _3b=$.data(_3a,"accordion").options; var p=_e(_3a,"selected",true); if(p){ _3c(_17(_3a,p)); }else{ _3c(_3b.selected); } function _3c(_3d){ var _3e=_3b.animate; _3b.animate=false; _30(_3a,_3d); _3b.animate=_3e; }; }; function _33(_3f){ var _40=$.data(_3f,"accordion").panels; for(var i=0;i<_40.length;i++){ _40[i].stop(true,true); } }; function add(_41,_42){ var _43=$.data(_41,"accordion"); var _44=_43.options; var _45=_43.panels; if(_42.selected==undefined){ _42.selected=true; } _33(_41); var pp=$("<div></div>").appendTo(_41); _45.push(pp); _27(_41,pp,_42); _1(_41); _44.onAdd.call(_41,_42.title,_45.length-1); if(_42.selected){ _30(_41,_45.length-1); } }; function _46(_47,_48){ var _49=$.data(_47,"accordion"); var _4a=_49.options; var _4b=_49.panels; _33(_47); var _4c=_1a(_47,_48); var _4d=_4c.panel("options").title; var _4e=_17(_47,_4c); if(!_4c){ return; } if(_4a.onBeforeRemove.call(_47,_4d,_4e)==false){ return; } _4b.splice(_4e,1); _4c.panel("destroy"); if(_4b.length){ _1(_47); var _4f=_15(_47); if(!_4f){ _30(_47,0); } } _4a.onRemove.call(_47,_4d,_4e); }; $.fn.accordion=function(_50,_51){ if(typeof _50=="string"){ return $.fn.accordion.methods[_50](this,_51); } _50=_50||{}; return this.each(function(){ var _52=$.data(this,"accordion"); if(_52){ $.extend(_52.options,_50); }else{ $.data(this,"accordion",{options:$.extend({},$.fn.accordion.defaults,$.fn.accordion.parseOptions(this),_50),accordion:$(this).addClass("accordion"),panels:[]}); _21(this); } _1e(this); _1(this); _39(this); }); }; $.fn.accordion.methods={options:function(jq){ return $.data(jq[0],"accordion").options; },panels:function(jq){ return $.data(jq[0],"accordion").panels; },resize:function(jq){ return jq.each(function(){ _1(this); }); },getSelections:function(jq){ return _13(jq[0]); },getSelected:function(jq){ return _15(jq[0]); },getPanel:function(jq,_53){ return _1a(jq[0],_53); },getPanelIndex:function(jq,_54){ return _17(jq[0],_54); },select:function(jq,_55){ return jq.each(function(){ _30(this,_55); }); },unselect:function(jq,_56){ return jq.each(function(){ _35(this,_56); }); },add:function(jq,_57){ return jq.each(function(){ add(this,_57); }); },remove:function(jq,_58){ return jq.each(function(){ _46(this,_58); }); }}; $.fn.accordion.parseOptions=function(_59){ var t=$(_59); return $.extend({},$.parser.parseOptions(_59,["width","height",{fit:"boolean",border:"boolean",animate:"boolean",multiple:"boolean",selected:"number"}])); }; $.fn.accordion.defaults={width:"auto",height:"auto",fit:false,border:true,animate:true,multiple:false,selected:0,onSelect:function(_5a,_5b){ },onUnselect:function(_5c,_5d){ },onAdd:function(_5e,_5f){ },onBeforeRemove:function(_60,_61){ },onRemove:function(_62,_63){ }}; })(jQuery);
JavaScript
$(function () { initLogin(); }) function initLogin() { $('#treeLeft').tree({ //初始化左侧功能树(不同用户显示的树是不同的) method: 'GET', url: 'ashx/MenuHandler.ashx?action=getUserMenu', lines: true, onClick: function (node) { //点击左侧的tree节点 打开右侧tabs显示内容 debugger if (node.attributes) { addTab(node.text, node.attributes.url, node.iconCls); } } }); $.ajax({ url: "ashx/bg_user_login.ashx", type: "post", data: { action: "getuser" }, dataType: "json", success: function (result) { if (result.success) { //console.log(result.msg); //当前用户对象 $("#div_welcome").html("当前登录用户:" + result.msg.UserName); if (!result.msg.IfChangePwd) { //如果是首次登陆必须重置密码 $("<div/>").dialog({ id: "ui_user_userfirstlogin_dialog", //给dialog一个id,操作完好销毁,否则一直在html里 href: "html/ui_user_firstlogin.html", title: "首次登陆需重置密码", height: 160, width: 360, modal: true, closable: false, buttons: [{ id: "ui_user_userfirstlogin_edit", //给button一个id 方便控制其可用和不可用 text: '修 改', handler: function () { $("#ui_user_userfirstlogin_form").form("submit", { url: "ashx/bg_user.ashx", onSubmit: function (param) { $('#ui_user_userfirstlogin_edit').linkbutton('disable'); //点击就不可用,防止连击 param.action = 'firstlogin'; //return $(this).form('validate'); //这么验证如果出错无法恢复按钮状态 if ($(this).form('validate')) return true; else { $('#ui_user_userfirstlogin_edit').linkbutton('enable'); //恢复按钮 return false; } }, success: function (data) { $('#ui_user_userfirstlogin_edit').linkbutton('enable'); //恢复按钮 var dataBack = $.parseJSON(data); //序列化成对象,否则是字符串 if (dataBack.success) { $("#ui_user_userfirstlogin_dialog").dialog('destroy'); //销毁dialog对象 $.show_warning("提示", dataBack.msg); } else { $('#ui_user_userfirstlogin_edit').linkbutton('enable'); $.show_warning("提示", dataBack.msg); } } }); } }, { text: '退 出', handler: function () { loginOut(); } }], onLoad: function () { $("#ui_user_firstlogin_pwd").focus(); //聚焦密码框 $("#ui_user_firstlogin_id").val(result.msg.Id); } }); } } else { //直接访问index页面没有cookie不会发这个ajax请求的,而是被FormsAuthentication带到了登录页面了 //这个else是有cookie,但是cookie里的用户再次验证的时候发现数据库里的当前用户已经修改密码/设置不可用等,然后干掉了cookie window.location.href = "login.html"; } } }); } function addTab(subtitle, url, icon) { if (!$('#tabs').tabs('exists', subtitle)) { $('#tabs').tabs('add', { title: subtitle, href: url, iconCls: icon, closable: true, loadingMessage: '正在加载中......' }); } else { $('#tabs').tabs('select', subtitle); } } function refreshTab() { var index = $('#tabs').tabs('getTabIndex', $('#tabs').tabs('getSelected')); if (index != -1) { $('#tabs').tabs('getTab', index).panel('refresh'); } } function closeTab() { $('.tabs-inner span').each(function (i, n) { var t = $(n).text(); if (t != '') { $('#tabs').tabs('close', t); } }); } //查看当前用户信息 function searchMyInfo() { $("<div/>").dialog({ id: "ui_myinfo_dialog", href: "html/ui_myinfo.html", title: "我的信息", height: 500, width: 580, modal: true, onLoad: function () { $.ajax({ url: "ashx/bg_user.ashx?action=getUserInfo&timespan=" + new Date().getTime(), type: "post", dataType: "json", success: function (result) { $("#ui_myinfo_userid").html(result[0].UserId); $("#ui_myinfo_username").html(result[0].UserName); $("#ui_myinfo_adddate").html(result[0].AddDate); $("#ui_myinfo_roles").html(result[0].RoleName.length > 12 ? "<span title=" + result[0].RoleName + ">" + result[0].RoleName.substring(0, 12) + "...</span>" : result[0].RoleName); $("#ui_myinfo_departments").html(result[0].DepartmentName.length > 12 ? "<span title=" + result[0].DepartmentName + ">" + result[0].DepartmentName.substring(0, 12) + "...</span>" : result[0].DepartmentName); //长度超过12个字符就隐藏 } }); $('#ui_myinfo_authority').tree({ url: "ashx/bg_menu.ashx?action=getMyAuthority&timespan=" + new Date().getTime(), onlyLeafCheck: true, checkbox: true }); }, onClose: function () { $("#ui_myinfo_dialog").dialog('destroy'); //销毁dialog对象 } }); } //修改密码 function changePwd() { $("<div/>").dialog({ id: "ui_user_userchangepwd_dialog", href: "html/ui_user_changepwd.html", title: "修改密码", height: 240, width: 380, modal: true, closable: false, buttons: [{ id: "ui_user_userchangepwd_edit", text: '修 改', handler: function () { $("#ui_user_userchangepwd_form").form("submit", { url: "ashx/bg_user.ashx", onSubmit: function (param) { $('#ui_user_userchangepwd_edit').linkbutton('disable'); //点击就不可用,防止连击 param.action = 'changepwd'; if ($(this).form('validate')) return true; else { $('#ui_user_userchangepwd_edit').linkbutton('enable'); //恢复按钮 return false; } }, success: function (data) { $('#ui_user_userchangepwd_edit').linkbutton('enable'); //恢复按钮 var dataBack = $.parseJSON(data); //序列化成对象 if (dataBack.success) { //$("#ui_user_userchangepwd_dialog").dialog('destroy'); //销毁dialog对象(已跳转,不需要销毁了) //$.show_warning("提示", dataBack.msg); alert(dataBack.msg); window.location.href = "login.html"; } else { $('#ui_user_userchangepwd_edit').linkbutton('enable'); $.show_warning("提示", dataBack.msg); } } }); } }, { text: '取 消', handler: function () { $("#ui_user_userchangepwd_dialog").dialog('destroy'); } }], onLoad: function () { $("#ui_user_userchangepwd_originalpwd").focus(); } }); } //退出系统 function loginOut() { debugger //$.messager.confirm('提示!', '确定退出系统?', function (r) { //if(r){ if (confirm("确定退出当前陆登账户?")) { var para = { "action": "logout" }; $.ajax({ url: "ashx/bg_user_login.ashx", type: "post", data: para, dataType: "json", success: function (result) { if (result.success) { window.location.href = "login.html"; } else { $.show_warning("提示", result.msg); } } }) } //} //}) }
JavaScript