code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
@if(Request.IsAuthenticated) { <text>Welcome <strong>@User.Identity.Name</strong>! @Html.ActionLink("Log Off", "LogOff", "Account")</text> } else { @Html.ActionLink("Log On", "LogOn", "Account") }
08102013project
trunk/CMS/Views/Shared/_LogOnPartial.cshtml
HTML+Razor
oos
219
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <!-- Google Font and style definitions --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:regular,bold" /> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <link rel="stylesheet" href="@Url.Content("~/Content/themes/base/ie.css")"> <![endif]--> <!-- Apple iOS and Android stuff --> <meta name="apple-mobile-web-app-capable" content="no" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no,maximum-scale=1" /> <link href="@Url.Content("~/Content/themes/base/style.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/base/light/theme.css")" rel="stylesheet" id="themestyle" /> <script src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script> <!-- Loading JS Files this way is not recommended! Merge them but keep their order --> <script src="@Url.Content("~/Scripts/plugins/functions.js")"></script> <!-- all Third Party Plugins and Whitelabel Plugins --> <script src="@Url.Content("~/Scripts/plugins/plugins.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Alert.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Dialog.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Form.js")"></script> <!-- configuration to overwrite settings --> <script src="@Url.Content("~/Scripts/plugins/config.js")"></script> </head> <body id="login"> <header> <h2>@ViewBag.Title</h2> </header> <section id="content"> @RenderBody() </section> <footer>Copyright 2013</footer> </body> </html>
08102013project
trunk/CMS/Views/Shared/_LogOnLayout.cshtml
HTML+Razor
oos
1,938
@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; } <h2> Sorry, an error occurred while processing your request. </h2>
08102013project
trunk/CMS/Views/Shared/Error.cshtml
HTML+Razor
oos
157
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <!-- Google Font and style definitions --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:regular,bold" /> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <link rel="stylesheet" href="@Url.Content("~/Content/themes/base/ie.css")"> <![endif]--> <!-- Apple iOS and Android stuff --> <meta name="apple-mobile-web-app-capable" content="no" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no,maximum-scale=1" /> <link href="@Url.Content("~/Content/themes/base/style.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/base/light/theme.css")" rel="stylesheet" id="themestyle" /> <script src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script> <!-- Loading JS Files this way is not recommended! Merge them but keep their order --> <script src="@Url.Content("~/Scripts/plugins/functions.js")"></script> <!-- all Third Party Plugins and Whitelabel Plugins --> <script src="@Url.Content("~/Scripts/plugins/plugins.js")"></script> <script src="@Url.Content("~/Scripts/plugins/editor.js")"></script> <script src="@Url.Content("~/Scripts/plugins/calendar.js")"></script> <script src="@Url.Content("~/Scripts/plugins/flot.js")"></script> <script src="@Url.Content("~/Scripts/plugins/elfinder.js")"></script> <script src="@Url.Content("~/Scripts/plugins/datatables.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Alert.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Autocomplete.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Breadcrumb.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Calendar.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Chart.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Color.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Date.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Editor.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_File.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Dialog.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Fileexplorer.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Form.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Gallery.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Multiselect.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Number.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Password.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Slider.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Store.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Time.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Valid.js")"></script> <script src="@Url.Content("~/Scripts/plugins/wl_Widget.js")"></script> <!-- configuration to overwrite settings --> <script src="@Url.Content("~/Scripts/plugins/config.js")"></script> <!-- the script which handles all the access to plugins etc... --> <script src="@Url.Content("~/Scripts/plugins/script.js")"></script> </head> <body> <div id="pageoptions"> <ul> <li> @Html.Partial("_LogOnPartial")</li> <li><a href="#" id="wl_config">Configuration</a></li> <li><a href="#">Settings</a></li> </ul> <div> <h3> Place for some configs</h3> <p> Li Europan lingues es membres del sam familie. Lor separat existentie es un myth. Por scientie, musica, sport etc, litot Europa usa li sam vocabular. Li lingues differe solmen in li grammatica, li pronunciation e li plu commun vocabules. Omnicos directe al desirabilite de un nov lingua franca: On refusa continuar payar custosi traductores.</p> </div> </div> <header> <div id="logo"> <a href="dashboard.html">Logo</a> </div> <div id="header"> <ul id="headernav"> <li><ul> <li><a href="icons.html">Icons</a><span>300+</span></li> <li><a href="#">Submenu</a><span>4</span> <ul> <li><a href="#">Just</a></li> <li><a href="#">another</a></li> <li><a href="#">Dropdown</a></li> <li><a href="#">Menu</a></li> </ul> </li> <li><a href="login.html">Login</a></li> <li><a href="wizard.html">Wizard</a><span>Bonus</span></li> <li><a href="#">Errorpage</a><span>new</span> <ul> <li><a href="error-403.html">403</a></li> <li><a href="error-404.html">404</a></li> <li><a href="error-405.html">405</a></li> <li><a href="error-500.html">500</a></li> <li><a href="error-503.html">503</a></li> </ul> </li> </ul></li> </ul> <div id="searchbox"> <form id="searchform" autocomplete="off"> <input type="search" name="query" id="search" placeholder="Search"> </form> </div> <ul id="searchboxresult"> </ul> </div> </header> <nav> <ul id="nav"> <li class="i_house"><a class="active" href="/"><span>Dashboard</span></a></li> <li class="i_book"><a><span>Documentation</span></a> <ul> <li><a href="doc-alert.html"><span>Alert Boxes</span></a></li> <li><a href="doc-breadcrumb.html"><span>Breadcrumb</span></a></li> <li><a href="doc-calendar.html"><span>Calendar</span></a></li> <li><a href="doc-charts.html"><span>Charts</span></a></li> <li><a href="doc-dialog.html"><span>Dialog</span></a></li> <li><a href="doc-editor.html"><span>Editor</span></a></li> <li><a href="doc-file.html"><span>File</span></a></li> <li><a href="doc-fileexplorer.html"><span>Fileexplorer</span></a></li> <li><a href="doc-form.html"><span>Form</span></a></li> <li><a href="doc-gallery.html"><span>Gallery</span></a></li> <li><a href="doc-inputfields.html"><span>Inputfields</span></a></li> <li><a href="doc-slider.html"><span>Slider</span></a></li> <li><a href="doc-store.html"><span>Store</span></a></li> <li><a href="doc-widget.html"><span>Widget</span></a></li> </ul> </li> <li class="i_create_write"><a href="form.html"><span>Form</span></a></li> <li class="i_graph"><a href="charts.html"><span>Charts</span></a></li> <li class="i_images"><a href="gallery.html"><span>Gallery</span></a></li> <li class="i_blocks_images"><a href="widgets.html"><span>Widgets</span></a></li> <li class="i_breadcrumb"><a href="breadcrumb.html"><span>Breadcrumb</span></a></li> <li class="i_file_cabinet"><a href="fileexplorer.html"><span>Fileexplorer</span></a></li> <li class="i_calendar_day"><a href="calendar.html"><span>Calendar</span></a></li> <li class="i_speech_bubbles_2"><a href="dialogs_and_buttons.html"><span>Dialogs &amp; Buttons</span></a></li> <li class="i_table"><a href="datatable.html"><span>Table</span></a></li> <li class="i_typo"><a href="typo.html"><span>Typo</span></a></li> <li class="i_grid"><a href="grid.html"><span>Grid</span></a></li> </ul> </nav> <section id="content"> @RenderBody() </section> <footer>Copyright 2013</footer> </body> </html>
08102013project
trunk/CMS/Views/Shared/_MainLayout.cshtml
HTML+Razor
oos
7,719
/*----------------------------------------------------------------------*/ /* wl_Store v 2.0 by revaxarts.com /* description: Uses LocalStorage to save information within the Browser /* enviroment /* dependency: jStorage /*----------------------------------------------------------------------*/ $.wl_Store = function (namespace) { if(typeof $.jStorage != 'object') $.error('wl_Store requires the jStorage library'); var namespace = namespace || 'wl_store', save = function (key, value) { return $.jStorage.set(namespace+'_'+key, value); }, get = function (key) { return $.jStorage.get(namespace+'_'+key); }; remove = function (key) { return $.jStorage.deleteKey(namespace+'_'+key); }, flush = function () { return $.jStorage.flush(); }, index = function () { return $.jStorage.index(); }; //public methods return { save: function (key, value) { return save(key, value); }, get: function (key) { return get(key); }, remove: function (key) { return remove(key); }, flush: function () { return flush(); }, index: function () { return index(); } } };
08102013project
trunk/CMS/Scripts/plugins/wl_Store.js
JavaScript
oos
1,209
$(document).ready(function() { //for Caching var $content = $('#content'); /*----------------------------------------------------------------------*/ /* preload images /*----------------------------------------------------------------------*/ //$.preload(); /*----------------------------------------------------------------------*/ /* Widgets /*----------------------------------------------------------------------*/ $content.find('div.widgets').wl_Widget(); /*----------------------------------------------------------------------*/ /* All Form Plugins /*----------------------------------------------------------------------*/ //Integers and decimals $content.find('input[type=number].integer').wl_Number(); $content.find('input[type=number].decimal').wl_Number({decimals:2,step:0.5}); //Date and Time fields $content.find('input.date, div.date').wl_Date(); $content.find('input.time').wl_Time(); //Autocompletes (source is required) $content.find('input.autocomplete').wl_Autocomplete({ source: ["ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskell","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"] }); //Elastic textareas (autogrow) $content.find('textarea[data-autogrow]').elastic(); //WYSIWYG Editor $content.find('textarea.html').wl_Editor(); //Validation $content.find('input[data-regex]').wl_Valid(); $content.find('input[type=email]').wl_Mail(); $content.find('input[type=url]').wl_URL(); //File Upload $content.find('input[type=file]').wl_File(); //Password and Color $content.find('input[type=password]').wl_Password(); $content.find('input.color').wl_Color(); //Sliders $content.find('div.slider').wl_Slider(); //Multiselects $content.find('select[multiple]').wl_Multiselect(); //The Form is called for the demo with options on line 497 //$content.find('form').wl_Form(); /*----------------------------------------------------------------------*/ /* Alert boxes /*----------------------------------------------------------------------*/ $content.find('div.alert').wl_Alert(); /*----------------------------------------------------------------------*/ /* Breadcrumb /*----------------------------------------------------------------------*/ $content.find('ul.breadcrumb').wl_Breadcrumb(); /*----------------------------------------------------------------------*/ /* datatable plugin /*----------------------------------------------------------------------*/ $content.find("table.datatable").dataTable({ "sPaginationType": "full_numbers" }); /*----------------------------------------------------------------------*/ /* uniform plugin && checkbox plugin (since 1.3.2) /* uniform plugin causes some issues on checkboxes and radios /*----------------------------------------------------------------------*/ $("select, input[type=file]").not('select[multiple]').uniform(); $('input:checkbox, input:radio').checkbox(); /*----------------------------------------------------------------------*/ /* Charts /*----------------------------------------------------------------------*/ $content.find('table.chart').wl_Chart({ onClick: function(value, legend, label, id){ $.msg("value is "+value+" from "+legend+" at "+label+" ("+id+")",{header:'Custom Callback'}); } }); /*----------------------------------------------------------------------*/ /* Fileexplorer /*----------------------------------------------------------------------*/ $content.find('div.fileexplorer').wl_Fileexplorer(); /*----------------------------------------------------------------------*/ /* Calendar (read http://arshaw.com/fullcalendar/docs/ for more info!) /*----------------------------------------------------------------------*/ $content.find('div.calendar').wl_Calendar({ eventSources: [ { url: 'http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic' },{ events: [ // put the array in the `events` property { title : 'Fixed Event', start : '2012-02-01' }, { title : 'long fixed Event', start : '2012-02-06', end : '2012-02-14' } ], color: '#f0a8a8', // an option! textColor: '#ffffff' // an option! },{ events: [ // put the array in the `events` property { title : 'Editable', start : '2012-02-09 12:30:00' } ], editable:true, color: '#a2e8a2', // an option! textColor: '#ffffff' // an option! } // any other event sources... ] }); /*----------------------------------------------------------------------*/ /* Gallery /*----------------------------------------------------------------------*/ //defined for the demo on line 518 //$content.find('ul.gallery').wl_Gallery(); /*----------------------------------------------------------------------*/ /* Tipsy Tooltip /*----------------------------------------------------------------------*/ $content.find('input[title]').tipsy({ gravity: function(){return ($(this).data('tooltip-gravity') || config.tooltip.gravity); }, fade: config.tooltip.fade, opacity: config.tooltip.opacity, color: config.tooltip.color, offset: config.tooltip.offset }); /*----------------------------------------------------------------------*/ /* Accordions /*----------------------------------------------------------------------*/ $content.find('div.accordion').accordion({ collapsible:true, autoHeight:false }); /*----------------------------------------------------------------------*/ /* Tabs /*----------------------------------------------------------------------*/ $content.find('div.tab').tabs({ fx: { opacity: 'toggle', duration: 'fast' } }); /*----------------------------------------------------------------------*/ /* Navigation Stuff /*----------------------------------------------------------------------*/ //Top Pageoptions $('#wl_config').click(function(){ var $pageoptions = $('#pageoptions'); if($pageoptions.height() < 200){ $pageoptions.animate({'height':200}); $(this).addClass('active'); }else{ $pageoptions.animate({'height':20}); $(this).removeClass('active'); } return false; }); //Header navigation for smaller screens var $headernav = $('ul#headernav'); $headernav.bind('click',function(){ //if(window.innerWidth > 800) return false; var ul = $headernav.find('ul').eq(0); (ul.is(':hidden')) ? ul.addClass('shown') : ul.removeClass('shown'); }); $headernav.find('ul > li').bind('click',function(event){ event.stopPropagation(); var children = $(this).children('ul'); if(children.length){ (children.is(':hidden')) ? children.addClass('shown') : children.removeClass('shown'); return false; } }); //Search Field Stuff var $searchform = $('#searchform'), $searchfield = $('#search'), livesearch = true; $searchfield .bind({ 'focus.wl': function(){ $searchfield.select().parent().animate({width: '150px'},100); }, 'blur.wl': function(){ $searchfield.parent().animate({width: '90px'},100); if(livesearch)$searchboxresult.fadeOut(); } }); //livesearch is active if(livesearch){ $searchfield.attr('placeholder','Live Search'); var $searchboxresult = $('#searchboxresult'), searchdelay = 800, //delay of search in milliseconds (prevent flooding) searchminimum = 3, //minimum of letter when search should start searchtimeout, searchterm, resulttitle; //insert the container if missing if(!$searchboxresult.length) $searchboxresult = $('<div id="searchboxresult"></div>').insertAfter('#searchbox'); //bind the key event $searchfield .bind({ 'keyup.wl': function(event){ //do nothing if the term hasn't change if(searchterm == $searchfield.val()) return false; //the current search value searchterm = $searchfield.val(); //clear the old timeout and start a new one clearTimeout(searchtimeout); //stop if term is too short if(searchterm.length < searchminimum){ $searchboxresult.fadeOut(); $searchfield.removeClass('load'); return false; } searchtimeout = setTimeout(function(){ $searchfield.addClass('load'); //get results with ajax $.post("search.php", { term: searchterm }, function(data){ $searchfield.removeClass('load'); //search value don't has to be too short if(searchterm.length < searchminimum){ $searchboxresult.fadeOut(); return false; } var count = data.length, html = ''; //we have results if(count){ for(var i = 0; i< count; i++){ resulttitle = ''; if(data[i].text.length > 105){ resulttitle = 'title="'+data[i].text+'"'; data[i].text = $.trim(data[i].text.substr(0,100))+'&hellip;'; } html += '<li><a href="'+data[i].href+'" '+resulttitle+'>'; if(data[i].img) html += '<img src="'+data[i].img+'" width="50">'; html += ''+data[i].text+'</a></li>'; } //no result to this search term }else{ html += '<li><a class="noresult">Nothing found for<br>"'+searchterm+'"</a></li>'; } //insert it and show $searchboxresult.html(html).fadeIn(); }, "json"); },searchdelay); } }); } $searchform .bind('submit.wl',function(){ //do something on submit var query = $searchfield.val(); }); //Main Navigation var $nav = $('#nav'); $nav.delegate('li','click.wl', function(event){ var _this = $(this), _parent = _this.parent(), a = _parent.find('a'); _parent.find('ul').slideUp('fast'); a.removeClass('active'); _this.find('ul:hidden').slideDown('fast'); _this.find('a').eq(0).addClass('active'); event.stopPropagation(); }); /*----------------------------------------------------------------------*/ /* Helpers /*----------------------------------------------------------------------*/ //placholder in inputs is not implemented well in all browsers, so we need to trick this $("[placeholder]").bind('focus.placeholder',function() { var el = $(this); if (el.val() == el.attr("placeholder") && !el.data('uservalue')) { el.val(""); el.removeClass("placeholder"); } }).bind('blur.placeholder',function() { var el = $(this); if (el.val() == "" || el.val() == el.attr("placeholder") && !el.data('uservalue')) { el.addClass("placeholder"); el.val(el.attr("placeholder")); el.data("uservalue",false); }else{ } }).bind('keyup.placeholder',function() { var el = $(this); if (el.val() == "") { el.data("uservalue",false); }else{ el.data("uservalue",true); } }).trigger('blur.placeholder'); /*-----------------------------------------------------------------------------------------------------------------------------*/ /* Following code is for the Demonstration only! /* Get inspired and use it further or just remove it! /*-----------------------------------------------------------------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Callback for Slider /*----------------------------------------------------------------------*/ $content.find('div.slider#slider_callback').wl_Slider({ onSlide:function(value){ $('#slider_callback_bar').width(value+'%').text(value); } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Rangeslider area how to /* http://revaxarts-themes.com/whitelabel/doc-sliders.html /*----------------------------------------------------------------------*/ $content.find('div.slider#slider_mousewheel').wl_Slider({ onSlide:function(values){ var _this = $('#slider_mousewheel'), _handler = _this.find('a'); _h1 = _handler.eq(0).offset(), _h2 = _handler.eq(1).offset(), value = _h1.left+(_h2.left-_h1.left)/2-_this.offset().left+5; $('#slider_mousewheel_left').width(value); $('#slider_mousewheel_right').width(_this.width()-value); } }); $('#slider_mousewheel_left, #slider_mousewheel_right').bind('mousewheel',function(event,delta){ event.preventDefault(); $.alert('Use the Slider above!\nThis is just for visualisation'); }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Button to clear localStorage /* http://revaxarts-themes.com/whitelabel/widgets.html /*----------------------------------------------------------------------*/ $content.find('.clearLocalStorage').bind('click',function(){ var wl_Store = new $.wl_Store(); if(wl_Store.flush()){ $.msg("LocalStorage as been cleared!"); }; return false; }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* needed for the Store Documentation /* http://revaxarts-themes.com/whitelabel/doc-store.html /*----------------------------------------------------------------------*/ $content.find('#save_store').bind('click',function(){ $.prompt('Storing some values?','This text is for the storage',function(value){ var wl_Store = new $.wl_Store('doc-store'); if(wl_Store.save('testvalue', value)){ $.msg('Your data has been saved!. You can reload the page now!',{live:10000}); }else{ $.msg('Sorry, but a problem while storing your data occurs! Maybe your browser isn\'t supported!',{live:10000}); } }); }); $content.find('#restore_store').bind('click',function(){ var wl_Store = new $.wl_Store('doc-store'); var value = wl_Store.get('testvalue'); if(value){ $.alert('your value is:\n'+value); }else{ $.alert('No value is set!'); } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Confirm Box for the Form Filler /* http://revaxarts-themes.com/whitelabel/form.html /*----------------------------------------------------------------------*/ $('#formfiller').click(function(){ var _this = this; $.confirm('To fill a form with your data you have to add a query string to the location.\nhttp://domain.tld/path?key=value&key2=value2',function(){ window.location.href = _this.href; }); return false; }); /*----------------------------------------------------------------------*/ /* Toggle to nativ/ajax submit /* http://revaxarts-themes.com/whitelabel/form.html /*----------------------------------------------------------------------*/ $('#formsubmitswitcher').click(function(){ var _this = $(this); if(_this.text() == 'send form natively'){ $content.find('form').wl_Form('set','ajax',false); $.msg('The form will now use the browser native submit method'); _this.text('send form with ajax'); }else{ $content.find('form').wl_Form('set','ajax',true); $.msg('The form will now be sent with an ajax request'); _this.text('send form natively'); } return false; }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* add some Callbacks to the Form /* http://revaxarts-themes.com/whitelabel/form.html /*----------------------------------------------------------------------*/ $content.find('form').wl_Form({ onSuccess: function(data, status){ if(window.console){ console.log(status); console.log(data); }; $.msg("Custom Callback on success\nDevelopers! Check your Console!"); }, onError: function(status, error, jqXHR){ $.msg("Callback on Error\nError Status: "+status+"\nError Msg: "+error); } }); /*----------------------------------------------------------------------*/ /* Gallery with some custom callbacks /* http://revaxarts-themes.com/whitelabel/gallery.html /*----------------------------------------------------------------------*/ $content.find('ul.gallery').wl_Gallery({ onEdit: function(el, href, title){ if(href){ $.confirm('For demonstration I use pixlr to edit images.\nDo you like to continue?',function(){ window.open('http://pixlr.com/editor/?referrer=whitelabel&image='+escape(href)+'&title='+escape(title)+''); }); } }, onDelete: function(el, href, title){ if(href){ $.confirm('Do you really like to delete this?',function(){ el.fadeOut(); }); } }, onMove: function(el, href, title, newOrder){ } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Message trigger buttons /* http://revaxarts-themes.com/whitelabel/dialogs_and_buttons.html /*----------------------------------------------------------------------*/ $('#message').click(function(){ $.msg("This is a simple Message"); }); $('#message_sticky').click(function(){ $.msg("This Message will stay until you click the cross",{sticky:true}); }); $('#message_header').click(function(){ $.msg("This is with a custom Header",{header:'Custom Header'}); }); $('#message_delay').click(function(){ $.msg("This stays exactly 10 seconds",{live:10000}); }); $('#message_methods').click(function(){ var m = $.msg("This message can be accessed via public methods",{sticky:true}); //do some action with a delay setTimeout(function(){ if(m)m.setHeader('Set a Header'); },3000); setTimeout(function(){ if(m)m.setBody('Set a custom Body'); },5000); setTimeout(function(){ if(m)m.setBody('..and close it with an optional callback function'); },8000); setTimeout(function(){ if(m)m.close(function(){ $.alert('This is the Callback function'); }); },12000); }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Dialog trigger buttons /* http://revaxarts-themes.com/whitelabel/dialogs_and_buttons.html /*----------------------------------------------------------------------*/ $('#dialog').click(function(){ $.alert("This is a simple Message"); }); $('#dialog_confirm').click(function(){ $.confirm("Do you really like to confirm this?", function(){ $.msg("confirmed!"); }, function(){ $.msg("You clicked cancel!"); }); }); $('#dialog_prompt').click(function(){ $.prompt("What do you really like?","Pizza", function(value){ $.msg("So, you like '"+value+"'?"); }, function(){ $.msg("You clicked cancel!"); }); }); $('#dialog_switch').click(function(){ if($.alert.defaults.nativ){ $(this).text('switch to nativ dialogs'); }else{ $(this).text('switch to jQuery Dialogs'); } $.alert.defaults.nativ = !$.alert.defaults.nativ; }); $('#dialog_methods').click(function(){ var a = $.alert("This message can be accessed via public methods"); //do some action with a delay setTimeout(function(){ if(a)a.setHeader('Set a Header'); },3000); setTimeout(function(){ if(a)a.setBody('Set a custom Body'); },5000); setTimeout(function(){ if(a)a.setBody('..and close it with an optional callback function'); },8000); setTimeout(function(){ if(a)a.close(function(){ $.msg('This is the Callback function'); }); },12000); }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Breadcrumb Demos /* http://revaxarts-themes.com/whitelabel/breadcrumb.html /*----------------------------------------------------------------------*/ $('#enablebreadcrumb').click(function(){ $('ul.breadcrumb').eq(4).wl_Breadcrumb('enable'); $.msg('enabled!'); }); $('#disablebreadcrumb').click(function(){ $('ul.breadcrumb').eq(4).wl_Breadcrumb('disable'); $.msg('disabled!'); }); $('ul.breadcrumb').eq(5).wl_Breadcrumb({ onChange:function(element,id){ $.msg(element.text()+' with id '+id); } }); /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Helps to make current section active in the Mainbar /*----------------------------------------------------------------------*/ var loc = location.pathname.replace(/\/([^.]+)\//g,''); var current = $nav.find('a[href="'+loc+'"]'); if(current.parent().parent().is('#nav')){ current.addClass('active'); }else{ current.parent().parent().parent().find('a').eq(0).addClass('active').next().show(); current.addClass('active'); } /*----------------------------------------------------------------------*/ }); /*----------------------------------------------------------------------*/ /* Autocomplete Function must be available befor wl_Autocomplete is called /*----------------------------------------------------------------------*/ window.myAutocompleteFunction = function(){ return ['Lorem ipsum dolor','sit amet consectetur adipiscing','elit Nulla et justo','est Vestibulum libero','enim adipiscing in','porta mollis sem','Duis lacinia','velit et est rhoncus','mattis Aliquam at','diam eu ipsum','rutrum tincidunt Etiam','nec porta erat Pellentesque','et elit sed sem','bibendum posuere Curabitur id','purus erat vel pretium','erat Ut ultricies semper','quam eu dignissim Cras sed','sapien arcu Phasellus sit amet','venenatis sapien Nulla facilisi','Curabitur ut','bibendum odio Fusce','vitae velit hendrerit','dui convallis tristique','eget nec leo','Vestibulum fermentum leo','ac rutrum interdum mauris','felis sodales arcu','non vehicula odio magna sed','tortor Etiam enim leo','interdum vitae elementum id','laoreet at massa Curabitur nisi dui','lobortis ut rutrum','quis gravida ut velit','Phasellus augue quam gravida non','vulputate vel tempus sit amet','nunc Proin convallis tristique purus']; };
08102013project
trunk/CMS/Scripts/plugins/script.js
JavaScript
oos
24,015
/* * File: jquery.dataTables.js * Version: 1.8.1 * Description: Paginate, search and sort HTML tables * Author: Allan Jardine (www.sprymedia.co.uk) * Created: 28/3/2008 * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: Mtaala * Contact: allan.jardine@sprymedia.co.uk * * Copyright 2008-2011 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, as supplied with this software. * * This source file 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 license files for details. * * For details please refer to: http://www.datatables.net */ /* * When considering jsLint, we need to allow eval() as it it is used for reading cookies */ /*jslint evil: true, undef: true, browser: true */ /*globals $, jQuery,_fnExternApiFunc,_fnInitalise,_fnInitComplete,_fnLanguageProcess,_fnAddColumn,_fnColumnOptions,_fnAddData,_fnCreateTr,_fnGatherData,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAjaxUpdate,_fnAjaxUpdateDraw,_fnAddOptionsHtml,_fnFeatureHtmlTable,_fnScrollDraw,_fnAjustColumnSizing,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnBuildSearchArray,_fnBuildSearchRow,_fnFilterCreateSearch,_fnDataToSearch,_fnSort,_fnSortAttachListener,_fnSortingClasses,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnFeatureHtmlLength,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnNodeToDataIndex,_fnVisbleColumns,_fnCalculateEnd,_fnConvertToWidth,_fnCalculateColumnWidths,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnArrayCmp,_fnDetectType,_fnSettingsFromNode,_fnGetDataMaster,_fnGetTrNodes,_fnGetTdNodes,_fnEscapeRegex,_fnDeleteIndex,_fnReOrderIndex,_fnColumnOrdering,_fnLog,_fnClearTable,_fnSaveState,_fnLoadState,_fnCreateCookie,_fnReadCookie,_fnDetectHeader,_fnGetUniqueThs,_fnScrollBarWidth,_fnApplyToChildren,_fnMap,_fnGetRowData,_fnGetCellData,_fnSetCellData,_fnGetObjectDataFn,_fnSetObjectDataFn*/ (function($, window, document) { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - DataTables variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Variable: dataTableSettings * Purpose: Store the settings for each dataTables instance * Scope: jQuery.fn */ $.fn.dataTableSettings = []; var _aoSettings = $.fn.dataTableSettings; /* Short reference for fast internal lookup */ /* * Variable: dataTableExt * Purpose: Container for customisable parts of DataTables * Scope: jQuery.fn */ $.fn.dataTableExt = {}; var _oExt = $.fn.dataTableExt; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - DataTables extensible objects * * The _oExt object is used to provide an area where user dfined plugins can be * added to DataTables. The following properties of the object are used: * oApi - Plug-in API functions * aTypes - Auto-detection of types * oSort - Sorting functions used by DataTables (based on the type) * oPagination - Pagination functions for different input styles * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Variable: sVersion * Purpose: Version string for plug-ins to check compatibility * Scope: jQuery.fn.dataTableExt * Notes: Allowed format is a.b.c.d.e where: * a:int, b:int, c:int, d:string(dev|beta), e:int. d and e are optional */ _oExt.sVersion = "1.8.1"; /* * Variable: sErrMode * Purpose: How should DataTables report an error. Can take the value 'alert' or 'throw' * Scope: jQuery.fn.dataTableExt */ _oExt.sErrMode = "alert"; /* * Variable: iApiIndex * Purpose: Index for what 'this' index API functions should use * Scope: jQuery.fn.dataTableExt */ _oExt.iApiIndex = 0; /* * Variable: oApi * Purpose: Container for plugin API functions * Scope: jQuery.fn.dataTableExt */ _oExt.oApi = { }; /* * Variable: aFiltering * Purpose: Container for plugin filtering functions * Scope: jQuery.fn.dataTableExt */ _oExt.afnFiltering = [ ]; /* * Variable: aoFeatures * Purpose: Container for plugin function functions * Scope: jQuery.fn.dataTableExt * Notes: Array of objects with the following parameters: * fnInit: Function for initialisation of Feature. Takes oSettings and returns node * cFeature: Character that will be matched in sDom - case sensitive * sFeature: Feature name - just for completeness :-) */ _oExt.aoFeatures = [ ]; /* * Variable: ofnSearch * Purpose: Container for custom filtering functions * Scope: jQuery.fn.dataTableExt * Notes: This is an object (the name should match the type) for custom filtering function, * which can be used for live DOM checking or formatted text filtering */ _oExt.ofnSearch = { }; /* * Variable: afnSortData * Purpose: Container for custom sorting data source functions * Scope: jQuery.fn.dataTableExt * Notes: Array (associative) of functions which is run prior to a column of this * 'SortDataType' being sorted upon. * Function input parameters: * object:oSettings- DataTables settings object * int:iColumn - Target column number * Return value: Array of data which exactly matched the full data set size for the column to * be sorted upon */ _oExt.afnSortData = [ ]; /* * Variable: oStdClasses * Purpose: Storage for the various classes that DataTables uses * Scope: jQuery.fn.dataTableExt */ _oExt.oStdClasses = { /* Two buttons buttons */ "sPagePrevEnabled": "paginate_enabled_previous", "sPagePrevDisabled": "paginate_disabled_previous", "sPageNextEnabled": "paginate_enabled_next", "sPageNextDisabled": "paginate_disabled_next", "sPageJUINext": "", "sPageJUIPrev": "", /* Full numbers paging buttons */ "sPageButton": "paginate_button", "sPageButtonActive": "paginate_active", "sPageButtonStaticDisabled": "paginate_button paginate_button_disabled", "sPageFirst": "first", "sPagePrevious": "previous", "sPageNext": "next", "sPageLast": "last", /* Stripping classes */ "sStripOdd": "odd", "sStripEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "sorting_asc", "sSortDesc": "sorting_desc", "sSortable": "sorting", /* Sortable in both directions */ "sSortableAsc": "sorting_asc_disabled", "sSortableDesc": "sorting_desc_disabled", "sSortableNone": "sorting_disabled", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ "sSortJUIAsc": "", "sSortJUIDesc": "", "sSortJUI": "", "sSortJUIAscAllowed": "", "sSortJUIDescAllowed": "", "sSortJUIWrapper": "", "sSortIcon": "", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sFooterTH": "" }; /* * Variable: oJUIClasses * Purpose: Storage for the various classes that DataTables uses - jQuery UI suitable * Scope: jQuery.fn.dataTableExt */ _oExt.oJUIClasses = { /* Two buttons buttons */ "sPagePrevEnabled": "fg-button ui-button ui-state-default ui-corner-left", "sPagePrevDisabled": "fg-button ui-button ui-state-default ui-corner-left ui-state-disabled", "sPageNextEnabled": "fg-button ui-button ui-state-default ui-corner-right", "sPageNextDisabled": "fg-button ui-button ui-state-default ui-corner-right ui-state-disabled", "sPageJUINext": "ui-icon ui-icon-circle-arrow-e", "sPageJUIPrev": "ui-icon ui-icon-circle-arrow-w", /* Full numbers paging buttons */ "sPageButton": "fg-button ui-button ui-state-default", "sPageButtonActive": "fg-button ui-button ui-state-default ui-state-disabled", "sPageButtonStaticDisabled": "fg-button ui-button ui-state-default ui-state-disabled", "sPageFirst": "first ui-corner-tl ui-corner-bl", "sPagePrevious": "previous", "sPageNext": "next", "sPageLast": "last ui-corner-tr ui-corner-br", /* Stripping classes */ "sStripOdd": "odd", "sStripEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+ "ui-buttonset-multi paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "ui-state-default", "sSortDesc": "ui-state-default", "sSortable": "ui-state-default", "sSortableAsc": "ui-state-default", "sSortableDesc": "ui-state-default", "sSortableNone": "ui-state-default", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ "sSortJUIAsc": "css_right ui-icon ui-icon-triangle-1-n", "sSortJUIDesc": "css_right ui-icon ui-icon-triangle-1-s", "sSortJUI": "css_right ui-icon ui-icon-carat-2-n-s", "sSortJUIAscAllowed": "css_right ui-icon ui-icon-carat-1-n", "sSortJUIDescAllowed": "css_right ui-icon ui-icon-carat-1-s", "sSortJUIWrapper": "DataTables_sort_wrapper", "sSortIcon": "DataTables_sort_icon", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead ui-state-default", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot ui-state-default", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sFooterTH": "ui-state-default" }; /* * Variable: oPagination * Purpose: Container for the various type of pagination that dataTables supports * Scope: jQuery.fn.dataTableExt */ _oExt.oPagination = { /* * Variable: two_button * Purpose: Standard two button (forward/back) pagination * Scope: jQuery.fn.dataTableExt.oPagination */ "two_button": { /* * Function: oPagination.two_button.fnInit * Purpose: Initalise dom elements required for pagination with forward/back buttons only * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nPaging - the DIV which contains this pagination control * function:fnCallbackDraw - draw function which must be called on update */ "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { var nPrevious, nNext, nPreviousInner, nNextInner; /* Store the next and previous elements in the oSettings object as they can be very * usful for automation - particularly testing */ if ( !oSettings.bJUI ) { nPrevious = document.createElement( 'div' ); nNext = document.createElement( 'div' ); } else { nPrevious = document.createElement( 'a' ); nNext = document.createElement( 'a' ); nNextInner = document.createElement('span'); nNextInner.className = oSettings.oClasses.sPageJUINext; nNext.appendChild( nNextInner ); nPreviousInner = document.createElement('span'); nPreviousInner.className = oSettings.oClasses.sPageJUIPrev; nPrevious.appendChild( nPreviousInner ); } nPrevious.className = oSettings.oClasses.sPagePrevDisabled; nNext.className = oSettings.oClasses.sPageNextDisabled; nPrevious.title = oSettings.oLanguage.oPaginate.sPrevious; nNext.title = oSettings.oLanguage.oPaginate.sNext; nPaging.appendChild( nPrevious ); nPaging.appendChild( nNext ); $(nPrevious).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "previous" ) ) { /* Only draw when the page has actually changed */ fnCallbackDraw( oSettings ); } } ); $(nNext).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "next" ) ) { fnCallbackDraw( oSettings ); } } ); /* Take the brutal approach to cancelling text selection */ $(nPrevious).bind( 'selectstart.DT', function () { return false; } ); $(nNext).bind( 'selectstart.DT', function () { return false; } ); /* ID the first elements only */ if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.p == "undefined" ) { nPaging.setAttribute( 'id', oSettings.sTableId+'_paginate' ); nPrevious.setAttribute( 'id', oSettings.sTableId+'_previous' ); nNext.setAttribute( 'id', oSettings.sTableId+'_next' ); } }, /* * Function: oPagination.two_button.fnUpdate * Purpose: Update the two button pagination at the end of the draw * Returns: - * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function to call on page change */ "fnUpdate": function ( oSettings, fnCallbackDraw ) { if ( !oSettings.aanFeatures.p ) { return; } /* Loop over each instance of the pager */ var an = oSettings.aanFeatures.p; for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { if ( an[i].childNodes.length !== 0 ) { an[i].childNodes[0].className = ( oSettings._iDisplayStart === 0 ) ? oSettings.oClasses.sPagePrevDisabled : oSettings.oClasses.sPagePrevEnabled; an[i].childNodes[1].className = ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) ? oSettings.oClasses.sPageNextDisabled : oSettings.oClasses.sPageNextEnabled; } } } }, /* * Variable: iFullNumbersShowPages * Purpose: Change the number of pages which can be seen * Scope: jQuery.fn.dataTableExt.oPagination */ "iFullNumbersShowPages": 5, /* * Variable: full_numbers * Purpose: Full numbers pagination * Scope: jQuery.fn.dataTableExt.oPagination */ "full_numbers": { /* * Function: oPagination.full_numbers.fnInit * Purpose: Initalise dom elements required for pagination with a list of the pages * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nPaging - the DIV which contains this pagination control * function:fnCallbackDraw - draw function which must be called on update */ "fnInit": function ( oSettings, nPaging, fnCallbackDraw ) { var nFirst = document.createElement( 'span' ); var nPrevious = document.createElement( 'span' ); var nList = document.createElement( 'span' ); var nNext = document.createElement( 'span' ); var nLast = document.createElement( 'span' ); nFirst.innerHTML = oSettings.oLanguage.oPaginate.sFirst; nPrevious.innerHTML = oSettings.oLanguage.oPaginate.sPrevious; nNext.innerHTML = oSettings.oLanguage.oPaginate.sNext; nLast.innerHTML = oSettings.oLanguage.oPaginate.sLast; var oClasses = oSettings.oClasses; nFirst.className = oClasses.sPageButton+" "+oClasses.sPageFirst; nPrevious.className = oClasses.sPageButton+" "+oClasses.sPagePrevious; nNext.className= oClasses.sPageButton+" "+oClasses.sPageNext; nLast.className = oClasses.sPageButton+" "+oClasses.sPageLast; nPaging.appendChild( nFirst ); nPaging.appendChild( nPrevious ); nPaging.appendChild( nList ); nPaging.appendChild( nNext ); nPaging.appendChild( nLast ); $(nFirst).bind( 'click.DT', function () { if ( oSettings.oApi._fnPageChange( oSettings, "first" ) ) { fnCallbackDraw( oSettings ); } } ); $(nPrevious).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "previous" ) ) { fnCallbackDraw( oSettings ); } } ); $(nNext).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "next" ) ) { fnCallbackDraw( oSettings ); } } ); $(nLast).bind( 'click.DT', function() { if ( oSettings.oApi._fnPageChange( oSettings, "last" ) ) { fnCallbackDraw( oSettings ); } } ); /* Take the brutal approach to cancelling text selection */ $('span', nPaging) .bind( 'mousedown.DT', function () { return false; } ) .bind( 'selectstart.DT', function () { return false; } ); /* ID the first elements only */ if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.p == "undefined" ) { nPaging.setAttribute( 'id', oSettings.sTableId+'_paginate' ); nFirst.setAttribute( 'id', oSettings.sTableId+'_first' ); nPrevious.setAttribute( 'id', oSettings.sTableId+'_previous' ); nNext.setAttribute( 'id', oSettings.sTableId+'_next' ); nLast.setAttribute( 'id', oSettings.sTableId+'_last' ); } }, /* * Function: oPagination.full_numbers.fnUpdate * Purpose: Update the list of page buttons shows * Returns: - * Inputs: object:oSettings - dataTables settings object * function:fnCallbackDraw - draw function to call on page change */ "fnUpdate": function ( oSettings, fnCallbackDraw ) { if ( !oSettings.aanFeatures.p ) { return; } var iPageCount = _oExt.oPagination.iFullNumbersShowPages; var iPageCountHalf = Math.floor(iPageCount / 2); var iPages = Math.ceil((oSettings.fnRecordsDisplay()) / oSettings._iDisplayLength); var iCurrentPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1; var sList = ""; var iStartButton, iEndButton, i, iLen; var oClasses = oSettings.oClasses; /* Pages calculation */ if (iPages < iPageCount) { iStartButton = 1; iEndButton = iPages; } else { if (iCurrentPage <= iPageCountHalf) { iStartButton = 1; iEndButton = iPageCount; } else { if (iCurrentPage >= (iPages - iPageCountHalf)) { iStartButton = iPages - iPageCount + 1; iEndButton = iPages; } else { iStartButton = iCurrentPage - Math.ceil(iPageCount / 2) + 1; iEndButton = iStartButton + iPageCount - 1; } } } /* Build the dynamic list */ for ( i=iStartButton ; i<=iEndButton ; i++ ) { if ( iCurrentPage != i ) { sList += '<span class="'+oClasses.sPageButton+'">'+i+'</span>'; } else { sList += '<span class="'+oClasses.sPageButtonActive+'">'+i+'</span>'; } } /* Loop over each instance of the pager */ var an = oSettings.aanFeatures.p; var anButtons, anStatic, nPaginateList; var fnClick = function(e) { /* Use the information in the element to jump to the required page */ var iTarget = (this.innerHTML * 1) - 1; oSettings._iDisplayStart = iTarget * oSettings._iDisplayLength; fnCallbackDraw( oSettings ); e.preventDefault(); }; var fnFalse = function () { return false; }; for ( i=0, iLen=an.length ; i<iLen ; i++ ) { if ( an[i].childNodes.length === 0 ) { continue; } /* Build up the dynamic list forst - html and listeners */ var qjPaginateList = $('span:eq(2)', an[i]); qjPaginateList.html( sList ); $('span', qjPaginateList).bind( 'click.DT', fnClick ).bind( 'mousedown.DT', fnFalse ) .bind( 'selectstart.DT', fnFalse ); /* Update the 'premanent botton's classes */ anButtons = an[i].getElementsByTagName('span'); anStatic = [ anButtons[0], anButtons[1], anButtons[anButtons.length-2], anButtons[anButtons.length-1] ]; $(anStatic).removeClass( oClasses.sPageButton+" "+oClasses.sPageButtonActive+" "+oClasses.sPageButtonStaticDisabled ); if ( iCurrentPage == 1 ) { anStatic[0].className += " "+oClasses.sPageButtonStaticDisabled; anStatic[1].className += " "+oClasses.sPageButtonStaticDisabled; } else { anStatic[0].className += " "+oClasses.sPageButton; anStatic[1].className += " "+oClasses.sPageButton; } if ( iPages === 0 || iCurrentPage == iPages || oSettings._iDisplayLength == -1 ) { anStatic[2].className += " "+oClasses.sPageButtonStaticDisabled; anStatic[3].className += " "+oClasses.sPageButtonStaticDisabled; } else { anStatic[2].className += " "+oClasses.sPageButton; anStatic[3].className += " "+oClasses.sPageButton; } } } } }; /* * Variable: oSort * Purpose: Wrapper for the sorting functions that can be used in DataTables * Scope: jQuery.fn.dataTableExt * Notes: The functions provided in this object are basically standard javascript sort * functions - they expect two inputs which they then compare and then return a priority * result. For each sort method added, two functions need to be defined, an ascending sort and * a descending sort. */ _oExt.oSort = { /* * text sorting */ "string-asc": function ( a, b ) { if ( typeof a != 'string' ) { a = ''; } if ( typeof b != 'string' ) { b = ''; } var x = a.toLowerCase(); var y = b.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "string-desc": function ( a, b ) { if ( typeof a != 'string' ) { a = ''; } if ( typeof b != 'string' ) { b = ''; } var x = a.toLowerCase(); var y = b.toLowerCase(); return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }, /* * html sorting (ignore html tags) */ "html-asc": function ( a, b ) { var x = a.replace( /<.*?>/g, "" ).toLowerCase(); var y = b.replace( /<.*?>/g, "" ).toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "html-desc": function ( a, b ) { var x = a.replace( /<.*?>/g, "" ).toLowerCase(); var y = b.replace( /<.*?>/g, "" ).toLowerCase(); return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }, /* * date sorting */ "date-asc": function ( a, b ) { var x = Date.parse( a ); var y = Date.parse( b ); if ( isNaN(x) || x==="" ) { x = Date.parse( "01/01/1970 00:00:00" ); } if ( isNaN(y) || y==="" ) { y = Date.parse( "01/01/1970 00:00:00" ); } return x - y; }, "date-desc": function ( a, b ) { var x = Date.parse( a ); var y = Date.parse( b ); if ( isNaN(x) || x==="" ) { x = Date.parse( "01/01/1970 00:00:00" ); } if ( isNaN(y) || y==="" ) { y = Date.parse( "01/01/1970 00:00:00" ); } return y - x; }, /* * numerical sorting */ "numeric-asc": function ( a, b ) { var x = (a=="-" || a==="") ? 0 : a*1; var y = (b=="-" || b==="") ? 0 : b*1; return x - y; }, "numeric-desc": function ( a, b ) { var x = (a=="-" || a==="") ? 0 : a*1; var y = (b=="-" || b==="") ? 0 : b*1; return y - x; } }; /* * Variable: aTypes * Purpose: Container for the various type of type detection that dataTables supports * Scope: jQuery.fn.dataTableExt * Notes: The functions in this array are expected to parse a string to see if it is a data * type that it recognises. If so then the function should return the name of the type (a * corresponding sort function should be defined!), if the type is not recognised then the * function should return null such that the parser and move on to check the next type. * Note that ordering is important in this array - the functions are processed linearly, * starting at index 0. * Note that the input for these functions is always a string! It cannot be any other data * type */ _oExt.aTypes = [ /* * Function: - * Purpose: Check to see if a string is numeric * Returns: string:'numeric' or null * Inputs: mixed:sText - string to check */ function ( sData ) { /* Allow zero length strings as a number */ if ( typeof sData == 'number' ) { return 'numeric'; } else if ( typeof sData != 'string' ) { return null; } var sValidFirstChars = "0123456789-"; var sValidChars = "0123456789."; var Char; var bDecimal = false; /* Check for a valid first char (no period and allow negatives) */ Char = sData.charAt(0); if (sValidFirstChars.indexOf(Char) == -1) { return null; } /* Check all the other characters are valid */ for ( var i=1 ; i<sData.length ; i++ ) { Char = sData.charAt(i); if (sValidChars.indexOf(Char) == -1) { return null; } /* Only allowed one decimal place... */ if ( Char == "." ) { if ( bDecimal ) { return null; } bDecimal = true; } } return 'numeric'; }, /* * Function: - * Purpose: Check to see if a string is actually a formatted date * Returns: string:'date' or null * Inputs: string:sText - string to check */ function ( sData ) { var iParse = Date.parse(sData); if ( (iParse !== null && !isNaN(iParse)) || (typeof sData == 'string' && sData.length === 0) ) { return 'date'; } return null; }, /* * Function: - * Purpose: Check to see if a string should be treated as an HTML string * Returns: string:'html' or null * Inputs: string:sText - string to check */ function ( sData ) { if ( typeof sData == 'string' && sData.indexOf('<') != -1 && sData.indexOf('>') != -1 ) { return 'html'; } return null; } ]; /* * Function: fnVersionCheck * Purpose: Check a version string against this version of DataTables. Useful for plug-ins * Returns: bool:true -this version of DataTables is greater or equal to the required version * false -this version of DataTales is not suitable * Inputs: string:sVersion - the version to check against. May be in the following formats: * "a", "a.b" or "a.b.c" * Notes: This function will only check the first three parts of a version string. It is * assumed that beta and dev versions will meet the requirements. This might change in future */ _oExt.fnVersionCheck = function( sVersion ) { /* This is cheap, but very effective */ var fnZPad = function (Zpad, count) { while(Zpad.length < count) { Zpad += '0'; } return Zpad; }; var aThis = _oExt.sVersion.split('.'); var aThat = sVersion.split('.'); var sThis = '', sThat = ''; for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) { sThis += fnZPad( aThis[i], 3 ); sThat += fnZPad( aThat[i], 3 ); } return parseInt(sThis, 10) >= parseInt(sThat, 10); }; /* * Variable: _oExternConfig * Purpose: Store information for DataTables to access globally about other instances * Scope: jQuery.fn.dataTableExt */ _oExt._oExternConfig = { /* int:iNextUnique - next unique number for an instance */ "iNextUnique": 0 }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - DataTables prototype * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Function: dataTable * Purpose: DataTables information * Returns: - * Inputs: object:oInit - initalisation options for the table */ $.fn.dataTable = function( oInit ) { /* * Function: classSettings * Purpose: Settings container function for all 'class' properties which are required * by dataTables * Returns: - * Inputs: - */ function classSettings () { this.fnRecordsTotal = function () { if ( this.oFeatures.bServerSide ) { return parseInt(this._iRecordsTotal, 10); } else { return this.aiDisplayMaster.length; } }; this.fnRecordsDisplay = function () { if ( this.oFeatures.bServerSide ) { return parseInt(this._iRecordsDisplay, 10); } else { return this.aiDisplay.length; } }; this.fnDisplayEnd = function () { if ( this.oFeatures.bServerSide ) { if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) { return this._iDisplayStart+this.aiDisplay.length; } else { return Math.min( this._iDisplayStart+this._iDisplayLength, this._iRecordsDisplay ); } } else { return this._iDisplayEnd; } }; /* * Variable: oInstance * Purpose: The DataTables object for this table * Scope: jQuery.dataTable.classSettings */ this.oInstance = null; /* * Variable: sInstance * Purpose: Unique idendifier for each instance of the DataTables object * Scope: jQuery.dataTable.classSettings */ this.sInstance = null; /* * Variable: oFeatures * Purpose: Indicate the enablement of key dataTable features * Scope: jQuery.dataTable.classSettings */ this.oFeatures = { "bPaginate": true, "bLengthChange": true, "bFilter": true, "bSort": true, "bInfo": true, "bAutoWidth": true, "bProcessing": false, "bSortClasses": true, "bStateSave": false, "bServerSide": false, "bDeferRender": false }; /* * Variable: oScroll * Purpose: Container for scrolling options * Scope: jQuery.dataTable.classSettings */ this.oScroll = { "sX": "", "sXInner": "", "sY": "", "bCollapse": false, "bInfinite": false, "iLoadGap": 100, "iBarWidth": 0, "bAutoCss": true }; /* * Variable: aanFeatures * Purpose: Array referencing the nodes which are used for the features * Scope: jQuery.dataTable.classSettings * Notes: The parameters of this object match what is allowed by sDom - i.e. * 'l' - Length changing * 'f' - Filtering input * 't' - The table! * 'i' - Information * 'p' - Pagination * 'r' - pRocessing */ this.aanFeatures = []; /* * Variable: oLanguage * Purpose: Store the language strings used by dataTables * Scope: jQuery.dataTable.classSettings * Notes: The words in the format _VAR_ are variables which are dynamically replaced * by javascript */ this.oLanguage = { "sProcessing": "Processing...", "sLengthMenu": "Show _MENU_ entries", "sZeroRecords": "No matching records found", "sEmptyTable": "No data available in table", "sLoadingRecords": "Loading...", "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries", "sInfoEmpty": "Showing 0 to 0 of 0 entries", "sInfoFiltered": "(filtered from _MAX_ total entries)", "sInfoPostFix": "", "sSearch": "Search:", "sUrl": "", "oPaginate": { "sFirst": "First", "sPrevious": "Previous", "sNext": "Next", "sLast": "Last" }, "fnInfoCallback": null }; /* * Variable: aoData * Purpose: Store data information * Scope: jQuery.dataTable.classSettings * Notes: This is an array of objects with the following parameters: * int: _iId - internal id for tracking * array: _aData - internal data - used for sorting / filtering etc * node: nTr - display node * array node: _anHidden - hidden TD nodes * string: _sRowStripe */ this.aoData = []; /* * Variable: aiDisplay * Purpose: Array of indexes which are in the current display (after filtering etc) * Scope: jQuery.dataTable.classSettings */ this.aiDisplay = []; /* * Variable: aiDisplayMaster * Purpose: Array of indexes for display - no filtering * Scope: jQuery.dataTable.classSettings */ this.aiDisplayMaster = []; /* * Variable: aoColumns * Purpose: Store information about each column that is in use * Scope: jQuery.dataTable.classSettings */ this.aoColumns = []; /* * Variable: aoHeader * Purpose: Store information about the table's header * Scope: jQuery.dataTable.classSettings */ this.aoHeader = []; /* * Variable: aoFooter * Purpose: Store information about the table's footer * Scope: jQuery.dataTable.classSettings */ this.aoFooter = []; /* * Variable: iNextId * Purpose: Store the next unique id to be used for a new row * Scope: jQuery.dataTable.classSettings */ this.iNextId = 0; /* * Variable: asDataSearch * Purpose: Search data array for regular expression searching * Scope: jQuery.dataTable.classSettings */ this.asDataSearch = []; /* * Variable: oPreviousSearch * Purpose: Store the previous search incase we want to force a re-search * or compare the old search to a new one * Scope: jQuery.dataTable.classSettings */ this.oPreviousSearch = { "sSearch": "", "bRegex": false, "bSmart": true }; /* * Variable: aoPreSearchCols * Purpose: Store the previous search for each column * Scope: jQuery.dataTable.classSettings */ this.aoPreSearchCols = []; /* * Variable: aaSorting * Purpose: Sorting information * Scope: jQuery.dataTable.classSettings * Notes: Index 0 - column number * Index 1 - current sorting direction * Index 2 - index of asSorting for this column */ this.aaSorting = [ [0, 'asc', 0] ]; /* * Variable: aaSortingFixed * Purpose: Sorting information that is always applied * Scope: jQuery.dataTable.classSettings */ this.aaSortingFixed = null; /* * Variable: asStripClasses * Purpose: Classes to use for the striping of a table * Scope: jQuery.dataTable.classSettings */ this.asStripClasses = []; /* * Variable: asDestoryStrips * Purpose: If restoring a table - we should restore it's striping classes as well * Scope: jQuery.dataTable.classSettings */ this.asDestoryStrips = []; /* * Variable: sDestroyWidth * Purpose: If restoring a table - we should restore it's width * Scope: jQuery.dataTable.classSettings */ this.sDestroyWidth = 0; /* * Variable: fnRowCallback * Purpose: Call this function every time a row is inserted (draw) * Scope: jQuery.dataTable.classSettings */ this.fnRowCallback = null; /* * Variable: fnHeaderCallback * Purpose: Callback function for the header on each draw * Scope: jQuery.dataTable.classSettings */ this.fnHeaderCallback = null; /* * Variable: fnFooterCallback * Purpose: Callback function for the footer on each draw * Scope: jQuery.dataTable.classSettings */ this.fnFooterCallback = null; /* * Variable: aoDrawCallback * Purpose: Array of callback functions for draw callback functions * Scope: jQuery.dataTable.classSettings * Notes: Each array element is an object with the following parameters: * function:fn - function to call * string:sName - name callback (feature). useful for arranging array */ this.aoDrawCallback = []; /* * Variable: fnPreDrawCallback * Purpose: Callback function for just before the table is redrawn. A return of false * will be used to cancel the draw. * Scope: jQuery.dataTable.classSettings */ this.fnPreDrawCallback = null; /* * Variable: fnInitComplete * Purpose: Callback function for when the table has been initalised * Scope: jQuery.dataTable.classSettings */ this.fnInitComplete = null; /* * Variable: sTableId * Purpose: Cache the table ID for quick access * Scope: jQuery.dataTable.classSettings */ this.sTableId = ""; /* * Variable: nTable * Purpose: Cache the table node for quick access * Scope: jQuery.dataTable.classSettings */ this.nTable = null; /* * Variable: nTHead * Purpose: Permanent ref to the thead element * Scope: jQuery.dataTable.classSettings */ this.nTHead = null; /* * Variable: nTFoot * Purpose: Permanent ref to the tfoot element - if it exists * Scope: jQuery.dataTable.classSettings */ this.nTFoot = null; /* * Variable: nTBody * Purpose: Permanent ref to the tbody element * Scope: jQuery.dataTable.classSettings */ this.nTBody = null; /* * Variable: nTableWrapper * Purpose: Cache the wrapper node (contains all DataTables controlled elements) * Scope: jQuery.dataTable.classSettings */ this.nTableWrapper = null; /* * Variable: bDeferLoading * Purpose: Indicate if when using server-side processing the loading of data * should be deferred until the second draw * Scope: jQuery.dataTable.classSettings */ this.bDeferLoading = false; /* * Variable: bInitialised * Purpose: Indicate if all required information has been read in * Scope: jQuery.dataTable.classSettings */ this.bInitialised = false; /* * Variable: aoOpenRows * Purpose: Information about open rows * Scope: jQuery.dataTable.classSettings * Notes: Has the parameters 'nTr' and 'nParent' */ this.aoOpenRows = []; /* * Variable: sDom * Purpose: Dictate the positioning that the created elements will take * Scope: jQuery.dataTable.classSettings * Notes: * The following options are allowed: * 'l' - Length changing * 'f' - Filtering input * 't' - The table! * 'i' - Information * 'p' - Pagination * 'r' - pRocessing * The following constants are allowed: * 'H' - jQueryUI theme "header" classes * 'F' - jQueryUI theme "footer" classes * The following syntax is expected: * '<' and '>' - div elements * '<"class" and '>' - div with a class * Examples: * '<"wrapper"flipt>', '<lf<t>ip>' */ this.sDom = 'lfrtip'; /* * Variable: sPaginationType * Purpose: Note which type of sorting should be used * Scope: jQuery.dataTable.classSettings */ this.sPaginationType = "two_button"; /* * Variable: iCookieDuration * Purpose: The cookie duration (for bStateSave) in seconds - default 2 hours * Scope: jQuery.dataTable.classSettings */ this.iCookieDuration = 60 * 60 * 2; /* * Variable: sCookiePrefix * Purpose: The cookie name prefix * Scope: jQuery.dataTable.classSettings */ this.sCookiePrefix = "SpryMedia_DataTables_"; /* * Variable: fnCookieCallback * Purpose: Callback function for cookie creation * Scope: jQuery.dataTable.classSettings */ this.fnCookieCallback = null; /* * Variable: aoStateSave * Purpose: Array of callback functions for state saving * Scope: jQuery.dataTable.classSettings * Notes: Each array element is an object with the following parameters: * function:fn - function to call. Takes two parameters, oSettings and the JSON string to * save that has been thus far created. Returns a JSON string to be inserted into a * json object (i.e. '"param": [ 0, 1, 2]') * string:sName - name of callback */ this.aoStateSave = []; /* * Variable: aoStateLoad * Purpose: Array of callback functions for state loading * Scope: jQuery.dataTable.classSettings * Notes: Each array element is an object with the following parameters: * function:fn - function to call. Takes two parameters, oSettings and the object stored. * May return false to cancel state loading. * string:sName - name of callback */ this.aoStateLoad = []; /* * Variable: oLoadedState * Purpose: State that was loaded from the cookie. Useful for back reference * Scope: jQuery.dataTable.classSettings */ this.oLoadedState = null; /* * Variable: sAjaxSource * Purpose: Source url for AJAX data for the table * Scope: jQuery.dataTable.classSettings */ this.sAjaxSource = null; /* * Variable: sAjaxDataProp * Purpose: Property from a given object from which to read the table data from. This can * be an empty string (when not server-side processing), in which case it is * assumed an an array is given directly. * Scope: jQuery.dataTable.classSettings */ this.sAjaxDataProp = 'aaData'; /* * Variable: bAjaxDataGet * Purpose: Note if draw should be blocked while getting data * Scope: jQuery.dataTable.classSettings */ this.bAjaxDataGet = true; /* * Variable: jqXHR * Purpose: The last jQuery XHR object that was used for server-side data gathering. * This can be used for working with the XHR information in one of the callbacks * Scope: jQuery.dataTable.classSettings */ this.jqXHR = null; /* * Variable: fnServerData * Purpose: Function to get the server-side data - can be overruled by the developer * Scope: jQuery.dataTable.classSettings */ this.fnServerData = function ( url, data, callback, settings ) { settings.jqXHR = $.ajax( { "url": url, "data": data, "success": callback, "dataType": "json", "cache": false, "error": function (xhr, error, thrown) { if ( error == "parsererror" ) { alert( "DataTables warning: JSON data from server could not be parsed. "+ "This is caused by a JSON formatting error." ); } } } ); }; /* * Variable: fnFormatNumber * Purpose: Format numbers for display * Scope: jQuery.dataTable.classSettings */ this.fnFormatNumber = function ( iIn ) { if ( iIn < 1000 ) { /* A small optimisation for what is likely to be the vast majority of use cases */ return iIn; } else { var s=(iIn+""), a=s.split(""), out="", iLen=s.length; for ( var i=0 ; i<iLen ; i++ ) { if ( i%3 === 0 && i !== 0 ) { out = ','+out; } out = a[iLen-i-1]+out; } } return out; }; /* * Variable: aLengthMenu * Purpose: List of options that can be used for the user selectable length menu * Scope: jQuery.dataTable.classSettings * Note: This varaible can take for form of a 1D array, in which case the value and the * displayed value in the menu are the same, or a 2D array in which case the value comes * from the first array, and the displayed value to the end user comes from the second * array. 2D example: [ [ 10, 25, 50, 100, -1 ], [ 10, 25, 50, 100, 'All' ] ]; */ this.aLengthMenu = [ 10, 25, 50, 100 ]; /* * Variable: iDraw * Purpose: Counter for the draws that the table does. Also used as a tracker for * server-side processing * Scope: jQuery.dataTable.classSettings */ this.iDraw = 0; /* * Variable: bDrawing * Purpose: Indicate if a redraw is being done - useful for Ajax * Scope: jQuery.dataTable.classSettings */ this.bDrawing = 0; /* * Variable: iDrawError * Purpose: Last draw error * Scope: jQuery.dataTable.classSettings */ this.iDrawError = -1; /* * Variable: _iDisplayLength, _iDisplayStart, _iDisplayEnd * Purpose: Display length variables * Scope: jQuery.dataTable.classSettings * Notes: These variable must NOT be used externally to get the data length. Rather, use * the fnRecordsTotal() (etc) functions. */ this._iDisplayLength = 10; this._iDisplayStart = 0; this._iDisplayEnd = 10; /* * Variable: _iRecordsTotal, _iRecordsDisplay * Purpose: Display length variables used for server side processing * Scope: jQuery.dataTable.classSettings * Notes: These variable must NOT be used externally to get the data length. Rather, use * the fnRecordsTotal() (etc) functions. */ this._iRecordsTotal = 0; this._iRecordsDisplay = 0; /* * Variable: bJUI * Purpose: Should we add the markup needed for jQuery UI theming? * Scope: jQuery.dataTable.classSettings */ this.bJUI = false; /* * Variable: oClasses * Purpose: Should we add the markup needed for jQuery UI theming? * Scope: jQuery.dataTable.classSettings */ this.oClasses = _oExt.oStdClasses; /* * Variable: bFiltered and bSorted * Purpose: Flags to allow callback functions to see what actions have been performed * Scope: jQuery.dataTable.classSettings */ this.bFiltered = false; this.bSorted = false; /* * Variable: bSortCellsTop * Purpose: Indicate that if multiple rows are in the header and there is more than one * unique cell per column, if the top one (true) or bottom one (false) should * be used for sorting / title by DataTables * Scope: jQuery.dataTable.classSettings */ this.bSortCellsTop = false; /* * Variable: oInit * Purpose: Initialisation object that is used for the table * Scope: jQuery.dataTable.classSettings */ this.oInit = null; } /* * Variable: oApi * Purpose: Container for publicly exposed 'private' functions * Scope: jQuery.dataTable */ this.oApi = {}; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - API functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Function: fnDraw * Purpose: Redraw the table * Returns: - * Inputs: bool:bComplete - Refilter and resort (if enabled) the table before the draw. * Optional: default - true */ this.fnDraw = function( bComplete ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( typeof bComplete != 'undefined' && bComplete === false ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } else { _fnReDraw( oSettings ); } }; /* * Function: fnFilter * Purpose: Filter the input based on data * Returns: - * Inputs: string:sInput - string to filter the table on * int:iColumn - optional - column to limit filtering to * bool:bRegex - optional - treat as regular expression or not - default false * bool:bSmart - optional - perform smart filtering or not - default true * bool:bShowGlobal - optional - show the input global filter in it's input box(es) * - default true */ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( !oSettings.oFeatures.bFilter ) { return; } if ( typeof bRegex == 'undefined' ) { bRegex = false; } if ( typeof bSmart == 'undefined' ) { bSmart = true; } if ( typeof bShowGlobal == 'undefined' ) { bShowGlobal = true; } if ( typeof iColumn == "undefined" || iColumn === null ) { /* Global filter */ _fnFilterComplete( oSettings, { "sSearch":sInput, "bRegex": bRegex, "bSmart": bSmart }, 1 ); if ( bShowGlobal && typeof oSettings.aanFeatures.f != 'undefined' ) { var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $('input', n[i]).val( sInput ); } } } else { /* Single column filter */ oSettings.aoPreSearchCols[ iColumn ].sSearch = sInput; oSettings.aoPreSearchCols[ iColumn ].bRegex = bRegex; oSettings.aoPreSearchCols[ iColumn ].bSmart = bSmart; _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } }; /* * Function: fnSettings * Purpose: Get the settings for a particular table for extern. manipulation * Returns: - * Inputs: - */ this.fnSettings = function( nNode ) { return _fnSettingsFromNode( this[_oExt.iApiIndex] ); }; /* * Function: fnVersionCheck * Notes: The function is the same as the 'static' function provided in the ext variable */ this.fnVersionCheck = _oExt.fnVersionCheck; /* * Function: fnSort * Purpose: Sort the table by a particular row * Returns: - * Inputs: int:iCol - the data index to sort on. Note that this will * not match the 'display index' if you have hidden data entries */ this.fnSort = function( aaSort ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); oSettings.aaSorting = aaSort; _fnSort( oSettings ); }; /* * Function: fnSortListener * Purpose: Attach a sort listener to an element for a given column * Returns: - * Inputs: node:nNode - the element to attach the sort listener to * int:iColumn - the column that a click on this node will sort on * function:fnCallback - callback function when sort is run - optional */ this.fnSortListener = function( nNode, iColumn, fnCallback ) { _fnSortAttachListener( _fnSettingsFromNode( this[_oExt.iApiIndex] ), nNode, iColumn, fnCallback ); }; /* * Function: fnAddData * Purpose: Add new row(s) into the table * Returns: array int: array of indexes (aoData) which have been added (zero length on error) * Inputs: array:mData - the data to be added. The length must match * the original data from the DOM * or * array array:mData - 2D array of data to be added * bool:bRedraw - redraw the table or not - default true * Notes: Warning - the refilter here will cause the table to redraw * starting at zero * Notes: Thanks to Yekimov Denis for contributing the basis for this function! */ this.fnAddData = function( mData, bRedraw ) { if ( mData.length === 0 ) { return []; } var aiReturn = []; var iTest; /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); /* Check if we want to add multiple rows or not */ if ( typeof mData[0] == "object" ) { for ( var i=0 ; i<mData.length ; i++ ) { iTest = _fnAddData( oSettings, mData[i] ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } } else { iTest = _fnAddData( oSettings, mData ); if ( iTest == -1 ) { return aiReturn; } aiReturn.push( iTest ); } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnReDraw( oSettings ); } return aiReturn; }; /* * Function: fnDeleteRow * Purpose: Remove a row for the table * Returns: array:aReturn - the row that was deleted * Inputs: mixed:mTarget - * int: - index of aoData to be deleted, or * node(TR): - TR element you want to delete * function:fnCallBack - callback function - default null * bool:bRedraw - redraw the table or not - default true */ this.fnDeleteRow = function( mTarget, fnCallBack, bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var i, iAODataIndex; iAODataIndex = (typeof mTarget == 'object') ? _fnNodeToDataIndex(oSettings, mTarget) : mTarget; /* Return the data array from this row */ var oData = oSettings.aoData.splice( iAODataIndex, 1 ); /* Remove the target row from the search array */ var iDisplayIndex = $.inArray( iAODataIndex, oSettings.aiDisplay ); oSettings.asDataSearch.splice( iDisplayIndex, 1 ); /* Delete from the display arrays */ _fnDeleteIndex( oSettings.aiDisplayMaster, iAODataIndex ); _fnDeleteIndex( oSettings.aiDisplay, iAODataIndex ); /* If there is a user callback function - call it */ if ( typeof fnCallBack == "function" ) { fnCallBack.call( this, oSettings, oData ); } /* Check for an 'overflow' they case for dislaying the table */ if ( oSettings._iDisplayStart >= oSettings.aiDisplay.length ) { oSettings._iDisplayStart -= oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } return oData; }; /* * Function: fnClearTable * Purpose: Quickly and simply clear a table * Returns: - * Inputs: bool:bRedraw - redraw the table or not - default true * Notes: Thanks to Yekimov Denis for contributing the basis for this function! */ this.fnClearTable = function( bRedraw ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); _fnClearTable( oSettings ); if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnDraw( oSettings ); } }; /* * Function: fnOpen * Purpose: Open a display row (append a row after the row in question) * Returns: node:nNewRow - the row opened * Inputs: node:nTr - the table row to 'open' * string|node|jQuery:mHtml - the HTML to put into the row * string:sClass - class to give the new TD cell */ this.fnOpen = function( nTr, mHtml, sClass ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); /* the old open one if there is one */ this.fnClose( nTr ); var nNewRow = document.createElement("tr"); var nNewCell = document.createElement("td"); nNewRow.appendChild( nNewCell ); nNewCell.className = sClass; nNewCell.colSpan = _fnVisbleColumns( oSettings ); if( typeof mHtml.jquery != 'undefined' || typeof mHtml == "object" ) { nNewCell.appendChild( mHtml ); } else { nNewCell.innerHTML = mHtml; } /* If the nTr isn't on the page at the moment - then we don't insert at the moment */ var nTrs = $('tr', oSettings.nTBody); if ( $.inArray(nTr, nTrs) != -1 ) { $(nNewRow).insertAfter(nTr); } oSettings.aoOpenRows.push( { "nTr": nNewRow, "nParent": nTr } ); return nNewRow; }; /* * Function: fnClose * Purpose: Close a display row * Returns: int: 0 (success) or 1 (failed) * Inputs: node:nTr - the table row to 'close' */ this.fnClose = function( nTr ) { /* Find settings from table node */ var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); for ( var i=0 ; i<oSettings.aoOpenRows.length ; i++ ) { if ( oSettings.aoOpenRows[i].nParent == nTr ) { var nTrParent = oSettings.aoOpenRows[i].nTr.parentNode; if ( nTrParent ) { /* Remove it if it is currently on display */ nTrParent.removeChild( oSettings.aoOpenRows[i].nTr ); } oSettings.aoOpenRows.splice( i, 1 ); return 0; } } return 1; }; /* * Function: fnGetData * Purpose: Return an array with the data which is used to make up the table * Returns: array array string: 2d data array ([row][column]) or array string: 1d data array * or string if both row and column are given * Inputs: mixed:mRow - optional - if not present, then the full 2D array for the table * if given then: * int: - return data object for aoData entry of this index * node(TR): - return data object for this TR element * int:iCol - optional - the column that you want the data of. This will take into * account mDataProp and return the value DataTables uses for this column */ this.fnGetData = function( mRow, iCol ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( typeof mRow != 'undefined' ) { var iRow = (typeof mRow == 'object') ? _fnNodeToDataIndex(oSettings, mRow) : mRow; if ( typeof iCol != 'undefined' ) { return _fnGetCellData( oSettings, iRow, iCol, '' ); } return (typeof oSettings.aoData[iRow] != 'undefined') ? oSettings.aoData[iRow]._aData : null; } return _fnGetDataMaster( oSettings ); }; /* * Function: fnGetNodes * Purpose: Return an array with the TR nodes used for drawing the table * Returns: array node: TR elements * or * node (if iRow specified) * Inputs: int:iRow - optional - if present then the array returned will be the node for * the row with the index 'iRow' */ this.fnGetNodes = function( iRow ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); if ( typeof iRow != 'undefined' ) { return (typeof oSettings.aoData[iRow] != 'undefined') ? oSettings.aoData[iRow].nTr : null; } return _fnGetTrNodes( oSettings ); }; /* * Function: fnGetPosition * Purpose: Get the array indexes of a particular cell from it's DOM element * Returns: int: - row index, or array[ int, int, int ]: - row index, column index (visible) * and column index including hidden columns * Inputs: node:nNode - this can either be a TR, TD or TH in the table's body, the return is * dependent on this input */ this.fnGetPosition = function( nNode ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var sNodeName = nNode.nodeName.toUpperCase(); if ( sNodeName == "TR" ) { return _fnNodeToDataIndex(oSettings, nNode); } else if ( sNodeName == "TD" || sNodeName == "TH" ) { var iDataIndex = _fnNodeToDataIndex(oSettings, nNode.parentNode); var anCells = _fnGetTdNodes( oSettings, iDataIndex ); for ( var i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( anCells[i] == nNode ) { return [ iDataIndex, _fnColumnIndexToVisible(oSettings, i ), i ]; } } } return null; }; /* * Function: fnUpdate * Purpose: Update a table cell or row - this method will accept either a single value to * update the cell with, an array of values with one element for each column or * an object in the same format as the original data source. The function is * self-referencing in order to make the multi column updates easier. * Returns: int: 0 okay, 1 error * Inputs: object | array string | string:mData - data to update the cell/row with * mixed:mRow - * int: - index of aoData to be updated, or * node(TR): - TR element you want to update * int:iColumn - the column to update - optional (not used of mData is an array or object) * bool:bRedraw - redraw the table or not - default true * bool:bAction - perform predraw actions or not (you will want this as 'true' if * you have bRedraw as true) - default true */ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var iVisibleColumn, i, iLen, sDisplay; var iRow = (typeof mRow == 'object') ? _fnNodeToDataIndex(oSettings, mRow) : mRow; if ( $.isArray(mData) && typeof mData == 'object' ) { /* Array update - update the whole row */ oSettings.aoData[iRow]._aData = mData.slice(); for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } } else if ( typeof mData == 'object' ) { /* Object update - update the whole row - assume the developer gets the object right */ oSettings.aoData[iRow]._aData = $.extend( true, {}, mData ); for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { this.fnUpdate( _fnGetCellData( oSettings, iRow, i ), iRow, i, false, false ); } } else { /* Individual cell update */ sDisplay = mData; _fnSetCellData( oSettings, iRow, iColumn, sDisplay ); if ( oSettings.aoColumns[iColumn].fnRender !== null ) { sDisplay = oSettings.aoColumns[iColumn].fnRender( { "iDataRow": iRow, "iDataColumn": iColumn, "aData": oSettings.aoData[iRow]._aData, "oSettings": oSettings } ); if ( oSettings.aoColumns[iColumn].bUseRendered ) { _fnSetCellData( oSettings, iRow, iColumn, sDisplay ); } } if ( oSettings.aoData[iRow].nTr !== null ) { /* Do the actual HTML update */ _fnGetTdNodes( oSettings, iRow )[iColumn].innerHTML = sDisplay; } } /* Modify the search index for this row (strictly this is likely not needed, since fnReDraw * will rebuild the search array - however, the redraw might be disabled by the user) */ var iDisplayIndex = $.inArray( iRow, oSettings.aiDisplay ); oSettings.asDataSearch[iDisplayIndex] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, iRow, 'filter' ) ); /* Perform pre-draw actions */ if ( typeof bAction == 'undefined' || bAction ) { _fnAjustColumnSizing( oSettings ); } /* Redraw the table */ if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnReDraw( oSettings ); } return 0; }; /* * Function: fnShowColoumn * Purpose: Show a particular column * Returns: - * Inputs: int:iCol - the column whose display should be changed * bool:bShow - show (true) or hide (false) the column * bool:bRedraw - redraw the table or not - default true */ this.fnSetColumnVis = function ( iCol, bShow, bRedraw ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var i, iLen; var iColumns = oSettings.aoColumns.length; var nTd, nCell, anTrs, jqChildren, bAppend, iBefore; /* No point in doing anything if we are requesting what is already true */ if ( oSettings.aoColumns[iCol].bVisible == bShow ) { return; } /* Show the column */ if ( bShow ) { var iInsert = 0; for ( i=0 ; i<iCol ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iInsert++; } } /* Need to decide if we should use appendChild or insertBefore */ bAppend = (iInsert >= _fnVisbleColumns( oSettings )); /* Which coloumn should we be inserting before? */ if ( !bAppend ) { for ( i=iCol ; i<iColumns ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iBefore = i; break; } } } for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { if ( bAppend ) { oSettings.aoData[i].nTr.appendChild( oSettings.aoData[i]._anHidden[iCol] ); } else { oSettings.aoData[i].nTr.insertBefore( oSettings.aoData[i]._anHidden[iCol], _fnGetTdNodes( oSettings, i )[iBefore] ); } } } } else { /* Remove a column from display */ for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { nTd = _fnGetTdNodes( oSettings, i )[iCol]; oSettings.aoData[i]._anHidden[iCol] = nTd; nTd.parentNode.removeChild( nTd ); } } } /* Clear to set the visible flag */ oSettings.aoColumns[iCol].bVisible = bShow; /* Redraw the header and footer based on the new column visibility */ _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* If there are any 'open' rows, then we need to alter the colspan for this col change */ for ( i=0, iLen=oSettings.aoOpenRows.length ; i<iLen ; i++ ) { oSettings.aoOpenRows[i].nTr.colSpan = _fnVisbleColumns( oSettings ); } /* Do a redraw incase anything depending on the table columns needs it * (built-in: scrolling) */ if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnAjustColumnSizing( oSettings ); _fnDraw( oSettings ); } _fnSaveState( oSettings ); }; /* * Function: fnPageChange * Purpose: Change the pagination * Returns: - * Inputs: string:sAction - paging action to take: "first", "previous", "next" or "last" * bool:bRedraw - redraw the table or not - optional - default true */ this.fnPageChange = function ( sAction, bRedraw ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); _fnPageChange( oSettings, sAction ); _fnCalculateEnd( oSettings ); if ( typeof bRedraw == 'undefined' || bRedraw ) { _fnDraw( oSettings ); } }; /* * Function: fnDestroy * Purpose: Destructor for the DataTable * Returns: - * Inputs: - */ this.fnDestroy = function ( ) { var oSettings = _fnSettingsFromNode( this[_oExt.iApiIndex] ); var nOrig = oSettings.nTableWrapper.parentNode; var nBody = oSettings.nTBody; var i, iLen; /* Flag to note that the table is currently being destoryed - no action should be taken */ oSettings.bDestroying = true; /* Restore hidden columns */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].bVisible === false ) { this.fnSetColumnVis( i, true ); } } /* Blitz all DT events */ $(oSettings.nTableWrapper).find('*').andSelf().unbind('.DT'); /* If there is an 'empty' indicator row, remove it */ $('tbody>tr>td.'+oSettings.oClasses.sRowEmpty, oSettings.nTable).parent().remove(); /* When scrolling we had to break the table up - restore it */ if ( oSettings.nTable != oSettings.nTHead.parentNode ) { $('>thead', oSettings.nTable).remove(); oSettings.nTable.appendChild( oSettings.nTHead ); } if ( oSettings.nTFoot && oSettings.nTable != oSettings.nTFoot.parentNode ) { $('>tfoot', oSettings.nTable).remove(); oSettings.nTable.appendChild( oSettings.nTFoot ); } /* Remove the DataTables generated nodes, events and classes */ oSettings.nTable.parentNode.removeChild( oSettings.nTable ); $(oSettings.nTableWrapper).remove(); oSettings.aaSorting = []; oSettings.aaSortingFixed = []; _fnSortingClasses( oSettings ); $(_fnGetTrNodes( oSettings )).removeClass( oSettings.asStripClasses.join(' ') ); if ( !oSettings.bJUI ) { $('th', oSettings.nTHead).removeClass( [ _oExt.oStdClasses.sSortable, _oExt.oStdClasses.sSortableAsc, _oExt.oStdClasses.sSortableDesc, _oExt.oStdClasses.sSortableNone ].join(' ') ); } else { $('th', oSettings.nTHead).removeClass( [ _oExt.oStdClasses.sSortable, _oExt.oJUIClasses.sSortableAsc, _oExt.oJUIClasses.sSortableDesc, _oExt.oJUIClasses.sSortableNone ].join(' ') ); $('th span.'+_oExt.oJUIClasses.sSortIcon, oSettings.nTHead).remove(); $('th', oSettings.nTHead).each( function () { var jqWrapper = $('div.'+_oExt.oJUIClasses.sSortJUIWrapper, this); var kids = jqWrapper.contents(); $(this).append( kids ); jqWrapper.remove(); } ); } /* Add the TR elements back into the table in their original order */ if ( oSettings.nTableReinsertBefore ) { nOrig.insertBefore( oSettings.nTable, oSettings.nTableReinsertBefore ); } else { nOrig.appendChild( oSettings.nTable ); } for ( i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { nBody.appendChild( oSettings.aoData[i].nTr ); } } /* Restore the width of the original table */ if ( oSettings.oFeatures.bAutoWidth === true ) { oSettings.nTable.style.width = _fnStringToCss(oSettings.sDestroyWidth); } /* If the were originally odd/even type classes - then we add them back here. Note * this is not fool proof (for example if not all rows as odd/even classes - but * it's a good effort without getting carried away */ $('>tr:even', nBody).addClass( oSettings.asDestoryStrips[0] ); $('>tr:odd', nBody).addClass( oSettings.asDestoryStrips[1] ); /* Remove the settings object from the settings array */ for ( i=0, iLen=_aoSettings.length ; i<iLen ; i++ ) { if ( _aoSettings[i] == oSettings ) { _aoSettings.splice( i, 1 ); } } /* End it all */ oSettings = null; }; /* * Function: fnAjustColumnSizing * Purpose: Update tale sizing based on content. This would most likely be used for scrolling * and will typically need a redraw after it. * Returns: - * Inputs: bool:bRedraw - redraw the table or not, you will typically want to - default true */ this.fnAdjustColumnSizing = function ( bRedraw ) { var oSettings = _fnSettingsFromNode(this[_oExt.iApiIndex]); _fnAjustColumnSizing( oSettings ); if ( typeof bRedraw == 'undefined' || bRedraw ) { this.fnDraw( false ); } else if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */ this.oApi._fnScrollDraw(oSettings); } }; /* * Plugin API functions * * This call will add the functions which are defined in _oExt.oApi to the * DataTables object, providing a rather nice way to allow plug-in API functions. Note that * this is done here, so that API function can actually override the built in API functions if * required for a particular purpose. */ /* * Function: _fnExternApiFunc * Purpose: Create a wrapper function for exporting an internal func to an external API func * Returns: function: - wrapped function * Inputs: string:sFunc - API function name */ function _fnExternApiFunc (sFunc) { return function() { var aArgs = [_fnSettingsFromNode(this[_oExt.iApiIndex])].concat( Array.prototype.slice.call(arguments) ); return _oExt.oApi[sFunc].apply( this, aArgs ); }; } for ( var sFunc in _oExt.oApi ) { if ( sFunc ) { /* * Function: anon * Purpose: Wrap the plug-in API functions in order to provide the settings as 1st arg * and execute in this scope * Returns: - * Inputs: - */ this[sFunc] = _fnExternApiFunc(sFunc); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Local functions * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Initalisation */ /* * Function: _fnInitalise * Purpose: Draw the table for the first time, adding all required features * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnInitalise ( oSettings ) { var i, iLen, iAjaxStart=oSettings.iInitDisplayStart; /* Ensure that the table data is fully initialised */ if ( oSettings.bInitialised === false ) { setTimeout( function(){ _fnInitalise( oSettings ); }, 200 ); return; } /* Show the display HTML options */ _fnAddOptionsHtml( oSettings ); /* Build and draw the header / footer for the table */ _fnBuildHead( oSettings ); _fnDrawHead( oSettings, oSettings.aoHeader ); if ( oSettings.nTFoot ) { _fnDrawHead( oSettings, oSettings.aoFooter ); } /* Okay to show that something is going on now */ _fnProcessingDisplay( oSettings, true ); /* Calculate sizes for columns */ if ( oSettings.oFeatures.bAutoWidth ) { _fnCalculateColumnWidths( oSettings ); } for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( oSettings.aoColumns[i].sWidth !== null ) { oSettings.aoColumns[i].nTh.style.width = _fnStringToCss( oSettings.aoColumns[i].sWidth ); } } /* If there is default sorting required - let's do it. The sort function will do the * drawing for us. Otherwise we draw the table regardless of the Ajax source - this allows * the table to look initialised for Ajax sourcing data (show 'loading' message possibly) */ if ( oSettings.oFeatures.bSort ) { _fnSort( oSettings ); } else if ( oSettings.oFeatures.bFilter ) { _fnFilterComplete( oSettings, oSettings.oPreviousSearch ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } /* if there is an ajax source load the data */ if ( oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide ) { oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, [], function(json) { var aData = json; if ( oSettings.sAjaxDataProp !== "" ) { var fnDataSrc = _fnGetObjectDataFn( oSettings.sAjaxDataProp ); aData = fnDataSrc( json ); } /* Got the data - add it to the table */ for ( i=0 ; i<aData.length ; i++ ) { _fnAddData( oSettings, aData[i] ); } /* Reset the init display for cookie saving. We've already done a filter, and * therefore cleared it before. So we need to make it appear 'fresh' */ oSettings.iInitDisplayStart = iAjaxStart; if ( oSettings.oFeatures.bSort ) { _fnSort( oSettings ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } _fnProcessingDisplay( oSettings, false ); _fnInitComplete( oSettings, json ); }, oSettings ); return; } /* Server-side processing initialisation complete is done at the end of _fnDraw */ if ( !oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); _fnInitComplete( oSettings ); } } /* * Function: _fnInitalise * Purpose: Draw the table for the first time, adding all required features * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnInitComplete ( oSettings, json ) { oSettings._bInitComplete = true; if ( typeof oSettings.fnInitComplete == 'function' ) { if ( typeof json != 'undefined' ) { oSettings.fnInitComplete.call( oSettings.oInstance, oSettings, json ); } else { oSettings.fnInitComplete.call( oSettings.oInstance, oSettings ); } } } /* * Function: _fnLanguageProcess * Purpose: Copy language variables from remote object to a local one * Returns: - * Inputs: object:oSettings - dataTables settings object * object:oLanguage - Language information * bool:bInit - init once complete */ function _fnLanguageProcess( oSettings, oLanguage, bInit ) { _fnMap( oSettings.oLanguage, oLanguage, 'sProcessing' ); _fnMap( oSettings.oLanguage, oLanguage, 'sLengthMenu' ); _fnMap( oSettings.oLanguage, oLanguage, 'sEmptyTable' ); _fnMap( oSettings.oLanguage, oLanguage, 'sLoadingRecords' ); _fnMap( oSettings.oLanguage, oLanguage, 'sZeroRecords' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfo' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfoEmpty' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfoFiltered' ); _fnMap( oSettings.oLanguage, oLanguage, 'sInfoPostFix' ); _fnMap( oSettings.oLanguage, oLanguage, 'sSearch' ); if ( typeof oLanguage.oPaginate != 'undefined' ) { _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sFirst' ); _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sPrevious' ); _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sNext' ); _fnMap( oSettings.oLanguage.oPaginate, oLanguage.oPaginate, 'sLast' ); } /* Backwards compatibility - if there is no sEmptyTable given, then use the same as * sZeroRecords - assuming that is given. */ if ( typeof oLanguage.sEmptyTable == 'undefined' && typeof oLanguage.sZeroRecords != 'undefined' ) { _fnMap( oSettings.oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable' ); } /* Likewise with loading records */ if ( typeof oLanguage.sLoadingRecords == 'undefined' && typeof oLanguage.sZeroRecords != 'undefined' ) { _fnMap( oSettings.oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords' ); } if ( bInit ) { _fnInitalise( oSettings ); } } /* * Function: _fnAddColumn * Purpose: Add a column to the list used for the table with default values * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nTh - the th element for this column */ function _fnAddColumn( oSettings, nTh ) { var iCol = oSettings.aoColumns.length; var oCol = { "sType": null, "_bAutoType": true, "bVisible": true, "bSearchable": true, "bSortable": true, "asSorting": [ 'asc', 'desc' ], "sSortingClass": oSettings.oClasses.sSortable, "sSortingClassJUI": oSettings.oClasses.sSortJUI, "sTitle": nTh ? nTh.innerHTML : '', "sName": '', "sWidth": null, "sWidthOrig": null, "sClass": null, "fnRender": null, "bUseRendered": true, "iDataSort": iCol, "mDataProp": iCol, "fnGetData": null, "fnSetData": null, "sSortDataType": 'std', "sDefaultContent": null, "sContentPadding": "", "nTh": nTh ? nTh : document.createElement('th'), "nTf": null }; oSettings.aoColumns.push( oCol ); /* Add a column specific filter */ if ( typeof oSettings.aoPreSearchCols[ iCol ] == 'undefined' || oSettings.aoPreSearchCols[ iCol ] === null ) { oSettings.aoPreSearchCols[ iCol ] = { "sSearch": "", "bRegex": false, "bSmart": true }; } else { /* Don't require that the user must specify bRegex and / or bSmart */ if ( typeof oSettings.aoPreSearchCols[ iCol ].bRegex == 'undefined' ) { oSettings.aoPreSearchCols[ iCol ].bRegex = true; } if ( typeof oSettings.aoPreSearchCols[ iCol ].bSmart == 'undefined' ) { oSettings.aoPreSearchCols[ iCol ].bSmart = true; } } /* Use the column options function to initialise classes etc */ _fnColumnOptions( oSettings, iCol, null ); } /* * Function: _fnColumnOptions * Purpose: Apply options for a column * Returns: - * Inputs: object:oSettings - dataTables settings object * int:iCol - column index to consider * object:oOptions - object with sType, bVisible and bSearchable */ function _fnColumnOptions( oSettings, iCol, oOptions ) { var oCol = oSettings.aoColumns[ iCol ]; /* User specified column options */ if ( typeof oOptions != 'undefined' && oOptions !== null ) { if ( typeof oOptions.sType != 'undefined' ) { oCol.sType = oOptions.sType; oCol._bAutoType = false; } _fnMap( oCol, oOptions, "bVisible" ); _fnMap( oCol, oOptions, "bSearchable" ); _fnMap( oCol, oOptions, "bSortable" ); _fnMap( oCol, oOptions, "sTitle" ); _fnMap( oCol, oOptions, "sName" ); _fnMap( oCol, oOptions, "sWidth" ); _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" ); _fnMap( oCol, oOptions, "sClass" ); _fnMap( oCol, oOptions, "fnRender" ); _fnMap( oCol, oOptions, "bUseRendered" ); _fnMap( oCol, oOptions, "iDataSort" ); _fnMap( oCol, oOptions, "mDataProp" ); _fnMap( oCol, oOptions, "asSorting" ); _fnMap( oCol, oOptions, "sSortDataType" ); _fnMap( oCol, oOptions, "sDefaultContent" ); _fnMap( oCol, oOptions, "sContentPadding" ); } /* Cache the data get and set functions for speed */ oCol.fnGetData = _fnGetObjectDataFn( oCol.mDataProp ); oCol.fnSetData = _fnSetObjectDataFn( oCol.mDataProp ); /* Feature sorting overrides column specific when off */ if ( !oSettings.oFeatures.bSort ) { oCol.bSortable = false; } /* Check that the class assignment is correct for sorting */ if ( !oCol.bSortable || ($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) ) { oCol.sSortingClass = oSettings.oClasses.sSortableNone; oCol.sSortingClassJUI = ""; } else if ( oCol.bSortable || ($.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) == -1) ) { oCol.sSortingClass = oSettings.oClasses.sSortable; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUI; } else if ( $.inArray('asc', oCol.asSorting) != -1 && $.inArray('desc', oCol.asSorting) == -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortableAsc; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIAscAllowed; } else if ( $.inArray('asc', oCol.asSorting) == -1 && $.inArray('desc', oCol.asSorting) != -1 ) { oCol.sSortingClass = oSettings.oClasses.sSortableDesc; oCol.sSortingClassJUI = oSettings.oClasses.sSortJUIDescAllowed; } } /* * Function: _fnAddData * Purpose: Add a data array to the table, creating DOM node etc * Returns: int: - >=0 if successful (index of new aoData entry), -1 if failed * Inputs: object:oSettings - dataTables settings object * array:aData - data array to be added * Notes: There are two basic methods for DataTables to get data to display - a JS array * (which is dealt with by this function), and the DOM, which has it's own optimised * function (_fnGatherData). Be careful to make the same changes here as there and vice-versa */ function _fnAddData ( oSettings, aDataSupplied ) { var oCol; /* Take an independent copy of the data source so we can bash it about as we wish */ var aDataIn = (typeof aDataSupplied.length == 'number') ? aDataSupplied.slice() : $.extend( true, {}, aDataSupplied ); /* Create the object for storing information about this new row */ var iRow = oSettings.aoData.length; var oData = { "nTr": null, "_iId": oSettings.iNextId++, "_aData": aDataIn, "_anHidden": [], "_sRowStripe": "" }; oSettings.aoData.push( oData ); /* Create the cells */ var nTd, sThisType; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; /* Use rendered data for filtering/sorting */ if ( typeof oCol.fnRender == 'function' && oCol.bUseRendered && oCol.mDataProp !== null ) { _fnSetCellData( oSettings, iRow, i, oCol.fnRender( { "iDataRow": iRow, "iDataColumn": i, "aData": oData._aData, "oSettings": oSettings } ) ); } /* See if we should auto-detect the column type */ if ( oCol._bAutoType && oCol.sType != 'string' ) { /* Attempt to auto detect the type - same as _fnGatherData() */ var sVarType = _fnGetCellData( oSettings, iRow, i, 'type' ); if ( sVarType !== null && sVarType !== '' ) { sThisType = _fnDetectType( sVarType ); if ( oCol.sType === null ) { oCol.sType = sThisType; } else if ( oCol.sType != sThisType ) { /* String is always the 'fallback' option */ oCol.sType = 'string'; } } } } /* Add to the display array */ oSettings.aiDisplayMaster.push( iRow ); /* Create the DOM imformation */ if ( !oSettings.oFeatures.bDeferRender ) { _fnCreateTr( oSettings, iRow ); } return iRow; } /* * Function: _fnCreateTr * Purpose: Create a new TR element (and it's TD children) for a row * Returns: void * Inputs: object:oSettings - dataTables settings object * int:iRow - Row to consider */ function _fnCreateTr ( oSettings, iRow ) { var oData = oSettings.aoData[iRow]; var nTd; if ( oData.nTr === null ) { oData.nTr = document.createElement('tr'); /* Special parameters can be given by the data source to be used on the row */ if ( typeof oData._aData.DT_RowId != 'undefined' ) { oData.nTr.setAttribute( 'id', oData._aData.DT_RowId ); } if ( typeof oData._aData.DT_RowClass != 'undefined' ) { $(oData.nTr).addClass( oData._aData.DT_RowClass ); } /* Process each column */ for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { var oCol = oSettings.aoColumns[i]; nTd = document.createElement('td'); /* Render if needed - if bUseRendered is true then we already have the rendered * value in the data source - so can just use that */ if ( typeof oCol.fnRender == 'function' && (!oCol.bUseRendered || oCol.mDataProp === null) ) { nTd.innerHTML = oCol.fnRender( { "iDataRow": iRow, "iDataColumn": i, "aData": oData._aData, "oSettings": oSettings } ); } else { nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' ); } /* Add user defined class */ if ( oCol.sClass !== null ) { nTd.className = oCol.sClass; } if ( oCol.bVisible ) { oData.nTr.appendChild( nTd ); oData._anHidden[i] = null; } else { oData._anHidden[i] = nTd; } } } } /* * Function: _fnGatherData * Purpose: Read in the data from the target table from the DOM * Returns: - * Inputs: object:oSettings - dataTables settings object * Notes: This is a optimised version of _fnAddData (more or less) for reading information * from the DOM. The basic actions must be identical in the two functions. */ function _fnGatherData( oSettings ) { var iLoop, i, iLen, j, jLen, jInner, nTds, nTrs, nTd, aLocalData, iThisIndex, iRow, iRows, iColumn, iColumns, sNodeName; /* * Process by row first * Add the data object for the whole table - storing the tr node. Note - no point in getting * DOM based data if we are going to go and replace it with Ajax source data. */ if ( oSettings.bDeferLoading || oSettings.sAjaxSource === null ) { nTrs = oSettings.nTBody.childNodes; for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { if ( nTrs[i].nodeName.toUpperCase() == "TR" ) { iThisIndex = oSettings.aoData.length; oSettings.aoData.push( { "nTr": nTrs[i], "_iId": oSettings.iNextId++, "_aData": [], "_anHidden": [], "_sRowStripe": '' } ); oSettings.aiDisplayMaster.push( iThisIndex ); nTds = nTrs[i].childNodes; jInner = 0; for ( j=0, jLen=nTds.length ; j<jLen ; j++ ) { sNodeName = nTds[j].nodeName.toUpperCase(); if ( sNodeName == "TD" || sNodeName == "TH" ) { _fnSetCellData( oSettings, iThisIndex, jInner, $.trim(nTds[j].innerHTML) ); jInner++; } } } } } /* Gather in the TD elements of the Table - note that this is basically the same as * fnGetTdNodes, but that function takes account of hidden columns, which we haven't yet * setup! */ nTrs = _fnGetTrNodes( oSettings ); nTds = []; for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { for ( j=0, jLen=nTrs[i].childNodes.length ; j<jLen ; j++ ) { nTd = nTrs[i].childNodes[j]; sNodeName = nTd.nodeName.toUpperCase(); if ( sNodeName == "TD" || sNodeName == "TH" ) { nTds.push( nTd ); } } } /* Sanity check */ if ( nTds.length != nTrs.length * oSettings.aoColumns.length ) { _fnLog( oSettings, 1, "Unexpected number of TD elements. Expected "+ (nTrs.length * oSettings.aoColumns.length)+" and got "+nTds.length+". DataTables does "+ "not support rowspan / colspan in the table body, and there must be one cell for each "+ "row/column combination." ); } /* Now process by column */ for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { /* Get the title of the column - unless there is a user set one */ if ( oSettings.aoColumns[iColumn].sTitle === null ) { oSettings.aoColumns[iColumn].sTitle = oSettings.aoColumns[iColumn].nTh.innerHTML; } var bAutoType = oSettings.aoColumns[iColumn]._bAutoType, bRender = typeof oSettings.aoColumns[iColumn].fnRender == 'function', bClass = oSettings.aoColumns[iColumn].sClass !== null, bVisible = oSettings.aoColumns[iColumn].bVisible, nCell, sThisType, sRendered, sValType; /* A single loop to rule them all (and be more efficient) */ if ( bAutoType || bRender || bClass || !bVisible ) { for ( iRow=0, iRows=oSettings.aoData.length ; iRow<iRows ; iRow++ ) { nCell = nTds[ (iRow*iColumns) + iColumn ]; /* Type detection */ if ( bAutoType && oSettings.aoColumns[iColumn].sType != 'string' ) { sValType = _fnGetCellData( oSettings, iRow, iColumn, 'type' ); if ( sValType !== '' ) { sThisType = _fnDetectType( sValType ); if ( oSettings.aoColumns[iColumn].sType === null ) { oSettings.aoColumns[iColumn].sType = sThisType; } else if ( oSettings.aoColumns[iColumn].sType != sThisType ) { /* String is always the 'fallback' option */ oSettings.aoColumns[iColumn].sType = 'string'; } } } /* Rendering */ if ( bRender ) { sRendered = oSettings.aoColumns[iColumn].fnRender( { "iDataRow": iRow, "iDataColumn": iColumn, "aData": oSettings.aoData[iRow]._aData, "oSettings": oSettings } ); nCell.innerHTML = sRendered; if ( oSettings.aoColumns[iColumn].bUseRendered ) { /* Use the rendered data for filtering/sorting */ _fnSetCellData( oSettings, iRow, iColumn, sRendered ); } } /* Classes */ if ( bClass ) { nCell.className += ' '+oSettings.aoColumns[iColumn].sClass; } /* Column visability */ if ( !bVisible ) { oSettings.aoData[iRow]._anHidden[iColumn] = nCell; nCell.parentNode.removeChild( nCell ); } else { oSettings.aoData[iRow]._anHidden[iColumn] = null; } } } } } /* * Function: _fnBuildHead * Purpose: Create the HTML header for the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnBuildHead( oSettings ) { var i, nTh, iLen, j, jLen; var anTr = oSettings.nTHead.getElementsByTagName('tr'); var iThs = oSettings.nTHead.getElementsByTagName('th').length; var iCorrector = 0; var jqChildren; /* If there is a header in place - then use it - otherwise it's going to get nuked... */ if ( iThs !== 0 ) { /* We've got a thead from the DOM, so remove hidden columns and apply width to vis cols */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; if ( oSettings.aoColumns[i].sClass !== null ) { $(nTh).addClass( oSettings.aoColumns[i].sClass ); } /* Set the title of the column if it is user defined (not what was auto detected) */ if ( oSettings.aoColumns[i].sTitle != nTh.innerHTML ) { nTh.innerHTML = oSettings.aoColumns[i].sTitle; } } } else { /* We don't have a header in the DOM - so we are going to have to create one */ var nTr = document.createElement( "tr" ); for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; nTh.innerHTML = oSettings.aoColumns[i].sTitle; if ( oSettings.aoColumns[i].sClass !== null ) { $(nTh).addClass( oSettings.aoColumns[i].sClass ); } nTr.appendChild( nTh ); } $(oSettings.nTHead).html( '' )[0].appendChild( nTr ); _fnDetectHeader( oSettings.aoHeader, oSettings.nTHead ); } /* Add the extra markup needed by jQuery UI's themes */ if ( oSettings.bJUI ) { for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { nTh = oSettings.aoColumns[i].nTh; var nDiv = document.createElement('div'); nDiv.className = oSettings.oClasses.sSortJUIWrapper; $(nTh).contents().appendTo(nDiv); var nSpan = document.createElement('span'); nSpan.className = oSettings.oClasses.sSortIcon; nDiv.appendChild( nSpan ); nTh.appendChild( nDiv ); } } /* Add sort listener */ var fnNoSelect = function (e) { this.onselectstart = function() { return false; }; return false; }; if ( oSettings.oFeatures.bSort ) { for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bSortable !== false ) { _fnSortAttachListener( oSettings, oSettings.aoColumns[i].nTh, i ); /* Take the brutal approach to cancelling text selection in header */ $(oSettings.aoColumns[i].nTh).bind( 'mousedown.DT', fnNoSelect ); } else { $(oSettings.aoColumns[i].nTh).addClass( oSettings.oClasses.sSortableNone ); } } } /* Deal with the footer - add classes if required */ if ( oSettings.oClasses.sFooterTH !== "" ) { $('>tr>th', oSettings.nTFoot).addClass( oSettings.oClasses.sFooterTH ); } /* Cache the footer elements */ if ( oSettings.nTFoot !== null ) { var anCells = _fnGetUniqueThs( oSettings, null, oSettings.aoFooter ); for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { if ( typeof anCells[i] != 'undefined' ) { oSettings.aoColumns[i].nTf = anCells[i]; } } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Drawing functions */ /* * Function: _fnDrawHead * Purpose: Draw the header (or footer) element based on the column visibility states. The * methodology here is to use the layout array from _fnDetectHeader, modified for * the instantaneous column visibility, to construct the new layout. The grid is * traversed over cell at a time in a rows x columns grid fashion, although each * cell insert can cover multiple elements in the grid - which is tracks using the * aApplied array. Cell inserts in the grid will only occur where there isn't * already a cell in that position. * Returns: - * Inputs: object:oSettings - dataTables settings object * array objects:aoSource - Layout array from _fnDetectHeader * boolean:bIncludeHidden - If true then include the hidden columns in the calc, * - optional: default false */ function _fnDrawHead( oSettings, aoSource, bIncludeHidden ) { var i, iLen, j, jLen, k, kLen; var aoLocal = []; var aApplied = []; var iColumns = oSettings.aoColumns.length; var iRowspan, iColspan; if ( typeof bIncludeHidden == 'undefined' ) { bIncludeHidden = false; } /* Make a copy of the master layout array, but without the visible columns in it */ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ ) { aoLocal[i] = aoSource[i].slice(); aoLocal[i].nTr = aoSource[i].nTr; /* Remove any columns which are currently hidden */ for ( j=iColumns-1 ; j>=0 ; j-- ) { if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden ) { aoLocal[i].splice( j, 1 ); } } /* Prep the applied array - it needs an element for each row */ aApplied.push( [] ); } for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ ) { /* All cells are going to be replaced, so empty out the row */ if ( aoLocal[i].nTr ) { for ( k=0, kLen=aoLocal[i].nTr.childNodes.length ; k<kLen ; k++ ) { aoLocal[i].nTr.removeChild( aoLocal[i].nTr.childNodes[0] ); } } for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ ) { iRowspan = 1; iColspan = 1; /* Check to see if there is already a cell (row/colspan) covering our target * insert point. If there is, then there is nothing to do. */ if ( typeof aApplied[i][j] == 'undefined' ) { aoLocal[i].nTr.appendChild( aoLocal[i][j].cell ); aApplied[i][j] = 1; /* Expand the cell to cover as many rows as needed */ while ( typeof aoLocal[i+iRowspan] != 'undefined' && aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell ) { aApplied[i+iRowspan][j] = 1; iRowspan++; } /* Expand the cell to cover as many columns as needed */ while ( typeof aoLocal[i][j+iColspan] != 'undefined' && aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell ) { /* Must update the applied array over the rows for the columns */ for ( k=0 ; k<iRowspan ; k++ ) { aApplied[i+k][j+iColspan] = 1; } iColspan++; } /* Do the actual expansion in the DOM */ aoLocal[i][j].cell.setAttribute('rowspan', iRowspan); aoLocal[i][j].cell.setAttribute('colspan', iColspan); } } } } /* * Function: _fnDraw * Purpose: Insert the required TR nodes into the table for display * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnDraw( oSettings ) { var i, iLen; var anRows = []; var iRowCount = 0; var bRowError = false; var iStrips = oSettings.asStripClasses.length; var iOpenRows = oSettings.aoOpenRows.length; /* Provide a pre-callback function which can be used to cancel the draw is false is returned */ if ( oSettings.fnPreDrawCallback !== null && oSettings.fnPreDrawCallback.call( oSettings.oInstance, oSettings ) === false ) { return; } oSettings.bDrawing = true; /* Check and see if we have an initial draw position from state saving */ if ( typeof oSettings.iInitDisplayStart != 'undefined' && oSettings.iInitDisplayStart != -1 ) { if ( oSettings.oFeatures.bServerSide ) { oSettings._iDisplayStart = oSettings.iInitDisplayStart; } else { oSettings._iDisplayStart = (oSettings.iInitDisplayStart >= oSettings.fnRecordsDisplay()) ? 0 : oSettings.iInitDisplayStart; } oSettings.iInitDisplayStart = -1; _fnCalculateEnd( oSettings ); } /* Server-side processing draw intercept */ if ( oSettings.bDeferLoading ) { oSettings.bDeferLoading = false; oSettings.iDraw++; } else if ( !oSettings.oFeatures.bServerSide ) { oSettings.iDraw++; } else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) ) { return; } if ( oSettings.aiDisplay.length !== 0 ) { var iStart = oSettings._iDisplayStart; var iEnd = oSettings._iDisplayEnd; if ( oSettings.oFeatures.bServerSide ) { iStart = 0; iEnd = oSettings.aoData.length; } for ( var j=iStart ; j<iEnd ; j++ ) { var aoData = oSettings.aoData[ oSettings.aiDisplay[j] ]; if ( aoData.nTr === null ) { _fnCreateTr( oSettings, oSettings.aiDisplay[j] ); } var nRow = aoData.nTr; /* Remove the old stripping classes and then add the new one */ if ( iStrips !== 0 ) { var sStrip = oSettings.asStripClasses[ iRowCount % iStrips ]; if ( aoData._sRowStripe != sStrip ) { $(nRow).removeClass( aoData._sRowStripe ).addClass( sStrip ); aoData._sRowStripe = sStrip; } } /* Custom row callback function - might want to manipule the row */ if ( typeof oSettings.fnRowCallback == "function" ) { nRow = oSettings.fnRowCallback.call( oSettings.oInstance, nRow, oSettings.aoData[ oSettings.aiDisplay[j] ]._aData, iRowCount, j ); if ( !nRow && !bRowError ) { _fnLog( oSettings, 0, "A node was not returned by fnRowCallback" ); bRowError = true; } } anRows.push( nRow ); iRowCount++; /* If there is an open row - and it is attached to this parent - attach it on redraw */ if ( iOpenRows !== 0 ) { for ( var k=0 ; k<iOpenRows ; k++ ) { if ( nRow == oSettings.aoOpenRows[k].nParent ) { anRows.push( oSettings.aoOpenRows[k].nTr ); } } } } } else { /* Table is empty - create a row with an empty message in it */ anRows[ 0 ] = document.createElement( 'tr' ); if ( typeof oSettings.asStripClasses[0] != 'undefined' ) { anRows[ 0 ].className = oSettings.asStripClasses[0]; } var sZero = oSettings.oLanguage.sZeroRecords.replace( '_MAX_', oSettings.fnFormatNumber(oSettings.fnRecordsTotal()) ); if ( oSettings.iDraw == 1 && oSettings.sAjaxSource !== null && !oSettings.oFeatures.bServerSide ) { sZero = oSettings.oLanguage.sLoadingRecords; } else if ( typeof oSettings.oLanguage.sEmptyTable != 'undefined' && oSettings.fnRecordsTotal() === 0 ) { sZero = oSettings.oLanguage.sEmptyTable; } var nTd = document.createElement( 'td' ); nTd.setAttribute( 'valign', "top" ); nTd.colSpan = _fnVisbleColumns( oSettings ); nTd.className = oSettings.oClasses.sRowEmpty; nTd.innerHTML = sZero; anRows[ iRowCount ].appendChild( nTd ); } /* Callback the header and footer custom funcation if there is one */ if ( typeof oSettings.fnHeaderCallback == 'function' ) { oSettings.fnHeaderCallback.call( oSettings.oInstance, $('>tr', oSettings.nTHead)[0], _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ); } if ( typeof oSettings.fnFooterCallback == 'function' ) { oSettings.fnFooterCallback.call( oSettings.oInstance, $('>tr', oSettings.nTFoot)[0], _fnGetDataMaster( oSettings ), oSettings._iDisplayStart, oSettings.fnDisplayEnd(), oSettings.aiDisplay ); } /* * Need to remove any old row from the display - note we can't just empty the tbody using * $().html('') since this will unbind the jQuery event handlers (even although the node * still exists!) - equally we can't use innerHTML, since IE throws an exception. */ var nAddFrag = document.createDocumentFragment(), nRemoveFrag = document.createDocumentFragment(), nBodyPar, nTrs; if ( oSettings.nTBody ) { nBodyPar = oSettings.nTBody.parentNode; nRemoveFrag.appendChild( oSettings.nTBody ); /* When doing infinite scrolling, only remove child rows when sorting, filtering or start * up. When not infinite scroll, always do it. */ if ( !oSettings.oScroll.bInfinite || !oSettings._bInitComplete || oSettings.bSorted || oSettings.bFiltered ) { nTrs = oSettings.nTBody.childNodes; for ( i=nTrs.length-1 ; i>=0 ; i-- ) { nTrs[i].parentNode.removeChild( nTrs[i] ); } } /* Put the draw table into the dom */ for ( i=0, iLen=anRows.length ; i<iLen ; i++ ) { nAddFrag.appendChild( anRows[i] ); } oSettings.nTBody.appendChild( nAddFrag ); if ( nBodyPar !== null ) { nBodyPar.appendChild( oSettings.nTBody ); } } /* Call all required callback functions for the end of a draw */ for ( i=oSettings.aoDrawCallback.length-1 ; i>=0 ; i-- ) { oSettings.aoDrawCallback[i].fn.call( oSettings.oInstance, oSettings ); } /* Draw is complete, sorting and filtering must be as well */ oSettings.bSorted = false; oSettings.bFiltered = false; oSettings.bDrawing = false; if ( oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); if ( typeof oSettings._bInitComplete == 'undefined' ) { _fnInitComplete( oSettings ); } } } /* * Function: _fnReDraw * Purpose: Redraw the table - taking account of the various features which are enabled * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnReDraw( oSettings ) { if ( oSettings.oFeatures.bSort ) { /* Sorting will refilter and draw for us */ _fnSort( oSettings, oSettings.oPreviousSearch ); } else if ( oSettings.oFeatures.bFilter ) { /* Filtering will redraw for us */ _fnFilterComplete( oSettings, oSettings.oPreviousSearch ); } else { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } /* * Function: _fnAjaxUpdate * Purpose: Update the table using an Ajax call * Returns: bool: block the table drawing or not * Inputs: object:oSettings - dataTables settings object */ function _fnAjaxUpdate( oSettings ) { if ( oSettings.bAjaxDataGet ) { _fnProcessingDisplay( oSettings, true ); var iColumns = oSettings.aoColumns.length; var aoData = [], mDataProp; var i; /* Paging and general */ oSettings.iDraw++; aoData.push( { "name": "sEcho", "value": oSettings.iDraw } ); aoData.push( { "name": "iColumns", "value": iColumns } ); aoData.push( { "name": "sColumns", "value": _fnColumnOrdering(oSettings) } ); aoData.push( { "name": "iDisplayStart", "value": oSettings._iDisplayStart } ); aoData.push( { "name": "iDisplayLength", "value": oSettings.oFeatures.bPaginate !== false ? oSettings._iDisplayLength : -1 } ); for ( i=0 ; i<iColumns ; i++ ) { mDataProp = oSettings.aoColumns[i].mDataProp; aoData.push( { "name": "mDataProp_"+i, "value": typeof(mDataProp)=="function" ? 'function' : mDataProp } ); } /* Filtering */ if ( oSettings.oFeatures.bFilter !== false ) { aoData.push( { "name": "sSearch", "value": oSettings.oPreviousSearch.sSearch } ); aoData.push( { "name": "bRegex", "value": oSettings.oPreviousSearch.bRegex } ); for ( i=0 ; i<iColumns ; i++ ) { aoData.push( { "name": "sSearch_"+i, "value": oSettings.aoPreSearchCols[i].sSearch } ); aoData.push( { "name": "bRegex_"+i, "value": oSettings.aoPreSearchCols[i].bRegex } ); aoData.push( { "name": "bSearchable_"+i, "value": oSettings.aoColumns[i].bSearchable } ); } } /* Sorting */ if ( oSettings.oFeatures.bSort !== false ) { var iFixed = oSettings.aaSortingFixed !== null ? oSettings.aaSortingFixed.length : 0; var iUser = oSettings.aaSorting.length; aoData.push( { "name": "iSortingCols", "value": iFixed+iUser } ); for ( i=0 ; i<iFixed ; i++ ) { aoData.push( { "name": "iSortCol_"+i, "value": oSettings.aaSortingFixed[i][0] } ); aoData.push( { "name": "sSortDir_"+i, "value": oSettings.aaSortingFixed[i][1] } ); } for ( i=0 ; i<iUser ; i++ ) { aoData.push( { "name": "iSortCol_"+(i+iFixed), "value": oSettings.aaSorting[i][0] } ); aoData.push( { "name": "sSortDir_"+(i+iFixed), "value": oSettings.aaSorting[i][1] } ); } for ( i=0 ; i<iColumns ; i++ ) { aoData.push( { "name": "bSortable_"+i, "value": oSettings.aoColumns[i].bSortable } ); } } oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aoData, function(json) { _fnAjaxUpdateDraw( oSettings, json ); }, oSettings ); return false; } else { return true; } } /* * Function: _fnAjaxUpdateDraw * Purpose: Data the data from the server (nuking the old) and redraw the table * Returns: - * Inputs: object:oSettings - dataTables settings object * object:json - json data return from the server. * The following must be defined: * iTotalRecords, iTotalDisplayRecords, aaData * The following may be defined: * sColumns */ function _fnAjaxUpdateDraw ( oSettings, json ) { if ( typeof json.sEcho != 'undefined' ) { /* Protect against old returns over-writing a new one. Possible when you get * very fast interaction, and later queires are completed much faster */ if ( json.sEcho*1 < oSettings.iDraw ) { return; } else { oSettings.iDraw = json.sEcho * 1; } } if ( !oSettings.oScroll.bInfinite || (oSettings.oScroll.bInfinite && (oSettings.bSorted || oSettings.bFiltered)) ) { _fnClearTable( oSettings ); } oSettings._iRecordsTotal = json.iTotalRecords; oSettings._iRecordsDisplay = json.iTotalDisplayRecords; /* Determine if reordering is required */ var sOrdering = _fnColumnOrdering(oSettings); var bReOrder = (typeof json.sColumns != 'undefined' && sOrdering !== "" && json.sColumns != sOrdering ); if ( bReOrder ) { var aiIndex = _fnReOrderIndex( oSettings, json.sColumns ); } var fnDataSrc = _fnGetObjectDataFn( oSettings.sAjaxDataProp ); var aData = fnDataSrc( json ); for ( var i=0, iLen=aData.length ; i<iLen ; i++ ) { if ( bReOrder ) { /* If we need to re-order, then create a new array with the correct order and add it */ var aDataSorted = []; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { aDataSorted.push( aData[i][ aiIndex[j] ] ); } _fnAddData( oSettings, aDataSorted ); } else { /* No re-order required, sever got it "right" - just straight add */ _fnAddData( oSettings, aData[i] ); } } oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); oSettings.bAjaxDataGet = false; _fnDraw( oSettings ); oSettings.bAjaxDataGet = true; _fnProcessingDisplay( oSettings, false ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Options (features) HTML */ /* * Function: _fnAddOptionsHtml * Purpose: Add the options to the page HTML for the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnAddOptionsHtml ( oSettings ) { /* * Create a temporary, empty, div which we can later on replace with what we have generated * we do it this way to rendering the 'options' html offline - speed :-) */ var nHolding = document.createElement( 'div' ); oSettings.nTable.parentNode.insertBefore( nHolding, oSettings.nTable ); /* * All DataTables are wrapped in a div */ oSettings.nTableWrapper = document.createElement( 'div' ); oSettings.nTableWrapper.className = oSettings.oClasses.sWrapper; if ( oSettings.sTableId !== '' ) { oSettings.nTableWrapper.setAttribute( 'id', oSettings.sTableId+'_wrapper' ); } oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling; /* Track where we want to insert the option */ var nInsertNode = oSettings.nTableWrapper; /* Loop over the user set positioning and place the elements as needed */ var aDom = oSettings.sDom.split(''); var nTmp, iPushFeature, cOption, nNewNode, cNext, sAttr, j; for ( var i=0 ; i<aDom.length ; i++ ) { iPushFeature = 0; cOption = aDom[i]; if ( cOption == '<' ) { /* New container div */ nNewNode = document.createElement( 'div' ); /* Check to see if we should append an id and/or a class name to the container */ cNext = aDom[i+1]; if ( cNext == "'" || cNext == '"' ) { sAttr = ""; j = 2; while ( aDom[i+j] != cNext ) { sAttr += aDom[i+j]; j++; } /* Replace jQuery UI constants */ if ( sAttr == "H" ) { sAttr = "fg-toolbar ui-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix"; } else if ( sAttr == "F" ) { sAttr = "fg-toolbar ui-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"; } /* The attribute can be in the format of "#id.class", "#id" or "class" This logic * breaks the string into parts and applies them as needed */ if ( sAttr.indexOf('.') != -1 ) { var aSplit = sAttr.split('.'); nNewNode.setAttribute('id', aSplit[0].substr(1, aSplit[0].length-1) ); nNewNode.className = aSplit[1]; } else if ( sAttr.charAt(0) == "#" ) { nNewNode.setAttribute('id', sAttr.substr(1, sAttr.length-1) ); } else { nNewNode.className = sAttr; } i += j; /* Move along the position array */ } nInsertNode.appendChild( nNewNode ); nInsertNode = nNewNode; } else if ( cOption == '>' ) { /* End container div */ nInsertNode = nInsertNode.parentNode; } else if ( cOption == 'l' && oSettings.oFeatures.bPaginate && oSettings.oFeatures.bLengthChange ) { /* Length */ nTmp = _fnFeatureHtmlLength( oSettings ); iPushFeature = 1; } else if ( cOption == 'f' && oSettings.oFeatures.bFilter ) { /* Filter */ nTmp = _fnFeatureHtmlFilter( oSettings ); iPushFeature = 1; } else if ( cOption == 'r' && oSettings.oFeatures.bProcessing ) { /* pRocessing */ nTmp = _fnFeatureHtmlProcessing( oSettings ); iPushFeature = 1; } else if ( cOption == 't' ) { /* Table */ nTmp = _fnFeatureHtmlTable( oSettings ); iPushFeature = 1; } else if ( cOption == 'i' && oSettings.oFeatures.bInfo ) { /* Info */ nTmp = _fnFeatureHtmlInfo( oSettings ); iPushFeature = 1; } else if ( cOption == 'p' && oSettings.oFeatures.bPaginate ) { /* Pagination */ nTmp = _fnFeatureHtmlPaginate( oSettings ); iPushFeature = 1; } else if ( _oExt.aoFeatures.length !== 0 ) { /* Plug-in features */ var aoFeatures = _oExt.aoFeatures; for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ ) { if ( cOption == aoFeatures[k].cFeature ) { nTmp = aoFeatures[k].fnInit( oSettings ); if ( nTmp ) { iPushFeature = 1; } break; } } } /* Add to the 2D features array */ if ( iPushFeature == 1 && nTmp !== null ) { if ( typeof oSettings.aanFeatures[cOption] != 'object' ) { oSettings.aanFeatures[cOption] = []; } oSettings.aanFeatures[cOption].push( nTmp ); nInsertNode.appendChild( nTmp ); } } /* Built our DOM structure - replace the holding div with what we want */ nHolding.parentNode.replaceChild( oSettings.nTableWrapper, nHolding ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Filtering */ /* * Function: _fnFeatureHtmlTable * Purpose: Add any control elements for the table - specifically scrolling * Returns: node: - Node to add to the DOM * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlTable ( oSettings ) { /* Chack if scrolling is enabled or not - if not then leave the DOM unaltered */ if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { return oSettings.nTable; } /* * The HTML structure that we want to generate in this function is: * div - nScroller * div - nScrollHead * div - nScrollHeadInner * table - nScrollHeadTable * thead - nThead * div - nScrollBody * table - oSettings.nTable * thead - nTheadSize * tbody - nTbody * div - nScrollFoot * div - nScrollFootInner * table - nScrollFootTable * tfoot - nTfoot */ var nScroller = document.createElement('div'), nScrollHead = document.createElement('div'), nScrollHeadInner = document.createElement('div'), nScrollBody = document.createElement('div'), nScrollFoot = document.createElement('div'), nScrollFootInner = document.createElement('div'), nScrollHeadTable = oSettings.nTable.cloneNode(false), nScrollFootTable = oSettings.nTable.cloneNode(false), nThead = oSettings.nTable.getElementsByTagName('thead')[0], nTfoot = oSettings.nTable.getElementsByTagName('tfoot').length === 0 ? null : oSettings.nTable.getElementsByTagName('tfoot')[0], oClasses = (typeof oInit.bJQueryUI != 'undefined' && oInit.bJQueryUI) ? _oExt.oJUIClasses : _oExt.oStdClasses; nScrollHead.appendChild( nScrollHeadInner ); nScrollFoot.appendChild( nScrollFootInner ); nScrollBody.appendChild( oSettings.nTable ); nScroller.appendChild( nScrollHead ); nScroller.appendChild( nScrollBody ); nScrollHeadInner.appendChild( nScrollHeadTable ); nScrollHeadTable.appendChild( nThead ); if ( nTfoot !== null ) { nScroller.appendChild( nScrollFoot ); nScrollFootInner.appendChild( nScrollFootTable ); nScrollFootTable.appendChild( nTfoot ); } nScroller.className = oClasses.sScrollWrapper; nScrollHead.className = oClasses.sScrollHead; nScrollHeadInner.className = oClasses.sScrollHeadInner; nScrollBody.className = oClasses.sScrollBody; nScrollFoot.className = oClasses.sScrollFoot; nScrollFootInner.className = oClasses.sScrollFootInner; if ( oSettings.oScroll.bAutoCss ) { nScrollHead.style.overflow = "hidden"; nScrollHead.style.position = "relative"; nScrollFoot.style.overflow = "hidden"; nScrollBody.style.overflow = "auto"; } nScrollHead.style.border = "0"; nScrollHead.style.width = "100%"; nScrollFoot.style.border = "0"; nScrollHeadInner.style.width = "150%"; /* will be overwritten */ /* Modify attributes to respect the clones */ nScrollHeadTable.removeAttribute('id'); nScrollHeadTable.style.marginLeft = "0"; oSettings.nTable.style.marginLeft = "0"; if ( nTfoot !== null ) { nScrollFootTable.removeAttribute('id'); nScrollFootTable.style.marginLeft = "0"; } /* Move any caption elements from the body to the header */ var nCaptions = $('>caption', oSettings.nTable); for ( var i=0, iLen=nCaptions.length ; i<iLen ; i++ ) { nScrollHeadTable.appendChild( nCaptions[i] ); } /* * Sizing */ /* When xscrolling add the width and a scroller to move the header with the body */ if ( oSettings.oScroll.sX !== "" ) { nScrollHead.style.width = _fnStringToCss( oSettings.oScroll.sX ); nScrollBody.style.width = _fnStringToCss( oSettings.oScroll.sX ); if ( nTfoot !== null ) { nScrollFoot.style.width = _fnStringToCss( oSettings.oScroll.sX ); } /* When the body is scrolled, then we also want to scroll the headers */ $(nScrollBody).scroll( function (e) { nScrollHead.scrollLeft = this.scrollLeft; if ( nTfoot !== null ) { nScrollFoot.scrollLeft = this.scrollLeft; } } ); } /* When yscrolling, add the height */ if ( oSettings.oScroll.sY !== "" ) { nScrollBody.style.height = _fnStringToCss( oSettings.oScroll.sY ); } /* Redraw - align columns across the tables */ oSettings.aoDrawCallback.push( { "fn": _fnScrollDraw, "sName": "scrolling" } ); /* Infinite scrolling event handlers */ if ( oSettings.oScroll.bInfinite ) { $(nScrollBody).scroll( function() { /* Use a blocker to stop scrolling from loading more data while other data is still loading */ if ( !oSettings.bDrawing ) { /* Check if we should load the next data set */ if ( $(this).scrollTop() + $(this).height() > $(oSettings.nTable).height() - oSettings.oScroll.iLoadGap ) { /* Only do the redraw if we have to - we might be at the end of the data */ if ( oSettings.fnDisplayEnd() < oSettings.fnRecordsDisplay() ) { _fnPageChange( oSettings, 'next' ); _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } } } ); } oSettings.nScrollHead = nScrollHead; oSettings.nScrollFoot = nScrollFoot; return nScroller; } /* * Function: _fnScrollDraw * Purpose: Update the various tables for resizing * Returns: node: - Node to add to the DOM * Inputs: object:o - dataTables settings object * Notes: It's a bit of a pig this function, but basically the idea to: * 1. Re-create the table inside the scrolling div * 2. Take live measurements from the DOM * 3. Apply the measurements * 4. Clean up */ function _fnScrollDraw ( o ) { var nScrollHeadInner = o.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = o.nTable.parentNode, i, iLen, j, jLen, anHeadToSize, anHeadSizers, anFootSizers, anFootToSize, oStyle, iVis, iWidth, aApplied=[], iSanityWidth; /* * 1. Re-create the table inside the scrolling div */ /* Remove the old minimised thead and tfoot elements in the inner table */ var nTheadSize = o.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { o.nTable.removeChild( nTheadSize[0] ); } if ( o.nTFoot !== null ) { /* Remove the old minimised footer element in the cloned header */ var nTfootSize = o.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { o.nTable.removeChild( nTfootSize[0] ); } } /* Clone the current header and footer elements and then place it into the inner table */ nTheadSize = o.nTHead.cloneNode(true); o.nTable.insertBefore( nTheadSize, o.nTable.childNodes[0] ); if ( o.nTFoot !== null ) { nTfootSize = o.nTFoot.cloneNode(true); o.nTable.insertBefore( nTfootSize, o.nTable.childNodes[1] ); } /* * 2. Take live measurements from the DOM - do not alter the DOM itself! */ /* Remove old sizing and apply the calculated column widths * Get the unique column headers in the newly created (cloned) header. We want to apply the * calclated sizes to this header */ if ( o.oScroll.sX === "" ) { nScrollBody.style.width = '100%'; nScrollHeadInner.parentNode.style.width = '100%'; } var nThs = _fnGetUniqueThs( o, nTheadSize ); for ( i=0, iLen=nThs.length ; i<iLen ; i++ ) { iVis = _fnVisibleToColumnIndex( o, i ); nThs[i].style.width = o.aoColumns[iVis].sWidth; } if ( o.nTFoot !== null ) { _fnApplyToChildren( function(n) { n.style.width = ""; }, nTfootSize.getElementsByTagName('tr') ); } /* Size the table as a whole */ iSanityWidth = $(o.nTable).outerWidth(); if ( o.oScroll.sX === "" ) { /* No x scrolling */ o.nTable.style.width = "100%"; /* I know this is rubbish - but IE7 will make the width of the table when 100% include * the scrollbar - which is shouldn't. This needs feature detection in future - to do */ if ( $.browser.msie && $.browser.version <= 7 ) { o.nTable.style.width = _fnStringToCss( $(o.nTable).outerWidth()-o.oScroll.iBarWidth ); } } else { if ( o.oScroll.sXInner !== "" ) { /* x scroll inner has been given - use it */ o.nTable.style.width = _fnStringToCss(o.oScroll.sXInner); } else if ( iSanityWidth == $(nScrollBody).width() && $(nScrollBody).height() < $(o.nTable).height() ) { /* There is y-scrolling - try to take account of the y scroll bar */ o.nTable.style.width = _fnStringToCss( iSanityWidth-o.oScroll.iBarWidth ); if ( $(o.nTable).outerWidth() > iSanityWidth-o.oScroll.iBarWidth ) { /* Not possible to take account of it */ o.nTable.style.width = _fnStringToCss( iSanityWidth ); } } else { /* All else fails */ o.nTable.style.width = _fnStringToCss( iSanityWidth ); } } /* Recalculate the sanity width - now that we've applied the required width, before it was * a temporary variable. This is required because the column width calculation is done * before this table DOM is created. */ iSanityWidth = $(o.nTable).outerWidth(); /* If x-scrolling is disabled, then the viewport cannot be less than the sanity width */ if ( o.oScroll.sX === "" ) { nScrollBody.style.width = _fnStringToCss( iSanityWidth+o.oScroll.iBarWidth ); nScrollHeadInner.parentNode.style.width = _fnStringToCss( iSanityWidth+o.oScroll.iBarWidth ); } /* We want the hidden header to have zero height, so remove padding and borders. Then * set the width based on the real headers */ anHeadToSize = o.nTHead.getElementsByTagName('tr'); anHeadSizers = nTheadSize.getElementsByTagName('tr'); _fnApplyToChildren( function(nSizer, nToSize) { oStyle = nSizer.style; oStyle.paddingTop = "0"; oStyle.paddingBottom = "0"; oStyle.borderTopWidth = "0"; oStyle.borderBottomWidth = "0"; oStyle.height = 0; iWidth = $(nSizer).width(); nToSize.style.width = _fnStringToCss( iWidth ); aApplied.push( iWidth ); }, anHeadSizers, anHeadToSize ); $(anHeadSizers).height(0); if ( o.nTFoot !== null ) { /* Clone the current footer and then place it into the body table as a "hidden header" */ anFootSizers = nTfootSize.getElementsByTagName('tr'); anFootToSize = o.nTFoot.getElementsByTagName('tr'); _fnApplyToChildren( function(nSizer, nToSize) { oStyle = nSizer.style; oStyle.paddingTop = "0"; oStyle.paddingBottom = "0"; oStyle.borderTopWidth = "0"; oStyle.borderBottomWidth = "0"; oStyle.height = 0; iWidth = $(nSizer).width(); nToSize.style.width = _fnStringToCss( iWidth ); aApplied.push( iWidth ); }, anFootSizers, anFootToSize ); $(anFootSizers).height(0); } /* * 3. Apply the measurements */ /* "Hide" the header and footer that we used for the sizing. We want to also fix their width * to what they currently are */ _fnApplyToChildren( function(nSizer) { nSizer.innerHTML = ""; nSizer.style.width = _fnStringToCss( aApplied.shift() ); }, anHeadSizers ); if ( o.nTFoot !== null ) { _fnApplyToChildren( function(nSizer) { nSizer.innerHTML = ""; nSizer.style.width = _fnStringToCss( aApplied.shift() ); }, anFootSizers ); } /* Sanity check that the table is of a sensible width. If not then we are going to get * misalignment */ if ( $(o.nTable).outerWidth() < iSanityWidth ) { if ( o.oScroll.sX === "" ) { _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+ " misalignment. It is suggested that you enable x-scrolling or increase the width"+ " the table has in which to be drawn" ); } else if ( o.oScroll.sXInner !== "" ) { _fnLog( o, 1, "The table cannot fit into the current element which will cause column"+ " misalignment. It is suggested that you increase the sScrollXInner property to"+ " allow it to draw in a larger area, or simply remove that parameter to allow"+ " automatic calculation" ); } } /* * 4. Clean up */ if ( o.oScroll.sY === "" ) { /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting * the scrollbar height from the visible display, rather than adding it on. We need to * set the height in order to sort this. Don't want to do it in any other browsers. */ if ( $.browser.msie && $.browser.version <= 7 ) { nScrollBody.style.height = _fnStringToCss( o.nTable.offsetHeight+o.oScroll.iBarWidth ); } } if ( o.oScroll.sY !== "" && o.oScroll.bCollapse ) { nScrollBody.style.height = _fnStringToCss( o.oScroll.sY ); var iExtra = (o.oScroll.sX !== "" && o.nTable.offsetWidth > nScrollBody.offsetWidth) ? o.oScroll.iBarWidth : 0; if ( o.nTable.offsetHeight < nScrollBody.offsetHeight ) { nScrollBody.style.height = _fnStringToCss( $(o.nTable).height()+iExtra ); } } /* Finally set the width's of the header and footer tables */ var iOuterWidth = $(o.nTable).outerWidth(); nScrollHeadTable.style.width = _fnStringToCss( iOuterWidth ); nScrollHeadInner.style.width = _fnStringToCss( iOuterWidth+o.oScroll.iBarWidth ); if ( o.nTFoot !== null ) { var nScrollFootInner = o.nScrollFoot.getElementsByTagName('div')[0], nScrollFootTable = nScrollFootInner.getElementsByTagName('table')[0]; nScrollFootInner.style.width = _fnStringToCss( o.nTable.offsetWidth+o.oScroll.iBarWidth ); nScrollFootTable.style.width = _fnStringToCss( o.nTable.offsetWidth ); } /* If sorting or filtering has occured, jump the scrolling back to the top */ if ( o.bSorted || o.bFiltered ) { nScrollBody.scrollTop = 0; } } /* * Function: _fnAjustColumnSizing * Purpose: Ajust the table column widths for new data * Returns: - * Inputs: object:oSettings - dataTables settings object * Notes: You would probably want to do a redraw after calling this function! */ function _fnAjustColumnSizing ( oSettings ) { /* Not interested in doing column width calculation if autowidth is disabled */ if ( oSettings.oFeatures.bAutoWidth === false ) { return false; } _fnCalculateColumnWidths( oSettings ); for ( var i=0 , iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oSettings.aoColumns[i].nTh.style.width = oSettings.aoColumns[i].sWidth; } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Filtering */ /* * Function: _fnFeatureHtmlFilter * Purpose: Generate the node required for filtering text * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlFilter ( oSettings ) { var sSearchStr = oSettings.oLanguage.sSearch; sSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ? sSearchStr.replace('_INPUT_', '<input type="text" />') : sSearchStr==="" ? '<input type="text" />' : sSearchStr+' <input type="text" />'; var nFilter = document.createElement( 'div' ); nFilter.className = oSettings.oClasses.sFilter; nFilter.innerHTML = '<label>'+sSearchStr+'</label>'; if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.f == "undefined" ) { nFilter.setAttribute( 'id', oSettings.sTableId+'_filter' ); } var jqFilter = $("input", nFilter); jqFilter.val( oSettings.oPreviousSearch.sSearch.replace('"','&quot;') ); jqFilter.bind( 'keyup.DT', function(e) { /* Update all other filter input elements for the new display */ var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != this.parentNode ) { $('input', n[i]).val( this.value ); } } /* Now do the filter */ if ( this.value != oSettings.oPreviousSearch.sSearch ) { _fnFilterComplete( oSettings, { "sSearch": this.value, "bRegex": oSettings.oPreviousSearch.bRegex, "bSmart": oSettings.oPreviousSearch.bSmart } ); } } ); jqFilter.bind( 'keypress.DT', function(e) { /* Prevent default */ if ( e.keyCode == 13 ) { return false; } } ); return nFilter; } /* * Function: _fnFilterComplete * Purpose: Filter the table using both the global filter and column based filtering * Returns: - * Inputs: object:oSettings - dataTables settings object * object:oSearch: search information * int:iForce - optional - force a research of the master array (1) or not (undefined or 0) */ function _fnFilterComplete ( oSettings, oInput, iForce ) { /* Filter on everything */ _fnFilter( oSettings, oInput.sSearch, iForce, oInput.bRegex, oInput.bSmart ); /* Now do the individual column filter */ for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ) { _fnFilterColumn( oSettings, oSettings.aoPreSearchCols[i].sSearch, i, oSettings.aoPreSearchCols[i].bRegex, oSettings.aoPreSearchCols[i].bSmart ); } /* Custom filtering */ if ( _oExt.afnFiltering.length !== 0 ) { _fnFilterCustom( oSettings ); } /* Tell the draw function we have been filtering */ oSettings.bFiltered = true; /* Redraw the table */ oSettings._iDisplayStart = 0; _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); /* Rebuild search array 'offline' */ _fnBuildSearchArray( oSettings, 0 ); } /* * Function: _fnFilterCustom * Purpose: Apply custom filtering functions * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnFilterCustom( oSettings ) { var afnFilters = _oExt.afnFiltering; for ( var i=0, iLen=afnFilters.length ; i<iLen ; i++ ) { var iCorrector = 0; for ( var j=0, jLen=oSettings.aiDisplay.length ; j<jLen ; j++ ) { var iDisIndex = oSettings.aiDisplay[j-iCorrector]; /* Check if we should use this row based on the filtering function */ if ( !afnFilters[i]( oSettings, _fnGetRowData( oSettings, iDisIndex, 'filter' ), iDisIndex ) ) { oSettings.aiDisplay.splice( j-iCorrector, 1 ); iCorrector++; } } } } /* * Function: _fnFilterColumn * Purpose: Filter the table on a per-column basis * Returns: - * Inputs: object:oSettings - dataTables settings object * string:sInput - string to filter on * int:iColumn - column to filter * bool:bRegex - treat search string as a regular expression or not * bool:bSmart - use smart filtering or not */ function _fnFilterColumn ( oSettings, sInput, iColumn, bRegex, bSmart ) { if ( sInput === "" ) { return; } var iIndexCorrector = 0; var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart ); for ( var i=oSettings.aiDisplay.length-1 ; i>=0 ; i-- ) { var sData = _fnDataToSearch( _fnGetCellData( oSettings, oSettings.aiDisplay[i], iColumn, 'filter' ), oSettings.aoColumns[iColumn].sType ); if ( ! rpSearch.test( sData ) ) { oSettings.aiDisplay.splice( i, 1 ); iIndexCorrector++; } } } /* * Function: _fnFilter * Purpose: Filter the data table based on user input and draw the table * Returns: - * Inputs: object:oSettings - dataTables settings object * string:sInput - string to filter on * int:iForce - optional - force a research of the master array (1) or not (undefined or 0) * bool:bRegex - treat as a regular expression or not * bool:bSmart - perform smart filtering or not */ function _fnFilter( oSettings, sInput, iForce, bRegex, bSmart ) { var i; var rpSearch = _fnFilterCreateSearch( sInput, bRegex, bSmart ); /* Check if we are forcing or not - optional parameter */ if ( typeof iForce == 'undefined' || iForce === null ) { iForce = 0; } /* Need to take account of custom filtering functions - always filter */ if ( _oExt.afnFiltering.length !== 0 ) { iForce = 1; } /* * If the input is blank - we want the full data set */ if ( sInput.length <= 0 ) { oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length); oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); } else { /* * We are starting a new search or the new search string is smaller * then the old one (i.e. delete). Search from the master array */ if ( oSettings.aiDisplay.length == oSettings.aiDisplayMaster.length || oSettings.oPreviousSearch.sSearch.length > sInput.length || iForce == 1 || sInput.indexOf(oSettings.oPreviousSearch.sSearch) !== 0 ) { /* Nuke the old display array - we are going to rebuild it */ oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length); /* Force a rebuild of the search array */ _fnBuildSearchArray( oSettings, 1 ); /* Search through all records to populate the search array * The the oSettings.aiDisplayMaster and asDataSearch arrays have 1 to 1 * mapping */ for ( i=0 ; i<oSettings.aiDisplayMaster.length ; i++ ) { if ( rpSearch.test(oSettings.asDataSearch[i]) ) { oSettings.aiDisplay.push( oSettings.aiDisplayMaster[i] ); } } } else { /* Using old search array - refine it - do it this way for speed * Don't have to search the whole master array again */ var iIndexCorrector = 0; /* Search the current results */ for ( i=0 ; i<oSettings.asDataSearch.length ; i++ ) { if ( ! rpSearch.test(oSettings.asDataSearch[i]) ) { oSettings.aiDisplay.splice( i-iIndexCorrector, 1 ); iIndexCorrector++; } } } } oSettings.oPreviousSearch.sSearch = sInput; oSettings.oPreviousSearch.bRegex = bRegex; oSettings.oPreviousSearch.bSmart = bSmart; } /* * Function: _fnBuildSearchArray * Purpose: Create an array which can be quickly search through * Returns: - * Inputs: object:oSettings - dataTables settings object * int:iMaster - use the master data array - optional */ function _fnBuildSearchArray ( oSettings, iMaster ) { /* Clear out the old data */ oSettings.asDataSearch.splice( 0, oSettings.asDataSearch.length ); var aArray = (typeof iMaster != 'undefined' && iMaster == 1) ? oSettings.aiDisplayMaster : oSettings.aiDisplay; for ( var i=0, iLen=aArray.length ; i<iLen ; i++ ) { oSettings.asDataSearch[i] = _fnBuildSearchRow( oSettings, _fnGetRowData( oSettings, aArray[i], 'filter' ) ); } } /* * Function: _fnBuildSearchRow * Purpose: Create a searchable string from a single data row * Returns: - * Inputs: object:oSettings - dataTables settings object * array:aData - Row data array to use for the data to search */ function _fnBuildSearchRow( oSettings, aData ) { var sSearch = ''; if ( typeof oSettings.__nTmpFilter == 'undefined' ) { oSettings.__nTmpFilter = document.createElement('div'); } var nTmp = oSettings.__nTmpFilter; for ( var j=0, jLen=oSettings.aoColumns.length ; j<jLen ; j++ ) { if ( oSettings.aoColumns[j].bSearchable ) { var sData = aData[j]; sSearch += _fnDataToSearch( sData, oSettings.aoColumns[j].sType )+' '; } } /* If it looks like there is an HTML entity in the string, attempt to decode it */ if ( sSearch.indexOf('&') !== -1 ) { nTmp.innerHTML = sSearch; sSearch = nTmp.textContent ? nTmp.textContent : nTmp.innerText; /* IE and Opera appear to put an newline where there is a <br> tag - remove it */ sSearch = sSearch.replace(/\n/g," ").replace(/\r/g,""); } return sSearch; } /* * Function: _fnFilterCreateSearch * Purpose: Build a regular expression object suitable for searching a table * Returns: RegExp: - constructed object * Inputs: string:sSearch - string to search for * bool:bRegex - treat as a regular expression or not * bool:bSmart - perform smart filtering or not */ function _fnFilterCreateSearch( sSearch, bRegex, bSmart ) { var asSearch, sRegExpString; if ( bSmart ) { /* Generate the regular expression to use. Something along the lines of: * ^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$ */ asSearch = bRegex ? sSearch.split( ' ' ) : _fnEscapeRegex( sSearch ).split( ' ' ); sRegExpString = '^(?=.*?'+asSearch.join( ')(?=.*?' )+').*$'; return new RegExp( sRegExpString, "i" ); } else { sSearch = bRegex ? sSearch : _fnEscapeRegex( sSearch ); return new RegExp( sSearch, "i" ); } } /* * Function: _fnDataToSearch * Purpose: Convert raw data into something that the user can search on * Returns: string: - search string * Inputs: string:sData - data to be modified * string:sType - data type */ function _fnDataToSearch ( sData, sType ) { if ( typeof _oExt.ofnSearch[sType] == "function" ) { return _oExt.ofnSearch[sType]( sData ); } else if ( sType == "html" ) { return sData.replace(/\n/g," ").replace( /<.*?>/g, "" ); } else if ( typeof sData == "string" ) { return sData.replace(/\n/g," "); } else if ( sData === null ) { return ''; } return sData; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Sorting */ /* * Function: _fnSort * Purpose: Change the order of the table * Returns: - * Inputs: object:oSettings - dataTables settings object * bool:bApplyClasses - optional - should we apply classes or not * Notes: We always sort the master array and then apply a filter again * if it is needed. This probably isn't optimal - but atm I can't think * of any other way which is (each has disadvantages). we want to sort aiDisplayMaster - * but according to aoData[]._aData */ function _fnSort ( oSettings, bApplyClasses ) { var iDataSort, iDataType, i, iLen, j, jLen, aaSort = [], aiOrig = [], oSort = _oExt.oSort, aoData = oSettings.aoData, aoColumns = oSettings.aoColumns; /* No sorting required if server-side or no sorting array */ if ( !oSettings.oFeatures.bServerSide && (oSettings.aaSorting.length !== 0 || oSettings.aaSortingFixed !== null) ) { if ( oSettings.aaSortingFixed !== null ) { aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting ); } else { aaSort = oSettings.aaSorting.slice(); } /* If there is a sorting data type, and a fuction belonging to it, then we need to * get the data from the developer's function and apply it for this column */ for ( i=0 ; i<aaSort.length ; i++ ) { var iColumn = aaSort[i][0]; var iVisColumn = _fnColumnIndexToVisible( oSettings, iColumn ); var sDataType = oSettings.aoColumns[ iColumn ].sSortDataType; if ( typeof _oExt.afnSortData[sDataType] != 'undefined' ) { var aData = _oExt.afnSortData[sDataType]( oSettings, iColumn, iVisColumn ); for ( j=0, jLen=aoData.length ; j<jLen ; j++ ) { _fnSetCellData( oSettings, j, iColumn, aData[j] ); } } } /* Create a value - key array of the current row positions such that we can use their * current position during the sort, if values match, in order to perform stable sorting */ for ( i=0, iLen=oSettings.aiDisplayMaster.length ; i<iLen ; i++ ) { aiOrig[ oSettings.aiDisplayMaster[i] ] = i; } /* Do the sort - here we want multi-column sorting based on a given data source (column) * and sorting function (from oSort) in a certain direction. It's reasonably complex to * follow on it's own, but this is what we want (example two column sorting): * fnLocalSorting = function(a,b){ * var iTest; * iTest = oSort['string-asc']('data11', 'data12'); * if (iTest !== 0) * return iTest; * iTest = oSort['numeric-desc']('data21', 'data22'); * if (iTest !== 0) * return iTest; * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); * } * Basically we have a test for each sorting column, if the data in that column is equal, * test the next column. If all columns match, then we use a numeric sort on the row * positions in the original data array to provide a stable sort. */ var iSortLen = aaSort.length; oSettings.aiDisplayMaster.sort( function ( a, b ) { var iTest, iDataSort, sDataType; for ( i=0 ; i<iSortLen ; i++ ) { iDataSort = aoColumns[ aaSort[i][0] ].iDataSort; sDataType = aoColumns[ iDataSort ].sType; iTest = oSort[ (sDataType?sDataType:'string')+"-"+aaSort[i][1] ]( _fnGetCellData( oSettings, a, iDataSort, 'sort' ), _fnGetCellData( oSettings, b, iDataSort, 'sort' ) ); if ( iTest !== 0 ) { return iTest; } } return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); } ); } /* Alter the sorting classes to take account of the changes */ if ( (typeof bApplyClasses == 'undefined' || bApplyClasses) && !oSettings.oFeatures.bDeferRender ) { _fnSortingClasses( oSettings ); } /* Tell the draw function that we have sorted the data */ oSettings.bSorted = true; /* Copy the master data into the draw array and re-draw */ if ( oSettings.oFeatures.bFilter ) { /* _fnFilter() will redraw the table for us */ _fnFilterComplete( oSettings, oSettings.oPreviousSearch, 1 ); } else { oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); oSettings._iDisplayStart = 0; /* reset display back to page 0 */ _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } } /* * Function: _fnSortAttachListener * Purpose: Attach a sort handler (click) to a node * Returns: - * Inputs: object:oSettings - dataTables settings object * node:nNode - node to attach the handler to * int:iDataIndex - column sorting index * function:fnCallback - callback function - optional */ function _fnSortAttachListener ( oSettings, nNode, iDataIndex, fnCallback ) { $(nNode).bind( 'click.DT', function (e) { /* If the column is not sortable - don't to anything */ if ( oSettings.aoColumns[iDataIndex].bSortable === false ) { return; } /* * This is a little bit odd I admit... I declare a temporary function inside the scope of * _fnBuildHead and the click handler in order that the code presented here can be used * twice - once for when bProcessing is enabled, and another time for when it is * disabled, as we need to perform slightly different actions. * Basically the issue here is that the Javascript engine in modern browsers don't * appear to allow the rendering engine to update the display while it is still excuting * it's thread (well - it does but only after long intervals). This means that the * 'processing' display doesn't appear for a table sort. To break the js thread up a bit * I force an execution break by using setTimeout - but this breaks the expected * thread continuation for the end-developer's point of view (their code would execute * too early), so we on;y do it when we absolutely have to. */ var fnInnerSorting = function () { var iColumn, iNextSort; /* If the shift key is pressed then we are multipe column sorting */ if ( e.shiftKey ) { /* Are we already doing some kind of sort on this column? */ var bFound = false; for ( var i=0 ; i<oSettings.aaSorting.length ; i++ ) { if ( oSettings.aaSorting[i][0] == iDataIndex ) { bFound = true; iColumn = oSettings.aaSorting[i][0]; iNextSort = oSettings.aaSorting[i][2]+1; if ( typeof oSettings.aoColumns[iColumn].asSorting[iNextSort] == 'undefined' ) { /* Reached the end of the sorting options, remove from multi-col sort */ oSettings.aaSorting.splice( i, 1 ); } else { /* Move onto next sorting direction */ oSettings.aaSorting[i][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort]; oSettings.aaSorting[i][2] = iNextSort; } break; } } /* No sort yet - add it in */ if ( bFound === false ) { oSettings.aaSorting.push( [ iDataIndex, oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] ); } } else { /* If no shift key then single column sort */ if ( oSettings.aaSorting.length == 1 && oSettings.aaSorting[0][0] == iDataIndex ) { iColumn = oSettings.aaSorting[0][0]; iNextSort = oSettings.aaSorting[0][2]+1; if ( typeof oSettings.aoColumns[iColumn].asSorting[iNextSort] == 'undefined' ) { iNextSort = 0; } oSettings.aaSorting[0][1] = oSettings.aoColumns[iColumn].asSorting[iNextSort]; oSettings.aaSorting[0][2] = iNextSort; } else { oSettings.aaSorting.splice( 0, oSettings.aaSorting.length ); oSettings.aaSorting.push( [ iDataIndex, oSettings.aoColumns[iDataIndex].asSorting[0], 0 ] ); } } /* Run the sort */ _fnSort( oSettings ); }; /* /fnInnerSorting */ if ( !oSettings.oFeatures.bProcessing ) { fnInnerSorting(); } else { _fnProcessingDisplay( oSettings, true ); setTimeout( function() { fnInnerSorting(); if ( !oSettings.oFeatures.bServerSide ) { _fnProcessingDisplay( oSettings, false ); } }, 0 ); } /* Call the user specified callback function - used for async user interaction */ if ( typeof fnCallback == 'function' ) { fnCallback( oSettings ); } } ); } /* * Function: _fnSortingClasses * Purpose: Set the sortting classes on the header * Returns: - * Inputs: object:oSettings - dataTables settings object * Notes: It is safe to call this function when bSort and bSortClasses are false */ function _fnSortingClasses( oSettings ) { var i, iLen, j, jLen, iFound; var aaSort, sClass; var iColumns = oSettings.aoColumns.length; var oClasses = oSettings.oClasses; for ( i=0 ; i<iColumns ; i++ ) { if ( oSettings.aoColumns[i].bSortable ) { $(oSettings.aoColumns[i].nTh).removeClass( oClasses.sSortAsc +" "+ oClasses.sSortDesc + " "+ oSettings.aoColumns[i].sSortingClass ); } } if ( oSettings.aaSortingFixed !== null ) { aaSort = oSettings.aaSortingFixed.concat( oSettings.aaSorting ); } else { aaSort = oSettings.aaSorting.slice(); } /* Apply the required classes to the header */ for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bSortable ) { sClass = oSettings.aoColumns[i].sSortingClass; iFound = -1; for ( j=0 ; j<aaSort.length ; j++ ) { if ( aaSort[j][0] == i ) { sClass = ( aaSort[j][1] == "asc" ) ? oClasses.sSortAsc : oClasses.sSortDesc; iFound = j; break; } } $(oSettings.aoColumns[i].nTh).addClass( sClass ); if ( oSettings.bJUI ) { /* jQuery UI uses extra markup */ var jqSpan = $("span", oSettings.aoColumns[i].nTh); jqSpan.removeClass(oClasses.sSortJUIAsc +" "+ oClasses.sSortJUIDesc +" "+ oClasses.sSortJUI +" "+ oClasses.sSortJUIAscAllowed +" "+ oClasses.sSortJUIDescAllowed ); var sSpanClass; if ( iFound == -1 ) { sSpanClass = oSettings.aoColumns[i].sSortingClassJUI; } else if ( aaSort[iFound][1] == "asc" ) { sSpanClass = oClasses.sSortJUIAsc; } else { sSpanClass = oClasses.sSortJUIDesc; } jqSpan.addClass( sSpanClass ); } } else { /* No sorting on this column, so add the base class. This will have been assigned by * _fnAddColumn */ $(oSettings.aoColumns[i].nTh).addClass( oSettings.aoColumns[i].sSortingClass ); } } /* * Apply the required classes to the table body * Note that this is given as a feature switch since it can significantly slow down a sort * on large data sets (adding and removing of classes is always slow at the best of times..) * Further to this, note that this code is admitadly fairly ugly. It could be made a lot * simpiler using jQuery selectors and add/removeClass, but that is significantly slower * (on the order of 5 times slower) - hence the direct DOM manipulation here. * Note that for defered drawing we do use jQuery - the reason being that taking the first * row found to see if the whole column needs processed can miss classes since the first * column might be new. */ sClass = oClasses.sSortColumn; if ( oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses ) { var nTds = _fnGetTdNodes( oSettings ); /* Remove the old classes */ if ( oSettings.oFeatures.bDeferRender ) { $(nTds).removeClass(sClass+'1 '+sClass+'2 '+sClass+'3'); } else if ( nTds.length >= iColumns ) { for ( i=0 ; i<iColumns ; i++ ) { if ( nTds[i].className.indexOf(sClass+"1") != -1 ) { for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+i].className = $.trim( nTds[(iColumns*j)+i].className.replace( sClass+"1", "" ) ); } } else if ( nTds[i].className.indexOf(sClass+"2") != -1 ) { for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+i].className = $.trim( nTds[(iColumns*j)+i].className.replace( sClass+"2", "" ) ); } } else if ( nTds[i].className.indexOf(sClass+"3") != -1 ) { for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+i].className = $.trim( nTds[(iColumns*j)+i].className.replace( " "+sClass+"3", "" ) ); } } } } /* Add the new classes to the table */ var iClass = 1, iTargetCol; for ( i=0 ; i<aaSort.length ; i++ ) { iTargetCol = parseInt( aaSort[i][0], 10 ); for ( j=0, jLen=(nTds.length/iColumns) ; j<jLen ; j++ ) { nTds[(iColumns*j)+iTargetCol].className += " "+sClass+iClass; } if ( iClass < 3 ) { iClass++; } } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Pagination. Note that most of the paging logic is done in * _oExt.oPagination */ /* * Function: _fnFeatureHtmlPaginate * Purpose: Generate the node required for default pagination * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlPaginate ( oSettings ) { if ( oSettings.oScroll.bInfinite ) { return null; } var nPaginate = document.createElement( 'div' ); nPaginate.className = oSettings.oClasses.sPaging+oSettings.sPaginationType; _oExt.oPagination[ oSettings.sPaginationType ].fnInit( oSettings, nPaginate, function( oSettings ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } ); /* Add a draw callback for the pagination on first instance, to update the paging display */ if ( typeof oSettings.aanFeatures.p == "undefined" ) { oSettings.aoDrawCallback.push( { "fn": function( oSettings ) { _oExt.oPagination[ oSettings.sPaginationType ].fnUpdate( oSettings, function( oSettings ) { _fnCalculateEnd( oSettings ); _fnDraw( oSettings ); } ); }, "sName": "pagination" } ); } return nPaginate; } /* * Function: _fnPageChange * Purpose: Alter the display settings to change the page * Returns: bool:true - page has changed, false - no change (no effect) eg 'first' on page 1 * Inputs: object:oSettings - dataTables settings object * string:sAction - paging action to take: "first", "previous", "next" or "last" */ function _fnPageChange ( oSettings, sAction ) { var iOldStart = oSettings._iDisplayStart; if ( sAction == "first" ) { oSettings._iDisplayStart = 0; } else if ( sAction == "previous" ) { oSettings._iDisplayStart = oSettings._iDisplayLength>=0 ? oSettings._iDisplayStart - oSettings._iDisplayLength : 0; /* Correct for underrun */ if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } else if ( sAction == "next" ) { if ( oSettings._iDisplayLength >= 0 ) { /* Make sure we are not over running the display array */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength < oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart += oSettings._iDisplayLength; } } else { oSettings._iDisplayStart = 0; } } else if ( sAction == "last" ) { if ( oSettings._iDisplayLength >= 0 ) { var iPages = parseInt( (oSettings.fnRecordsDisplay()-1) / oSettings._iDisplayLength, 10 ) + 1; oSettings._iDisplayStart = (iPages-1) * oSettings._iDisplayLength; } else { oSettings._iDisplayStart = 0; } } else { _fnLog( oSettings, 0, "Unknown paging action: "+sAction ); } return iOldStart != oSettings._iDisplayStart; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: HTML info */ /* * Function: _fnFeatureHtmlInfo * Purpose: Generate the node required for the info display * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlInfo ( oSettings ) { var nInfo = document.createElement( 'div' ); nInfo.className = oSettings.oClasses.sInfo; /* Actions that are to be taken once only for this feature */ if ( typeof oSettings.aanFeatures.i == "undefined" ) { /* Add draw callback */ oSettings.aoDrawCallback.push( { "fn": _fnUpdateInfo, "sName": "information" } ); /* Add id */ if ( oSettings.sTableId !== '' ) { nInfo.setAttribute( 'id', oSettings.sTableId+'_info' ); } } return nInfo; } /* * Function: _fnUpdateInfo * Purpose: Update the information elements in the display * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnUpdateInfo ( oSettings ) { /* Show information about the table */ if ( !oSettings.oFeatures.bInfo || oSettings.aanFeatures.i.length === 0 ) { return; } var iStart = oSettings._iDisplayStart+1, iEnd = oSettings.fnDisplayEnd(), iMax = oSettings.fnRecordsTotal(), iTotal = oSettings.fnRecordsDisplay(), sStart = oSettings.fnFormatNumber( iStart ), sEnd = oSettings.fnFormatNumber( iEnd ), sMax = oSettings.fnFormatNumber( iMax ), sTotal = oSettings.fnFormatNumber( iTotal ), sOut; /* When infinite scrolling, we are always starting at 1. _iDisplayStart is used only * internally */ if ( oSettings.oScroll.bInfinite ) { sStart = oSettings.fnFormatNumber( 1 ); } if ( oSettings.fnRecordsDisplay() === 0 && oSettings.fnRecordsDisplay() == oSettings.fnRecordsTotal() ) { /* Empty record set */ sOut = oSettings.oLanguage.sInfoEmpty+ oSettings.oLanguage.sInfoPostFix; } else if ( oSettings.fnRecordsDisplay() === 0 ) { /* Rmpty record set after filtering */ sOut = oSettings.oLanguage.sInfoEmpty +' '+ oSettings.oLanguage.sInfoFiltered.replace('_MAX_', sMax)+ oSettings.oLanguage.sInfoPostFix; } else if ( oSettings.fnRecordsDisplay() == oSettings.fnRecordsTotal() ) { /* Normal record set */ sOut = oSettings.oLanguage.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_TOTAL_', sTotal)+ oSettings.oLanguage.sInfoPostFix; } else { /* Record set after filtering */ sOut = oSettings.oLanguage.sInfo. replace('_START_', sStart). replace('_END_', sEnd). replace('_TOTAL_', sTotal) +' '+ oSettings.oLanguage.sInfoFiltered.replace('_MAX_', oSettings.fnFormatNumber(oSettings.fnRecordsTotal()))+ oSettings.oLanguage.sInfoPostFix; } if ( oSettings.oLanguage.fnInfoCallback !== null ) { sOut = oSettings.oLanguage.fnInfoCallback( oSettings, iStart, iEnd, iMax, iTotal, sOut ); } var n = oSettings.aanFeatures.i; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $(n[i]).html( sOut ); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Length change */ /* * Function: _fnFeatureHtmlLength * Purpose: Generate the node required for user display length changing * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlLength ( oSettings ) { if ( oSettings.oScroll.bInfinite ) { return null; } /* This can be overruled by not using the _MENU_ var/macro in the language variable */ var sName = (oSettings.sTableId === "") ? "" : 'name="'+oSettings.sTableId+'_length"'; var sStdMenu = '<select size="1" '+sName+'>'; var i, iLen; if ( oSettings.aLengthMenu.length == 2 && typeof oSettings.aLengthMenu[0] == 'object' && typeof oSettings.aLengthMenu[1] == 'object' ) { for ( i=0, iLen=oSettings.aLengthMenu[0].length ; i<iLen ; i++ ) { sStdMenu += '<option value="'+oSettings.aLengthMenu[0][i]+'">'+ oSettings.aLengthMenu[1][i]+'</option>'; } } else { for ( i=0, iLen=oSettings.aLengthMenu.length ; i<iLen ; i++ ) { sStdMenu += '<option value="'+oSettings.aLengthMenu[i]+'">'+ oSettings.aLengthMenu[i]+'</option>'; } } sStdMenu += '</select>'; var nLength = document.createElement( 'div' ); if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.l == "undefined" ) { nLength.setAttribute( 'id', oSettings.sTableId+'_length' ); } nLength.className = oSettings.oClasses.sLength; nLength.innerHTML = '<label>'+oSettings.oLanguage.sLengthMenu.replace( '_MENU_', sStdMenu )+'</label>'; /* * Set the length to the current display length - thanks to Andrea Pavlovic for this fix, * and Stefan Skopnik for fixing the fix! */ $('select option[value="'+oSettings._iDisplayLength+'"]',nLength).attr("selected",true); $('select', nLength).bind( 'change.DT', function(e) { var iVal = $(this).val(); /* Update all other length options for the new display */ var n = oSettings.aanFeatures.l; for ( i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != this.parentNode ) { $('select', n[i]).val( iVal ); } } /* Redraw the table */ oSettings._iDisplayLength = parseInt(iVal, 10); _fnCalculateEnd( oSettings ); /* If we have space to show extra rows (backing up from the end point - then do so */ if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() ) { oSettings._iDisplayStart = oSettings.fnDisplayEnd() - oSettings._iDisplayLength; if ( oSettings._iDisplayStart < 0 ) { oSettings._iDisplayStart = 0; } } if ( oSettings._iDisplayLength == -1 ) { oSettings._iDisplayStart = 0; } _fnDraw( oSettings ); } ); return nLength; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Feature: Processing incidator */ /* * Function: _fnFeatureHtmlProcessing * Purpose: Generate the node required for the processing node * Returns: node * Inputs: object:oSettings - dataTables settings object */ function _fnFeatureHtmlProcessing ( oSettings ) { var nProcessing = document.createElement( 'div' ); if ( oSettings.sTableId !== '' && typeof oSettings.aanFeatures.r == "undefined" ) { nProcessing.setAttribute( 'id', oSettings.sTableId+'_processing' ); } nProcessing.innerHTML = oSettings.oLanguage.sProcessing; nProcessing.className = oSettings.oClasses.sProcessing; oSettings.nTable.parentNode.insertBefore( nProcessing, oSettings.nTable ); return nProcessing; } /* * Function: _fnProcessingDisplay * Purpose: Display or hide the processing indicator * Returns: - * Inputs: object:oSettings - dataTables settings object * bool: * true - show the processing indicator * false - don't show */ function _fnProcessingDisplay ( oSettings, bShow ) { if ( oSettings.oFeatures.bProcessing ) { var an = oSettings.aanFeatures.r; for ( var i=0, iLen=an.length ; i<iLen ; i++ ) { an[i].style.visibility = bShow ? "visible" : "hidden"; } } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Support functions */ /* * Function: _fnVisibleToColumnIndex * Purpose: Covert the index of a visible column to the index in the data array (take account * of hidden columns) * Returns: int:i - the data index * Inputs: object:oSettings - dataTables settings object */ function _fnVisibleToColumnIndex( oSettings, iMatch ) { var iColumn = -1; for ( var i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible === true ) { iColumn++; } if ( iColumn == iMatch ) { return i; } } return null; } /* * Function: _fnColumnIndexToVisible * Purpose: Covert the index of an index in the data array and convert it to the visible * column index (take account of hidden columns) * Returns: int:i - the data index * Inputs: object:oSettings - dataTables settings object */ function _fnColumnIndexToVisible( oSettings, iMatch ) { var iVisible = -1; for ( var i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible === true ) { iVisible++; } if ( i == iMatch ) { return oSettings.aoColumns[i].bVisible === true ? iVisible : null; } } return null; } /* * Function: _fnNodeToDataIndex * Purpose: Take a TR element and convert it to an index in aoData * Returns: int:i - index if found, null if not * Inputs: object:s - dataTables settings object * node:n - the TR element to find */ function _fnNodeToDataIndex( s, n ) { var i, iLen; /* Optimisation - see if the nodes which are currently visible match, since that is * the most likely node to be asked for (a selector or event for example) */ for ( i=s._iDisplayStart, iLen=s._iDisplayEnd ; i<iLen ; i++ ) { if ( s.aoData[ s.aiDisplay[i] ].nTr == n ) { return s.aiDisplay[i]; } } /* Otherwise we are in for a slog through the whole data cache */ for ( i=0, iLen=s.aoData.length ; i<iLen ; i++ ) { if ( s.aoData[i].nTr == n ) { return i; } } return null; } /* * Function: _fnVisbleColumns * Purpose: Get the number of visible columns * Returns: int:i - the number of visible columns * Inputs: object:oS - dataTables settings object */ function _fnVisbleColumns( oS ) { var iVis = 0; for ( var i=0 ; i<oS.aoColumns.length ; i++ ) { if ( oS.aoColumns[i].bVisible === true ) { iVis++; } } return iVis; } /* * Function: _fnCalculateEnd * Purpose: Rcalculate the end point based on the start point * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnCalculateEnd( oSettings ) { if ( oSettings.oFeatures.bPaginate === false ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { /* Set the end point of the display - based on how many elements there are * still to display */ if ( oSettings._iDisplayStart + oSettings._iDisplayLength > oSettings.aiDisplay.length || oSettings._iDisplayLength == -1 ) { oSettings._iDisplayEnd = oSettings.aiDisplay.length; } else { oSettings._iDisplayEnd = oSettings._iDisplayStart + oSettings._iDisplayLength; } } } /* * Function: _fnConvertToWidth * Purpose: Convert a CSS unit width to pixels (e.g. 2em) * Returns: int:iWidth - width in pixels * Inputs: string:sWidth - width to be converted * node:nParent - parent to get the with for (required for * relative widths) - optional */ function _fnConvertToWidth ( sWidth, nParent ) { if ( !sWidth || sWidth === null || sWidth === '' ) { return 0; } if ( typeof nParent == "undefined" ) { nParent = document.getElementsByTagName('body')[0]; } var iWidth; var nTmp = document.createElement( "div" ); nTmp.style.width = _fnStringToCss( sWidth ); nParent.appendChild( nTmp ); iWidth = nTmp.offsetWidth; nParent.removeChild( nTmp ); return ( iWidth ); } /* * Function: _fnCalculateColumnWidths * Purpose: Calculate the width of columns for the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnCalculateColumnWidths ( oSettings ) { var iTableWidth = oSettings.nTable.offsetWidth; var iUserInputs = 0; var iTmpWidth; var iVisibleColumns = 0; var iColums = oSettings.aoColumns.length; var i, iIndex, iCorrector, iWidth; var oHeaders = $('th', oSettings.nTHead); /* Convert any user input sizes into pixel sizes */ for ( i=0 ; i<iColums ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iVisibleColumns++; if ( oSettings.aoColumns[i].sWidth !== null ) { iTmpWidth = _fnConvertToWidth( oSettings.aoColumns[i].sWidthOrig, oSettings.nTable.parentNode ); if ( iTmpWidth !== null ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth ); } iUserInputs++; } } } /* If the number of columns in the DOM equals the number that we have to process in * DataTables, then we can use the offsets that are created by the web-browser. No custom * sizes can be set in order for this to happen, nor scrolling used */ if ( iColums == oHeaders.length && iUserInputs === 0 && iVisibleColumns == iColums && oSettings.oScroll.sX === "" && oSettings.oScroll.sY === "" ) { for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { iTmpWidth = $(oHeaders[i]).width(); if ( iTmpWidth !== null ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iTmpWidth ); } } } else { /* Otherwise we are going to have to do some calculations to get the width of each column. * Construct a 1 row table with the widest node in the data, and any user defined widths, * then insert it into the DOM and allow the browser to do all the hard work of * calculating table widths. */ var nCalcTmp = oSettings.nTable.cloneNode( false ), nTheadClone = oSettings.nTHead.cloneNode(true), nBody = document.createElement( 'tbody' ), nTr = document.createElement( 'tr' ), nDivSizing; nCalcTmp.removeAttribute( "id" ); nCalcTmp.appendChild( nTheadClone ); if ( oSettings.nTFoot !== null ) { nCalcTmp.appendChild( oSettings.nTFoot.cloneNode(true) ); _fnApplyToChildren( function(n) { n.style.width = ""; }, nCalcTmp.getElementsByTagName('tr') ); } nCalcTmp.appendChild( nBody ); nBody.appendChild( nTr ); /* Remove any sizing that was previously applied by the styles */ var jqColSizing = $('thead th', nCalcTmp); if ( jqColSizing.length === 0 ) { jqColSizing = $('tbody tr:eq(0)>td', nCalcTmp); } /* Apply custom sizing to the cloned header */ var nThs = _fnGetUniqueThs( oSettings, nTheadClone ); iCorrector = 0; for ( i=0 ; i<iColums ; i++ ) { var oColumn = oSettings.aoColumns[i]; if ( oColumn.bVisible && oColumn.sWidthOrig !== null && oColumn.sWidthOrig !== "" ) { nThs[i-iCorrector].style.width = _fnStringToCss( oColumn.sWidthOrig ); } else if ( oColumn.bVisible ) { nThs[i-iCorrector].style.width = ""; } else { iCorrector++; } } /* Find the biggest td for each column and put it into the table */ for ( i=0 ; i<iColums ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { var nTd = _fnGetWidestNode( oSettings, i ); if ( nTd !== null ) { nTd = nTd.cloneNode(true); if ( oSettings.aoColumns[i].sContentPadding !== "" ) { nTd.innerHTML += oSettings.aoColumns[i].sContentPadding; } nTr.appendChild( nTd ); } } } /* Build the table and 'display' it */ var nWrapper = oSettings.nTable.parentNode; nWrapper.appendChild( nCalcTmp ); /* When scrolling (X or Y) we want to set the width of the table as appropriate. However, * when not scrolling leave the table width as it is. This results in slightly different, * but I think correct behaviour */ if ( oSettings.oScroll.sX !== "" && oSettings.oScroll.sXInner !== "" ) { nCalcTmp.style.width = _fnStringToCss(oSettings.oScroll.sXInner); } else if ( oSettings.oScroll.sX !== "" ) { nCalcTmp.style.width = ""; if ( $(nCalcTmp).width() < nWrapper.offsetWidth ) { nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth ); } } else if ( oSettings.oScroll.sY !== "" ) { nCalcTmp.style.width = _fnStringToCss( nWrapper.offsetWidth ); } nCalcTmp.style.visibility = "hidden"; /* Scrolling considerations */ _fnScrollingWidthAdjust( oSettings, nCalcTmp ); /* Read the width's calculated by the browser and store them for use by the caller. We * first of all try to use the elements in the body, but it is possible that there are * no elements there, under which circumstances we use the header elements */ var oNodes = $("tbody tr:eq(0)", nCalcTmp).children(); if ( oNodes.length === 0 ) { oNodes = _fnGetUniqueThs( oSettings, $('thead', nCalcTmp)[0] ); } /* Browsers need a bit of a hand when a width is assigned to any columns when * x-scrolling as they tend to collapse the table to the min-width, even if * we sent the column widths. So we need to keep track of what the table width * should be by summing the user given values, and the automatic values */ if ( oSettings.oScroll.sX !== "" ) { var iTotal = 0; iCorrector = 0; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { if ( oSettings.aoColumns[i].sWidthOrig === null ) { iTotal += $(oNodes[iCorrector]).outerWidth(); } else { iTotal += parseInt(oSettings.aoColumns[i].sWidth.replace('px',''), 10) + ($(oNodes[iCorrector]).outerWidth() - $(oNodes[iCorrector]).width()); } iCorrector++; } } nCalcTmp.style.width = _fnStringToCss( iTotal ); oSettings.nTable.style.width = _fnStringToCss( iTotal ); } iCorrector = 0; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { if ( oSettings.aoColumns[i].bVisible ) { iWidth = $(oNodes[iCorrector]).width(); if ( iWidth !== null && iWidth > 0 ) { oSettings.aoColumns[i].sWidth = _fnStringToCss( iWidth ); } iCorrector++; } } oSettings.nTable.style.width = _fnStringToCss( $(nCalcTmp).outerWidth() ); nCalcTmp.parentNode.removeChild( nCalcTmp ); } } /* * Function: _fnScrollingWidthAdjust * Purpose: Adjust a table's width to take account of scrolling * Returns: - * Inputs: object:oSettings - dataTables settings object * node:n - table node */ function _fnScrollingWidthAdjust ( oSettings, n ) { if ( oSettings.oScroll.sX === "" && oSettings.oScroll.sY !== "" ) { /* When y-scrolling only, we want to remove the width of the scroll bar so the table * + scroll bar will fit into the area avaialble. */ var iOrigWidth = $(n).width(); n.style.width = _fnStringToCss( $(n).outerWidth()-oSettings.oScroll.iBarWidth ); } else if ( oSettings.oScroll.sX !== "" ) { /* When x-scrolling both ways, fix the table at it's current size, without adjusting */ n.style.width = _fnStringToCss( $(n).outerWidth() ); } } /* * Function: _fnGetWidestNode * Purpose: Get the widest node * Returns: string: - max strlens for each column * Inputs: object:oSettings - dataTables settings object * int:iCol - column of interest */ function _fnGetWidestNode( oSettings, iCol ) { var iMaxIndex = _fnGetMaxLenString( oSettings, iCol ); if ( iMaxIndex < 0 ) { return null; } if ( oSettings.aoData[iMaxIndex].nTr === null ) { var n = document.createElement('td'); n.innerHTML = _fnGetCellData( oSettings, iMaxIndex, iCol, '' ); return n; } return _fnGetTdNodes(oSettings, iMaxIndex)[iCol]; } /* * Function: _fnGetMaxLenString * Purpose: Get the maximum strlen for each data column * Returns: string: - max strlens for each column * Inputs: object:oSettings - dataTables settings object * int:iCol - column of interest */ function _fnGetMaxLenString( oSettings, iCol ) { var iMax = -1; var iMaxIndex = -1; for ( var i=0 ; i<oSettings.aoData.length ; i++ ) { var s = _fnGetCellData( oSettings, i, iCol, 'display' )+""; s = s.replace( /<.*?>/g, "" ); if ( s.length > iMax ) { iMax = s.length; iMaxIndex = i; } } return iMaxIndex; } /* * Function: _fnStringToCss * Purpose: Append a CSS unit (only if required) to a string * Returns: 0 if match, 1 if length is different, 2 if no match * Inputs: array:aArray1 - first array * array:aArray2 - second array */ function _fnStringToCss( s ) { if ( s === null ) { return "0px"; } if ( typeof s == 'number' ) { if ( s < 0 ) { return "0px"; } return s+"px"; } /* Check if the last character is not 0-9 */ var c = s.charCodeAt( s.length-1 ); if (c < 0x30 || c > 0x39) { return s; } return s+"px"; } /* * Function: _fnArrayCmp * Purpose: Compare two arrays * Returns: 0 if match, 1 if length is different, 2 if no match * Inputs: array:aArray1 - first array * array:aArray2 - second array */ function _fnArrayCmp( aArray1, aArray2 ) { if ( aArray1.length != aArray2.length ) { return 1; } for ( var i=0 ; i<aArray1.length ; i++ ) { if ( aArray1[i] != aArray2[i] ) { return 2; } } return 0; } /* * Function: _fnDetectType * Purpose: Get the sort type based on an input string * Returns: string: - type (defaults to 'string' if no type can be detected) * Inputs: string:sData - data we wish to know the type of * Notes: This function makes use of the DataTables plugin objct _oExt * (.aTypes) such that new types can easily be added. */ function _fnDetectType( sData ) { var aTypes = _oExt.aTypes; var iLen = aTypes.length; for ( var i=0 ; i<iLen ; i++ ) { var sType = aTypes[i]( sData ); if ( sType !== null ) { return sType; } } return 'string'; } /* * Function: _fnSettingsFromNode * Purpose: Return the settings object for a particular table * Returns: object: Settings object - or null if not found * Inputs: node:nTable - table we are using as a dataTable */ function _fnSettingsFromNode ( nTable ) { for ( var i=0 ; i<_aoSettings.length ; i++ ) { if ( _aoSettings[i].nTable == nTable ) { return _aoSettings[i]; } } return null; } /* * Function: _fnGetDataMaster * Purpose: Return an array with the full table data * Returns: array array:aData - Master data array * Inputs: object:oSettings - dataTables settings object */ function _fnGetDataMaster ( oSettings ) { var aData = []; var iLen = oSettings.aoData.length; for ( var i=0 ; i<iLen; i++ ) { aData.push( oSettings.aoData[i]._aData ); } return aData; } /* * Function: _fnGetTrNodes * Purpose: Return an array with the TR nodes for the table * Returns: array: - TR array * Inputs: object:oSettings - dataTables settings object */ function _fnGetTrNodes ( oSettings ) { var aNodes = []; for ( var i=0, iLen=oSettings.aoData.length ; i<iLen ; i++ ) { if ( oSettings.aoData[i].nTr !== null ) { aNodes.push( oSettings.aoData[i].nTr ); } } return aNodes; } /* * Function: _fnGetTdNodes * Purpose: Return an flat array with all TD nodes for the table, or row * Returns: array: - TD array * Inputs: object:oSettings - dataTables settings object * int:iIndividualRow - aoData index to get the nodes for - optional if not * given then the return array will contain all nodes for the table */ function _fnGetTdNodes ( oSettings, iIndividualRow ) { var anReturn = []; var iCorrector; var anTds; var iRow, iRows=oSettings.aoData.length, iColumn, iColumns, oData, sNodeName, iStart=0, iEnd=iRows; /* Allow the collection to be limited to just one row */ if ( typeof iIndividualRow != 'undefined' ) { iStart = iIndividualRow; iEnd = iIndividualRow+1; } for ( iRow=iStart ; iRow<iEnd ; iRow++ ) { oData = oSettings.aoData[iRow]; if ( oData.nTr !== null ) { /* get the TD child nodes - taking into account text etc nodes */ anTds = []; for ( iColumn=0, iColumns=oData.nTr.childNodes.length ; iColumn<iColumns ; iColumn++ ) { sNodeName = oData.nTr.childNodes[iColumn].nodeName.toLowerCase(); if ( sNodeName == 'td' || sNodeName == 'th' ) { anTds.push( oData.nTr.childNodes[iColumn] ); } } iCorrector = 0; for ( iColumn=0, iColumns=oSettings.aoColumns.length ; iColumn<iColumns ; iColumn++ ) { if ( oSettings.aoColumns[iColumn].bVisible ) { anReturn.push( anTds[iColumn-iCorrector] ); } else { anReturn.push( oData._anHidden[iColumn] ); iCorrector++; } } } } return anReturn; } /* * Function: _fnEscapeRegex * Purpose: scape a string stuch that it can be used in a regular expression * Returns: string: - escaped string * Inputs: string:sVal - string to escape */ function _fnEscapeRegex ( sVal ) { var acEscape = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^' ]; var reReplace = new RegExp( '(\\' + acEscape.join('|\\') + ')', 'g' ); return sVal.replace(reReplace, '\\$1'); } /* * Function: _fnDeleteIndex * Purpose: Take an array of integers (index array) and remove a target integer (value - not * the key!) * Returns: - * Inputs: a:array int - Index array to target * int:iTarget - value to find */ function _fnDeleteIndex( a, iTarget ) { var iTargetIndex = -1; for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { if ( a[i] == iTarget ) { iTargetIndex = i; } else if ( a[i] > iTarget ) { a[i]--; } } if ( iTargetIndex != -1 ) { a.splice( iTargetIndex, 1 ); } } /* * Function: _fnReOrderIndex * Purpose: Figure out how to reorder a display list * Returns: array int:aiReturn - index list for reordering * Inputs: object:oSettings - dataTables settings object */ function _fnReOrderIndex ( oSettings, sColumns ) { var aColumns = sColumns.split(','); var aiReturn = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { for ( var j=0 ; j<iLen ; j++ ) { if ( oSettings.aoColumns[i].sName == aColumns[j] ) { aiReturn.push( j ); break; } } } return aiReturn; } /* * Function: _fnColumnOrdering * Purpose: Get the column ordering that DataTables expects * Returns: string: - comma separated list of names * Inputs: object:oSettings - dataTables settings object */ function _fnColumnOrdering ( oSettings ) { var sNames = ''; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { sNames += oSettings.aoColumns[i].sName+','; } if ( sNames.length == iLen ) { return ""; } return sNames.slice(0, -1); } /* * Function: _fnLog * Purpose: Log an error message * Returns: - * Inputs: int:iLevel - log error messages, or display them to the user * string:sMesg - error message */ function _fnLog( oSettings, iLevel, sMesg ) { var sAlert = oSettings.sTableId === "" ? "DataTables warning: " +sMesg : "DataTables warning (table id = '"+oSettings.sTableId+"'): " +sMesg; if ( iLevel === 0 ) { if ( _oExt.sErrMode == 'alert' ) { alert( sAlert ); } else { throw sAlert; } return; } else if ( typeof console != 'undefined' && typeof console.log != 'undefined' ) { console.log( sAlert ); } } /* * Function: _fnClearTable * Purpose: Nuke the table * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnClearTable( oSettings ) { oSettings.aoData.splice( 0, oSettings.aoData.length ); oSettings.aiDisplayMaster.splice( 0, oSettings.aiDisplayMaster.length ); oSettings.aiDisplay.splice( 0, oSettings.aiDisplay.length ); _fnCalculateEnd( oSettings ); } /* * Function: _fnSaveState * Purpose: Save the state of a table in a cookie such that the page can be reloaded * Returns: - * Inputs: object:oSettings - dataTables settings object */ function _fnSaveState ( oSettings ) { if ( !oSettings.oFeatures.bStateSave || typeof oSettings.bDestroying != 'undefined' ) { return; } /* Store the interesting variables */ var i, iLen, sTmp; var sValue = "{"; sValue += '"iCreate":'+ new Date().getTime()+','; sValue += '"iStart":'+ (oSettings.oScroll.bInfinite ? 0 : oSettings._iDisplayStart)+','; sValue += '"iEnd":'+ (oSettings.oScroll.bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd)+','; sValue += '"iLength":'+ oSettings._iDisplayLength+','; sValue += '"sFilter":"'+ encodeURIComponent(oSettings.oPreviousSearch.sSearch)+'",'; sValue += '"sFilterEsc":'+ !oSettings.oPreviousSearch.bRegex+','; sValue += '"aaSorting":[ '; for ( i=0 ; i<oSettings.aaSorting.length ; i++ ) { sValue += '['+oSettings.aaSorting[i][0]+',"'+oSettings.aaSorting[i][1]+'"],'; } sValue = sValue.substring(0, sValue.length-1); sValue += "],"; sValue += '"aaSearchCols":[ '; for ( i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ) { sValue += '["'+encodeURIComponent(oSettings.aoPreSearchCols[i].sSearch)+ '",'+!oSettings.aoPreSearchCols[i].bRegex+'],'; } sValue = sValue.substring(0, sValue.length-1); sValue += "],"; sValue += '"abVisCols":[ '; for ( i=0 ; i<oSettings.aoColumns.length ; i++ ) { sValue += oSettings.aoColumns[i].bVisible+","; } sValue = sValue.substring(0, sValue.length-1); sValue += "]"; /* Save state from any plug-ins */ for ( i=0, iLen=oSettings.aoStateSave.length ; i<iLen ; i++ ) { sTmp = oSettings.aoStateSave[i].fn( oSettings, sValue ); if ( sTmp !== "" ) { sValue = sTmp; } } sValue += "}"; _fnCreateCookie( oSettings.sCookiePrefix+oSettings.sInstance, sValue, oSettings.iCookieDuration, oSettings.sCookiePrefix, oSettings.fnCookieCallback ); } /* * Function: _fnLoadState * Purpose: Attempt to load a saved table state from a cookie * Returns: - * Inputs: object:oSettings - dataTables settings object * object:oInit - DataTables init object so we can override settings */ function _fnLoadState ( oSettings, oInit ) { if ( !oSettings.oFeatures.bStateSave ) { return; } var oData, i, iLen; var sData = _fnReadCookie( oSettings.sCookiePrefix+oSettings.sInstance ); if ( sData !== null && sData !== '' ) { /* Try/catch the JSON eval - if it is bad then we ignore it - note that 1.7.0 and before * incorrectly used single quotes for some strings - hence the replace below */ try { oData = (typeof $.parseJSON == 'function') ? $.parseJSON( sData.replace(/'/g, '"') ) : eval( '('+sData+')' ); } catch( e ) { return; } /* Allow custom and plug-in manipulation functions to alter the data set which was * saved, and also reject any saved state by returning false */ for ( i=0, iLen=oSettings.aoStateLoad.length ; i<iLen ; i++ ) { if ( !oSettings.aoStateLoad[i].fn( oSettings, oData ) ) { return; } } /* Store the saved state so it might be accessed at any time (particualrly a plug-in */ oSettings.oLoadedState = $.extend( true, {}, oData ); /* Restore key features */ oSettings._iDisplayStart = oData.iStart; oSettings.iInitDisplayStart = oData.iStart; oSettings._iDisplayEnd = oData.iEnd; oSettings._iDisplayLength = oData.iLength; oSettings.oPreviousSearch.sSearch = decodeURIComponent(oData.sFilter); oSettings.aaSorting = oData.aaSorting.slice(); oSettings.saved_aaSorting = oData.aaSorting.slice(); /* * Search filtering - global reference added in 1.4.1 * Note that we use a 'not' for the value of the regular expression indicator to maintain * compatibility with pre 1.7 versions, where this was basically inverted. Added in 1.7.0 */ if ( typeof oData.sFilterEsc != 'undefined' ) { oSettings.oPreviousSearch.bRegex = !oData.sFilterEsc; } /* Column filtering - added in 1.5.0 beta 6 */ if ( typeof oData.aaSearchCols != 'undefined' ) { for ( i=0 ; i<oData.aaSearchCols.length ; i++ ) { oSettings.aoPreSearchCols[i] = { "sSearch": decodeURIComponent(oData.aaSearchCols[i][0]), "bRegex": !oData.aaSearchCols[i][1] }; } } /* Column visibility state - added in 1.5.0 beta 10 */ if ( typeof oData.abVisCols != 'undefined' ) { /* Pass back visibiliy settings to the init handler, but to do not here override * the init object that the user might have passed in */ oInit.saved_aoColumns = []; for ( i=0 ; i<oData.abVisCols.length ; i++ ) { oInit.saved_aoColumns[i] = {}; oInit.saved_aoColumns[i].bVisible = oData.abVisCols[i]; } } } } /* * Function: _fnCreateCookie * Purpose: Create a new cookie with a value to store the state of a table * Returns: - * Inputs: string:sName - name of the cookie to create * string:sValue - the value the cookie should take * int:iSecs - duration of the cookie * string:sBaseName - sName is made up of the base + file name - this is the base * function:fnCallback - User definable function to modify the cookie */ function _fnCreateCookie ( sName, sValue, iSecs, sBaseName, fnCallback ) { var date = new Date(); date.setTime( date.getTime()+(iSecs*1000) ); /* * Shocking but true - it would appear IE has major issues with having the path not having * a trailing slash on it. We need the cookie to be available based on the path, so we * have to append the file name to the cookie name. Appalling. Thanks to vex for adding the * patch to use at least some of the path */ var aParts = window.location.pathname.split('/'); var sNameFile = sName + '_' + aParts.pop().replace(/[\/:]/g,"").toLowerCase(); var sFullCookie, oData; if ( fnCallback !== null ) { oData = (typeof $.parseJSON == 'function') ? $.parseJSON( sValue ) : eval( '('+sValue+')' ); sFullCookie = fnCallback( sNameFile, oData, date.toGMTString(), aParts.join('/')+"/" ); } else { sFullCookie = sNameFile + "=" + encodeURIComponent(sValue) + "; expires=" + date.toGMTString() +"; path=" + aParts.join('/')+"/"; } /* Are we going to go over the cookie limit of 4KiB? If so, try to delete a cookies * belonging to DataTables. This is FAR from bullet proof */ var sOldName="", iOldTime=9999999999999; var iLength = _fnReadCookie( sNameFile )!==null ? document.cookie.length : sFullCookie.length + document.cookie.length; if ( iLength+10 > 4096 ) /* Magic 10 for padding */ { var aCookies =document.cookie.split(';'); for ( var i=0, iLen=aCookies.length ; i<iLen ; i++ ) { if ( aCookies[i].indexOf( sBaseName ) != -1 ) { /* It's a DataTables cookie, so eval it and check the time stamp */ var aSplitCookie = aCookies[i].split('='); try { oData = eval( '('+decodeURIComponent(aSplitCookie[1])+')' ); } catch( e ) { continue; } if ( typeof oData.iCreate != 'undefined' && oData.iCreate < iOldTime ) { sOldName = aSplitCookie[0]; iOldTime = oData.iCreate; } } } if ( sOldName !== "" ) { document.cookie = sOldName+"=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path="+ aParts.join('/') + "/"; } } document.cookie = sFullCookie; } /* * Function: _fnReadCookie * Purpose: Read an old cookie to get a cookie with an old table state * Returns: string: - contents of the cookie - or null if no cookie with that name found * Inputs: string:sName - name of the cookie to read */ function _fnReadCookie ( sName ) { var aParts = window.location.pathname.split('/'), sNameEQ = sName + '_' + aParts[aParts.length-1].replace(/[\/:]/g,"").toLowerCase() + '=', sCookieContents = document.cookie.split(';'); for( var i=0 ; i<sCookieContents.length ; i++ ) { var c = sCookieContents[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(sNameEQ) === 0) { return decodeURIComponent( c.substring(sNameEQ.length,c.length) ); } } return null; } /* * Function: _fnDetectHeader * Purpose: Use the DOM source to create up an array of header cells. The idea here is to * create a layout grid (array) of rows x columns, which contains a reference * to the cell that that point in the grid (regardless of col/rowspan), such that * any column / row could be removed and the new grid constructed * Returns: void * Outputs: array object:aLayout - Array to store the calculated layout in * Inputs: node:nThead - The header/footer element for the table */ function _fnDetectHeader ( aLayout, nThead ) { var nTrs = nThead.getElementsByTagName('tr'); var nCell; var i, j, k, l, iLen, jLen, iColShifted; var fnShiftCol = function ( a, i, j ) { while ( typeof a[i][j] != 'undefined' ) { j++; } return j; }; aLayout.splice( 0, aLayout.length ); /* We know how many rows there are in the layout - so prep it */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { aLayout.push( [] ); } /* Calculate a layout array */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { var iColumn = 0; /* For every cell in the row... */ for ( j=0, jLen=nTrs[i].childNodes.length ; j<jLen ; j++ ) { nCell = nTrs[i].childNodes[j]; if ( nCell.nodeName.toUpperCase() == "TD" || nCell.nodeName.toUpperCase() == "TH" ) { /* Get the col and rowspan attributes from the DOM and sanitise them */ var iColspan = nCell.getAttribute('colspan') * 1; var iRowspan = nCell.getAttribute('rowspan') * 1; iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan; iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan; /* There might be colspan cells already in this row, so shift our target * accordingly */ iColShifted = fnShiftCol( aLayout, i, iColumn ); /* If there is col / rowspan, copy the information into the layout grid */ for ( l=0 ; l<iColspan ; l++ ) { for ( k=0 ; k<iRowspan ; k++ ) { aLayout[i+k][iColShifted+l] = { "cell": nCell, "unique": iColspan == 1 ? true : false }; aLayout[i+k].nTr = nTrs[i]; } } } } } } /* * Function: _fnGetUniqueThs * Purpose: Get an array of unique th elements, one for each column * Returns: array node:aReturn - list of unique ths * Inputs: object:oSettings - dataTables settings object * node:nHeader - automatically detect the layout from this node - optional * array object:aLayout - thead/tfoot layout from _fnDetectHeader - optional */ function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( typeof aLayout == 'undefined' ) { aLayout = oSettings.aoHeader; if ( typeof nHeader != 'undefined' ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (typeof aReturn[j] == 'undefined' || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; } /* * Function: _fnScrollBarWidth * Purpose: Get the width of a scroll bar in this browser being used * Returns: int: - width in pixels * Inputs: - * Notes: All credit for this function belongs to Alexandre Gomes. Thanks for sharing! * http://www.alexandre-gomes.com/?p=115 */ function _fnScrollBarWidth () { var inner = document.createElement('p'); var style = inner.style; style.width = "100%"; style.height = "200px"; var outer = document.createElement('div'); style = outer.style; style.position = "absolute"; style.top = "0px"; style.left = "0px"; style.visibility = "hidden"; style.width = "200px"; style.height = "150px"; style.overflow = "hidden"; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if ( w1 == w2 ) { w2 = outer.clientWidth; } document.body.removeChild(outer); return (w1 - w2); } /* * Function: _fnApplyToChildren * Purpose: Apply a given function to the display child nodes of an element array (typically * TD children of TR rows * Returns: - (done by reference) * Inputs: function:fn - Method to apply to the objects * array nodes:an1 - List of elements to look through for display children * array nodes:an2 - Another list (identical structure to the first) - optional */ function _fnApplyToChildren( fn, an1, an2 ) { for ( var i=0, iLen=an1.length ; i<iLen ; i++ ) { for ( var j=0, jLen=an1[i].childNodes.length ; j<jLen ; j++ ) { if ( an1[i].childNodes[j].nodeType == 1 ) { if ( typeof an2 != 'undefined' ) { fn( an1[i].childNodes[j], an2[i].childNodes[j] ); } else { fn( an1[i].childNodes[j] ); } } } } } /* * Function: _fnMap * Purpose: See if a property is defined on one object, if so assign it to the other object * Returns: - (done by reference) * Inputs: object:oRet - target object * object:oSrc - source object * string:sName - property * string:sMappedName - name to map too - optional, sName used if not given */ function _fnMap( oRet, oSrc, sName, sMappedName ) { if ( typeof sMappedName == 'undefined' ) { sMappedName = sName; } if ( typeof oSrc[sName] != 'undefined' ) { oRet[sMappedName] = oSrc[sName]; } } /* * Function: _fnGetRowData * Purpose: Get an array of data for a given row from the internal data cache * Returns: array: - Data array * Inputs: object:oSettings - dataTables settings object * int:iRow - aoData row id * string:sSpecific - data get type ('type' 'filter' 'sort') */ function _fnGetRowData( oSettings, iRow, sSpecific ) { var out = []; for ( var i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { out.push( _fnGetCellData( oSettings, iRow, i, sSpecific ) ); } return out; } /* * Function: _fnGetCellData * Purpose: Get the data for a given cell from the internal cache, taking into account data mapping * Returns: *: - Cell data * Inputs: object:oSettings - dataTables settings object * int:iRow - aoData row id * int:iCol - Column index * string:sSpecific - data get type ('display', 'type' 'filter' 'sort') */ function _fnGetCellData( oSettings, iRow, iCol, sSpecific ) { var sData; var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; if ( (sData=oCol.fnGetData( oData )) === undefined ) { if ( oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null ) { _fnLog( oSettings, 0, "Requested unknown parameter '"+oCol.mDataProp+ "' from the data source for row "+iRow ); oSettings.iDrawError = oSettings.iDraw; } return oCol.sDefaultContent; } /* When the data source is null, we can use default column data */ if ( sData === null && oCol.sDefaultContent !== null ) { sData = oCol.sDefaultContent; } if ( sSpecific == 'display' && sData === null ) { return ''; } return sData; } /* * Function: _fnSetCellData * Purpose: Set the value for a specific cell, into the internal data cache * Returns: *: - Cell data * Inputs: object:oSettings - dataTables settings object * int:iRow - aoData row id * int:iCol - Column index * *:val - Value to set */ function _fnSetCellData( oSettings, iRow, iCol, val ) { var oCol = oSettings.aoColumns[iCol]; var oData = oSettings.aoData[iRow]._aData; oCol.fnSetData( oData, val ); } /* * Function: _fnGetObjectDataFn * Purpose: Return a function that can be used to get data from a source object, taking * into account the ability to use nested objects as a source * Returns: function: - Data get function * Inputs: string|int|function:mSource - The data source for the object */ function _fnGetObjectDataFn( mSource ) { if ( mSource === null ) { /* Give an empty string for rendering / sorting etc */ return function (data) { return null; }; } else if ( typeof mSource == 'function' ) { return function (data) { return mSource( data ); }; } else if ( typeof mSource == 'string' && mSource.indexOf('.') != -1 ) { /* If there is a . in the source string then the data source is in a nested object * we provide two 'quick' functions for the look up to speed up the most common * operation, and a generalised one for when it is needed */ var a = mSource.split('.'); if ( a.length == 2 ) { return function (data) { return data[ a[0] ][ a[1] ]; }; } else if ( a.length == 3 ) { return function (data) { return data[ a[0] ][ a[1] ][ a[2] ]; }; } else { return function (data) { for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { data = data[ a[i] ]; } return data; }; } } else { /* Array or flat object mapping */ return function (data) { return data[mSource]; }; } } /* * Function: _fnSetObjectDataFn * Purpose: Return a function that can be used to set data from a source object, taking * into account the ability to use nested objects as a source * Returns: function: - Data set function * Inputs: string|int|function:mSource - The data source for the object */ function _fnSetObjectDataFn( mSource ) { if ( mSource === null ) { /* Nothing to do when the data source is null */ return function (data, val) {}; } else if ( typeof mSource == 'function' ) { return function (data, val) { return mSource( data, val ); }; } else if ( typeof mSource == 'string' && mSource.indexOf('.') != -1 ) { /* Like the get, we need to get data from a nested object. Again two fast lookup * functions are provided, and a generalised one. */ var a = mSource.split('.'); if ( a.length == 2 ) { return function (data, val) { data[ a[0] ][ a[1] ] = val; }; } else if ( a.length == 3 ) { return function (data, val) { data[ a[0] ][ a[1] ][ a[2] ] = val; }; } else { return function (data, val) { for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ ) { data = data[ a[i] ]; } data[ a[a.length-1] ] = val; }; } } else { /* Array or flat object mapping */ return function (data, val) { data[mSource] = val; }; } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - API * I'm not happy with this solution... - To be fixed in 2.0 */ this.oApi._fnExternApiFunc = _fnExternApiFunc; this.oApi._fnInitalise = _fnInitalise; this.oApi._fnInitComplete = _fnInitComplete; this.oApi._fnLanguageProcess = _fnLanguageProcess; this.oApi._fnAddColumn = _fnAddColumn; this.oApi._fnColumnOptions = _fnColumnOptions; this.oApi._fnAddData = _fnAddData; this.oApi._fnCreateTr = _fnCreateTr; this.oApi._fnGatherData = _fnGatherData; this.oApi._fnBuildHead = _fnBuildHead; this.oApi._fnDrawHead = _fnDrawHead; this.oApi._fnDraw = _fnDraw; this.oApi._fnReDraw = _fnReDraw; this.oApi._fnAjaxUpdate = _fnAjaxUpdate; this.oApi._fnAjaxUpdateDraw = _fnAjaxUpdateDraw; this.oApi._fnAddOptionsHtml = _fnAddOptionsHtml; this.oApi._fnFeatureHtmlTable = _fnFeatureHtmlTable; this.oApi._fnScrollDraw = _fnScrollDraw; this.oApi._fnAjustColumnSizing = _fnAjustColumnSizing; this.oApi._fnFeatureHtmlFilter = _fnFeatureHtmlFilter; this.oApi._fnFilterComplete = _fnFilterComplete; this.oApi._fnFilterCustom = _fnFilterCustom; this.oApi._fnFilterColumn = _fnFilterColumn; this.oApi._fnFilter = _fnFilter; this.oApi._fnBuildSearchArray = _fnBuildSearchArray; this.oApi._fnBuildSearchRow = _fnBuildSearchRow; this.oApi._fnFilterCreateSearch = _fnFilterCreateSearch; this.oApi._fnDataToSearch = _fnDataToSearch; this.oApi._fnSort = _fnSort; this.oApi._fnSortAttachListener = _fnSortAttachListener; this.oApi._fnSortingClasses = _fnSortingClasses; this.oApi._fnFeatureHtmlPaginate = _fnFeatureHtmlPaginate; this.oApi._fnPageChange = _fnPageChange; this.oApi._fnFeatureHtmlInfo = _fnFeatureHtmlInfo; this.oApi._fnUpdateInfo = _fnUpdateInfo; this.oApi._fnFeatureHtmlLength = _fnFeatureHtmlLength; this.oApi._fnFeatureHtmlProcessing = _fnFeatureHtmlProcessing; this.oApi._fnProcessingDisplay = _fnProcessingDisplay; this.oApi._fnVisibleToColumnIndex = _fnVisibleToColumnIndex; this.oApi._fnColumnIndexToVisible = _fnColumnIndexToVisible; this.oApi._fnNodeToDataIndex = _fnNodeToDataIndex; this.oApi._fnVisbleColumns = _fnVisbleColumns; this.oApi._fnCalculateEnd = _fnCalculateEnd; this.oApi._fnConvertToWidth = _fnConvertToWidth; this.oApi._fnCalculateColumnWidths = _fnCalculateColumnWidths; this.oApi._fnScrollingWidthAdjust = _fnScrollingWidthAdjust; this.oApi._fnGetWidestNode = _fnGetWidestNode; this.oApi._fnGetMaxLenString = _fnGetMaxLenString; this.oApi._fnStringToCss = _fnStringToCss; this.oApi._fnArrayCmp = _fnArrayCmp; this.oApi._fnDetectType = _fnDetectType; this.oApi._fnSettingsFromNode = _fnSettingsFromNode; this.oApi._fnGetDataMaster = _fnGetDataMaster; this.oApi._fnGetTrNodes = _fnGetTrNodes; this.oApi._fnGetTdNodes = _fnGetTdNodes; this.oApi._fnEscapeRegex = _fnEscapeRegex; this.oApi._fnDeleteIndex = _fnDeleteIndex; this.oApi._fnReOrderIndex = _fnReOrderIndex; this.oApi._fnColumnOrdering = _fnColumnOrdering; this.oApi._fnLog = _fnLog; this.oApi._fnClearTable = _fnClearTable; this.oApi._fnSaveState = _fnSaveState; this.oApi._fnLoadState = _fnLoadState; this.oApi._fnCreateCookie = _fnCreateCookie; this.oApi._fnReadCookie = _fnReadCookie; this.oApi._fnDetectHeader = _fnDetectHeader; this.oApi._fnGetUniqueThs = _fnGetUniqueThs; this.oApi._fnScrollBarWidth = _fnScrollBarWidth; this.oApi._fnApplyToChildren = _fnApplyToChildren; this.oApi._fnMap = _fnMap; this.oApi._fnGetRowData = _fnGetRowData; this.oApi._fnGetCellData = _fnGetCellData; this.oApi._fnSetCellData = _fnSetCellData; this.oApi._fnGetObjectDataFn = _fnGetObjectDataFn; this.oApi._fnSetObjectDataFn = _fnSetObjectDataFn; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Section - Constructor */ /* Want to be able to reference "this" inside the this.each function */ var _that = this; return this.each(function() { var i=0, iLen, j, jLen, k, kLen; /* Check to see if we are re-initalising a table */ for ( i=0, iLen=_aoSettings.length ; i<iLen ; i++ ) { /* Base check on table node */ if ( _aoSettings[i].nTable == this ) { if ( typeof oInit == 'undefined' || ( typeof oInit.bRetrieve != 'undefined' && oInit.bRetrieve === true ) ) { return _aoSettings[i].oInstance; } else if ( typeof oInit.bDestroy != 'undefined' && oInit.bDestroy === true ) { _aoSettings[i].oInstance.fnDestroy(); break; } else { _fnLog( _aoSettings[i], 0, "Cannot reinitialise DataTable.\n\n"+ "To retrieve the DataTables object for this table, please pass either no arguments "+ "to the dataTable() function, or set bRetrieve to true. Alternatively, to destory "+ "the old table and create a new one, set bDestroy to true (note that a lot of "+ "changes to the configuration can be made through the API which is usually much "+ "faster)." ); return; } } /* If the element we are initialising has the same ID as a table which was previously * initialised, but the table nodes don't match (from before) then we destory the old * instance by simply deleting it. This is under the assumption that the table has been * destroyed by other methods. Anyone using non-id selectors will need to do this manually */ if ( _aoSettings[i].sTableId !== "" && _aoSettings[i].sTableId == this.getAttribute('id') ) { _aoSettings.splice( i, 1 ); break; } } /* Make a complete and independent copy of the settings object */ var oSettings = new classSettings(); _aoSettings.push( oSettings ); var bInitHandedOff = false; var bUsePassedData = false; /* Set the id */ var sId = this.getAttribute( 'id' ); if ( sId !== null ) { oSettings.sTableId = sId; oSettings.sInstance = sId; } else { oSettings.sInstance = _oExt._oExternConfig.iNextUnique ++; } /* Sanity check */ if ( this.nodeName.toLowerCase() != 'table' ) { _fnLog( oSettings, 0, "Attempted to initialise DataTables on a node which is not a "+ "table: "+this.nodeName ); return; } /* Set the table node */ oSettings.nTable = this; /* Keep a reference to the 'this' instance for the table. Note that if this table is being * created with others, we retrieve a unique instance to ease API access. */ oSettings.oInstance = _that.length == 1 ? _that : $(this).dataTable(); /* Bind the API functions to the settings, so we can perform actions whenever oSettings is * available */ oSettings.oApi = _that.oApi; /* State the table's width for if a destroy is called at a later time */ oSettings.sDestroyWidth = $(this).width(); /* Store the features that we have available */ if ( typeof oInit != 'undefined' && oInit !== null ) { oSettings.oInit = oInit; _fnMap( oSettings.oFeatures, oInit, "bPaginate" ); _fnMap( oSettings.oFeatures, oInit, "bLengthChange" ); _fnMap( oSettings.oFeatures, oInit, "bFilter" ); _fnMap( oSettings.oFeatures, oInit, "bSort" ); _fnMap( oSettings.oFeatures, oInit, "bInfo" ); _fnMap( oSettings.oFeatures, oInit, "bProcessing" ); _fnMap( oSettings.oFeatures, oInit, "bAutoWidth" ); _fnMap( oSettings.oFeatures, oInit, "bSortClasses" ); _fnMap( oSettings.oFeatures, oInit, "bServerSide" ); _fnMap( oSettings.oFeatures, oInit, "bDeferRender" ); _fnMap( oSettings.oScroll, oInit, "sScrollX", "sX" ); _fnMap( oSettings.oScroll, oInit, "sScrollXInner", "sXInner" ); _fnMap( oSettings.oScroll, oInit, "sScrollY", "sY" ); _fnMap( oSettings.oScroll, oInit, "bScrollCollapse", "bCollapse" ); _fnMap( oSettings.oScroll, oInit, "bScrollInfinite", "bInfinite" ); _fnMap( oSettings.oScroll, oInit, "iScrollLoadGap", "iLoadGap" ); _fnMap( oSettings.oScroll, oInit, "bScrollAutoCss", "bAutoCss" ); _fnMap( oSettings, oInit, "asStripClasses" ); _fnMap( oSettings, oInit, "fnPreDrawCallback" ); _fnMap( oSettings, oInit, "fnRowCallback" ); _fnMap( oSettings, oInit, "fnHeaderCallback" ); _fnMap( oSettings, oInit, "fnFooterCallback" ); _fnMap( oSettings, oInit, "fnCookieCallback" ); _fnMap( oSettings, oInit, "fnInitComplete" ); _fnMap( oSettings, oInit, "fnServerData" ); _fnMap( oSettings, oInit, "fnFormatNumber" ); _fnMap( oSettings, oInit, "aaSorting" ); _fnMap( oSettings, oInit, "aaSortingFixed" ); _fnMap( oSettings, oInit, "aLengthMenu" ); _fnMap( oSettings, oInit, "sPaginationType" ); _fnMap( oSettings, oInit, "sAjaxSource" ); _fnMap( oSettings, oInit, "sAjaxDataProp" ); _fnMap( oSettings, oInit, "iCookieDuration" ); _fnMap( oSettings, oInit, "sCookiePrefix" ); _fnMap( oSettings, oInit, "sDom" ); _fnMap( oSettings, oInit, "bSortCellsTop" ); _fnMap( oSettings, oInit, "oSearch", "oPreviousSearch" ); _fnMap( oSettings, oInit, "aoSearchCols", "aoPreSearchCols" ); _fnMap( oSettings, oInit, "iDisplayLength", "_iDisplayLength" ); _fnMap( oSettings, oInit, "bJQueryUI", "bJUI" ); _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" ); /* Callback functions which are array driven */ if ( typeof oInit.fnDrawCallback == 'function' ) { oSettings.aoDrawCallback.push( { "fn": oInit.fnDrawCallback, "sName": "user" } ); } if ( typeof oInit.fnStateSaveCallback == 'function' ) { oSettings.aoStateSave.push( { "fn": oInit.fnStateSaveCallback, "sName": "user" } ); } if ( typeof oInit.fnStateLoadCallback == 'function' ) { oSettings.aoStateLoad.push( { "fn": oInit.fnStateLoadCallback, "sName": "user" } ); } if ( oSettings.oFeatures.bServerSide && oSettings.oFeatures.bSort && oSettings.oFeatures.bSortClasses ) { /* Enable sort classes for server-side processing. Safe to do it here, since server-side * processing must be enabled by the developer */ oSettings.aoDrawCallback.push( { "fn": _fnSortingClasses, "sName": "server_side_sort_classes" } ); } else if ( oSettings.oFeatures.bDeferRender ) { oSettings.aoDrawCallback.push( { "fn": _fnSortingClasses, "sName": "defer_sort_classes" } ); } if ( typeof oInit.bJQueryUI != 'undefined' && oInit.bJQueryUI ) { /* Use the JUI classes object for display. You could clone the oStdClasses object if * you want to have multiple tables with multiple independent classes */ oSettings.oClasses = _oExt.oJUIClasses; if ( typeof oInit.sDom == 'undefined' ) { /* Set the DOM to use a layout suitable for jQuery UI's theming */ oSettings.sDom = '<"H"lfr>t<"F"ip>'; } } /* Calculate the scroll bar width and cache it for use later on */ if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { oSettings.oScroll.iBarWidth = _fnScrollBarWidth(); } if ( typeof oInit.iDisplayStart != 'undefined' && typeof oSettings.iInitDisplayStart == 'undefined' ) { /* Display start point, taking into account the save saving */ oSettings.iInitDisplayStart = oInit.iDisplayStart; oSettings._iDisplayStart = oInit.iDisplayStart; } /* Must be done after everything which can be overridden by a cookie! */ if ( typeof oInit.bStateSave != 'undefined' ) { oSettings.oFeatures.bStateSave = oInit.bStateSave; _fnLoadState( oSettings, oInit ); oSettings.aoDrawCallback.push( { "fn": _fnSaveState, "sName": "state_save" } ); } if ( typeof oInit.iDeferLoading != 'undefined' ) { oSettings.bDeferLoading = true; oSettings._iRecordsTotal = oInit.iDeferLoading; oSettings._iRecordsDisplay = oInit.iDeferLoading; } if ( typeof oInit.aaData != 'undefined' ) { bUsePassedData = true; } /* Backwards compatability */ /* aoColumns / aoData - remove at some point... */ if ( typeof oInit != 'undefined' && typeof oInit.aoData != 'undefined' ) { oInit.aoColumns = oInit.aoData; } /* Language definitions */ if ( typeof oInit.oLanguage != 'undefined' ) { if ( typeof oInit.oLanguage.sUrl != 'undefined' && oInit.oLanguage.sUrl !== "" ) { /* Get the language definitions from a file */ oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl; $.getJSON( oSettings.oLanguage.sUrl, null, function( json ) { _fnLanguageProcess( oSettings, json, true ); } ); bInitHandedOff = true; } else { _fnLanguageProcess( oSettings, oInit.oLanguage, false ); } } /* Warning: The _fnLanguageProcess function is async to the remainder of this function due * to the XHR. We use _bInitialised in _fnLanguageProcess() to check this the processing * below is complete. The reason for spliting it like this is optimisation - we can fire * off the XHR (if needed) and then continue processing the data. */ } else { /* Create a dummy object for quick manipulation later on. */ oInit = {}; } /* * Stripes * Add the strip classes now that we know which classes to apply - unless overruled */ if ( typeof oInit.asStripClasses == 'undefined' ) { oSettings.asStripClasses.push( oSettings.oClasses.sStripOdd ); oSettings.asStripClasses.push( oSettings.oClasses.sStripEven ); } /* Remove row stripe classes if they are already on the table row */ var bStripeRemove = false; var anRows = $('>tbody>tr', this); for ( i=0, iLen=oSettings.asStripClasses.length ; i<iLen ; i++ ) { if ( anRows.filter(":lt(2)").hasClass( oSettings.asStripClasses[i]) ) { bStripeRemove = true; break; } } if ( bStripeRemove ) { /* Store the classes which we are about to remove so they can be readded on destory */ oSettings.asDestoryStrips = [ '', '' ]; if ( $(anRows[0]).hasClass(oSettings.oClasses.sStripOdd) ) { oSettings.asDestoryStrips[0] += oSettings.oClasses.sStripOdd+" "; } if ( $(anRows[0]).hasClass(oSettings.oClasses.sStripEven) ) { oSettings.asDestoryStrips[0] += oSettings.oClasses.sStripEven; } if ( $(anRows[1]).hasClass(oSettings.oClasses.sStripOdd) ) { oSettings.asDestoryStrips[1] += oSettings.oClasses.sStripOdd+" "; } if ( $(anRows[1]).hasClass(oSettings.oClasses.sStripEven) ) { oSettings.asDestoryStrips[1] += oSettings.oClasses.sStripEven; } anRows.removeClass( oSettings.asStripClasses.join(' ') ); } /* * Columns * See if we should load columns automatically or use defined ones */ var anThs = []; var aoColumnsInit; var nThead = this.getElementsByTagName('thead'); if ( nThead.length !== 0 ) { _fnDetectHeader( oSettings.aoHeader, nThead[0] ); anThs = _fnGetUniqueThs( oSettings ); } /* If not given a column array, generate one with nulls */ if ( typeof oInit.aoColumns == 'undefined' ) { aoColumnsInit = []; for ( i=0, iLen=anThs.length ; i<iLen ; i++ ) { aoColumnsInit.push( null ); } } else { aoColumnsInit = oInit.aoColumns; } /* Add the columns */ for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { /* Check if we have column visibilty state to restore */ if ( typeof oInit.saved_aoColumns != 'undefined' && oInit.saved_aoColumns.length == iLen ) { if ( aoColumnsInit[i] === null ) { aoColumnsInit[i] = {}; } aoColumnsInit[i].bVisible = oInit.saved_aoColumns[i].bVisible; } _fnAddColumn( oSettings, anThs ? anThs[i] : null ); } /* Add options from column definations */ if ( typeof oInit.aoColumnDefs != 'undefined' ) { /* Loop over the column defs array - loop in reverse so first instace has priority */ for ( i=oInit.aoColumnDefs.length-1 ; i>=0 ; i-- ) { /* Each column def can target multiple columns, as it is an array */ var aTargets = oInit.aoColumnDefs[i].aTargets; if ( !$.isArray( aTargets ) ) { _fnLog( oSettings, 1, 'aTargets must be an array of targets, not a '+(typeof aTargets) ); } for ( j=0, jLen=aTargets.length ; j<jLen ; j++ ) { if ( typeof aTargets[j] == 'number' && aTargets[j] >= 0 ) { /* 0+ integer, left to right column counting. We add columns which are unknown * automatically. Is this the right behaviour for this? We should at least * log it in future. We cannot do this for the negative or class targets, only here. */ while( oSettings.aoColumns.length <= aTargets[j] ) { _fnAddColumn( oSettings ); } _fnColumnOptions( oSettings, aTargets[j], oInit.aoColumnDefs[i] ); } else if ( typeof aTargets[j] == 'number' && aTargets[j] < 0 ) { /* Negative integer, right to left column counting */ _fnColumnOptions( oSettings, oSettings.aoColumns.length+aTargets[j], oInit.aoColumnDefs[i] ); } else if ( typeof aTargets[j] == 'string' ) { /* Class name matching on TH element */ for ( k=0, kLen=oSettings.aoColumns.length ; k<kLen ; k++ ) { if ( aTargets[j] == "_all" || $(oSettings.aoColumns[k].nTh).hasClass( aTargets[j] ) ) { _fnColumnOptions( oSettings, k, oInit.aoColumnDefs[i] ); } } } } } } /* Add options from column array - after the defs array so this has priority */ if ( typeof aoColumnsInit != 'undefined' ) { for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { _fnColumnOptions( oSettings, i, aoColumnsInit[i] ); } } /* * Sorting * Check the aaSorting array */ for ( i=0, iLen=oSettings.aaSorting.length ; i<iLen ; i++ ) { if ( oSettings.aaSorting[i][0] >= oSettings.aoColumns.length ) { oSettings.aaSorting[i][0] = 0; } var oColumn = oSettings.aoColumns[ oSettings.aaSorting[i][0] ]; /* Add a default sorting index */ if ( typeof oSettings.aaSorting[i][2] == 'undefined' ) { oSettings.aaSorting[i][2] = 0; } /* If aaSorting is not defined, then we use the first indicator in asSorting */ if ( typeof oInit.aaSorting == "undefined" && typeof oSettings.saved_aaSorting == "undefined" ) { oSettings.aaSorting[i][1] = oColumn.asSorting[0]; } /* Set the current sorting index based on aoColumns.asSorting */ for ( j=0, jLen=oColumn.asSorting.length ; j<jLen ; j++ ) { if ( oSettings.aaSorting[i][1] == oColumn.asSorting[j] ) { oSettings.aaSorting[i][2] = j; break; } } } /* Do a first pass on the sorting classes (allows any size changes to be taken into * account, and also will apply sorting disabled classes if disabled */ _fnSortingClasses( oSettings ); /* * Final init * Cache the header, body and footer as required, creating them if needed */ var thead = $('>thead', this); if ( thead.length === 0 ) { thead = [ document.createElement( 'thead' ) ]; this.appendChild( thead[0] ); } oSettings.nTHead = thead[0]; var tbody = $('>tbody', this); if ( tbody.length === 0 ) { tbody = [ document.createElement( 'tbody' ) ]; this.appendChild( tbody[0] ); } oSettings.nTBody = tbody[0]; var tfoot = $('>tfoot', this); if ( tfoot.length > 0 ) { oSettings.nTFoot = tfoot[0]; _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot ); } /* Check if there is data passing into the constructor */ if ( bUsePassedData ) { for ( i=0 ; i<oInit.aaData.length ; i++ ) { _fnAddData( oSettings, oInit.aaData[ i ] ); } } else { /* Grab the data from the page */ _fnGatherData( oSettings ); } /* Copy the data index array */ oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); /* Initialisation complete - table can be drawn */ oSettings.bInitialised = true; /* Check if we need to initialise the table (it might not have been handed off to the * language processor) */ if ( bInitHandedOff === false ) { _fnInitalise( oSettings ); } }); }; })(jQuery, window, document);
08102013project
trunk/CMS/Scripts/plugins/datatables.js
JavaScript
oos
234,441
/*----------------------------------------------------------------------*/ /* wl_Editor v 1.1 by revaxarts.com /* description: makes a WYSIWYG Editor /* dependency: jWYSIWYG Editor /*----------------------------------------------------------------------*/ $.fn.wl_Editor = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Editor.methods[method]) { return $.fn.wl_Editor.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Editor')) { var opts = $.extend({}, $this.data('wl_Editor'), method); } else { var opts = $.extend({}, $.fn.wl_Editor.defaults, method, $this.data()); } } else { try { return $this.wysiwyg(method, args[1], args[2], args[3]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Editor')) { $this.data('wl_Editor', {}); //detroying and re-made the editor crashes safari on iOS Devices so I disabled it. //normally the browser don't get resized as much. //wysiwyg isn't working on iPhone anyway /* $(window).bind('resize.' + 'wl_Editor', function () { $this.wysiwyg('destroy').wysiwyg(opts.eOpts); }); */ //make an array out of the buttons or use it if it is allready an array opts.buttons = opts.buttons.split('|') || opts.buttons; //set initial options opts.eOpts = { initialContent: opts.initialContent, css: opts.css }; //set buttons visible if they are in the array var controls = {}; $.each(opts.buttons, function (i, id) { controls[id] = { visible: true }; }); //add them to the options $.extend(true, opts.eOpts, { controls: controls }, opts.eOpts); //call the jWYSIWYG plugin $this.wysiwyg(opts.eOpts); } else { } if (opts) $.extend($this.data('wl_Editor'), opts); }); }; $.fn.wl_Editor.defaults = { css: 'css/light/editor.css', buttons: 'bold|italic|underline|strikeThrough|justifyLeft|justifyCenter|justifyRight|justifyFull|highlight|colorpicker|indent|outdent|subscript|superscript|undo|redo|insertOrderedList|insertUnorderedList|insertHorizontalRule|createLink|insertImage|h1|h2|h3|h4|h5|h6|paragraph|rtl|ltr|cut|copy|paste|increaseFontSize|decreaseFontSize|html|code|removeFormat|insertTable', initialContent: "" }; $.fn.wl_Editor.version = '1.1'; $.fn.wl_Editor.methods = { destroy: function () { var $this = $(this); //destroy it! $this.wysiwyg('destroy'); $this.removeData('wl_Editor'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Editor.defaults[key] !== undefined || $.fn.wl_Editor.defaults[key] == null) { $this.data('wl_Editor')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Editor.js
JavaScript
oos
3,197
/*----------------------------------------------------------------------*/ /* wl_Alert v 1.1 by revaxarts.com /* description: Handles alert boxes /* dependency: jquery UI Slider, fadeOutSlide plugin /*----------------------------------------------------------------------*/ $.fn.wl_Alert = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Alert.methods[method]) { return $.fn.wl_Alert.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Alert')) { var opts = $.extend({}, $this.data('wl_Alert'), method); } else { var opts = $.extend({}, $.fn.wl_Alert.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Alert')) { $this.data('wl_Alert', {}); //bind click events to hide alert box $this.bind('click.wl_Alert', function (event) { event.preventDefault(); //Don't hide if it is sticky if (!$this.data('wl_Alert').sticky) { $.fn.wl_Alert.methods.close.call($this[0]); } //prevent hiding the box if an inline link is clicked }).find('a').bind('click.wl_Alert', function (event) { event.stopPropagation(); }); } else { } //show it if it is hidden if ($this.is(':hidden')) { $this.slideDown(opts.speed / 2); } if (opts) $.extend($this.data('wl_Alert'), opts); }); }; $.fn.wl_Alert.defaults = { speed: 500, sticky: false, onBeforeClose: function (element) {}, onClose: function (element) {} }; $.fn.wl_Alert.version = '1.1'; $.fn.wl_Alert.methods = { close: function () { var $this = $(this), opts = $this.data('wl_Alert'); //call callback and stop if it returns false if (opts.onBeforeClose.call(this, $this) === false) { return false; }; //fadeout and call an callback $this.fadeOutSlide(opts.speed, function () { opts.onClose.call($this[0], $this); }); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Alert.defaults[key] !== undefined || $.fn.wl_Alert.defaults[key] == null) { $this.data('wl_Alert')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } }; //to create an alert box on the fly $.wl_Alert = function (text, cssclass, insert, after, options) { //go thru all $('div.alert').each(function () { var _this = $(this); //...and hide if one with the same text is allready set if (_this.text() == text) { _this.slideUp($.fn.wl_Alert.defaults.speed); } }); //create a new DOM element and inject it var al = $('<div class="alert ' + cssclass + '">' + text + '</div>').hide(); (after) ? al.appendTo(insert).wl_Alert(options) : al.prependTo(insert).wl_Alert(options); //return the element return al; };
08102013project
trunk/CMS/Scripts/plugins/wl_Alert.js
JavaScript
oos
3,174
/*----------------------------------------------------------------------*/ /* wl_Breadcrumb v 1.0 by revaxarts.com /* description: Makes and handles a Breadcrumb navigation /* dependency: /*----------------------------------------------------------------------*/ $.fn.wl_Breadcrumb = function (method) { var args = arguments; return this.each(function () { var $this = $(this), $li = $this.find('li'); $a = $this.find('a'); if ($.fn.wl_Breadcrumb.methods[method]) { return $.fn.wl_Breadcrumb.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Breadcrumb')) { var opts = $.extend({}, $this.data('wl_Breadcrumb'), method); } else { var opts = $.extend({}, $.fn.wl_Breadcrumb.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } //get the current field or use the first if not set var $current = $this.find('a.active').eq(0); if (!$current.length) $current = $a.eq(opts.start); if (!$this.data('wl_Breadcrumb')) { $this.data('wl_Breadcrumb', {}); //each anchor $a.each(function (i) { var _this = $(this); //save the id _this.data('id', i); //prepend numbers if set if (opts.numbers) _this.text((i + 1) + '. ' + _this.text()); }); //each listelement $li.each(function (i) { var _this = $(this); //if has a class (must be an icon) if (_this.attr('class')) { //innerwrap the anchor to attach the icon $a.eq(i).wrapInner('<span class="' + _this.attr('class') + '"/>'); //remove the class from the list element _this.removeAttr('class'); } }); //add a 'last' class to the last element for IE :( if($.browser.msie)$li.filter(':last').addClass('last'); //Bind the click handler $this.delegate('a', 'click.wl_Breadcrumb', function () { var opts = $this.data('wl_Breadcrumb') || opts; //if disabled stop if (opts.disabled) return false; var _this = $(this); //if not allownextonly or data is current+1 or current-x if (!opts.allownextonly || _this.data('id') - $this.find('a.active').data('id') <= 1) { //activate and trigger callback $.fn.wl_Breadcrumb.methods.activate.call($this[0], _this); opts.onChange.call($this[0], _this, _this.data('id')); } return false; }); //connected breadcrumb if (opts.connect) { var $connect = $('#' + opts.connect), $pages = $connect.children(); //bind event to all 'next' class elements $connect.find('.next').bind('click.wl_Breadcrumb', function () { $this.wl_Breadcrumb('next'); return false; }); //bind event to all 'prev' class elements $connect.find('.prev').bind('click.wl_Breadcrumb', function () { $this.wl_Breadcrumb('prev'); return false; }); //hide all and show the starting one $pages.hide().eq(opts.start).show(); } //disable if set if (opts.disabled) { $this.wl_Breadcrumb('disable'); } } else { } if (opts) $.extend($this.data('wl_Breadcrumb'), opts); //activate the current part $.fn.wl_Breadcrumb.methods.activate.call(this, $current); }); }; $.fn.wl_Breadcrumb.defaults = { start: 0, numbers: false, allownextonly: false, disabled: false, connect: null, onChange: function () {} }; $.fn.wl_Breadcrumb.version = '1.0'; $.fn.wl_Breadcrumb.methods = { activate: function (element) { var $this = $(this); //element is a number so we mean the id if (typeof element === 'number') { element = $this.find('li').eq(element).find('a'); element.trigger('click.wl_Breadcrumb'); return false; } var _opts = $this.data('wl_Breadcrumb'); //remove classes $this.find('a').removeClass('active previous'); //find all previous tabs and add a class element.parent().prevAll().find('a').addClass('previous'); //add and active class to the current tab element.addClass('active'); //connected breadcrumb if (_opts.connect) { var $connect = $('#' + _opts.connect), $pages = $connect.children(); //hide all and show selected $pages.hide().eq(element.data('id')).show(); } }, disable: function () { var $this = $(this); //disable and add class disable $this.wl_Breadcrumb('set', 'disabled', true); $this.addClass('disabled'); }, enable: function () { var $this = $(this); //enable and remove class disable $this.wl_Breadcrumb('set', 'disabled', false); $this.removeClass('disabled'); }, next: function () { var $this = $(this); //click next tab $this.find('a.active').parent().next().find('a').trigger('click.wl_Breadcrumb'); }, prev: function () { var $this = $(this); //click prev tab $this.find('a.active').parent().prev().find('a').trigger('click.wl_Breadcrumb'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Breadcrumb.defaults[key] !== undefined || $.fn.wl_Breadcrumb.defaults[key] == null) { $this.data('wl_Breadcrumb')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Breadcrumb.js
JavaScript
oos
5,543
/*----------------------------------------------------------------------*/ /* wl_Slider v 1.1.1 by revaxarts.com /* description: /* dependency: jquery UI Slider, mousewheel plugin /*----------------------------------------------------------------------*/ $.fn.wl_Slider = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Slider.methods[method]) { return $.fn.wl_Slider.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Slider')) { var opts = $.extend({}, $this.data('wl_Slider'), method); } else { var opts = $.extend({}, $.fn.wl_Slider.defaults, method, $this.data()); } } else { try { return $this.slider(method, args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Slider')) { $this.data('wl_Slider', {}); //bind mousewheel events $this.bind('mousewheel.wl_Slider', function (event, delta) { if (opts.mousewheel) { //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; event.preventDefault(); //slider with one handler if ($this.data('range') !== true) { var _value = $this.slider('value'); $.fn.wl_Slider.methods.values.call($this[0], _value + (delta * opts.step)); //update the tooltip if (opts.tooltip){ var _handle = $this.find('a'); _handle.tipsy('setTitel',opts.tooltipPattern.replace('%n', _value + (delta * opts.step))); _handle.tipsy('update'); } //slider with two handlers } else { var _values = $this.slider('values'); var _handler = $this.find('a'), _h1 = _handler.eq(0).offset(), _h2 = _handler.eq(1).offset(); //callculate the affected handler depending on the mouseposition if (opts.orientation == 'horizontal') { if (_h1.left + (_h2.left - _h1.left) / 2 > event.clientX) { $.fn.wl_Slider.methods.values.call($this[0], Math.min(_values[0] + (delta * opts.step), _values[1]), _values[1]); } else { $.fn.wl_Slider.methods.values.call($this[0], _values[0], Math.max(_values[1] + (delta * opts.step), _values[0])); } } else if (opts.orientation == 'vertical') { if (_h2.top + (_h1.top - _h2.top) / 2 < event.pageY) { $.fn.wl_Slider.methods.values.call($this[0], Math.min(_values[0] + (delta * opts.step), _values[1]), _values[1]); } else { $.fn.wl_Slider.methods.values.call($this[0], _values[0], Math.max(_values[1] + (delta * opts.step), _values[0])); } } //update the tooltip if (opts.tooltip){ _handler.eq(0).tipsy('setTitel',opts.tooltipPattern.replace('%n', _values[0] + (delta * opts.step))); _handler.eq(0).tipsy('update'); _handler.eq(1).tipsy('setTitel',opts.tooltipPattern.replace('%n', _values[0] + (delta * opts.step))); _handler.eq(1).tipsy('update'); } } $.fn.wl_Slider.methods.slide.call($this[0]); } }); } else { //destroy it $this.unbind('slide slidechange').slider('destroy'); } //call the jQuery UI slider plugin and add callbacks $this.slider(opts).bind('slide', function (event, ui) { $.fn.wl_Slider.methods.slide.call($this[0], ui.value); }).bind('slidechange', function (event, ui) { $.fn.wl_Slider.methods.change.call($this[0], ui.value); }); //slider is connected to an input field if (opts.connect) { //single slider if ($this.data('range') !== true) { var _input = $('#' + opts.connect), _value = _input.val() || $this.data('value') || opts.min; if(!_input.data('wl_Number')) _input.wl_Number(); $this.unbind('slide slidechange').slider('value', _value); //set callbacks on slide to change input fields $this.bind('slide', function (event, ui) { _input.val(ui.value); $.fn.wl_Slider.methods.slide.call($this[0], ui.value); }).bind('slidechange', function (event, ui) { _input.val(ui.value); $.fn.wl_Slider.methods.change.call($this[0], ui.value); }); _input.val(_value).wl_Number('set', $.extend({}, opts, { onChange: function (value) { $this.slider('value', value); $this.wl_Slider('slide'); $this.wl_Slider('change'); } })); //range slider with two handlers } else { var _input = $.parseData(opts.connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]), _value1 = _input1.val() || $this.data('values')[0] || opts.min, _value2 = _input2.val() || $this.data('values')[1] || opts.max; if(!_input1.data('wl_Number')) _input1.wl_Number(); if(!_input2.data('wl_Number')) _input2.wl_Number(); //set callbacks on slide to change input fields $this.unbind('slide slidechange').slider('option', 'values', [_value1, _value2]).bind('slide', function (event, ui) { _input1.val(ui.values[0]); _input2.val(ui.values[1]); $.fn.wl_Slider.methods.slide.call($this[0], ui.values); }).bind('slidechange', function (event, ui) { _input1.val(ui.values[0]); _input2.val(ui.values[1]); $.fn.wl_Slider.methods.change.call($this[0], ui.values); }); //set callbacks to the connected input fields _input1.wl_Number('set', $.extend({}, opts, { onChange: function (value) { $this.slider('option', 'values', [value, _input2.val()]); _input2.wl_Number('set', 'min', parseFloat(value)); $this.wl_Slider('slide'); $this.wl_Slider('change'); }, min: opts.min, max: _input2.val() || _value2 })).val(_value1); _input2.wl_Number('set', $.extend({}, opts, { onChange: function (value) { $this.slider('option', 'values', [_input1.val(), value]); _input1.wl_Number('set', 'max', parseFloat(value)); $this.wl_Slider('slide'); $this.wl_Slider('change'); }, min: _input1.val() || _value1, max: opts.max })).val(_value2); } } //activate tooltip if(opts.tooltip){ var e = $this.find('.ui-slider-handle'); var gravity, handles = []; //set the gravity if($.isArray(opts.tooltipGravity)){ if(opts.orientation == 'horizontal'){ gravity = opts.tooltipGravity[0]; }else if(opts.orientation == 'vertical'){ gravity = opts.tooltipGravity[1]; } }else{ gravity = opts.tooltipGravity; } //for each handle (e) $.each(e, function(i,handle){ var value; handles.push($(handle)); //get the value as array. set it to zero if undefined (required for init) if(opts.values){ value = opts.values; }else if(opts.value){ value = [opts.value]; }else{ value = [0,0]; } //use tipsy for a tooltip handles[i].tipsy($.extend({}, config.tooltip, { trigger: 'manual', gravity: gravity, html: true, fallback: opts.tooltipPattern.replace('%n',value[i]), appendTo: handles[i] })); //prevent the tooltip to wrap var tip = handles[i].tipsy('tip'); tip.find('.tipsy-inner').css('white-space','nowrap'); //bind events to the handler(s) handles[i].bind({ 'mouseenter.wl_Slider touchstart.wl_Slider':function(){handles[i].tipsy('show');}, 'mouseleave.wl_Slider touchend.wl_Slider':function(){handles[i].tipsy('hide');}, 'mouseenter touchstart':function(){handles[i].data('mouseIsOver',true);}, 'mouseleave touchend':function(){handles[i].data('mouseIsOver',false);} }); }); $this //unbind events if the slider starts (prevents flickering if the cursor leaves the handle) .bind('slidestart', function (event, ui) { $(ui.handle).unbind('mouseleave.wl_Slider touchstart.wl_Slider mouseenter.wl_Slider touchend.wl_Slider'); }) //rebind them again on slidestop .bind('slidestop', function (event, ui) { var handle = $(ui.handle); handle.bind({ 'mouseenter.wl_Slider touchstart.wl_Slider':function(){handle.tipsy('show');}, 'mouseleave.wl_Slider touchend.wl_Slider':function(){handle.tipsy('hide');} }); //hide the tooltip if the mouse isn't over the handle if(!handle.data('mouseIsOver'))handle.tipsy('hide'); }) //update the tooltip on the slide event .bind('slide', function (event, ui) { var handle = $(ui.handle); handle.tipsy('setTitel',opts.tooltipPattern.replace('%n',ui.value)); handle.tipsy('update'); }); } //disable if set if (opts.disabled) { $this.fn.wl_Slider.methods.disable.call($this[0]); } if (opts) $.extend($this.data('wl_Slider'), opts); }); }; $.fn.wl_Slider.defaults = { min: 0, max: 100, step: 1, animate: false, disabled: false, orientation: 'horizontal', range: false, mousewheel: true, connect: null, tooltip: false, tooltipGravity: ['s','w'], tooltipPattern: '%n', onSlide: function (value) {}, onChange: function (value) {} }; $.fn.wl_Slider.version = '1.1.1'; $.fn.wl_Slider.methods = { disable: function () { var $this = $(this), opts = $this.data('wl_Slider'); //disable slider $this.slider('disable'); //disable connected input fields if (opts.connect) { if ($this.data('range') !== true) { $('#' + opts.connect).prop('disabled', true); } else { var _input = $.parseData(opts.connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]); _input1.attr('disabled', true); _input2.attr('disabled', true); } } $this.data('wl_Slider').disabled = true; }, enable: function () { var $this = $(this), opts = $this.data('wl_Slider'); //enable slider $this.slider('enable'); //enable connected input fields if ($this.data('wl_Slider').connect) { if ($this.data('range') !== true) { $('#' + opts.connect).prop('disabled', false); } else { var _input = $.parseData(opts.connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]); _input1.removeAttr('disabled'); _input2.removeAttr('disabled'); } } $this.data('wl_Slider').disabled = false; }, change: function (value) { var $this = $(this), opts = $this.data('wl_Slider'); if ($this.data('range') !== true) { opts.onChange.call(this, value || $this.slider('value')); } else { opts.onChange.call(this, value || $this.slider('values')); } }, slide: function (value) { var $this = $(this), opts = $this.data('wl_Slider'); if ($this.data('range') !== true) { opts.onSlide.call(this, value || $this.slider('value')); } else { opts.onSlide.call(this, value || $this.slider('values')); } }, value: function () { var $this = $(this), opts = $this.data('wl_Slider'); if (opts.range !== true) { $this.slider('value', arguments[0]); } }, values: function () { var $this = $(this), opts = $this.data('wl_Slider'); if (opts.range === true) { if (typeof arguments[0] === 'object') { $this.slider('values', 0, arguments[0][0]); $this.slider('values', 1, arguments[0][1]); } else { $this.slider('values', 0, arguments[0]); $this.slider('values', 1, arguments[1]); } } else { $.fn.wl_Slider.methods.value.call(this, arguments[0]); } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } if ($this.data('wl_Slider').connect) { if ($this.data('range') !== true) { var _input1 = $('#' + $this.data('wl_Slider').connect); } else { var _input = $.parseData($this.data('wl_Slider').connect, true), _input1 = $('#' + _input[0]), _input2 = $('#' + _input[1]); } } $.each(options, function (key, value) { if ($.fn.wl_Slider.defaults[key] !== undefined || $.fn.wl_Slider.defaults[key] == null) { $this.slider('option', key, value).data('wl_Slider')[key] = value; if (_input1) _input1.data(key, value).trigger('change'); if (_input2) _input2.data(key, value).trigger('change'); } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Slider.js
JavaScript
oos
12,687
$(document).ready(function () { /*----------------------------------------------------------------------*/ /* Parse the data from an data-attribute of DOM Elements /*----------------------------------------------------------------------*/ $.parseData = function (data, returnArray) { if (/^\[(.*)\]$/.test(data)) { //array data = data.substr(1, data.length - 2).split(','); } if (returnArray && !$.isArray(data) && data != null) { data = Array(data); } return data; }; /*----------------------------------------------------------------------*/ /* Image Preloader /* http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript /*----------------------------------------------------------------------*/ // Arguments are image paths relative to the current page. $.preload = function() { var cache = [], args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } }; /*----------------------------------------------------------------------*/ /* fadeInSlide by revaxarts.com /* Fades out a box and slide it up before it will get removed /*----------------------------------------------------------------------*/ $.fn.fadeInSlide = function (speed, callback) { if ($.isFunction(speed)) callback = speed; if (!speed) speed = 200; if (!callback) callback = function () {}; this.each(function () { var $this = $(this); $this.fadeTo(speed / 2, 1).slideDown(speed / 2, function () { callback(); }); }); return this; }; /*----------------------------------------------------------------------*/ /* fadeOutSlide by revaxarts.com /* Fades out a box and slide it up before it will get removed /*----------------------------------------------------------------------*/ $.fn.fadeOutSlide = function (speed, callback) { if ($.isFunction(speed)) callback = speed; if (!speed) speed = 200; if (!callback) callback = function () {}; this.each(function () { var $this = $(this); $this.fadeTo(speed / 2, 0).slideUp(speed / 2, function () { $this.remove(); callback(); }); }); return this; }; /*----------------------------------------------------------------------*/ /* textFadeOut by revaxarts.com /* Fades out a box and slide it up before it will get removed /*----------------------------------------------------------------------*/ $.fn.textFadeOut = function (text, delay, callback) { if (!text) return false; if ($.isFunction(delay)) callback = delay; if (!delay) delay = 2000; if (!callback) callback = function () {}; this.each(function () { var $this = $(this); $this.stop().text(text).show().delay(delay).fadeOut(1000,function(){ $this.text('').show(); callback(); }) }); return this; }; /*----------------------------------------------------------------------*/ /* leadingZero by revaxarts.com /* adds a leding zero if necessary /*----------------------------------------------------------------------*/ $.leadingZero = function (value) { value = parseInt(value, 10); if(!isNaN(value)) { (value < 10) ? value = '0' + value : value; } return value; }; });
08102013project
trunk/CMS/Scripts/plugins/functions.js
JavaScript
oos
3,383
$(document).ready(function() { var $body = $('body'), $content = $('#content'); //IE doen't like that fadein if(!$.browser.msie) $body.fadeTo(0,0.0).delay(500).fadeTo(1000, 1); $("input").not('input[type=submit]').uniform(); $content.find('.breadcrumb').wl_Breadcrumb({ allownextonly:true, onChange: function(el,id){ switch(id){ case 0: //Start break; case 1: //Information break; case 2: //Summery break; case 3: //Installation break; case 4: //Finish break; } } }); $('#loginbtn').click(function(){ location.href="login.html"; }); });
08102013project
trunk/CMS/Scripts/plugins/wizard.js
JavaScript
oos
716
$(document).ready(function () { /** * FullCalendar v1.5.1 * http://arshaw.com/fullcalendar/ * * Use fullcalendar.css for basic styling. * For event drag & drop, requires jQuery UI draggable. * For event resizing, requires jQuery UI resizable. * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Sat Apr 9 14:09:51 2011 -0700 * */ (function($, undefined) { var defaults = { // display defaultView: 'month', aspectRatio: 1.35, header: { left: 'title', center: '', right: 'today prev,next' }, weekends: true, // editing //editable: false, //disableDragging: false, //disableResizing: false, allDayDefault: true, ignoreTimezone: true, // event ajax lazyFetching: true, startParam: 'start', endParam: 'end', // time formats titleFormat: { month: 'MMMM yyyy', week: "MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}", day: 'dddd, MMM d, yyyy' }, columnFormat: { month: 'ddd', week: 'ddd M/d', day: 'dddd M/d' }, timeFormat: { // for event elements '': 'h(:mm)t' // default }, // locale isRTL: false, firstDay: 0, monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'], monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], buttonText: { prev: '&nbsp;&#9668;&nbsp;', next: '&nbsp;&#9658;&nbsp;', prevYear: '&nbsp;&lt;&lt;&nbsp;', nextYear: '&nbsp;&gt;&gt;&nbsp;', today: 'today', month: 'month', week: 'week', day: 'day' }, // jquery-ui theming theme: false, buttonIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e' }, //selectable: false, unselectAuto: true, dropAccept: '*' }; // right-to-left defaults var rtlDefaults = { header: { left: 'next,prev today', center: '', right: 'title' }, buttonText: { prev: '&nbsp;&#9658;&nbsp;', next: '&nbsp;&#9668;&nbsp;', prevYear: '&nbsp;&gt;&gt;&nbsp;', nextYear: '&nbsp;&lt;&lt;&nbsp;' }, buttonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w' } }; var fc = $.fullCalendar = { version: "1.5.1" }; var fcViews = fc.views = {}; $.fn.fullCalendar = function(options) { // method calling if (typeof options == 'string') { var args = Array.prototype.slice.call(arguments, 1); var res; this.each(function() { var calendar = $.data(this, 'fullCalendar'); if (calendar && $.isFunction(calendar[options])) { var r = calendar[options].apply(calendar, args); if (res === undefined) { res = r; } if (options == 'destroy') { $.removeData(this, 'fullCalendar'); } } }); if (res !== undefined) { return res; } return this; } // would like to have this logic in EventManager, but needs to happen before options are recursively extended var eventSources = options.eventSources || []; delete options.eventSources; if (options.events) { eventSources.push(options.events); delete options.events; } options = $.extend(true, {}, defaults, (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {}, options ); this.each(function(i, _element) { var element = $(_element); var calendar = new Calendar(element, options, eventSources); element.data('fullCalendar', calendar); // TODO: look into memory leak implications calendar.render(); }); return this; }; // function for adding/overriding defaults function setDefaults(d) { $.extend(true, defaults, d); } function Calendar(element, options, eventSources) { var t = this; // exports t.options = options; t.render = render; t.destroy = destroy; t.refetchEvents = refetchEvents; t.reportEvents = reportEvents; t.reportEventChange = reportEventChange; t.rerenderEvents = rerenderEvents; t.changeView = changeView; t.select = select; t.unselect = unselect; t.prev = prev; t.next = next; t.prevYear = prevYear; t.nextYear = nextYear; t.today = today; t.gotoDate = gotoDate; t.incrementDate = incrementDate; t.formatDate = function(format, date) { return formatDate(format, date, options) }; t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; t.getDate = getDate; t.getView = getView; t.option = option; t.trigger = trigger; // imports EventManager.call(t, options, eventSources); var isFetchNeeded = t.isFetchNeeded; var fetchEvents = t.fetchEvents; // locals var _element = element[0]; var header; var headerElement; var content; var tm; // for making theme classes var currentView; var viewInstances = {}; var elementOuterWidth; var suggestedViewHeight; var absoluteViewElement; var resizeUID = 0; var ignoreWindowResize = 0; var date = new Date(); var events = []; var _dragElement; /* Main Rendering -----------------------------------------------------------------------------*/ setYMD(date, options.year, options.month, options.date); function render(inc) { if (!content) { initialRender(); }else{ calcSize(); markSizesDirty(); markEventsDirty(); renderView(inc); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } if (options.theme) { element.addClass('ui-widget'); } content = $("<div class='fc-content' style='position:relative'/>") .prependTo(element); header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } changeView(options.defaultView); $(window).resize(windowResize); // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize if (!bodyVisible()) { lateRender(); } } // called when we know the calendar couldn't be rendered when it was initialized, // but we think it's ready now function lateRender() { setTimeout(function() { // IE7 needs this so dimensions are calculated correctly if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once renderView(); } },0); } function destroy() { $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return _element.offsetWidth !== 0; } function bodyVisible() { return $('body')[0].offsetWidth !== 0; } /* View Rendering -----------------------------------------------------------------------------*/ // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached unselect(); var oldView = currentView; var newViewElement; if (oldView) { (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) setMinHeight(content, content.height()); oldView.element.hide(); }else{ setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated } content.css('overflow', 'hidden'); currentView = viewInstances[newViewName]; if (currentView) { currentView.element.show(); }else{ currentView = viewInstances[newViewName] = new fcViews[newViewName]( newViewElement = absoluteViewElement = $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>") .appendTo(content), t // the calendar object ); } if (oldView) { header.deactivateButton(oldView.name); } header.activateButton(newViewName); renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null content.css('overflow', ''); if (oldView) { setMinHeight(content, 1); } if (!newViewElement) { (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) } ignoreWindowResize--; } } function renderView(inc) { if (elementVisible()) { ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached unselect(); if (suggestedViewHeight === undefined) { calcSize(); } var forceEventRender = false; if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { // view must render an entire new date range (and refetch/render events) currentView.render(date, inc || 0); // responsible for clearing events setSize(true); forceEventRender = true; } else if (currentView.sizeDirty) { // view must resize (and rerender events) currentView.clearEvents(); setSize(); forceEventRender = true; } else if (currentView.eventsDirty) { currentView.clearEvents(); forceEventRender = true; } currentView.sizeDirty = false; currentView.eventsDirty = false; updateEvents(forceEventRender); elementOuterWidth = element.outerWidth(); header.updateTitle(currentView.title); var today = new Date(); if (today >= currentView.start && today < currentView.end) { header.disableButton('today'); }else{ header.enableButton('today'); } ignoreWindowResize--; currentView.trigger('viewDisplay', _element); } } /* Resizing -----------------------------------------------------------------------------*/ function updateSize() { markSizesDirty(); if (elementVisible()) { calcSize(); setSize(); unselect(); currentView.clearEvents(); currentView.renderEvents(events); currentView.sizeDirty = false; } } function markSizesDirty() { $.each(viewInstances, function(i, inst) { inst.sizeDirty = true; }); } function calcSize() { if (options.contentHeight) { suggestedViewHeight = options.contentHeight; } else if (options.height) { suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); } else { suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); } } function setSize(dateChanged) { // todo: dateChanged? ignoreWindowResize++; currentView.setHeight(suggestedViewHeight, dateChanged); if (absoluteViewElement) { absoluteViewElement.css('position', 'relative'); absoluteViewElement = null; } currentView.setWidth(content.width(), dateChanged); ignoreWindowResize--; } function windowResize() { if (!ignoreWindowResize) { if (currentView.start) { // view has already been rendered var uid = ++resizeUID; setTimeout(function() { // add a delay if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { ignoreWindowResize++; // in case the windowResize callback changes the height updateSize(); currentView.trigger('windowResize', _element); ignoreWindowResize--; } } }, 200); }else{ // calendar must have been initialized in a 0x0 iframe that has just been resized lateRender(); } } } /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ // fetches events if necessary, rerenders events if necessary (or if forced) function updateEvents(forceRender) { if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { refetchEvents(); } else if (forceRender) { rerenderEvents(); } } function refetchEvents() { fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents } // called when event data arrives function reportEvents(_events) { events = _events; rerenderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } // attempts to rerenderEvents function rerenderEvents(modifiedEventID) { markEventsDirty(); if (elementVisible()) { currentView.clearEvents(); currentView.renderEvents(events, modifiedEventID); currentView.eventsDirty = false; } } function markEventsDirty() { $.each(viewInstances, function(i, inst) { inst.eventsDirty = true; }); } /* Selection -----------------------------------------------------------------------------*/ function select(start, end, allDay) { currentView.select(start, end, allDay===undefined ? true : allDay); } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { renderView(-1); } function next() { renderView(1); } function prevYear() { addYears(date, -1); renderView(); } function nextYear() { addYears(date, 1); renderView(); } function today() { date = new Date(); renderView(); } function gotoDate(year, month, dateOfMonth) { if (year instanceof Date) { date = cloneDate(year); // provided 1 argument, a Date }else{ setYMD(date, year, month, dateOfMonth); } renderView(); } function incrementDate(years, months, days) { if (years !== undefined) { addYears(date, years); } if (months !== undefined) { addMonths(date, months); } if (days !== undefined) { addDays(date, days); } renderView(); } function getDate() { return cloneDate(date); } /* Misc -----------------------------------------------------------------------------*/ function getView() { return currentView; } function option(name, value) { if (value === undefined) { return options[name]; } if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { options[name] = value; updateSize(); } } function trigger(name, thisObj) { if (options[name]) { return options[name].apply( thisObj || _element, Array.prototype.slice.call(arguments, 2) ); } } /* External Dragging ------------------------------------------------------------------------*/ if (options.droppable) { $(document) .bind('dragstart', function(ev, ui) { var _e = ev.target; var e = $(_e); if (!e.parents('.fc').length) { // not already inside a calendar var accept = options.dropAccept; if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { _dragElement = _e; currentView.dragStart(_dragElement, ev, ui); } } }) .bind('dragstop', function(ev, ui) { if (_dragElement) { currentView.dragStop(_dragElement, ev, ui); _dragElement = null; } }); } } function Header(calendar, options) { var t = this; // exports t.render = render; t.destroy = destroy; t.updateTitle = updateTitle; t.activateButton = activateButton; t.deactivateButton = deactivateButton; t.disableButton = disableButton; t.enableButton = enableButton; // locals var element = $([]); var tm; function render() { tm = options.theme ? 'ui' : 'fc'; var sections = options.header; if (sections) { element = $("<table class='fc-header' style='width:100%'/>") .append( $("<tr/>") .append(renderSection('left')) .append(renderSection('center')) .append(renderSection('right')) ); return element; } } function destroy() { element.remove(); } function renderSection(position) { var e = $("<td class='fc-header-" + position + "'/>"); var buttonStr = options.header[position]; if (buttonStr) { $.each(buttonStr.split(' '), function(i) { if (i > 0) { e.append("<span class='fc-header-space'/>"); } var prevButton; $.each(this.split(','), function(j, buttonName) { if (buttonName == 'title') { e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>"); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } prevButton = null; }else{ var buttonClick; if (calendar[buttonName]) { buttonClick = calendar[buttonName]; // calendar method } else if (fcViews[buttonName]) { buttonClick = function() { button.removeClass(tm + '-state-hover'); // forget why calendar.changeView(buttonName); }; } if (buttonClick) { var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here? var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here? var button = $( "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" + "<span class='fc-button-inner'>" + "<span class='fc-button-content'>" + (icon ? "<span class='fc-icon-wrap'>" + "<span class='ui-icon ui-icon-" + icon + "'/>" + "</span>" : text ) + "</span>" + "<span class='fc-button-effect'><span></span></span>" + "</span>" + "</span>" ); if (button) { button .click(function() { if (!button.hasClass(tm + '-state-disabled')) { buttonClick(); } }) .mousedown(function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-down'); }) .mouseup(function() { button.removeClass(tm + '-state-down'); }) .hover( function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-hover'); }, function() { button .removeClass(tm + '-state-hover') .removeClass(tm + '-state-down'); } ) .appendTo(e); if (!prevButton) { button.addClass(tm + '-corner-left'); } prevButton = button; } } } }); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } }); } return e; } function updateTitle(html) { element.find('h2') .html(html); } function activateButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-active'); } function deactivateButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-active'); } function disableButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-disabled'); } function enableButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-disabled'); } } fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options, _sources) { var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.normalizeEvent = normalizeEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || start < rangeStart || end > rangeEnd; } function fetchEvents(start, end) { rangeStart = start; rangeEnd = end; cache = []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = len; for (var i=0; i<len; i++) { fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(events) { if (fetchID == currentFetchID) { if (events) { for (var i=0; i<events.length; i++) { events[i].source = source; normalizeEvent(events[i]); } cache = cache.concat(events); } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i](source, rangeStart, rangeEnd, callback); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { pushLoading(); events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) { callback(events); popLoading(); }); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; var data = $.extend({}, source.data || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); if (startParam) { data[startParam] = Math.round(+rangeStart / 1000); } if (endParam) { data[endParam] = Math.round(+rangeEnd / 1000); } pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); popLoading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(source) { source = _addEventSource(source); if (source) { pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function _addEventSource(source) { if ($.isFunction(source) || $.isArray(source)) { source = { events: source }; } else if (typeof source == 'string') { source = { url: source }; } if (typeof source == 'object') { normalizeSource(source); sources.push(source); return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } /* Manipulation -----------------------------------------------------------------------------*/ function updateEvent(event) { // update an existing event var i, len = cache.length, e, defaultEventEnd = getView().defaultEventEnd, // getView??? startDelta = event.start - event._start, endDelta = event.end ? (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end : 0; // was null and event was just resized for (i=0; i<len; i++) { e = cache[i]; if (e._id == event._id && e != event) { e.start = new Date(+e.start + startDelta); if (event.end) { if (e.end) { e.end = new Date(+e.end + endDelta); }else{ e.end = new Date(+defaultEventEnd(e) + endDelta); } }else{ e.end = null; } e.title = event.title; e.url = event.url; e.allDay = event.allDay; e.className = event.className; e.editable = event.editable; e.color = event.color; e.backgroudColor = event.backgroudColor; e.borderColor = event.borderColor; e.textColor = event.textColor; normalizeEvent(e); } } normalizeEvent(event); reportEvents(cache); } function renderEvent(event, stick) { normalizeEvent(event); if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } reportEvents(cache); } function removeEvents(filter) { if (!filter) { // remove all cache = []; // clear all array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = []; } } }else{ if (!$.isFunction(filter)) { // an event ID var id = filter + ''; filter = function(e) { return e._id == id; }; } cache = $.grep(cache, filter, true); // remove events from array sources for (var i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter) { // an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function pushLoading() { if (!loadingLevel++) { trigger('loading', null, true); } } function popLoading() { if (!--loadingLevel) { trigger('loading', null, false); } } /* Event Normalization -----------------------------------------------------------------------------*/ function normalizeEvent(event) { var source = event.source || {}; var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone); event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + ''); if (event.date) { if (!event.start) { event.start = event.date; } delete event.date; } event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone)); event.end = parseDate(event.end, ignoreTimezone); if (event.end && event.end <= event.start) { event.end = null; } event._end = event.end ? cloneDate(event.end) : null; if (event.allDay === undefined) { event.allDay = firstDefined(source.allDayDefault, options.allDayDefault); } if (event.className) { if (typeof event.className == 'string') { event.className = event.className.split(/\s+/); } }else{ event.className = []; } // TODO: if there is no start date, return false to indicate an invalid event } /* Utils ------------------------------------------------------------------------------*/ function normalizeSource(source) { if (source.className) { // TODO: repeat code, same code for event classNames if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } }else{ source.className = []; } var normalizers = fc.sourceNormalizers; for (var i=0; i<normalizers.length; i++) { normalizers[i](source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } } fc.addDays = addDays; fc.cloneDate = cloneDate; fc.parseDate = parseDate; fc.parseISO8601 = parseISO8601; fc.parseTime = parseTime; fc.formatDate = formatDate; fc.formatDates = formatDates; /* Date Math -----------------------------------------------------------------------------*/ var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], DAY_MS = 86400000, HOUR_MS = 3600000, MINUTE_MS = 60000; function addYears(d, n, keepTime) { d.setFullYear(d.getFullYear() + n); if (!keepTime) { clearTime(d); } return d; } function addMonths(d, n, keepTime) { // prevents day overflow/underflow if (+d) { // prevent infinite looping on invalid dates var m = d.getMonth() + n, check = cloneDate(d); check.setDate(1); check.setMonth(m); d.setMonth(m); if (!keepTime) { clearTime(d); } while (d.getMonth() != check.getMonth()) { d.setDate(d.getDate() + (d < check ? 1 : -1)); } } return d; } function addDays(d, n, keepTime) { // deals with daylight savings if (+d) { var dd = d.getDate() + n, check = cloneDate(d); check.setHours(9); // set to middle of day check.setDate(dd); d.setDate(dd); if (!keepTime) { clearTime(d); } fixDate(d, check); } return d; } function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes if (+d) { // prevent infinite looping on invalid dates while (d.getDate() != check.getDate()) { d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS); } } } function addMinutes(d, n) { d.setMinutes(d.getMinutes() + n); return d; } function clearTime(d) { d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0); return d; } function cloneDate(d, dontKeepTime) { if (dontKeepTime) { return clearTime(new Date(+d)); } return new Date(+d); } function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1 var i=0, d; do { d = new Date(1970, i++, 1); } while (d.getHours()); // != 0 return d; } function skipWeekend(date, inc, excl) { inc = inc || 1; while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) { addDays(date, inc); } return date; } function dayDiff(d1, d2) { // d1 - d2 return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS); } function setYMD(date, y, m, d) { if (y !== undefined && y != date.getFullYear()) { date.setDate(1); date.setMonth(0); date.setFullYear(y); } if (m !== undefined && m != date.getMonth()) { date.setDate(1); date.setMonth(m); } if (d !== undefined) { date.setDate(d); } } /* Date Parsing -----------------------------------------------------------------------------*/ function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true if (typeof s == 'object') { // already a Date object return s; } if (typeof s == 'number') { // a UNIX timestamp return new Date(s * 1000); } if (typeof s == 'string') { if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp return new Date(parseFloat(s) * 1000); } if (ignoreTimezone === undefined) { ignoreTimezone = true; } return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null); } // TODO: never return invalid dates (like from new Date(<string>)), return null instead return null; } function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false // derived from http://delete.me.uk/2005/03/iso8601.html // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/); if (!m) { return null; } var date = new Date(m[1], 0, 1); if (ignoreTimezone || !m[14]) { var check = new Date(m[1], 0, 1, 9, 0); if (m[3]) { date.setMonth(m[3] - 1); check.setMonth(m[3] - 1); } if (m[5]) { date.setDate(m[5]); check.setDate(m[5]); } fixDate(date, check); if (m[7]) { date.setHours(m[7]); } if (m[8]) { date.setMinutes(m[8]); } if (m[10]) { date.setSeconds(m[10]); } if (m[12]) { date.setMilliseconds(Number("0." + m[12]) * 1000); } fixDate(date, check); }else{ date.setUTCFullYear( m[1], m[3] ? m[3] - 1 : 0, m[5] || 1 ); date.setUTCHours( m[7] || 0, m[8] || 0, m[10] || 0, m[12] ? Number("0." + m[12]) * 1000 : 0 ); var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0); offset *= m[15] == '-' ? 1 : -1; date = new Date(+date + (offset * 60 * 1000)); } return date; } function parseTime(s) { // returns minutes since start of day if (typeof s == 'number') { // an hour return s * 60; } if (typeof s == 'object') { // a Date object return s.getHours() * 60 + s.getMinutes(); } var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/); if (m) { var h = parseInt(m[1], 10); if (m[3]) { h %= 12; if (m[3].toLowerCase().charAt(0) == 'p') { h += 12; } } return h * 60 + (m[2] ? parseInt(m[2], 10) : 0); } } /* Date Formatting -----------------------------------------------------------------------------*/ // TODO: use same function formatDate(date, [date2], format, [options]) function formatDate(date, format, options) { return formatDates(date, null, format, options); } function formatDates(date1, date2, format, options) { options = options || defaults; var date = date1, otherDate = date2, i, len = format.length, c, i2, formatter, res = ''; for (i=0; i<len; i++) { c = format.charAt(i); if (c == "'") { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == "'") { if (date) { if (i2 == i+1) { res += "'"; }else{ res += format.substring(i+1, i2); } i = i2; } break; } } } else if (c == '(') { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == ')') { var subres = formatDate(date, format.substring(i+1, i2), options); if (parseInt(subres.replace(/\D/, ''), 10)) { res += subres; } i = i2; break; } } } else if (c == '[') { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == ']') { var subformat = format.substring(i+1, i2); var subres = formatDate(date, subformat, options); if (subres != formatDate(otherDate, subformat, options)) { res += subres; } i = i2; break; } } } else if (c == '{') { date = date2; otherDate = date1; } else if (c == '}') { date = date1; otherDate = date2; } else { for (i2=len; i2>i; i2--) { if (formatter = dateFormatters[format.substring(i, i2)]) { if (date) { res += formatter(date, options); } i = i2 - 1; break; } } if (i2 == i) { if (date) { res += c; } } } } return res; }; var dateFormatters = { s : function(d) { return d.getSeconds() }, ss : function(d) { return zeroPad(d.getSeconds()) }, m : function(d) { return d.getMinutes() }, mm : function(d) { return zeroPad(d.getMinutes()) }, h : function(d) { return d.getHours() % 12 || 12 }, hh : function(d) { return zeroPad(d.getHours() % 12 || 12) }, H : function(d) { return d.getHours() }, HH : function(d) { return zeroPad(d.getHours()) }, d : function(d) { return d.getDate() }, dd : function(d) { return zeroPad(d.getDate()) }, ddd : function(d,o) { return o.dayNamesShort[d.getDay()] }, dddd: function(d,o) { return o.dayNames[d.getDay()] }, M : function(d) { return d.getMonth() + 1 }, MM : function(d) { return zeroPad(d.getMonth() + 1) }, MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] }, MMMM: function(d,o) { return o.monthNames[d.getMonth()] }, yy : function(d) { return (d.getFullYear()+'').substring(2) }, yyyy: function(d) { return d.getFullYear() }, t : function(d) { return d.getHours() < 12 ? 'a' : 'p' }, tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' }, T : function(d) { return d.getHours() < 12 ? 'A' : 'P' }, TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' }, u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") }, S : function(d) { var date = d.getDate(); if (date > 10 && date < 20) { return 'th'; } return ['st', 'nd', 'rd'][date%10-1] || 'th'; } }; fc.applyAll = applyAll; /* Event Date Math -----------------------------------------------------------------------------*/ function exclEndDay(event) { if (event.end) { return _exclEndDay(event.end, event.allDay); }else{ return addDays(cloneDate(event.start), 1); } } function _exclEndDay(end, allDay) { end = cloneDate(end); return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); } function segCmp(a, b) { return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); } function segsCollide(seg1, seg2) { return seg1.end > seg2.start && seg1.start < seg2.end; } /* Event Sorting -----------------------------------------------------------------------------*/ // event rendering utilities function sliceSegs(events, visEventEnds, start, end) { var segs = [], i, len=events.length, event, eventStart, eventEnd, segStart, segEnd, isStart, isEnd; for (i=0; i<len; i++) { event = events[i]; eventStart = event.start; eventEnd = visEventEnds[i]; if (eventEnd > start && eventStart < end) { if (eventStart < start) { segStart = cloneDate(start); isStart = false; }else{ segStart = eventStart; isStart = true; } if (eventEnd > end) { segEnd = cloneDate(end); isEnd = false; }else{ segEnd = eventEnd; isEnd = true; } segs.push({ event: event, start: segStart, end: segEnd, isStart: isStart, isEnd: isEnd, msLength: segEnd - segStart }); } } return segs.sort(segCmp); } // event rendering calculation utilities function stackSegs(segs) { var levels = [], i, len = segs.length, seg, j, collide, k; for (i=0; i<len; i++) { seg = segs[i]; j = 0; // the level index where seg should belong while (true) { collide = false; if (levels[j]) { for (k=0; k<levels[j].length; k++) { if (segsCollide(levels[j][k], seg)) { collide = true; break; } } } if (collide) { j++; }else{ break; } } if (levels[j]) { levels[j].push(seg); }else{ levels[j] = [seg]; } } return levels; } /* Event Element Binding -----------------------------------------------------------------------------*/ function lazySegBind(container, segs, bindHandlers) { container.unbind('mouseover').mouseover(function(ev) { var parent=ev.target, e, i, seg; while (parent != this) { e = parent; parent = parent.parentNode; } if ((i = e._fci) !== undefined) { e._fci = undefined; seg = segs[i]; bindHandlers(seg.event, seg.element, seg); $(ev.target).trigger(ev); } ev.stopPropagation(); }); } /* Element Dimensions -----------------------------------------------------------------------------*/ function setOuterWidth(element, width, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.width(Math.max(0, width - hsides(e, includeMargins))); } } function setOuterHeight(element, height, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.height(Math.max(0, height - vsides(e, includeMargins))); } } function hsides(element, includeMargins) { return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0); } function hpadding(element) { return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) + (parseFloat($.css(element[0], 'paddingRight', true)) || 0); } function hmargins(element) { return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) + (parseFloat($.css(element[0], 'marginRight', true)) || 0); } function hborders(element) { return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0); } function vsides(element, includeMargins) { return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0); } function vpadding(element) { return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) + (parseFloat($.css(element[0], 'paddingBottom', true)) || 0); } function vmargins(element) { return (parseFloat($.css(element[0], 'marginTop', true)) || 0) + (parseFloat($.css(element[0], 'marginBottom', true)) || 0); } function vborders(element) { return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0); } function setMinHeight(element, height) { height = (typeof height == 'number' ? height + 'px' : height); element.each(function(i, _element) { _element.style.cssText += ';min-height:' + height + ';_height:' + height; // why can't we just use .css() ? i forget }); } /* Misc Utils -----------------------------------------------------------------------------*/ //TODO: arraySlice //TODO: isFunction, grep ? function noop() { } function cmp(a, b) { return a - b; } function arrayMax(a) { return Math.max.apply(Math, a); } function zeroPad(n) { return (n < 10 ? '0' : '') + n; } function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object if (obj[name] !== undefined) { return obj[name]; } var parts = name.split(/(?=[A-Z])/), i=parts.length-1, res; for (; i>=0; i--) { res = obj[parts[i].toLowerCase()]; if (res !== undefined) { return res; } } return obj['']; } function htmlEscape(s) { return s.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#039;') .replace(/"/g, '&quot;') .replace(/\n/g, '<br />'); } function cssKey(_element) { return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); } function disableTextSelection(element) { element .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); } /* function enableTextSelection(element) { element .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); } */ function markFirstLast(e) { e.children() .removeClass('fc-first fc-last') .filter(':first-child') .addClass('fc-first') .end() .filter(':last-child') .addClass('fc-last'); } function setDayID(cell, date) { cell.each(function(i, _cell) { _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]); // TODO: make a way that doesn't rely on order of classes }); } function getSkinCss(event, opt) { var source = event.source || {}; var eventColor = event.color; var sourceColor = source.color; var optionColor = opt('eventColor'); var backgroundColor = event.backgroundColor || eventColor || source.backgroundColor || sourceColor || opt('eventBackgroundColor') || optionColor; var borderColor = event.borderColor || eventColor || source.borderColor || sourceColor || opt('eventBorderColor') || optionColor; var textColor = event.textColor || source.textColor || opt('eventTextColor'); var statements = []; if (backgroundColor) { statements.push('background-color:' + backgroundColor); } if (borderColor) { statements.push('border-color:' + borderColor); } if (textColor) { statements.push('color:' + textColor); } return statements.join(';'); } function applyAll(functions, thisObj, args) { if ($.isFunction(functions)) { functions = [ functions ]; } if (functions) { var i; var ret; for (i=0; i<functions.length; i++) { ret = functions[i].apply(thisObj, args) || ret; } return ret; } } function firstDefined() { for (var i=0; i<arguments.length; i++) { if (arguments[i] !== undefined) { return arguments[i]; } } } fcViews.month = MonthView; function MonthView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'month'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addMonths(date, delta); date.setDate(1); } var start = cloneDate(date, true); start.setDate(1); var end = addMonths(cloneDate(start), 1); var visStart = cloneDate(start); var visEnd = cloneDate(end); var firstDay = opt('firstDay'); var nwe = opt('weekends') ? 0 : 1; if (nwe) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7)); addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7); var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7)); if (opt('weekMode') == 'fixed') { addDays(visEnd, (6 - rowCnt) * 7); rowCnt = 6; } t.title = formatDate(start, opt('titleFormat')); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(6, rowCnt, nwe ? 5 : 7, true); } } fcViews.basicWeek = BasicWeekView; function BasicWeekView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'basicWeek'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDates = calendar.formatDates; function render(date, delta) { if (delta) { addDays(date, delta * 7); } var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); var end = addDays(cloneDate(start), 7); var visStart = cloneDate(start); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(1, 1, weekends ? 7 : 5, false); } } fcViews.basicDay = BasicDayView; //TODO: when calendar's date starts out on a weekend, shouldn't happen function BasicDayView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'basicDay'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = cloneDate(date, true); t.end = t.visEnd = addDays(cloneDate(t.start), 1); renderBasic(1, 1, 1, false); } } setDefaults({ weekMode: 'fixed' }); function BasicView(element, calendar, viewName) { var t = this; // exports t.renderBasic = renderBasic; t.setHeight = setHeight; t.setWidth = setWidth; t.renderDayOverlay = renderDayOverlay; t.defaultSelectionEnd = defaultSelectionEnd; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // for selection (kinda hacky) t.dragStart = dragStart; t.dragStop = dragStop; t.defaultEventEnd = defaultEventEnd; t.getHoverListener = function() { return hoverListener }; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = function() { return true }; t.allDayRow = allDayRow; t.allDayBounds = allDayBounds; t.getRowCnt = function() { return rowCnt }; t.getColCnt = function() { return colCnt }; t.getColWidth = function() { return colWidth }; t.getDaySegmentContainer = function() { return daySegmentContainer }; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); BasicEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var clearEvents = t.clearEvents; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var daySelectionMousedown = t.daySelectionMousedown; var formatDate = calendar.formatDate; // locals var head; var headCells; var body; var bodyRows; var bodyCells; var bodyFirstCells; var bodyCellTopInners; var daySegmentContainer; var viewWidth; var viewHeight; var colWidth; var rowCnt, colCnt; var coordinateGrid; var hoverListener; var colContentPositions; var rtl, dis, dit; var firstDay; var nwe; var tm; var colFormat; /* Rendering ------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-grid')); function renderBasic(maxr, r, c, showNumbers) { rowCnt = r; colCnt = c; updateOptions(); var firstTime = !body; if (firstTime) { buildSkeleton(maxr, showNumbers); }else{ clearEvents(); } updateCells(firstTime); } function updateOptions() { rtl = opt('isRTL'); if (rtl) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } firstDay = opt('firstDay'); nwe = opt('weekends') ? 0 : 1; tm = opt('theme') ? 'ui' : 'fc'; colFormat = opt('columnFormat'); } function buildSkeleton(maxRowCnt, showNumbers) { var s; var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var i, j; var table; s = "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + "<thead>" + "<tr>"; for (i=0; i<colCnt; i++) { s += "<th class='fc- " + headerClass + "'/>"; // need fc- for setDayID } s += "</tr>" + "</thead>" + "<tbody>"; for (i=0; i<maxRowCnt; i++) { s += "<tr class='fc-week" + i + "'>"; for (j=0; j<colCnt; j++) { s += "<td class='fc- " + contentClass + " fc-day" + (i*colCnt+j) + "'>" + // need fc- for setDayID "<div>" + (showNumbers ? "<div class='fc-day-number'/>" : '' ) + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "</tr>"; } s += "</tbody>" + "</table>"; table = $(s).appendTo(element); head = table.find('thead'); headCells = head.find('th'); body = table.find('tbody'); bodyRows = body.find('tr'); bodyCells = body.find('td'); bodyFirstCells = bodyCells.filter(':first-child'); bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div'); markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's markFirstLast(bodyRows); // marks first+last td's bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells dayBind(bodyCells); daySegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(element); } function updateCells(firstTime) { var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating? var month = t.start.getMonth(); var today = clearTime(new Date()); var cell; var date; var row; if (dowDirty) { headCells.each(function(i, _cell) { cell = $(_cell); date = indexDate(i); cell.html(formatDate(date, colFormat)); setDayID(cell, date); }); } bodyCells.each(function(i, _cell) { cell = $(_cell); date = indexDate(i); if (date.getMonth() == month) { cell.removeClass('fc-other-month'); }else{ cell.addClass('fc-other-month'); } if (+date == +today) { cell.addClass(tm + '-state-highlight fc-today'); }else{ cell.removeClass(tm + '-state-highlight fc-today'); } cell.find('div.fc-day-number').text(date.getDate()); if (dowDirty) { setDayID(cell, date); } }); bodyRows.each(function(i, _row) { row = $(_row); if (i < rowCnt) { row.show(); if (i == rowCnt-1) { row.addClass('fc-last'); }else{ row.removeClass('fc-last'); } }else{ row.hide(); } }); } function setHeight(height) { viewHeight = height; var bodyHeight = viewHeight - head.height(); var rowHeight; var rowHeightLast; var cell; if (opt('weekMode') == 'variable') { rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); }else{ rowHeight = Math.floor(bodyHeight / rowCnt); rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); } bodyFirstCells.each(function(i, _cell) { if (i < rowCnt) { cell = $(_cell); setMinHeight( cell.find('> div'), (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); } function setWidth(width) { viewWidth = width; colContentPositions.clear(); colWidth = Math.floor(viewWidth / colCnt); setOuterWidth(headCells.slice(0, -1), colWidth); } /* Day clicking and binding -----------------------------------------------------------*/ function dayBind(days) { days.click(dayClick) .mousedown(daySelectionMousedown); } function dayClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data var date = indexDate(index); trigger('dayClick', this, date, true, ev); } } /* Semi-transparent Overlay Helpers ------------------------------------------------------*/ function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var rowStart = cloneDate(t.visStart); var rowEnd = addDays(cloneDate(rowStart), colCnt); for (var i=0; i<rowCnt; i++) { var stretchStart = new Date(Math.max(rowStart, overlayStart)); var stretchEnd = new Date(Math.min(rowEnd, overlayEnd)); if (stretchStart < stretchEnd) { var colStart, colEnd; if (rtl) { colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1; colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1; }else{ colStart = dayDiff(stretchStart, rowStart); colEnd = dayDiff(stretchEnd, rowStart); } dayBind( renderCellOverlay(i, colStart, i, colEnd-1) ); } addDays(rowStart, 7); addDays(rowEnd, 7); } } function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive var rect = coordinateGrid.rect(row0, col0, row1, col1, element); return renderOverlay(rect, element); } /* Selection -----------------------------------------------------------------------*/ function defaultSelectionEnd(startDate, allDay) { return cloneDate(startDate); } function renderSelection(startDate, endDate, allDay) { renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time??? } function clearSelection() { clearOverlays(); } function reportDayClick(date, allDay, ev) { var cell = dateCell(date); var _element = bodyCells[cell.row*colCnt + cell.col]; trigger('dayClick', _element, date, allDay, ev); } /* External Dragging -----------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { var d = cellDate(cell); trigger('drop', _dragElement, d, true, ev, ui); } } /* Utilities --------------------------------------------------------*/ function defaultEventEnd(event) { return cloneDate(event.start); } coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; headCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); bodyRows.each(function(i, _e) { if (i < rowCnt) { e = $(_e); n = e.offset().top; if (i) { p[1] = n; } p = [n]; rows[i] = p; } }); p[1] = n + e.outerHeight(); }); hoverListener = new HoverListener(coordinateGrid); colContentPositions = new HorizontalPositionCache(function(col) { return bodyCellTopInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { return _cellDate(cell.row, cell.col); } function _cellDate(row, col) { return addDays(cloneDate(t.visStart), row*7 + col*dis+dit); // what about weekends in middle of week? } function indexDate(index) { return _cellDate(Math.floor(index/colCnt), index%colCnt); } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit; } function allDayRow(i) { return bodyRows.eq(i); } function allDayBounds(i) { return { left: 0, right: viewWidth }; } } function BasicEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileSegs; // for DayEventRenderer t.clearEvents = clearEvents; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var getDaySegmentContainer = t.getDaySegmentContainer; var getHoverListener = t.getHoverListener; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; /* Rendering --------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); renderDaySegs(compileSegs(events), modifiedEventId); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); } function compileSegs(events) { var rowCnt = getRowCnt(), colCnt = getColCnt(), d1 = cloneDate(t.visStart), d2 = addDays(cloneDate(d1), colCnt), visEventsEnds = $.map(events, exclEndDay), i, row, j, level, k, seg, segs=[]; for (i=0; i<rowCnt; i++) { row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2)); for (j=0; j<row.length; j++) { level = row[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.row = i; seg.level = j; // not needed anymore segs.push(seg); } } addDays(d1, 7); addDays(d2, 7); } return segs; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } /* Dragging ----------------------------------------------------------------------------*/ function draggableDayEvent(event, eventElement) { var hoverListener = getHoverListener(); var dayDelta; eventElement.draggable({ zIndex: 9, delay: 50, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta); clearOverlays(); if (cell) { //setOverflowHidden(true); dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1); renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ //setOverflowHidden(false); dayDelta = 0; } }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (dayDelta) { eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui); }else{ eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } //setOverflowHidden(false); } }); } } fcViews.agendaWeek = AgendaWeekView; function AgendaWeekView(element, calendar) { var t = this; // exports t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaWeek'); var opt = t.opt; var renderAgenda = t.renderAgenda; var formatDates = calendar.formatDates; function render(date, delta) { if (delta) { addDays(date, delta * 7); } var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); var end = addDays(cloneDate(start), 7); var visStart = cloneDate(start); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderAgenda(weekends ? 7 : 5); } } fcViews.agendaDay = AgendaDayView; function AgendaDayView(element, calendar) { var t = this; // exports t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaDay'); var opt = t.opt; var renderAgenda = t.renderAgenda; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } var start = cloneDate(date, true); var end = addDays(cloneDate(start), 1); t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = start; t.end = t.visEnd = end; renderAgenda(1); } } setDefaults({ allDaySlot: true, allDayText: 'all-day', firstHour: 6, slotMinutes: 30, defaultEventMinutes: 120, axisFormat: 'h(:mm)tt', timeFormat: { agenda: 'h:mm{ - h:mm}' }, dragOpacity: { agenda: .5 }, minTime: 0, maxTime: 24 }); // TODO: make it work in quirks mode (event corners, all-day height) // TODO: test liquid width, especially in IE6 function AgendaView(element, calendar, viewName) { var t = this; // exports t.renderAgenda = renderAgenda; t.setWidth = setWidth; t.setHeight = setHeight; t.beforeHide = beforeHide; t.afterShow = afterShow; t.defaultEventEnd = defaultEventEnd; t.timePosition = timePosition; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = cellIsAllDay; t.allDayRow = getAllDayRow; t.allDayBounds = allDayBounds; t.getHoverListener = function() { return hoverListener }; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getDaySegmentContainer = function() { return daySegmentContainer }; t.getSlotSegmentContainer = function() { return slotSegmentContainer }; t.getMinMinute = function() { return minMinute }; t.getMaxMinute = function() { return maxMinute }; t.getBodyContent = function() { return slotContent }; // !!?? t.getRowCnt = function() { return 1 }; t.getColCnt = function() { return colCnt }; t.getColWidth = function() { return colWidth }; t.getSlotHeight = function() { return slotHeight }; t.defaultSelectionEnd = defaultSelectionEnd; t.renderDayOverlay = renderDayOverlay; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // selection mousedown hack t.dragStart = dragStart; t.dragStop = dragStop; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); AgendaEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var clearEvents = t.clearEvents; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var reportSelection = t.reportSelection; var unselect = t.unselect; var daySelectionMousedown = t.daySelectionMousedown; var slotSegHtml = t.slotSegHtml; var formatDate = calendar.formatDate; // locals var dayTable; var dayHead; var dayHeadCells; var dayBody; var dayBodyCells; var dayBodyCellInners; var dayBodyFirstCell; var dayBodyFirstCellStretcher; var slotLayer; var daySegmentContainer; var allDayTable; var allDayRow; var slotScroller; var slotContent; var slotSegmentContainer; var slotTable; var slotTableFirstInner; var axisFirstCells; var gutterCells; var selectionHelper; var viewWidth; var viewHeight; var axisWidth; var colWidth; var gutterWidth; var slotHeight; // TODO: what if slotHeight changes? (see issue 650) var savedScrollTop; var colCnt; var slotCnt; var coordinateGrid; var hoverListener; var colContentPositions; var slotTopCache = {}; var tm; var firstDay; var nwe; // no weekends (int) var rtl, dis, dit; // day index sign / translate var minMinute, maxMinute; var colFormat; /* Rendering -----------------------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-agenda')); function renderAgenda(c) { colCnt = c; updateOptions(); if (!dayTable) { buildSkeleton(); }else{ clearEvents(); } updateCells(); } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; nwe = opt('weekends') ? 0 : 1; firstDay = opt('firstDay'); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } minMinute = parseTime(opt('minTime')); maxMinute = parseTime(opt('maxTime')); colFormat = opt('columnFormat'); } function buildSkeleton() { var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var s; var i; var d; var maxd; var minutes; var slotNormal = opt('slotMinutes') % 15 == 0; s = "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + "<thead>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID } s += "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" + "</tr>" + "</thead>" + "<tbody>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID "<div>" + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" + "</tr>" + "</tbody>" + "</table>"; dayTable = $(s).appendTo(element); dayHead = dayTable.find('thead'); dayHeadCells = dayHead.find('th').slice(1, -1); dayBody = dayTable.find('tbody'); dayBodyCells = dayBody.find('td').slice(0, -1); dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); dayBodyFirstCell = dayBodyCells.eq(0); dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); markFirstLast(dayHead.add(dayHead.find('tr'))); markFirstLast(dayBody.add(dayBody.find('tr'))); axisFirstCells = dayHead.find('th:first'); gutterCells = dayTable.find('.fc-agenda-gutter'); slotLayer = $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") .appendTo(element); if (opt('allDaySlot')) { daySegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotLayer); s = "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" + "<tr>" + "<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" + "<td>" + "<div class='fc-day-content'><div style='position:relative'/></div>" + "</td>" + "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" + "</tr>" + "</table>"; allDayTable = $(s).appendTo(slotLayer); allDayRow = allDayTable.find('tr'); dayBind(allDayRow.find('td')); axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); slotLayer.append( "<div class='fc-agenda-divider " + headerClass + "'>" + "<div class='fc-agenda-divider-inner'/>" + "</div>" ); }else{ daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() } slotScroller = $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>") .appendTo(slotLayer); slotContent = $("<div style='position:relative;width:100%;overflow:hidden'/>") .appendTo(slotScroller); slotSegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotContent); s = "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" + "<tbody>"; d = zeroDate(); maxd = addMinutes(cloneDate(d), maxMinute); addMinutes(d, minMinute); slotCnt = 0; for (i=0; d < maxd; i++) { minutes = d.getMinutes(); s += "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" + "<th class='fc-agenda-axis " + headerClass + "'>" + ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : '&nbsp;') + "</th>" + "<td class='" + contentClass + "'>" + "<div style='position:relative'>&nbsp;</div>" + "</td>" + "</tr>"; addMinutes(d, opt('slotMinutes')); slotCnt++; } s += "</tbody>" + "</table>"; slotTable = $(s).appendTo(slotContent); slotTableFirstInner = slotTable.find('div:first'); slotBind(slotTable.find('td')); axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); } function updateCells() { var i; var headCell; var bodyCell; var date; var today = clearTime(new Date()); for (i=0; i<colCnt; i++) { date = colDate(i); headCell = dayHeadCells.eq(i); headCell.html(formatDate(date, colFormat)); bodyCell = dayBodyCells.eq(i); if (+date == +today) { bodyCell.addClass(tm + '-state-highlight fc-today'); }else{ bodyCell.removeClass(tm + '-state-highlight fc-today'); } setDayID(headCell.add(bodyCell), date); } } function setHeight(height, dateChanged) { if (height === undefined) { height = viewHeight; } viewHeight = height; slotTopCache = {}; var headHeight = dayBody.position().top; var allDayHeight = slotScroller.position().top; // including divider var bodyHeight = Math.min( // total body height, including borders height - headHeight, // when scrollbars slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border ); dayBodyFirstCellStretcher .height(bodyHeight - vsides(dayBodyFirstCell)); slotLayer.css('top', headHeight); slotScroller.height(bodyHeight - allDayHeight - 1); slotHeight = slotTableFirstInner.height() + 1; // +1 for border if (dateChanged) { resetScroll(); } } function setWidth(width) { viewWidth = width; colContentPositions.clear(); axisWidth = 0; setOuterWidth( axisFirstCells .width('') .each(function(i, _cell) { axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); }), axisWidth ); var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) //slotTable.width(slotTableWidth); gutterWidth = slotScroller.width() - slotTableWidth; if (gutterWidth) { setOuterWidth(gutterCells, gutterWidth); gutterCells .show() .prev() .removeClass('fc-last'); }else{ gutterCells .hide() .prev() .addClass('fc-last'); } colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt); setOuterWidth(dayHeadCells.slice(0, -1), colWidth); } function resetScroll() { var d0 = zeroDate(); var scrollDate = cloneDate(d0); scrollDate.setHours(opt('firstHour')); var top = timePosition(d0, scrollDate) + 1; // +1 for the border function scroll() { slotScroller.scrollTop(top); } scroll(); setTimeout(scroll, 0); // overrides any previous scroll state made by the browser } function beforeHide() { savedScrollTop = slotScroller.scrollTop(); } function afterShow() { slotScroller.scrollTop(savedScrollTop); } /* Slot/Day clicking and binding -----------------------------------------------------------------------*/ function dayBind(cells) { cells.click(slotClick) .mousedown(daySelectionMousedown); } function slotBind(cells) { cells.click(slotClick) .mousedown(slotSelectionMousedown); } function slotClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth)); var date = colDate(col); var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data if (rowMatch) { var mins = parseInt(rowMatch[1]) * opt('slotMinutes'); var hours = Math.floor(mins/60); date.setHours(hours); date.setMinutes(mins%60 + minMinute); trigger('dayClick', dayBodyCells[col], date, false, ev); }else{ trigger('dayClick', dayBodyCells[col], date, true, ev); } } } /* Semi-transparent Overlay Helpers -----------------------------------------------------*/ function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var visStart = cloneDate(t.visStart); var startCol, endCol; if (rtl) { startCol = dayDiff(endDate, visStart)*dis+dit+1; endCol = dayDiff(startDate, visStart)*dis+dit+1; }else{ startCol = dayDiff(startDate, visStart); endCol = dayDiff(endDate, visStart); } startCol = Math.max(0, startCol); endCol = Math.min(colCnt, endCol); if (startCol < endCol) { dayBind( renderCellOverlay(0, startCol, 0, endCol-1) ); } } function renderCellOverlay(row0, col0, row1, col1) { // only for all-day? var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer); return renderOverlay(rect, slotLayer); } function renderSlotOverlay(overlayStart, overlayEnd) { var dayStart = cloneDate(t.visStart); var dayEnd = addDays(cloneDate(dayStart), 1); for (var i=0; i<colCnt; i++) { var stretchStart = new Date(Math.max(dayStart, overlayStart)); var stretchEnd = new Date(Math.min(dayEnd, overlayEnd)); if (stretchStart < stretchEnd) { var col = i*dis+dit; var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords var top = timePosition(dayStart, stretchStart); var bottom = timePosition(dayStart, stretchEnd); rect.top = top; rect.height = bottom - top; slotBind( renderOverlay(rect, slotContent) ); } addDays(dayStart, 1); addDays(dayEnd, 1); } } /* Coordinate Utilities -----------------------------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; dayHeadCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); if (opt('allDaySlot')) { e = allDayRow; n = e.offset().top; rows[0] = [n, n+e.outerHeight()]; } var slotTableTop = slotContent.offset().top; var slotScrollerTop = slotScroller.offset().top; var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight(); function constrain(n) { return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n)); } for (var i=0; i<slotCnt; i++) { rows.push([ constrain(slotTableTop + slotHeight*i), constrain(slotTableTop + slotHeight*(i+1)) ]); } }); hoverListener = new HoverListener(coordinateGrid); colContentPositions = new HorizontalPositionCache(function(col) { return dayBodyCellInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { // "cell" terminology is now confusing return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { var d = colDate(cell.col); var slotIndex = cell.row; if (opt('allDaySlot')) { slotIndex--; } if (slotIndex >= 0) { addMinutes(d, minMinute + slotIndex * opt('slotMinutes')); } return d; } function colDate(col) { // returns dates with 00:00:00 return addDays(cloneDate(t.visStart), col*dis+dit); } function cellIsAllDay(cell) { return opt('allDaySlot') && !cell.row; } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; } // get the Y coordinate of the given time on the given day (both Date objects) function timePosition(day, time) { // both date objects. day holds 00:00 of current day day = cloneDate(day, true); if (time < addMinutes(cloneDate(day), minMinute)) { return 0; } if (time >= addMinutes(cloneDate(day), maxMinute)) { return slotTable.height(); } var slotMinutes = opt('slotMinutes'), minutes = time.getHours()*60 + time.getMinutes() - minMinute, slotI = Math.floor(minutes / slotMinutes), slotTop = slotTopCache[slotI]; if (slotTop === undefined) { slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization??? } return Math.max(0, Math.round( slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) )); } function allDayBounds() { return { left: axisWidth, right: viewWidth - gutterWidth } } function getAllDayRow(index) { return allDayRow; } function defaultEventEnd(event) { var start = cloneDate(event.start); if (event.allDay) { return start; } return addMinutes(start, opt('defaultEventMinutes')); } /* Selection ---------------------------------------------------------------------------------*/ function defaultSelectionEnd(startDate, allDay) { if (allDay) { return cloneDate(startDate); } return addMinutes(cloneDate(startDate), opt('slotMinutes')); } function renderSelection(startDate, endDate, allDay) { // only for all-day if (allDay) { if (opt('allDaySlot')) { renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); } }else{ renderSlotSelection(startDate, endDate); } } function renderSlotSelection(startDate, endDate) { var helperOption = opt('selectHelper'); coordinateGrid.build(); if (helperOption) { var col = dayDiff(startDate, t.visStart) * dis + dit; if (col >= 0 && col < colCnt) { // only works when times are on same day var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords var top = timePosition(startDate, startDate); var bottom = timePosition(startDate, endDate); if (bottom > top) { // protect against selections that are entirely before or after visible range rect.top = top; rect.height = bottom - top; rect.left += 2; rect.width -= 5; if ($.isFunction(helperOption)) { var helperRes = helperOption(startDate, endDate); if (helperRes) { rect.position = 'absolute'; rect.zIndex = 8; selectionHelper = $(helperRes) .css(rect) .appendTo(slotContent); } }else{ rect.isStart = true; // conside rect a "seg" now rect.isEnd = true; // selectionHelper = $(slotSegHtml( { title: '', start: startDate, end: endDate, className: ['fc-select-helper'], editable: false }, rect )); selectionHelper.css('opacity', opt('dragOpacity')); } if (selectionHelper) { slotBind(selectionHelper); slotContent.append(selectionHelper); setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended setOuterHeight(selectionHelper, rect.height, true); } } } }else{ renderSlotOverlay(startDate, endDate); } } function clearSelection() { clearOverlays(); if (selectionHelper) { selectionHelper.remove(); selectionHelper = null; } } function slotSelectionMousedown(ev) { if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button unselect(ev); var dates; hoverListener.start(function(cell, origCell) { clearSelection(); if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) { var d1 = cellDate(origCell); var d2 = cellDate(cell); dates = [ d1, addMinutes(cloneDate(d1), opt('slotMinutes')), d2, addMinutes(cloneDate(d2), opt('slotMinutes')) ].sort(cmp); renderSlotSelection(dates[0], dates[3]); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], false, ev); } reportSelection(dates[0], dates[3], false, ev); } }); } } function reportDayClick(date, allDay, ev) { trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); } /* External Dragging --------------------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { if (cellIsAllDay(cell)) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); }else{ var d1 = cellDate(cell); var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); renderSlotOverlay(d1, d2); } } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); } } } function AgendaEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileDaySegs; // for DayEventRenderer t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var setHeight = t.setHeight; var getDaySegmentContainer = t.getDaySegmentContainer; var getSlotSegmentContainer = t.getSlotSegmentContainer; var getHoverListener = t.getHoverListener; var getMaxMinute = t.getMaxMinute; var getMinMinute = t.getMinMinute; var timePosition = t.timePosition; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSlotHeight = t.getSlotHeight; var getBodyContent = t.getBodyContent; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var eventResize = t.eventResize; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var calendar = t.calendar; var formatDate = calendar.formatDate; var formatDates = calendar.formatDates; /* Rendering ----------------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); var i, len=events.length, dayEvents=[], slotEvents=[]; for (i=0; i<len; i++) { if (events[i].allDay) { dayEvents.push(events[i]); }else{ slotEvents.push(events[i]); } } if (opt('allDaySlot')) { renderDaySegs(compileDaySegs(dayEvents), modifiedEventId); setHeight(); // no params means set to viewHeight } renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } function compileDaySegs(events) { var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)), i, levelCnt=levels.length, level, j, seg, segs=[]; for (i=0; i<levelCnt; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.row = 0; seg.level = i; // not needed anymore segs.push(seg); } } return segs; } function compileSlotSegs(events) { var colCnt = getColCnt(), minMinute = getMinMinute(), maxMinute = getMaxMinute(), d = addMinutes(cloneDate(t.visStart), minMinute), visEventEnds = $.map(events, slotEventEnd), i, col, j, level, k, seg, segs=[]; for (i=0; i<colCnt; i++) { col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute))); countForwardSegs(col); for (j=0; j<col.length; j++) { level = col[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.col = i; seg.level = j; segs.push(seg); } } addDays(d, 1, true); } return segs; } function slotEventEnd(event) { if (event.end) { return cloneDate(event.end); }else{ return addMinutes(cloneDate(event.start), opt('defaultEventMinutes')); } } // renders events in the 'time slots' at the bottom function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, classes, top, bottom, colI, levelI, forward, leftmost, availWidth, outerWidth, left, html='', eventElements, eventElement, triggerRes, vsideCache={}, hsideCache={}, key, val, contentElement, height, slotSegmentContainer = getSlotSegmentContainer(), rtl, dis, dit, colCnt = getColCnt(); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } // calculate position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; top = timePosition(seg.start, seg.start); bottom = timePosition(seg.start, seg.end); colI = seg.col; levelI = seg.level; forward = seg.forward || 0; leftmost = colContentLeft(colI*dis + dit); availWidth = colContentRight(colI*dis + dit) - leftmost; availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS if (levelI) { // indented and thin outerWidth = availWidth / (levelI + forward + 1); }else{ if (forward) { // moderately wide, aligned left still outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer = }else{ // can be entire width, aligned left outerWidth = availWidth; } } left = leftmost + // leftmost possible (availWidth / (levelI + forward + 1) * levelI) // indentation * dis + (rtl ? availWidth - outerWidth : 0); // rtl seg.top = top; seg.left = left; seg.outerWidth = outerWidth; seg.outerHeight = bottom - top; html += slotSegHtml(event, seg); } slotSegmentContainer[0].innerHTML = html; // faster than html() eventElements = slotSegmentContainer.children(); // retrieve elements, run through eventRender callback, bind event handlers for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; eventElement = $(eventElements[i]); // faster than eq() triggerRes = trigger('eventRender', event, event, eventElement); if (triggerRes === false) { eventElement.remove(); }else{ if (triggerRes && triggerRes !== true) { eventElement.remove(); eventElement = $(triggerRes) .css({ position: 'absolute', top: seg.top, left: seg.left }) .appendTo(slotSegmentContainer); } seg.element = eventElement; if (event._id === modifiedEventId) { bindSlotSeg(event, eventElement, seg); }else{ eventElement[0]._fci = i; // for lazySegBind } reportEventElement(event, eventElement); } } lazySegBind(slotSegmentContainer, segs, bindSlotSeg); // record event sides and title positions for (i=0; i<segCnt; i++) { seg = segs[i]; if (eventElement = seg.element) { val = vsideCache[key = seg.key = cssKey(eventElement[0])]; seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val; val = hsideCache[key]; seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val; contentElement = eventElement.find('div.fc-event-content'); if (contentElement.length) { seg.contentTop = contentElement[0].offsetTop; } } } // set all positions/dimensions at once for (i=0; i<segCnt; i++) { seg = segs[i]; if (eventElement = seg.element) { eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; height = Math.max(0, seg.outerHeight - seg.vsides); eventElement[0].style.height = height + 'px'; event = seg.event; if (seg.contentTop !== undefined && height - seg.contentTop < 10) { // not enough room for title, put it in the time header eventElement.find('div.fc-event-time') .text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title); eventElement.find('div.fc-event-title') .remove(); } trigger('eventAfterRender', event, event, eventElement); } } } function slotSegHtml(event, seg) { var html = "<"; var url = event.url; var skinCss = getSkinCss(event, opt); var skinCssAttr = (skinCss ? " style='" + skinCss + "'" : ''); var classes = ['fc-event', 'fc-event-skin', 'fc-event-vert']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (seg.isStart) { classes.push('fc-corner-top'); } if (seg.isEnd) { classes.push('fc-corner-bottom'); } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } if (url) { html += "a href='" + htmlEscape(event.url) + "'"; }else{ html += "div"; } html += " class='" + classes.join(' ') + "'" + " style='position:absolute;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner fc-event-skin'" + skinCssAttr + ">" + "<div class='fc-event-head fc-event-skin'" + skinCssAttr + ">" + "<div class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</div>" + "</div>" + "<div class='fc-event-content'>" + "<div class='fc-event-title'>" + htmlEscape(event.title) + "</div>" + "</div>" + "<div class='fc-event-bg'></div>" + "</div>"; // close inner if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-s'>=</div>"; } html += "</" + (url ? "a" : "div") + ">"; return html; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement, seg.isStart); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } function bindSlotSeg(event, eventElement, seg) { var timeElement = eventElement.find('div.fc-event-time'); if (isEventDraggable(event)) { draggableSlotEvent(event, eventElement, timeElement); } if (seg.isEnd && isEventResizable(event)) { resizableSlotEvent(event, eventElement, timeElement); } eventElementHandlers(event, eventElement); } /* Dragging -----------------------------------------------------------------------------------*/ // when event starts out FULL-DAY function draggableDayEvent(event, eventElement, isStart) { var origWidth; var revert; var allDay=true; var dayDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var slotHeight = getSlotHeight(); var minMinute = getMinMinute(); eventElement.draggable({ zIndex: 9, opacity: opt('dragOpacity', 'month'), // use whatever the month view was using revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origWidth = eventElement.width(); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { clearOverlays(); if (cell) { //setOverflowHidden(true); revert = false; dayDelta = colDelta * dis; if (!cell.row) { // on full-days renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); resetElement(); }else{ // mouse is over bottom slots if (isStart) { if (allDay) { // convert event to temporary slot-event eventElement.width(colWidth - 10); // don't use entire width setOuterHeight( eventElement, slotHeight * Math.round( (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) / opt('slotMinutes') ) ); eventElement.draggable('option', 'grid', [colWidth, 1]); allDay = false; } }else{ revert = true; } } revert = revert || (allDay && !dayDelta); }else{ resetElement(); //setOverflowHidden(false); revert = true; } eventElement.draggable('option', 'revert', revert); }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (revert) { // hasn't moved or is out of bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); }else{ // changed! var minuteDelta = 0; if (!allDay) { minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight) * opt('slotMinutes') + minMinute - (event.start.getHours() * 60 + event.start.getMinutes()); } eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); } //setOverflowHidden(false); } }); function resetElement() { if (!allDay) { eventElement .width(origWidth) .height('') .draggable('option', 'grid', null); allDay = true; } } } // when event starts out IN TIMESLOTS function draggableSlotEvent(event, eventElement, timeElement) { var origPosition; var allDay=false; var dayDelta; var minuteDelta; var prevMinuteDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colCnt = getColCnt(); var colWidth = getColWidth(); var slotHeight = getSlotHeight(); eventElement.draggable({ zIndex: 9, scroll: false, grid: [colWidth, slotHeight], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origPosition = eventElement.position(); minuteDelta = prevMinuteDelta = 0; hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell); clearOverlays(); if (cell) { dayDelta = colDelta * dis; if (opt('allDaySlot') && !cell.row) { // over full days if (!allDay) { // convert to temporary all-day event allDay = true; timeElement.hide(); eventElement.draggable('option', 'grid', null); } renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ // on slots resetElement(); } } }, ev, 'drag'); }, drag: function(ev, ui) { minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes'); if (minuteDelta != prevMinuteDelta) { if (!allDay) { updateTimeText(minuteDelta); } prevMinuteDelta = minuteDelta; } }, stop: function(ev, ui) { var cell = hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (cell && (dayDelta || minuteDelta || allDay)) { // changed! eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); }else{ // either no change or out-of-bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position updateTimeText(0); showEvents(event, eventElement); } } }); function updateTimeText(minuteDelta) { var newStart = addMinutes(cloneDate(event.start), minuteDelta); var newEnd; if (event.end) { newEnd = addMinutes(cloneDate(event.end), minuteDelta); } timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); } function resetElement() { // convert back to original slot-event if (allDay) { timeElement.css('display', ''); // show() was causing display=inline eventElement.draggable('option', 'grid', [colWidth, slotHeight]); allDay = false; } } } /* Resizing --------------------------------------------------------------------------------------*/ function resizableSlotEvent(event, eventElement, timeElement) { var slotDelta, prevSlotDelta; var slotHeight = getSlotHeight(); eventElement.resizable({ handles: { s: 'div.ui-resizable-s' }, grid: slotHeight, start: function(ev, ui) { slotDelta = prevSlotDelta = 0; hideEvents(event, eventElement); eventElement.css('z-index', 9); trigger('eventResizeStart', this, event, ev, ui); }, resize: function(ev, ui) { // don't rely on ui.size.height, doesn't take grid into account slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight); if (slotDelta != prevSlotDelta) { timeElement.text( formatDates( event.start, (!slotDelta && !event.end) ? null : // no change, so don't display time range addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta), opt('timeFormat') ) ); prevSlotDelta = slotDelta; } }, stop: function(ev, ui) { trigger('eventResizeStop', this, event, ev, ui); if (slotDelta) { eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui); }else{ eventElement.css('z-index', 8); showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } } }); } } function countForwardSegs(levels) { var i, j, k, level, segForward, segBack; for (i=levels.length-1; i>0; i--) { level = levels[i]; for (j=0; j<level.length; j++) { segForward = level[j]; for (k=0; k<levels[i-1].length; k++) { segBack = levels[i-1][k]; if (segsCollide(segForward, segBack)) { segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1); } } } } } function View(element, calendar, viewName) { var t = this; // exports t.element = element; t.calendar = calendar; t.name = viewName; t.opt = opt; t.trigger = trigger; //t.setOverflowHidden = setOverflowHidden; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; t.reportEvents = reportEvents; t.eventEnd = eventEnd; t.reportEventElement = reportEventElement; t.reportEventClear = reportEventClear; t.eventElementHandlers = eventElementHandlers; t.showEvents = showEvents; t.hideEvents = hideEvents; t.eventDrop = eventDrop; t.eventResize = eventResize; // t.title // t.start, t.end // t.visStart, t.visEnd // imports var defaultEventEnd = t.defaultEventEnd; var normalizeEvent = calendar.normalizeEvent; // in EventManager var reportEventChange = calendar.reportEventChange; // locals var eventsByID = {}; var eventElements = []; var eventElementsByID = {}; var options = calendar.options; function opt(name, viewNameOverride) { var v = options[name]; if (typeof v == 'object') { return smartProperty(v, viewNameOverride || viewName); } return v; } function trigger(name, thisObj) { return calendar.trigger.apply( calendar, [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t]) ); } /* function setOverflowHidden(bool) { element.css('overflow', bool ? 'hidden' : ''); } */ function isEventDraggable(event) { return isEventEditable(event) && !opt('disableDragging'); } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true return isEventEditable(event) && !opt('disableResizing'); } function isEventEditable(event) { return firstDefined(event.editable, (event.source || {}).editable, opt('editable')); } /* Event Data ------------------------------------------------------------------------------*/ // report when view receives new events function reportEvents(events) { // events are already normalized at this point eventsByID = {}; var i, len=events.length, event; for (i=0; i<len; i++) { event = events[i]; if (eventsByID[event._id]) { eventsByID[event._id].push(event); }else{ eventsByID[event._id] = [event]; } } } // returns a Date object for an event's end function eventEnd(event) { return event.end ? cloneDate(event.end) : defaultEventEnd(event); } /* Event Elements ------------------------------------------------------------------------------*/ // report when view creates an element for an event function reportEventElement(event, element) { eventElements.push(element); if (eventElementsByID[event._id]) { eventElementsByID[event._id].push(element); }else{ eventElementsByID[event._id] = [element]; } } function reportEventClear() { eventElements = []; eventElementsByID = {}; } // attaches eventClick, eventMouseover, eventMouseout function eventElementHandlers(event, eventElement) { eventElement .click(function(ev) { if (!eventElement.hasClass('ui-draggable-dragging') && !eventElement.hasClass('ui-resizable-resizing')) { return trigger('eventClick', this, event, ev); } }) .hover( function(ev) { trigger('eventMouseover', this, event, ev); }, function(ev) { trigger('eventMouseout', this, event, ev); } ); // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element) // TODO: same for resizing } function showEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'show'); } function hideEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'hide'); } function eachEventElement(event, exceptElement, funcName) { var elements = eventElementsByID[event._id], i, len = elements.length; for (i=0; i<len; i++) { if (!exceptElement || elements[i][0] != exceptElement[0]) { elements[i][funcName](); } } } /* Event Modification Reporting ---------------------------------------------------------------------------------*/ function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) { var oldAllDay = event.allDay; var eventId = event._id; moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay); trigger( 'eventDrop', e, event, dayDelta, minuteDelta, allDay, function() { // TODO: investigate cases where this inverse technique might not work moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay); reportEventChange(eventId); }, ev, ui ); reportEventChange(eventId); } function eventResize(e, event, dayDelta, minuteDelta, ev, ui) { var eventId = event._id; elongateEvents(eventsByID[eventId], dayDelta, minuteDelta); trigger( 'eventResize', e, event, dayDelta, minuteDelta, function() { // TODO: investigate cases where this inverse technique might not work elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta); reportEventChange(eventId); }, ev, ui ); reportEventChange(eventId); } /* Event Modification Math ---------------------------------------------------------------------------------*/ function moveEvents(events, dayDelta, minuteDelta, allDay) { minuteDelta = minuteDelta || 0; for (var e, len=events.length, i=0; i<len; i++) { e = events[i]; if (allDay !== undefined) { e.allDay = allDay; } addMinutes(addDays(e.start, dayDelta, true), minuteDelta); if (e.end) { e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta); } normalizeEvent(e, options); } } function elongateEvents(events, dayDelta, minuteDelta) { minuteDelta = minuteDelta || 0; for (var e, len=events.length, i=0; i<len; i++) { e = events[i]; e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta); normalizeEvent(e, options); } } } function DayEventRenderer() { var t = this; // exports t.renderDaySegs = renderDaySegs; t.resizableDayEvent = resizableDayEvent; // imports var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventResize = t.eventResize; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var allDayRow = t.allDayRow; var allDayBounds = t.allDayBounds; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var dayOfWeekCol = t.dayOfWeekCol; var dateCell = t.dateCell; var compileDaySegs = t.compileDaySegs; var getDaySegmentContainer = t.getDaySegmentContainer; var bindDaySeg = t.bindDaySeg; //TODO: streamline this var formatDates = t.calendar.formatDates; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var clearSelection = t.clearSelection; /* Rendering -----------------------------------------------------------------------------*/ function renderDaySegs(segs, modifiedEventId) { var segmentContainer = getDaySegmentContainer(); var rowDivs; var rowCnt = getRowCnt(); var colCnt = getColCnt(); var i = 0; var rowI; var levelI; var colHeights; var j; var segCnt = segs.length; var seg; var top; var k; segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html() daySegElementResolve(segs, segmentContainer.children()); daySegElementReport(segs); daySegHandlers(segs, segmentContainer, modifiedEventId); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); rowDivs = getRowDivs(); // set row heights, calculate event tops (in relation to row top) for (rowI=0; rowI<rowCnt; rowI++) { levelI = 0; colHeights = []; for (j=0; j<colCnt; j++) { colHeights[j] = 0; } while (i<segCnt && (seg = segs[i]).row == rowI) { // loop through segs in a row top = arrayMax(colHeights.slice(seg.startCol, seg.endCol)); seg.top = top; top += seg.outerHeight; for (k=seg.startCol; k<seg.endCol; k++) { colHeights[k] = top; } i++; } rowDivs[rowI].height(arrayMax(colHeights)); } daySegSetTops(segs, getRowTops(rowDivs)); } function renderTempDaySegs(segs, adjustRow, adjustTop) { var tempContainer = $("<div/>"); var elements; var segmentContainer = getDaySegmentContainer(); var i; var segCnt = segs.length; var element; tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() elements = tempContainer.children(); segmentContainer.append(elements); daySegElementResolve(segs, elements); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); daySegSetTops(segs, getRowTops(getRowDivs())); elements = []; for (i=0; i<segCnt; i++) { element = segs[i].element; if (element) { if (segs[i].row === adjustRow) { element.css('top', adjustTop); } elements.push(element[0]); } } return $(elements); } function daySegHTML(segs) { // also sets seg.left and seg.outerWidth var rtl = opt('isRTL'); var i; var segCnt=segs.length; var seg; var event; var url; var classes; var bounds = allDayBounds(); var minLeft = bounds.left; var maxLeft = bounds.right; var leftCol; var rightCol; var left; var right; var skinCss; var html = ''; // calculate desired position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; classes = ['fc-event', 'fc-event-skin', 'fc-event-hori']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (rtl) { if (seg.isStart) { classes.push('fc-corner-right'); } if (seg.isEnd) { classes.push('fc-corner-left'); } leftCol = dayOfWeekCol(seg.end.getDay()-1); rightCol = dayOfWeekCol(seg.start.getDay()); left = seg.isEnd ? colContentLeft(leftCol) : minLeft; right = seg.isStart ? colContentRight(rightCol) : maxLeft; }else{ if (seg.isStart) { classes.push('fc-corner-left'); } if (seg.isEnd) { classes.push('fc-corner-right'); } leftCol = dayOfWeekCol(seg.start.getDay()); rightCol = dayOfWeekCol(seg.end.getDay()-1); left = seg.isStart ? colContentLeft(leftCol) : minLeft; right = seg.isEnd ? colContentRight(rightCol) : maxLeft; } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } url = event.url; skinCss = getSkinCss(event, opt); if (url) { html += "<a href='" + htmlEscape(url) + "'"; }else{ html += "<div"; } html += " class='" + classes.join(' ') + "'" + " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" + ">" + "<div" + " class='fc-event-inner fc-event-skin'" + (skinCss ? " style='" + skinCss + "'" : '') + ">"; if (!event.allDay && seg.isStart) { html += "<span class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</span>"; } html += "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" + "</div>"; if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" + "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7 "</div>"; } html += "</" + (url ? "a" : "div" ) + ">"; seg.left = left; seg.outerWidth = right - left; seg.startCol = leftCol; seg.endCol = rightCol + 1; // needs to be exclusive } return html; } function daySegElementResolve(segs, elements) { // sets seg.element var i; var segCnt = segs.length; var seg; var event; var element; var triggerRes; for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; element = $(elements[i]); // faster than .eq() triggerRes = trigger('eventRender', event, event, element); if (triggerRes === false) { element.remove(); }else{ if (triggerRes && triggerRes !== true) { triggerRes = $(triggerRes) .css({ position: 'absolute', left: seg.left }); element.replaceWith(triggerRes); element = triggerRes; } seg.element = element; } } } function daySegElementReport(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { reportEventElement(seg.event, element); } } } function daySegHandlers(segs, segmentContainer, modifiedEventId) { var i; var segCnt = segs.length; var seg; var element; var event; // retrieve elements, run through eventRender callback, bind handlers for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { event = seg.event; if (event._id === modifiedEventId) { bindDaySeg(event, element, seg); }else{ element[0]._fci = i; // for lazySegBind } } } lazySegBind(segmentContainer, segs, bindDaySeg); } function daySegCalcHSides(segs) { // also sets seg.key var i; var segCnt = segs.length; var seg; var element; var key, val; var hsideCache = {}; // record event horizontal sides for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key = cssKey(element[0]); val = hsideCache[key]; if (val === undefined) { val = hsideCache[key] = hsides(element, true); } seg.hsides = val; } } } function daySegSetWidths(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; } } } function daySegCalcHeights(segs) { var i; var segCnt = segs.length; var seg; var element; var key, val; var vmarginCache = {}; // record event heights for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key; // created in daySegCalcHSides val = vmarginCache[key]; if (val === undefined) { val = vmarginCache[key] = vmargins(element); } seg.outerHeight = element[0].offsetHeight + val; } } } function getRowDivs() { var i; var rowCnt = getRowCnt(); var rowDivs = []; for (i=0; i<rowCnt; i++) { rowDivs[i] = allDayRow(i) .find('td:first div.fc-day-content > div'); // optimal selector? } return rowDivs; } function getRowTops(rowDivs) { var i; var rowCnt = rowDivs.length; var tops = []; for (i=0; i<rowCnt; i++) { tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!! } return tops; } function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender var i; var segCnt = segs.length; var seg; var element; var event; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px'; event = seg.event; trigger('eventAfterRender', event, event, element); } } } /* Resizing -----------------------------------------------------------------------------------*/ function resizableDayEvent(event, element, seg) { var rtl = opt('isRTL'); var direction = rtl ? 'w' : 'e'; var handle = element.find('div.ui-resizable-' + direction); var isResizing = false; // TODO: look into using jquery-ui mouse widget for this stuff disableTextSelection(element); // prevent native <a> selection for IE element .mousedown(function(ev) { // prevent native <a> selection for others ev.preventDefault(); }) .click(function(ev) { if (isResizing) { ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called // (eventElementHandlers needs to be bound after resizableDayEvent) } }); handle.mousedown(function(ev) { if (ev.which != 1) { return; // needs to be left mouse button } isResizing = true; var hoverListener = t.getHoverListener(); var rowCnt = getRowCnt(); var colCnt = getColCnt(); var dis = rtl ? -1 : 1; var dit = rtl ? colCnt-1 : 0; var elementTop = element.css('top'); var dayDelta; var helpers; var eventCopy = $.extend({}, event); var minCell = dateCell(event.start); clearSelection(); $('body') .css('cursor', direction + '-resize') .one('mouseup', mouseup); trigger('eventResizeStart', this, event, ev); hoverListener.start(function(cell, origCell) { if (cell) { var r = Math.max(minCell.row, cell.row); var c = cell.col; if (rowCnt == 1) { r = 0; // hack for all-day area in agenda views } if (r == minCell.row) { if (rtl) { c = Math.min(minCell.col, c); }else{ c = Math.max(minCell.col, c); } } dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); var newEnd = addDays(eventEnd(event), dayDelta, true); if (dayDelta) { eventCopy.end = newEnd; var oldHelpers = helpers; helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); helpers.find('*').css('cursor', direction + '-resize'); if (oldHelpers) { oldHelpers.remove(); } hideEvents(event); }else{ if (helpers) { showEvents(event); helpers.remove(); helpers = null; } } clearOverlays(); renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start } }, ev); function mouseup(ev) { trigger('eventResizeStop', this, event, ev); $('body').css('cursor', ''); hoverListener.stop(); clearOverlays(); if (dayDelta) { eventResize(this, event, dayDelta, 0, ev); // event redraw will clear helpers } // otherwise, the drag handler already restored the old events setTimeout(function() { // make this happen after the element's click event isResizing = false; },0); } }); } } //BUG: unselect needs to be triggered when events are dragged+dropped function SelectionManager() { var t = this; // exports t.select = select; t.unselect = unselect; t.reportSelection = reportSelection; t.daySelectionMousedown = daySelectionMousedown; // imports var opt = t.opt; var trigger = t.trigger; var defaultSelectionEnd = t.defaultSelectionEnd; var renderSelection = t.renderSelection; var clearSelection = t.clearSelection; // locals var selected = false; // unselectAuto if (opt('selectable') && opt('unselectAuto')) { $(document).mousedown(function(ev) { var ignore = opt('unselectCancel'); if (ignore) { if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match return; } } unselect(ev); }); } function select(startDate, endDate, allDay) { unselect(); if (!endDate) { endDate = defaultSelectionEnd(startDate, allDay); } renderSelection(startDate, endDate, allDay); reportSelection(startDate, endDate, allDay); } function unselect(ev) { if (selected) { selected = false; clearSelection(); trigger('unselect', null, ev); } } function reportSelection(startDate, endDate, allDay, ev) { selected = true; trigger('select', null, startDate, endDate, allDay, ev); } function daySelectionMousedown(ev) { // not really a generic manager method, oh well var cellDate = t.cellDate; var cellIsAllDay = t.cellIsAllDay; var hoverListener = t.getHoverListener(); var reportDayClick = t.reportDayClick; // this is hacky and sort of weird if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button unselect(ev); var _mousedownElement = this; var dates; hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell clearSelection(); if (cell && cellIsAllDay(cell)) { dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); renderSelection(dates[0], dates[1], true); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], true, ev); } reportSelection(dates[0], dates[1], true, ev); } }); } } } function OverlayManager() { var t = this; // exports t.renderOverlay = renderOverlay; t.clearOverlays = clearOverlays; // locals var usedOverlays = []; var unusedOverlays = []; function renderOverlay(rect, parent) { var e = unusedOverlays.shift(); if (!e) { e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"); } if (e[0].parentNode != parent[0]) { e.appendTo(parent); } usedOverlays.push(e.css(rect).show()); return e; } function clearOverlays() { var e; while (e = usedOverlays.shift()) { unusedOverlays.push(e.hide().unbind()); } } } function CoordinateGrid(buildFunc) { var t = this; var rows; var cols; t.build = function() { rows = []; cols = []; buildFunc(rows, cols); }; t.cell = function(x, y) { var rowCnt = rows.length; var colCnt = cols.length; var i, r=-1, c=-1; for (i=0; i<rowCnt; i++) { if (y >= rows[i][0] && y < rows[i][1]) { r = i; break; } } for (i=0; i<colCnt; i++) { if (x >= cols[i][0] && x < cols[i][1]) { c = i; break; } } return (r>=0 && c>=0) ? { row:r, col:c } : null; }; t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive var origin = originElement.offset(); return { top: rows[row0][0] - origin.top, left: cols[col0][0] - origin.left, width: cols[col1][1] - cols[col0][0], height: rows[row1][1] - rows[row0][0] }; }; } function HoverListener(coordinateGrid) { var t = this; var bindType; var change; var firstCell; var cell; t.start = function(_change, ev, _bindType) { change = _change; firstCell = cell = null; coordinateGrid.build(); mouse(ev); bindType = _bindType || 'mousemove'; $(document).bind(bindType, mouse); }; function mouse(ev) { var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) { if (newCell) { if (!firstCell) { firstCell = newCell; } change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); }else{ change(newCell, firstCell); } cell = newCell; } } t.stop = function() { $(document).unbind(bindType, mouse); return cell; }; } function HorizontalPositionCache(getElement) { var t = this, elements = {}, lefts = {}, rights = {}; function e(i) { return elements[i] = elements[i] || getElement(i); } t.left = function(i) { return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i]; }; t.right = function(i) { return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i]; }; t.clear = function() { elements = {}; lefts = {}; rights = {}; }; } })(jQuery); /* * FullCalendar v1.5.1 Google Calendar Plugin * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Sat Apr 9 14:09:51 2011 -0700 * */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.sourceNormalizers.push(function(sourceOptions) { if (sourceOptions.dataType == 'gcal' || sourceOptions.dataType === undefined && (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { sourceOptions.dataType = 'gcal'; if (sourceOptions.editable === undefined) { sourceOptions.editable = false; } } }); fc.sourceFetchers.push(function(sourceOptions, start, end) { if (sourceOptions.dataType == 'gcal') { return transformOptions(sourceOptions, start, end); } }); function transformOptions(sourceOptions, start, end) { var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { 'start-min': formatDate(start, 'u'), 'start-max': formatDate(end, 'u'), 'singleevents': true, 'max-results': 9999 }); var ctz = sourceOptions.currentTimezone; if (ctz) { data.ctz = ctz = ctz.replace(' ', '_'); } return $.extend({}, sourceOptions, { url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', dataType: 'jsonp', data: data, startParam: false, endParam: false, success: function(data) { var events = []; if (data.feed.entry) { $.each(data.feed.entry, function(i, entry) { var startStr = entry['gd$when'][0]['startTime']; var start = parseISO8601(startStr, true); var end = parseISO8601(entry['gd$when'][0]['endTime'], true); var allDay = startStr.indexOf('T') == -1; var url; $.each(entry.link, function(i, link) { if (link.type == 'text/html') { url = link.href; if (ctz) { url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz; } } }); if (allDay) { addDays(end, -1); // make inclusive } events.push({ id: entry['gCal$uid']['value'], title: entry['title']['$t'], url: url, start: start, end: end, allDay: allDay, location: entry['gd$where'][0]['valueString'], description: entry['content']['$t'] }); }); } var args = [events].concat(Array.prototype.slice.call(arguments, 1)); var res = applyAll(success, this, args); if ($.isArray(res)) { return res; } return events; } }); } // legacy fc.gcalFeed = function(url, sourceOptions) { return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); }; })(jQuery); });
08102013project
trunk/CMS/Scripts/plugins/calendar.js
JavaScript
oos
137,464
/*----------------------------------------------------------------------*/ /* wl_Fileexplorer v 1.0 by revaxarts.com /* description: makes a Fileexplorer /* dependency: elFinder plugin (elfinder.js) /*----------------------------------------------------------------------*/ $.fn.wl_Fileexplorer = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Fileexplorer.methods[method]) { return $.fn.wl_Fileexplorer.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Fileexplorer')) { var opts = $.extend({}, $this.data('wl_Fileexplorer'), method); } else { var opts = $.extend({}, $.fn.wl_Fileexplorer.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Fileexplorer')) { $this.data('wl_Fileexplorer', {}); //simple: call the plugin! //this has potential. maybe there are some options in future updates $this.elfinder(opts); } else { } if (opts) $.extend($this.data('wl_Fileexplorer'), opts); }); }; $.fn.wl_Fileexplorer.defaults = { url: 'elfinder/php/connector.php', toolbar: [ ['back', 'reload', 'open', 'select', 'quicklook', 'info', 'rename', 'copy', 'cut', 'paste', 'rm', 'mkdir', 'mkfile', 'upload', 'duplicate', 'edit', 'archive', 'extract', 'resize', 'icons', 'list', 'help'] ] }; $.fn.wl_Fileexplorer.version = '1.0'; $.fn.wl_Fileexplorer.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Fileexplorer.defaults[key] !== undefined || $.fn.wl_Fileexplorer.defaults[key] == null) { $this.data('wl_Fileexplorer')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Fileexplorer.js
JavaScript
oos
2,116
/*----------------------------------------------------------------------*/ /* wl_Chart v 1.3 by revaxarts.com /* description: extends the flot library /* dependency: flot library /*----------------------------------------------------------------------*/ $.fn.wl_Chart = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Chart.methods[method]) { return $.fn.wl_Chart.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Chart')) { var opts = $.extend({}, $this.data('wl_Chart'), method); } else { var opts = $.extend({}, $.fn.wl_Chart.defaults, method, $this.data()); } } else { try { return $this.data('wl_Chart').plot[method](args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } //throw an error if wrong chart typ is set if (!/^(lines|bars|pie)$/.test(opts.type)) { $.error('Type of "' + opts.type + '" is not allowed'); } if (!$this.data('wl_Chart')) { $this.data('wl_Chart', {}); //bind a resize event to redraw the chart if the window size change $(window).bind('resize.wl_Chart', function () { $this.data('wl_Chart').holder.width('99%'); $.fn.wl_Chart.methods.draw.call($this[0]); }); //make a holder for the chart and set the width too 99% (100% causes overflow problems in some browsers) opts.holder = $('<div/>', { 'class': 'chart' }).css({ width: (opts.width || $this.width() || '100%') / 100 * 99, height: opts.height || 300 })[(opts.tableBefore) ? 'insertAfter' : 'insertBefore']($this); } else { //quick destroy opts.holder.unbind("plothover").unbind('mouseout'); } //set the width opts.width = opts.holder.width(); //show or hide the table (opts.hideTable) ? $this.hide() : $this.show(); //bind the click event on the stats opts.holder.bind("plotclick", function (event, pos, item) { if (item) { var patt = {}; switch (opts.type) { case 'bars': patt['value'] = item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.dataIndex].label; patt['id'] = item.seriesIndex; break; case 'pie': patt['value'] = item.datapoint[1][0][1]; patt['label'] = item.series.xaxis.options.ticks[0][1]; patt['id'] = item.seriesIndex; break; default: patt['value'] = item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.datapoint[0]].label; patt['id'] = item.seriesIndex; } patt['legend'] = item.series.label; opts.onClick.call($this[0], patt['value'], patt['legend'], patt['label'], patt['id'], item); } }); //We have a tooltip if (opts.tooltip) { //attach the tipsy tooltip to the holder opts.holder.tipsy($.extend({}, config.tooltip, { fallback: '', followMouse: true, gravity: opts.tooltipGravity || 'n' })); var prev = null, text; //bind a hover event to the graph opts.holder.bind("plothover", function (e, pos, item) { if (item) { //check if we don't have to do the same stuff more then once if (item.datapoint.toString() != prev) { var patt = {}; prev = item.datapoint.toString(); switch (opts.type) { case 'bars': //stacked bars have an offset (http://support.revaxarts-themes.com/discussion/165/tooltip-on-a-stacked-chart) patt['value'] = (opts.stack) ? item.datapoint[1]-item.datapoint[2] : item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.dataIndex].label; patt['id'] = item.seriesIndex; break; case 'pie': patt['value'] = item.datapoint[1][0][1]; patt['label'] = item.series.xaxis.options.ticks[0][1]; patt['id'] = item.seriesIndex; break; default: patt['value'] = item.datapoint[1]; patt['label'] = item.series.xaxis.ticks[item.datapoint[0]].label; patt['id'] = item.seriesIndex; } patt['legend'] = item.series.label; //is the pattern a function or a simple string? if ($.isFunction(opts.tooltipPattern)) { text = opts.tooltipPattern.call($this[0], patt['value'], patt['legend'], patt['label'], patt['id'], item); } else { text = opts.tooltipPattern.replace(/%1/g, patt['value']).replace(/%2/g, patt['legend']).replace(/%3/g, patt['label']).replace(/%4/g, patt['id']); } //set the title and show the tooltip opts.holder.tipsy('setTitel', text); opts.holder.tipsy('show'); } else { return; } } else { //hide tooltip if we leave the point opts.holder.tipsy('hide'); prev = null; } }).bind('mouseout', function () { //hide tooltip if we leave the plot opts.holder.tipsy('hide'); prev = null; }); } //the colors are maybe not an array if they a specified within a data attribute if (!$.isArray(opts.colors)) { opts.colors = $.parseData(opts.colors, true); } var colors = []; //a data object is set (no table) if (!$.isEmptyObject(opts.data)) { //labels on the x axis are set if (opts.xlabels) { //convert them in the proper format opts.xlabels = $.map(opts.xlabels, function (value, key) { return [[key, value]]; }); //no labels are set } else { //get labels out of the data opts.xlabels = function () { var ret = []; $.each(opts.data, function (i, e) { $.map(opts.data[i].data, function (value, key) { ret[value[0]] = key; }); }); return $.map(ret, function (value, key) { return key; }); }(); } //define colors in a loop colors = $.map(opts.data, function (value, key) { return opts.colors[key % opts.colors.length]; }); //data is from a table } else if ($.isEmptyObject(opts.data) && $this.is('table')) { opts.xlabels = opts.xlabels || []; opts.data = []; switch (opts.orientation) { //table is in horizontal mode (normal) case 'horizontal': var $xlabels = $this.find('thead th'), $legends = $this.find('tbody th'), $rows = $this.find('tbody tr'); var legendlength = $legends.length; //strip the very first cell because it's not necessary if (legendlength) $xlabels = $xlabels.slice(1); //fetch each row of the table $rows.each(function (i, row) { var data = $(row).find('td'), _d = []; //fetch each cell of the row data.each(function (j, td) { var d = parseFloat(td.innerHTML); //only numbers are valid if (!isNaN(d)) _d.push([j, (d || 0)]); //some stuff for the labels on the x axis opts.xlabels.push([j, $xlabels.eq(j).text()]); }); //push the data in the data-object for this row (label) opts.data.push({ 'label': $legends.eq(i).text(), 'data': (opts.type != 'pie') ? _d : _d[0][1] }); //define colors in a loop colors[i] = $rows.eq(i).data('color') || opts.colors[i] || colors[i % opts.colors.length]; }); break; //table is in vertical mode case 'vertical': var $xlabels = $this.find('tbody th'), $legends = $this.find('thead th'), $rows = $this.find('tbody tr'); var legendlength = $legends.length; if (legendlength) { $legends = $legends.slice(1); legendlength--; } var _d = []; //fetch each row of the table $rows.each(function (i, row) { var data = $(row).find('td'); data.each(function (j, td) { var d = parseFloat(td.innerHTML); _d[j] = _d[j] || []; //only numbers are valid if (!isNaN(d)) _d[j].push([i, (d || 0)]); }); //some stuff for the labels on the x axis opts.xlabels.push([i, $xlabels.eq(i).text()]); }); //push the data in the data-object for this row (label) and define the colors for (var i = 0; i < legendlength; i++) { opts.data.push({ 'label': $legends.eq(i).text(), 'data': _d[i] }); colors[i] = opts.colors[i] || colors[i % opts.colors.length]; } break; default: //trigger an error $.error('Orientation "' + opts.orientation + '" is not allowed'); } } else { //trigger an error id no data or ttable is set $.error('No data or data table!'); } opts.colors = colors; var std = {}; //define some chart type specific standards switch (opts.type) { case 'bars': std = { points: { show: (opts.points !== null) ? opts.points : false }, bars: { order: (opts.stack) ? null : true, show: true, border: false, fill: (opts.fill !== null) ? opts.fill : true, fillColor: (opts.fillColor !== null) ? opts.fillColor : null, align: opts.align || 'center', horizontal: opts.horizontal || false, barWidth: opts.barWidth || (opts.stack) ? 0.85 : 0.85 / opts.data.length, lineWidth: (opts.lineWidth !== null) ? opts.lineWidth : 0 }, lines: { show: false }, pie: { show: false } }; break; case 'pie': std = { points: { show: (opts.points !== null) ? opts.points : true }, bars: { show: false }, lines: { show: false }, pie: { show: true, label: true, tilt: opts.tilt || 1, innerRadius: (opts.innerRadius) ? opts.innerRadius : 0, radius: (opts.tilt && !opts.radius) ? 0.8 : opts.radius || 1, shadowSize: 2 } }; break; case 'lines': default: std = { points: { show: (opts.points !== null) ? opts.points : true }, bars: { show: false }, lines: { show: true, lineWidth: (opts.lineWidth !== null) ? opts.lineWidth : 4, fill: (opts.fill !== null) ? opts.fill : false, fillColor: (opts.fillColor !== null) ? opts.fillColor : null }, pie: { show: false } }; } //some more standards and maybe the flot object var options = $.extend(true, {}, { series: $.extend(true, {}, { //must set to null not to false stack: (opts.stack) ? true : null, points: { show: opts.points } }, std), shadowSize: opts.shadowSize || 0, grid: { hoverable: opts.tooltip, clickable: true, color: '#666', borderWidth: null }, legend: { show: opts.legend, position: (/^(ne|nw|se|sw)$/.test(opts.legendPosition)) ? opts.legendPosition : 'ne' }, colors: opts.colors, xaxis: { ticks: opts.xlabels } }, opts.flot); //extend the flot object opts.flotobj = $.extend({}, opts.flotobj, options); if (opts) $.extend($this.data('wl_Chart'), opts); //let's draw the graph $.fn.wl_Chart.methods.draw.call(this); }); }; $.fn.wl_Chart.defaults = { width: null, height: 300, hideTable: true, tableBefore: false, data: {}, stack: false, type: 'lines', points: null, shadowSize: 2, fill: null, fillColor: null, lineWidth: null, legend: true, legendPosition: "ne", // or "nw" or "se" or "sw" tooltip: true, tooltipGravity: 'n', tooltipPattern: function (value, legend, label, id, itemobj) { return "value is " + value + " from " + legend + " at " + label + " (" + id + ")"; }, orientation: 'horizontal', colors: ['#b2e7b2', '#f0b7b7', '#b5f0f0', '#e8e8b3', '#efb7ef', '#bbb6f0'], flot: {}, onClick: function (value, legend, label, id, itemobj) {} }; $.fn.wl_Chart.version = '1.3'; $.fn.wl_Chart.methods = { draw: function () { var $this = $(this), _opts = $this.data('wl_Chart'); //draw the chart and save it within the DOM $this.data('wl_Chart').plot = $.plot(_opts.holder, _opts.data, _opts.flotobj); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Chart.defaults[key] !== undefined || $.fn.wl_Chart.defaults[key] == null) { $this.data('wl_Chart')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Chart.js
JavaScript
oos
12,617
/*----------------------------------------------------------------------*/ /* wl_Valid v 1.0 by revaxarts.com /* description: validates an input /* dependency: /*----------------------------------------------------------------------*/ $.fn.wl_Valid = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Valid.methods[method]) { return $.fn.wl_Valid.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Valid')) { var opts = $.extend({}, $this.data('wl_Valid'), method); } else { var opts = $.extend({}, $.fn.wl_Valid.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } //regex is a string => convert it if (typeof opts.regex === 'string') { opts.regex = new RegExp(opts.regex); } if (!$this.data('wl_Valid')) { $this.data('wl_Valid', {}); $this.bind({ //validate on change event 'change.wl_Valid': function () { var opts = $this.data('wl_Valid') || opts; $.fn.wl_Valid.methods.validate.call($this[0]); //callback opts.onChange.call($this[0], $this, $this.val()); if (!opts.valid) { //error callback opts.onError.call($this[0], $this, $this.val()); } }, //for instant callback 'keyup.wl_Valid': function () { var opts = $this.data('wl_Valid') || opts; if (opts.instant) { //validate only if minlength is reached if ($this.val().length >= $this.data('wl_Valid').minLength) { $this.wl_Valid('validate'); } } } }); } else { } if (opts) $.extend($this.data('wl_Valid'), opts); $.fn.wl_Valid.methods.validate.call($this); }); }; $.fn.wl_Valid.defaults = { errorClass: 'error', instant: true, regex: /.*/, minLength: 0, onChange: function ($this, value) {}, onError: function ($this, value) {} }; $.fn.wl_Valid.version = '1.0'; $.fn.wl_Valid.methods = { validate: function () { var $this = $(this), opts = $this.data('wl_Valid') || opts, value = $this.val(); //check for validation, empty is valid too! opts.valid = (!value || opts.regex.test(value)); //field is valid or equal to a placeholder attribute if (opts.valid || (value == $this.attr('placeholder'))) { $this.removeClass(opts.errorClass); } else { $this.addClass(opts.errorClass); } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Valid.defaults[key] !== undefined || $.fn.wl_Valid.defaults[key] == null) { switch (key) { case 'regex': value = new RegExp(value); break; default: } $this.data('wl_Valid')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } }; /*----------------------------------------------------------------------*/ /* wl_Mail by revaxarts.com /* description: Shorthand for wl_Valid for email addresses /* dependency: wl_Valid /*----------------------------------------------------------------------*/ $.fn.wl_Mail = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Valid.methods[method]) { return $.fn.wl_Valid.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Valid')) { var opts = $.extend({}, $this.data('wl_Valid'), method); } else { var opts = $.extend({}, $.fn.wl_Mail.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } $this.wl_Valid(opts); if (opts) $.extend($this.data('wl_Valid'), opts); }); }; $.fn.wl_Mail.defaults = { regex: /^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(\d{1,3}\.){3}\d{1,3}\]?)$/i, onChange: function (element, value) { element.val(value.toLowerCase()); } }; /*----------------------------------------------------------------------*/ /* wl_URL by revaxarts.com /* description: Shorthand for wl_Valid for urls /* dependency: wl_Valid /*----------------------------------------------------------------------*/ $.fn.wl_URL = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Valid.methods[method]) { return $.fn.wl_Valid.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Valid')) { var opts = $.extend({}, $this.data('wl_Valid'), method); } else { var opts = $.extend({}, $.fn.wl_URL.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } $this.wl_Valid(opts); if (opts) $.extend($this.data('wl_Valid'), opts); }); }; $.fn.wl_URL.defaults = { regex: /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w]))*\.+(([\w#!:.?+=&%@!\-\/]))?/, instant: false, onChange: function (element, value) { if (value != '' && !/^(ftp|http|https):\/\//.test(value)) element.val('http://' + value).trigger('change.wl_Valid'); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Valid.js
JavaScript
oos
5,592
/*----------------------------------------------------------------------*/ /* wl_Widget v 1.2 by revaxarts.com /* description: handles all function for the widgets /* dependency: wl_Store, jquery sortable a.d. /*----------------------------------------------------------------------*/ $.fn.wl_Widget = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Widget.methods[method]) { return $.fn.wl_Widget.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Widget')) { var opts = $.extend({}, $this.data('wl_Widget'), method); } else { var opts = $.extend({}, $.fn.wl_Widget.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Widget')) { $this.data('wl_Widget', {}); //find the widgets within the conatainer var $widgets = $this.find('div.widget'); //iterate thru the widgets $widgets.each(function () { var $widget = $(this), _opts = $.extend({}, opts, $widget.data()), $handle = $widget.find('h3.handle'), $content = $widget.find('div').eq(0), $container = $widget.parent(); $widget.data('wl_Widget', {}); //set an icon if (_opts.icon) { $handle.addClass('icon'); $('<a>', { 'class': 'icon i_' + _opts.icon }).appendTo($handle); } //if sortable add a class if (_opts.sortable) { $widget.addClass('sortable'); } //if collapsible if(_opts.collapsible){ //add the collapse button $('<a>', { 'class': 'collapse', 'title': _opts.text.collapse }).appendTo($handle); //collapse if set if (_opts.collapsed) { $content.hide(); $widget.addClass('collapsed'); $handle.find('a.collapse').attr('title',_opts.text.expand); } //handle the collapse button (touchstart is required for iOS devices) $handle.delegate('a.collapse', 'click.wl_Widget touchstart.wl_Widget', function (event) { var _opts = $widget.data('wl_Widget') || _opts, _content = $widget.find('div').eq(0); if (_content.is(':hidden')) { //expand hidden content _content.slideDown(100, function () { $widget.removeClass('collapsed').data('wl_Widget').collapsed = false; $handle.find('a.collapse').attr('title',_opts.text.collapse); //callback _opts.onExpand.call($widget[0]); //save $.fn.wl_Widget.methods.save(); //trigger resize for some plugins $(window).resize(); }); } else { //hide content $content.slideUp(100, function () { $widget.addClass('collapsed').data('wl_Widget').collapsed = true; $handle.find('a.collapse').attr('title',_opts.text.expand); //callback _opts.onCollapse.call($widget[0]); //save $.fn.wl_Widget.methods.save(); }); } return false; //doublclick is equal to collapse button }).bind('dblclick', function () { $handle.find('a.collapse').trigger('click'); return false; }); } //handle the reload button (touchstart is required for iOS devices) $handle.delegate('a.reload', 'click.wl_Widget touchstart.wl_Widget', function (event) { var _opts = $widget.data('wl_Widget') || _opts, _content = $widget.find('div').eq(0); $widget.addClass('loading'); //set height to prevent "jumping" _content.height($content.height()); //removeContent and replace it with a loading information if (_opts.removeContent) { _content.html(_opts.text.loading); } _content.load(_opts.load, function (response, status, xhr) { $widget.removeClass('loading'); _content.height('auto'); //error occured if (status == "error") { _content.html(xhr.status + " " + xhr.statusText); } //autoreload is set if (_opts.reload) { clearTimeout($widget.data('wl_Widget').timeout); $widget.data('wl_Widget').timeout = setTimeout(function () { $handle.find('a.reload').trigger('click.wl_Widget'); }, _opts.reload * 1000); } }); return false; }); //prevent other anochrs to bubble up the DOM $handle.delegate('a', 'click.wl_Widget', function (event) { event.stopPropagation(); return false; }); if (_opts) $.extend($widget.data('wl_Widget'), _opts); //ajax widgets get a reload button if (_opts.load) { $('<a>', { 'class': 'reload', 'title': _opts.text.reload }).appendTo($handle).trigger('click.wl_Widget'); } }); //Handling sortable and restoring positions var $maincontent = $('#content'); //save the total count of widgets if (!$maincontent.data('wl_Widget')) { $maincontent.data('wl_Widget', { containercount: $('div.widgets').length, currentid: 1 }); } //if all widgets are initialized if ($maincontent.data('wl_Widget').currentid++ >= $maincontent.data('wl_Widget').containercount) { var $container = $('div.widgets'); //get data from the storage var wl_Store = new $.wl_Store('wl_' + location.pathname.toString()); //iterate thru the containers $container.each(function (i, cont) { var widgets = wl_Store.get('widgets_' + i), $cont = $(this); if (!widgets) return false; //iterate thru the widgets from the container id i $.each(widgets, function (widget, options) { var _widget = $('#' + widget); //widget should be collpased (options.collapsed && _widget.data('wl_Widget').collapsible) ? _widget.addClass('collapsed').find('div').eq(0).hide().data('wl_Widget', { collapsed: true }) : _widget.removeClass('collapsed').find('div').eq(0).show().data('wl_Widget', { collapsed: false }); //position handling if (_widget.length && (_widget.prevAll('div').length != options.position || _widget.parent()[0] !== $cont[0])) { children = $cont.children('div.widget'); if (children.eq(options.position).length) { _widget.insertBefore(children.eq(options.position)); } else if (children.length) { _widget.insertAfter(children.eq(options.position - 1)); } else { _widget.appendTo($cont); } } }); }); //use jQuery UI sortable plugin for the widget sortable function $container.sortable({ items: $container.find('div.widget.sortable'), containment: '#content', opacity: 0.8, distance: 5, handle: 'h3.handle', connectWith: $container, forceHelperSize: true, placeholder: 'sortable_placeholder', forcePlaceholderSize: true, zIndex: 10000, start: function (event, ui) { ui.item.data('wl_Widget').onDrag.call(ui.item[0]); }, stop: function (event, ui) { ui.item.data('wl_Widget').onDrop.call(ui.item[0]); $.fn.wl_Widget.methods.save(); } }); } } else { } if (opts) $.extend($this.data('wl_Widget'), opts); }); }; $.fn.wl_Widget.defaults = { collapsed: false, load: null, reload: false, removeContent: true, collapsible: true, sortable: true, text: { loading: 'loading...', reload: 'reload', collapse: 'collapse widget', expand: 'expand widget' }, onDrag: function () {}, onDrop: function () {}, onExpand: function () {}, onCollapse: function () {} }; $.fn.wl_Widget.version = '1.2'; $.fn.wl_Widget.methods = { save: function () { var $containers = $('div.widgets'), wl_Store = new $.wl_Store('wl_' + location.pathname.toString()); //iterate thru the containers $containers.each(function (containerid, e) { var _widgets = {}; //get info from all widgets from that container $(this).find('div.widget').each(function (pos, e) { var _t = $(this); _widgets[this.id] = { position: pos, collapsed: _t.find('div').eq(0).is(':hidden') }; }); //store the info wl_Store.save('widgets_' + containerid, _widgets); }); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Widget.defaults[key] !== undefined || $.fn.wl_Widget.defaults[key] == null) { $this.data('wl_Widget')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Widget.js
JavaScript
oos
9,082
/*----------------------------------------------------------------------*/ /* wl_Number v 1.0 by revaxarts.com /* description: Make a Number field out of an input field /* dependency: mousewheel plugin /*----------------------------------------------------------------------*/ $.fn.wl_Number = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Number.methods[method]) { return $.fn.wl_Number.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Number')) { var opts = $.extend({}, $this.data('wl_Number'), method); } else { var opts = $.extend({}, $.fn.wl_Number.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Number')) { $this.data('wl_Number', {}); //fetch the nativ attributes opts.min = $this.attr('min') || opts.min; opts.max = $this.attr('max') || opts.max; opts.step = $this.attr('step') || opts.step; $this.bind({ //bind the mouswheel event 'mousewheel.wl_Number': function (event, delta) { var opts = $this.data('wl_Number') || opts; if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; //multiply with 10 if shift key is pressed if (event.shiftKey) delta *= 10; $.fn.wl_Number.methods.change.call($this[0], delta); } }, 'change.wl_Number': function () { var _this = $(this); //correct the input $.fn.wl_Number.methods.correct.call($this[0]); //callback _this.data('wl_Number').onChange.call($this[0], _this.val()); } }); } else { } if (opts) $.extend($this.data('wl_Number'), opts); }); }; $.fn.wl_Number.defaults = { step: 1, decimals: 0, start: 0, min: null, max: null, mousewheel: true, onChange: function (value) {}, onError: function (value) {} }; $.fn.wl_Number.version = '1.0'; $.fn.wl_Number.methods = { correct: function () { var $this = $(this), //replace ',' with '.' because in some countries comma is the separator val = $this.val().replace(/,/g, '.'); if (val) $.fn.wl_Number.methods.printValue.call(this, parseFloat(val)); }, change: function (delta) { var $this = $(this), //the current value _current = $this.val() || $this.data('wl_Number').start, //calculate the new value _new = parseFloat(_current, 10) + (delta * $this.data('wl_Number').step); $.fn.wl_Number.methods.printValue.call(this, _new); $this.trigger('change.wl_Number'); }, printValue: function (value) { var $this = $(this), opts = $this.data('wl_Number') || opts; //is not a number if (isNaN(value) && value != '') { //callback opts.onError.call(this, $this.val()); //write '0', focus and select it $this.val(0).focus().select(); $this.trigger('change.wl_Number'); return; } //don't go over min and max values if (opts.min != null) value = Math.max(opts.min, value); if (opts.max != null) value = Math.min(opts.max, value); //decimals? use parseFloat if yes or round the value if it is an integer (no decimals) (opts.decimals) ? value = parseFloat(value, opts.decimals).toFixed(opts.decimals) : value = Math.round(value); //write value $this.val(value); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Number.defaults[key] !== undefined || $.fn.wl_Number.defaults[key] == null) { $this.data('wl_Number')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Number.js
JavaScript
oos
4,070
/*----------------------------------------------------------------------*/ /* wl_Form v 1.3.5 by revaxarts.com /* description: handles the serialization, unserialization and sending /* of a form /* dependency: $.confirm, wl_Number*, wl_Slider*, wl_Date*, wl_Value*, /* wl_Password*, wl_File*, wl_Multiselect* /* * only when fields are within the form /*----------------------------------------------------------------------*/ $.fn.wl_Form = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Form.methods[method]) { return $.fn.wl_Form.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Form')) { var opts = $.extend({}, $this.data('wl_Form'), method); } else { var opts = $.extend({}, $.fn.wl_Form.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } //all fields within that form var $inputs = $this.find('input,textarea,select,div.date,div.slider'), //$required = $inputs.filter('[required]'), //Does not work on IE7/8 $submitbtn = (opts.submitButton instanceof jQuery) ? opts.submitButton : $this.find(opts.submitButton), $resetbtn = (opts.resetButton instanceof jQuery) ? opts.resetButton : $this.find(opts.resetButton); if (!$this.data('wl_Form')) { $this.data('wl_Form', {}); //get options from the forms nativ attributes opts.action = $this.attr('action') || opts.action; opts.method = $this.attr('method') || opts.method; //prevent the forms default behaviour $this.bind({ 'submit.wl_Form': function (event) { event.preventDefault(); return false; }, 'reset.wl_Form': function (event) { event.preventDefault(); return false; } }); //bind the click action to the submit button $submitbtn.bind('click.wl_Form', function (event) { $.fn.wl_Form.methods.submit.call($this[0]); return false; }); //bind the click action to the submit button $resetbtn.bind('click.wl_Form', function (event) { $.fn.wl_Form.methods.reset.call($this[0]); return false; }); //iterate through the fields $inputs.each(function () { var _this = $(this), _row = _this.closest('section'), //the label should be nice readable _label = _row.find('label').eq(0).html() || this.name || this.id || ''; //This is required because IEs < 9 can't handle this as expected if (_this.is('[required]') || typeof _this.prop('required') == 'string') { _this.data('required', true); //only append one required asterix if(!_row.find('span.required').length) _row.find('label').eq(0).append('&nbsp;<span class="required">&nbsp;</span>'); } //add the label to the field (and strip out unwanted info) _this.data('wl_label', _label.replace(/<span>([^<]+)<\/span>|<([^>]+)\/?>/g, '')); //set initial data for Form reset _this.data('wl_initdata', function () { var _type = _this.attr("type"); if (_type == "checkbox" || _type == "radio") { return _this.prop("checked"); //datepicker } else if (_this.data('wl_Date')) { return _this.datepicker('getDate'); //slider } else if (_this.data('wl_Slider')) { if (!_this.data('wl_Slider').connect) { if (_this.data('wl_Slider').range) { return _this.slider('option', 'values'); } else { return _this.slider('option', 'value'); } } //other fields } else { return _this.val(); } }()); }); //set the form status after the submit button if status is true if (opts.status && !$submitbtn.closest('div').is('span.wl_formstatus')) { $submitbtn.closest('div').append('<span class="wl_formstatus"></span>'); } //parse the location.search parameters if (opts.parseQuery) { $this.wl_Form.methods.unserialize.call(this); } } else { } if (opts) $.extend($this.data('wl_Form'), opts); }); }; $.fn.wl_Form.defaults = { submitButton: 'button.submit', resetButton: 'button.reset', method: 'post', action: null, ajax: true, serialize: false, parseQuery: true, dataType: 'text', status: true, sent: false, confirmSend: true, text: { required: 'This field is required', valid: 'This field is invalid', password: 'This password is to short', passwordmatch: 'This password doesn\'t match', fileinqueue: 'There is at least one file in the queue', incomplete: 'Please fill out the form correctly!', send: 'send form...', sendagain: 'send again?', success: 'form sent!', error: 'error while sending!', parseerror: 'Can\'t unserialize query string:\n %e' }, tooltip: { gravity: 'nw' }, onRequireError: function (element) {}, onValidError: function (element) {}, onPasswordError: function (element) {}, onFileError: function (element) {}, onBeforePrepare: function () {}, onBeforeSubmit: function (data) {}, onReset: function () {}, onComplete: function (textStatus, jqXHR) {}, onError: function (textStatus, error, jqXHR) {}, onSuccess: function (data, textStatus, jqXHR) {} }; $.fn.wl_Form.version = '1.3.5'; $.fn.wl_Form.methods = { disable: function () { var $this = $(this), _inputs = $this.find($this.data('wl_Form').submitButton + ',input,textarea,select,div.date,div.slider'); //iterate through all fields _inputs.each(function () { var _this = $(this); if (_this.is('div')) { //disable slider and datefields if (_this.is('div.slider') && _this.data('wl_Slider')) { _this.wl_Slider('disable'); } else if (_this.is('div.date') && _this.data('wl_Date')) { _this.wl_Date('disable'); } } else { //disable normal fields _this.prop('disabled', true); } }); $this.data('wl_Form').disabled = true; }, enable: function () { var $this = $(this), _inputs = $this.find($this.data('wl_Form').submitButton + ',input,textarea,select,div.date,div.slider'); //iterate through all fields _inputs.each(function () { var _this = $(this); if (_this.is('div')) { //enable slider and datefields if (_this.is('div.slider') && _this.data('wl_Slider')) { _this.wl_Slider('enable'); } else if (_this.is('div.date') && _this.data('wl_Date')) { _this.wl_Date('enable'); } } else { //enable normal fields _this.prop('disabled', false); } }); $this.data('wl_Form').disabled = false; }, reset: function () { var $this = $(this), _inputs = $this.find('input,textarea,select,div.date,div.slider'); //trigger callback if ($this.data('wl_Form').onReset.call($this[0]) === false) return false; //remove all errorclasses $this.find('section.error').removeClass('error'); //iterate through all fields _inputs.each(function () { var _this = $(this), _type = _this.attr("type"); if (_type == "checkbox") { _this.prop("checked", _this.data('wl_initdata')).trigger('change'); //radio buttons } else if (_type == "radio") { _this.prop("checked", _this.data('wl_initdata')).trigger('change'); //datepicker } else if (_this.data('wl_Date')) { _this.datepicker('setDate', _this.data('wl_initdata')); //time } else if (_this.data('wl_Time')) { _this.val(_this.data('wl_initdata')); //multi select } else if (_this.data('wl_Multiselect')) { _this.wl_Multiselect('clear'); _this.wl_Multiselect('select', _this.data('wl_initdata')); //slider } else if (_this.data('wl_Slider')) { if (!_this.data('wl_Slider').connect) { if (_this.data('wl_Slider').range) { _this.slider('option', 'values', $.parseData(_this.data('wl_initdata'))); } else { _this.slider('option', 'value', _this.data('wl_initdata')); } _this.wl_Slider("change"); _this.wl_Slider("slide"); } //prevent file inputs to get triggered } else if (_this.data('wl_File')) { _this.wl_File('reset'); //wysiwyg editor } else if (_this.data('wl_Editor')) { _this.val(_this.data('wl_initdata')).wysiwyg("setContent", _this.data('wl_initdata')); //colorpicker } else if (_this.data('wl_Color')) { _this.wl_Color('set', 'value', _this.data('wl_initdata')); //other fields } else { _this.val(_this.data('wl_initdata')).trigger('change'); //placeholder text needs some CSS if (_this.is('[placeholder]')) { if (_this.data('wl_initdata') == "" || _this.data('wl_initdata') == _this.attr("placeholder")) { _this.addClass("placeholder").val(_this.attr("placeholder")).data("uservalue", false); } else { _this.removeClass("placeholder").data("uservalue", true); } } } }); }, submit: function () { //collect some required info var $this = $(this), _data = {}, _opts = $this.data('wl_Form'), _inputs = $this.find('input,textarea,select,div.date,div.slider'), _statusel = $this.find('.wl_formstatus'), _requiredelements = Array(), _validelements = Array(), _passwordelements = Array(), _fileelements = Array(), _submit = true, _submitbtn = (_opts.submitButton instanceof jQuery) ? _opts.submitButton : $this.find(_opts.submitButton), _callbackReturn, _addHiddenField = function (after, id, name, value) { if (!$('#' + id).length) $('<input>', { type: 'hidden', id: id, name: name, value: value }).insertAfter(after); }; //status reset _statusel.text(""); //iterate through all fields _inputs.each(function (i, e) { var _this = $(this), _row = _this.closest('section'); //remove all error classes _row.removeClass('error'); //if a placeholder is set remove the value temporary if (_this.prop('placeholder') && _this.val() == _this.prop('placeholder') && !_this.data('uservalue')) { _this.val(''); } //if field is required and a value isn't set or it is a checkbox and the checkbox isn't checked or it is a file upload with no files if (_this.data('required')) { if ((!_this.val() || _this.is(':checkbox') && !_this.is(':checked')) && !_this.data('wl_File')) { _requiredelements.push(_this); _submit = false; } else if (_this.is(':radio')) { //get all checked radios; var checked = $('input[name='+_this.attr('name')+']:checked'); //no radio button is selected if(!checked.length){ _requiredelements.push(_this); _submit = false; } } else if (_this.data('wl_File') && !_this.data('wl_File').files.length) { //use the filepool for the tooltip _requiredelements.push(_row.find('.fileuploadpool').eq(0)); _submit = false; } } //if it is a valid field but it isn't valid if (_this.data('wl_Valid') && !_this.data('wl_Valid').valid) { _validelements.push(_this); _submit = false; } //check if there is a file in the queue if (_this.data('wl_File') && !$.isEmptyObject(_this.data('wl_File').queue)) { //use the filepool for the tooltip _fileelements.push(_row.find('.fileuploadpool').eq(0)); _submit = false; } //if it is a password if (_this.data('wl_Password')) { var value = _this.val(); //password confirmation is set and the confirmation isn't equal the password or the password is shorter than the minlength of the password field if ((_this.data('wl_Password').confirm && _this.data('wl_Password').connect && value != $('#' + _this.data('wl_Password').connect).val()) || (value && value.length < _this.data('wl_Password').minLength)) { //_row.addClass('error'); _passwordelements.push(_this); _submit = false; } }; }); //if some of the above errors occures if (!_submit) { //iterate through all required fields $.each(_requiredelements, function (i, e) { var _row = e.closest('section'); _row.addClass('error'); //callback _opts.onRequireError.call(e[0], e); //store the old tooltip if set var orgtitle = e.attr('original-title'); if(orgtitle) e.removeData('tipsy').removeAttr('original-title'); //use tipsy for a tooltip e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || _opts.text.required })); e.tipsy('show'); //hide the tooltip on every radio button if(e.is(':radio')){ var radiosiblings = $('input[name='+e.attr('name')+']'); radiosiblings.bind('focus.tooltip, click.tooltip, change.tooltip', function () { e.unbind('focus.tooltip, click.tooltip, change.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('title',orgtitle).tipsy(config.tooltip); }); }else{ //hide tooltip on fieldfocus or change e.bind('focus.tooltip, click.tooltip, change.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip, change.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); } }); //iterate through all valid fields $.each(_validelements, function (i, e) { var _row = e.closest('section'); //highlight the row _row.addClass('error'); //callback _opts.onValidError.call(e[0], e); //store the old tooltip if set var orgtitle = e.attr('original-title'); if(orgtitle) e.removeData('tipsy').removeAttr('original-title'); //use tipsy for a tooltip e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || e.data('wl_Valid').errortext || _opts.text.valid })); e.tipsy('show'); //hide tooltip on fieldfocus e.bind('focus.tooltip, click.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); }); //iterate through all password fields $.each(_passwordelements, function (i, e) { var text = '', value = e.val(), _row = e.closest('section'); //highlight the row _row.addClass('error'); //store the old tooltip if set var orgtitle = e.attr('original-title'); if(orgtitle) e.removeData('tipsy').removeAttr('original-title'); //confirmation is set if (e.data('wl_Password').confirm) { var connect = $('#' + e.data('wl_Password').connect); //but password is not equal confimration if (value != connect.val()) { //tipsy on the confirmation field connect.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: connect.data('errortext') || _opts.text.passwordmatch })); connect.tipsy('show'); //hide tooltip in fieldfocus connect.bind('focus.tooltip, click.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); } } //length is to short if (value.length < e.data('wl_Password').minLength) { _opts.onPasswordError.call(e[0], e); //tipsy e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || _opts.text.password })); e.tipsy('show'); //hide tooltip in fieldfocus e.bind('focus.tooltip, click.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip').tipsy('hide'); //restore the old tooltip if(orgtitle) e.attr('original-title',orgtitle).tipsy(config.tooltip); }); } }); //iterate through all file upload fields $.each(_fileelements, function (i, e) { var _row = e.closest('section'); //highlight the row _row.addClass('error'); //callback _opts.onFileError.call(e[0], e); //use tipsy for a tooltip e.tipsy($.extend({}, config.tooltip, _opts.tooltip, { trigger: 'manual', fallback: e.data('errortext') || _opts.text.fileinqueue })); e.tipsy('show'); //hide tooltip on fieldfocus or change e.bind('focus.tooltip, click.tooltip, change.tooltip', function () { $(this).unbind('focus.tooltip, click.tooltip, change.tooltip').tipsy('hide'); }); }); //Set status message _statusel.text(_opts.text.incomplete); return false; } //confirmation is required if the form was allready sent if (_opts.confirmSend && _opts.sent === true) { $.confirm(_opts.text.sendagain, function () { _opts.sent = false; $.fn.wl_Form.methods.submit.call($this[0]); }); return false; } //callback can return false if (_opts.onBeforePrepare.call($this[0]) === false) { return false; } //iterate through all fields and prepare data _inputs.each(function (i, e) { var _el = $(e), key = _el.attr('name') || e.id, value = null; //datepicker if (_el.data('wl_Date')) { var connect = $this.find('input[data-connect=' + e.id + ']').eq(0), dateobj = new Date(_el.datepicker('getDate')), //format: YYYY-MM-DD date = dateobj.getFullYear() + '-' + $.leadingZero(dateobj.getMonth() + 1) + '-' + $.leadingZero(dateobj.getDate()); if (dateobj.getTime()) { //is connected to a timefield if (connect.length) { value = date + ' ' + (connect.data('wl_Time').time || '00:00'); //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, value); } else { value = date; //correct the format on nativ submit if (!_opts.ajax) _el.val(value); } } //inline Date needs a hidden input for nativ submit if (!_opts.ajax && _el.is('div')) { _addHiddenField(_el, key + '_wlHidden', key, value) } _data[key] = value; //slider } else if (_el.data('wl_Slider')) { //if it is connected we have a input field too so skip it if (!_el.data('wl_Slider').connect) { if (_el.data('wl_Slider').range !== true) { value = _el.slider('option', 'value'); //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, value); } else { value = _el.slider('option', 'values'); //insert hidden fields for non ajax submit if (!_opts.ajax) { for (var i = value.length - 1; i >= 0; i--) { _addHiddenField(_el, key + '_' + i + '_wlHidden', key + '[]', value[i]); } } } _data[key] = value; } else { //form needs a name attribute for nativ submit if (!_opts.ajax) { if (_el.data('wl_Slider').range !== true) { var input = $('#' + _el.data('wl_Slider').connect); if (!input.attr('name')) input.attr('name', _el.data('wl_Slider').connect); } else { var connect = $.parseData(_el.data('wl_Slider').connect, true); var input1 = $('#' + connect[0]); var input2 = $('#' + connect[1]); if (!input1.attr('name')) input1.attr('name', connect[0]); if (!input2.attr('name')) input2.attr('name', connect[1]); } } } //wysiwyg editor } else if (_el.data('wl_Editor')) { //copy the content to the textarea _el.wysiwyg('save'); _data[key] = _el.val(); //file upload } else if (_el.data('wl_File')) { _data[key] = _el.data('wl_File').files; //if no file was uploaded value is null if ($.isEmptyObject(_data[key])) { _data[key] = null; //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, 'null'); } else { //insert hidden fields for non ajax submit if (!_opts.ajax) { for (var i = _data[key].length - 1; i >= 0; i--) { _addHiddenField(_el, key + '_' + i + '_wlHidden', key + '[]', _data[key][i]); } } } //timefield } else if (_el.data('wl_Time')) { //if it is connected we have a datefield too so skip it if (!_el.data('wl_Time').connect) { _data[key] = _el.data('wl_Time').time; //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, _el.data('wl_Time').time); } //password } else if (_el.data('wl_Password')) { //only add if it's not the confirmation field if (!_el.data('wl_Password').confirmfield) _data[key] = _el.val(); if (!_opts.ajax && _el.data('wl_Password').confirmfield) _el.prop('disabled', true); //radio buttons } else if (_el.is(':radio')) { if (_el.is(':checked')) { //use the value attribute if present or id as fallback (new in 1.1) _data[key] = (_el.val() != 'on') ? _el.val() : e.id; } //checkbox } else if (_el.is(':checkbox')) { //if checkbox name has '[]' at the and we need an array if (/\[\]$/.test(key)) { _data[key] = _data[key] || []; //checkbox is checked if (_el.is(':checked')) { //if value = 'on' value isn't set use id or val if id isn't defined var val = _el.val(); _data[key].push((val != 'on') ? val : _el.attr('id') || val); } } else { //use value if set and true or false if not set if (_el.is(':checked')) { var val = _el.val(); _data[key] = (val != 'on') ? val : _el.is(':checked') || (_el.attr('id') || val); }else{ //use always 0 (false) if unchecked _data[key] = 0; } } //convert true to 1 and false to 0 if(_data[key] === true) { _data[key] = 1; }else if(_data[key] === false) { _data[key] = 0; } //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_el, key + '_wlHidden', key, _data[key]); //number field } else if (_el.data('wl_Number')) { value = _el.val(); if (isNaN(value)) { value = null; } _data[key] = value; //other fields } else { var val = _el.val(); //if name attribute has '[]' at the and we need an array if (/\[\]$/.test(key) && !$.isArray(val)) { _data[key] = _data[key] || []; _data[key].push(val); } else { _data[key] = val; } } }); //add the name attribut of the submit button to the data (native behavior) var submitbtnname = _submitbtn.attr('name'); if(submitbtnname){ _data[submitbtnname] = _submitbtn.attr('value') || true; //insert a hidden field for non ajax submit if (!_opts.ajax) _addHiddenField(_submitbtn, submitbtnname + '_wlHidden', submitbtnname, _data[submitbtnname]); } //callback _callbackReturn = _opts.onBeforeSubmit.call($this[0], _data); //can return false to prevent sending if (_callbackReturn === false) { return false; //can return an object to modifie the _data } else if (typeof _callbackReturn == 'object') { _data = _callbackReturn; } //should we serialize it? (key=value&key2=value2&...) if (_opts.serialize) { _data = $.param(_data); } //set status text _statusel.text(_opts.text.send); //send the form natively if (!_opts.ajax) { $this.unbind('submit.wl_Form'); $this.submit(); return false; } //now disable it $.fn.wl_Form.methods.disable.call(this); //send the form $.ajax({ url: _opts.action, type: _opts.method, data: _data, dataType: _opts.dataType, //callback on success success: function (data, textStatus, jqXHR) { _statusel.textFadeOut(_opts.text.success); _opts.onSuccess.call($this[0], data, textStatus, jqXHR); }, //callback on complete complete: function (jqXHR, textStatus) { $.fn.wl_Form.methods.enable.call($this[0]); _opts.sent = true; _opts.onComplete.call($this[0], textStatus, jqXHR); }, //callback on error error: function (jqXHR, textStatus, error) { _statusel.text(_opts.text.error); _opts.onError.call($this[0], textStatus, error, jqXHR); } }); }, unserialize: function (string) { var $this = $(this), _searchquery = string || location.search.substr(1); //parse only if we have something to parse if (_searchquery) { //could throw an error because its an userinput try { //prepare string to get a clean array with with key => value values = decodeURIComponent(_searchquery).split('&'); var serialized_values = []; $.each(values, function () { var properties = this.split("="), key = properties.shift(); properties = properties.join('='); if ((typeof key !== 'undefined') && (typeof properties !== 'undefined')) { key = key.replace(/\+/g, " "); //handle Array if (/\[\]$/.test(key)) { key = key.replace('[]', ''); serialized_values[key] = serialized_values[key] || []; serialized_values[key].push(properties.replace(/\+/g, " ")); } else { serialized_values[key] = properties.replace(/\+/g, " "); } } }); values = serialized_values; // Iterate through each element $this.find("input,textarea,select,div.date,div.slider").each(function () { var _this = $(this), _type = _this.attr("type"), tag_name = this.name || this.id; //remove '[]' if present if (/\[\]$/.test(tag_name)) tag_name = tag_name.replace('[]', ''); // Set the values to field if (values[tag_name] != null) { //chechboxes if (_type == "checkbox") { _this.data('wl_initdata', (values[tag_name] == 'true')).prop("checked", (values[tag_name] == 'true')); //radio buttons } else if (_type == "radio") { $('input[id="' + values[tag_name] + '"]').data('wl_initdata', true).attr("checked", true); //password } else if (_type == "password") { //don't write passwords for security reasons //_this.val(values[tag_name]).trigger('change') //datepicker } else if (_this.data('wl_Date') && _this.is('input')) { if (/(\d\d:\d\d)$/.test(values[tag_name])) { var time = values[tag_name].substr(11), date = values[tag_name].substr(0, 10); _this.data('wl_initdata', new Date(date)).datepicker('setDate', new Date(date)); $('input[data-connect="' + tag_name + '"]').data('wl_initdata', time).val(time).data('wl_Time').time = time; } else { _this.data('wl_initdata', new Date(values[tag_name])).datepicker('setDate', new Date(values[tag_name])); } //inline datepicker } else if (_this.data('wl_Date') && _this.is('div')) { _this.data('wl_initdata', new Date(values[tag_name])).datepicker('setDate', new Date(values[tag_name])); //colorpicker } else if (_this.data('wl_Color')) { _this.data('wl_initdata', values[tag_name]).wl_Color('set', 'value', values[tag_name]); //Slider } else if (_this.data('wl_Slider')) { if (!_this.data('wl_Slider').connect) { if (_this.data('wl_Slider').range) { _this.slider('option', 'values', $.parseData(values[tag_name])); } else { _this.slider('option', 'value', values[tag_name]); } _this.data('wl_initdata', values[tag_name]); _this.wl_Slider("change"); _this.wl_Slider("slide"); } //Multiselect } else if (_this.data('wl_Multiselect')) { _this.data('wl_initdata', values[tag_name]).wl_Multiselect('select', values[tag_name]); //wysiwyg editor } else if (_this.data('wl_Editor')) { _this.data('wl_initdata', values[tag_name]).val(values[tag_name]).wysiwyg("setContent", values[tag_name]); //other fields } else { _this.data('wl_initdata', values[tag_name]).val(values[tag_name]).trigger('change'); } } }); } catch (e) { //call a message to prevent crashing the application $.msg($this.data('wl_Form').text.parseerror.replace('%e', e)); } } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Form.defaults[key] !== undefined && $.fn.wl_Form.defaults[key] !== null) { $this.data('wl_Form')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Form.js
JavaScript
oos
29,239
/*----------------------------------------------------------------------*/ /* wl_Gallery v 1.3 by revaxarts.com /* description: makes a sortable gallery /* dependency: jQuery UI sortable /*----------------------------------------------------------------------*/ $.fn.wl_Gallery = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Gallery.methods[method]) { return $.fn.wl_Gallery.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Gallery')) { var opts = $.extend({}, $this.data('wl_Gallery'), method); } else { var opts = $.extend({}, $.fn.wl_Gallery.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } var $items = $this.find('a'); if (!$this.data('wl_Gallery')) { $this.data('wl_Gallery', {}); //make it sortable $this.sortable({ containment: $this, opacity: 0.8, distance: 5, handle: 'img', forceHelperSize: true, placeholder: 'sortable_placeholder', forcePlaceholderSize: true, start: function (event, ui) { $this.dragging = true; ui.item.trigger('mouseleave'); }, stop: function (event, ui) { $this.dragging = false; }, update: function (event, ui) { var _a = ui.item.find('a').eq(0); //callback action opts.onMove.call($this[0], ui.item, _a.attr('href'), _a.attr('title'), $this.find('li')); } }); opts.images = []; //add the rel attribut for the fancybox $items.attr('rel', opts.group).fancybox(opts.fancybox); $items.each(function () { var _this = $(this), _image = _this.find('img'), _append = $('<span>'); //add edit and delete buttons if(opts.editBtn) _append.append('<a class="edit">Edit</a>'); if(opts.deleteBtn) _append.append('<a class="delete">Delete</a>'); if(opts.deleteBtn || opts.editBtn) _this.append(_append); //store images within the DOM opts.images.push({ image: _image.attr('rel') || _image.attr('src'), thumb: _image.attr('src'), title: _image.attr('title'), description: _image.attr('alt') }); }); if(opts.deleteBtn || opts.editBtn){ //bind the mouseenter animation $this.delegate('li', 'mouseenter', function (event) { if (!$this.dragging) { var _this = $(this), _img = _this.find('img'), _pan = _this.find('span'); _img.animate({ top: -20 }, 200); _pan.animate({ top: 80 }, 200); } //bind the mouseleave animation }).delegate('li', 'mouseleave', function (event) { var _this = $(this), _img = _this.find('img'), _pan = _this.find('span'); _img.animate({ top: 0 }, 200); _pan.animate({ top: 140 }, 200); }); } if(opts.editBtn){ //bind the edit event to the button $this.find('a.edit').bind('click.wl_Gallery touchstart.wl_Gallery', function (event) { event.stopPropagation(); event.preventDefault(); var opts = $this.data('wl_Gallery') || opts, _this = $(this), _element = _this.parent().parent().parent(), _href = _element.find('a')[0].href, _title = _element.find('a')[0].title; //callback action opts.onEdit.call($this[0], _element, _href, _title); return false; }); } if(opts.deleteBtn){ //bind the delete event to the button $this.find('a.delete').bind('click.wl_Gallery touchstart.wl_Gallery', function (event) { event.stopPropagation(); event.preventDefault(); var opts = $this.data('wl_Gallery') || opts, _this = $(this), _element = _this.parent().parent().parent(), _href = _element.find('a')[0].href, _title = _element.find('a')[0].title; //callback action opts.onDelete.call($this[0], _element, _href, _title); return false; }); } } else { } if (opts) $.extend($this.data('wl_Gallery'), opts); }); }; $.fn.wl_Gallery.defaults = { group: 'wl_gallery', editBtn: true, deleteBtn: true, fancybox: {}, onEdit: function (element, href, title) {}, onDelete: function (element, href, title) {}, onMove: function (element, href, title, newOrder) {} }; $.fn.wl_Gallery.version = '1.3'; $.fn.wl_Gallery.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Gallery.defaults[key] !== undefined || $.fn.wl_Gallery.defaults[key] == null) { $this.data('wl_Gallery')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Gallery.js
JavaScript
oos
5,089
/*----------------------------------------------------------------------*/ /* wl_File v 1.2 by revaxarts.com /* description:makes a fancy html5 file upload input field /* dependency: jQuery File Upload Plugin 5.0.2 /*----------------------------------------------------------------------*/ $.fn.wl_File = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_File.methods[method]) { return $.fn.wl_File.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_File')) { var opts = $.extend({}, $this.data('wl_File'), method); } else { var opts = $.extend({}, $.fn.wl_File.defaults, method, $this.data()); } } else { try { return $this.fileupload(method, args[1], args[2], args[3], args[4]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_File')) { $this.data('wl_File', {}); //The queue, the upload files and drag&drop support of the current browser var queue = {}, files = [], queuelength = 0, tempdata, maxNumberOfFiles, dragdropsupport = isEventSupported('dragstart') && isEventSupported('drop') && !! window.FileReader; //get native multiple attribute or use defined one opts.multiple = ($this.is('[multiple]') || typeof $this.prop('multiple') === 'string') || opts.multiple; //used for the form opts.queue = {}; opts.files = []; if (typeof opts.allowedExtensions === 'string') opts.allowedExtensions = $.parseData(opts.allowedExtensions); //the container for the buttons opts.ui = $('<div>', { 'class': 'fileuploadui' }).insertAfter($this); //start button only if autoUpload is false if (!opts.autoUpload) { opts.uiStart = $('<a>', { 'class': 'btn small fileupload_start', 'title': opts.text.start }).html(opts.text.start).bind('click', function () { $.each(queue, function (file) { upload(queue[file].data); }); }).appendTo(opts.ui); } //cancel/remove all button opts.uiCancel = $('<a>', { 'class': 'btn small fileupload_cancel', 'title': opts.text.cancel_all }).html(opts.text.cancel_all).appendTo(opts.ui).bind('click', function () { var _this = $(this), el = opts.filepool.find('li'); el.addClass('error'); //IE and Opera delete the data on submit so we store it temporarily if (!$this.data('wl_File')) $this.data('wl_File', tempdata); files = $this.data('wl_File').files = []; queuelength = 0; $.each(queue, function (name) { if (queue[name]) { queue[name].fileupload.abort(); delete queue[name]; } }); el.delay(700).fadeOut(function () { //trigger a change for required inputs opts.filepool.trigger('change'); _this.text(opts.text.cancel_all).attr('title', opts.text.cancel_all); $(this).remove(); }); //trigger delete event opts.onDelete.call($this[0], $.map(el,function(k,v){return $(k).data('fileName');})); }); //filepool and dropzone opts.filepool = $('<ul>', { 'class': 'fileuploadpool' }).insertAfter($this) //cancel one files .delegate('a.cancel', 'click', function () { var el = $(this).parent(), name = el.data('fileName'); //IE and Opera delete the data on submit so we store it temporarily if (!$this.data('wl_File')) $this.data('wl_File', tempdata); //remove clicked file from the list $this.data('wl_File').files = files = $.map(files, function (filename) { if (filename != name) return filename; }); //abort upload queue[name].fileupload.abort(); //remove from queue delete queue[name]; queuelength--; el.addClass('error').delay(700).fadeOut(); //trigger cancel event opts.onCancel.call($this[0], name); //trigger a change for required inputs opts.filepool.trigger('change'); }) //remove file from list .delegate('a.remove', 'click', function () { var el = $(this).parent(), name = el.data('fileName'); if (!$this.data('wl_File')) $this.data('wl_File', tempdata); //remove clicked file from the list $this.data('wl_File').files = files = $.map(files, function (filename) { if (filename != name) return filename; }); el.fadeOut(); //trigger cancel event opts.onDelete.call($this[0], [name]); //trigger a change for required inputs opts.filepool.trigger('change'); }) //add some classes to the filepool .addClass((!opts.multiple) ? 'single' : 'multiple').addClass((dragdropsupport) ? 'drop' : 'nodrop'); //call the fileupload plugin $this.fileupload({ url: opts.url, dropZone: (opts.dragAndDrop) ? opts.filepool : null, fileInput: $this, //required singleFileUploads: true, sequentialUploads: opts.sequentialUploads, //must be an array paramName: opts.paramName + '[]', formData: opts.formData, add: function (e, data) { //cancel current upload and remove item on single upload field if (!opts.multiple) { opts.uiCancel.click(); opts.filepool.find('li').remove(); } //add files to the queue $.each(data.files, function (i, file) { file.ext = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase(); queuelength++; var error = getError(file); if (!error) { //add file to queue and to filepool addFile(file, data); } else { //reduces queuelength queuelength--; //throw error opts.onFileError.call($this[0], error, file); } }); //IE and Opera delete the data on submit so we store it temporarily if ($this.data('wl_File')) { $this.data('wl_File').queue = queue; tempdata = $this.data('wl_File'); } else if (tempdata) { tempdata.queue = queue; } //trigger a change for required inputs opts.filepool.trigger('change'); opts.onAdd.call($this[0], e, data); //start upload if autoUpload is true if (opts.autoUpload) upload(data); }, send: function (e, data) { $.each(data.files, function (i, file) { queue[file.name].element.addClass(data.textStatus); queue[file.name].progress.width('100%'); queue[file.name].status.text(opts.text.uploading); }); //rename cancel button opts.uiCancel.text(opts.text.cancel_all).attr('title', opts.text.cancel_all); return opts.onSend.call($this[0], e, data); }, done: function (e, data) { $this.data('wl_File', tempdata); //set states for each file and push them in the list $.each(data.files, function (i, file) { if (queue[file.name]) { queue[file.name].element.addClass(data.textStatus); queue[file.name].progress.width('100%'); queue[file.name].status.text(opts.text.done); queue[file.name].cancel.removeAttr('class').addClass('remove').attr('title', opts.text.remove); if ($.inArray(file.name, files) == -1) { files.push(file.name); $this.data('wl_File').files = files; } //delete from the queue queuelength--; delete queue[file.name]; } }); opts.onDone.call($this[0], e, data); //empty queue => all files uploaded if ($.isEmptyObject(queue)) { //trigger a change for required inputs opts.filepool.trigger('change'); opts.uiCancel.text(opts.text.remove_all).attr('title', opts.text.remove_all); opts.onFinish.call($this[0], e, data); } }, fail: function (e, data) { opts.onFail.call($this[0], e, data); }, always: function (e, data) { opts.onAlways.call($this[0], e, data); }, progress: function (e, data) { //calculate progress for each file $.each(data.files, function (i, file) { if (queue[file.name]) { var percentage = Math.round(parseInt(data.loaded / data.total * 100, 10)); queue[file.name].progress.width(percentage + '%'); queue[file.name].status.text(opts.text.uploading + percentage + '%'); } }); opts.onProgress.call($this[0], e, data); }, progressall: function (e, data) { opts.onProgressAll.call($this[0], e, data); }, start: function (e) { opts.onStart.call($this[0], e); }, stop: function (e) { opts.onStop.call($this[0], e); }, change: function (e, data) { opts.onChange.call($this[0], e, data); }, drop: function (e, data) { opts.onDrop.call($this[0], e, data); }, dragover: function (e) { opts.onDragOver.call($this[0], e); } }); } else { } //upload method function upload(data) { $.each(data.files, function (i, file) { if (queue[file.name]) queue[file.name].fileupload = data.submit(); }); } //add files to the queue and to the filepool function addFile(file, data) { var name = file.name; var html = $('<li><span class="name">' + name + '</span><span class="progress"></span><span class="status">' + opts.text.ready + '</span><a class="cancel" title="' + opts.text.cancel + '">' + opts.text.cancel + '</a></li>').data('fileName', name).appendTo(opts.filepool); queue[name] = { element: html, data: data, progress: html.find('.progress'), status: html.find('.status'), cancel: html.find('.cancel') }; } //check for errors function getError(file) { if (opts.maxNumberOfFiles && (files.length >= opts.maxNumberOfFiles || queuelength > opts.maxNumberOfFiles)) { return { msg: 'maxNumberOfFiles', code: 1 }; } if (opts.allowedExtensions && $.inArray(file.ext, opts.allowedExtensions) == -1) { return { msg: 'allowedExtensions', code: 2 }; } if (typeof file.size === 'number' && opts.maxFileSize && file.size > opts.maxFileSize) { return { msg: 'maxFileSize', code: 3 }; } if (typeof file.size === 'number' && opts.minFileSize && file.size < opts.minFileSize) { return { msg: 'minFileSize', code: 4 }; } return null; } //took from the modernizr script (thanks paul) function isEventSupported(eventName) { var element = document.createElement('div'); eventName = 'on' + eventName; // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those var isSupported = eventName in element; if (!isSupported) { // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element if (!element.setAttribute) { element = document.createElement('div'); } if (element.setAttribute && element.removeAttribute) { element.setAttribute(eventName, ''); isSupported = typeof element[eventName] == 'function'; // If property was created, "remove it" (by setting value to `undefined`) if (typeof element[eventName] != undefined) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } if (opts) $.extend($this.data('wl_File'), opts); }); }; $.fn.wl_File.defaults = { url: 'upload.php', autoUpload: true, paramName: 'files', multiple: false, allowedExtensions: false, maxNumberOfFiles: 0, maxFileSize: 0, minFileSize: 0, sequentialUploads: false, dragAndDrop: true, formData: {}, text: { ready: 'ready', cancel: 'cancel', remove: 'remove', uploading: 'uploading...', done: 'done', start: 'start upload', add_files: 'add files', cancel_all: 'cancel upload', remove_all: 'remove all' }, onAdd: function (e, data) {}, onDelete:function(files){}, onCancel:function(file){}, onSend: function (e, data) {}, onDone: function (e, data) {}, onFinish: function (e, data) {}, onFail: function (e, data) {}, onAlways: function (e, data) {}, onProgress: function (e, data) {}, onProgressAll: function (e, data) {}, onStart: function (e) {}, onStop: function (e) {}, onChange: function (e, data) {}, onDrop: function (e, data) {}, onDragOver: function (e) {}, onFileError: function (error, fileobj) {} }; $.fn.wl_File.version = '1.2'; $.fn.wl_File.methods = { reset: function () { var $this = $(this), opts = $this.data('wl_File'); //default value if uniform is used if($.uniform)$this.next().html($.uniform.options.fileDefaultText); //empty file pool opts.filepool.empty(); //reset button opts.uiCancel.attr('title',opts.text.cancel_all).text(opts.text.cancel_all); //clear array $this.data('wl_File').files = []; }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_File.defaults[key] !== undefined || $.fn.wl_File.defaults[key] == null) { $this.data('wl_File')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_File.js
JavaScript
oos
13,582
/*----------------------------------------------------------------------*/ /* wl_Date v 1.0 by revaxarts.com /* description: extends the Datepicker /* dependency: jQuery Datepicker, mousewheel plugin /*----------------------------------------------------------------------*/ $.fn.wl_Date = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Date.methods[method]) { return $.fn.wl_Date.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Date')) { var opts = $.extend({}, $this.data('wl_Date'), method); } else { var opts = $.extend({}, $.fn.wl_Date.defaults, method, $this.data()); } } else { try { return $this.datepicker(method, args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Date')) { $this.data('wl_Date', {}); //call the jQuery UI datepicker plugin $this.datepicker(opts); //bind a mousewheel event to the input field $this.bind('mousewheel.wl_Date', function (event, delta) { if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; //shift key is pressed if (event.shiftKey) { var _date = $this.datepicker('getDate'); //new delta is the current month day count (month in days) delta *= new Date(_date.getFullYear(), _date.getMonth() + 1, 0).getDate(); } //call the method $.fn.wl_Date.methods.changeDay.call($this[0], delta); } }); //value is set and has to get translated (self-explanatory) if (opts.value) { var today = new Date().getTime(); switch (opts.value) { case 'now': case 'today': $this.datepicker('setDate', new Date()); break; case 'next': case 'tomorrow': $this.datepicker('setDate', new Date(today + 864e5 * 1)); break; case 'prev': case 'yesterday': $this.datepicker('setDate', new Date(today + 864e5 * -1)); break; default: //if a valid number add them as days to the date field if (!isNaN(opts.value)) $this.datepicker('setDate', new Date(today + 864e5 * opts.value)); } } //disable if set if (opts.disabled) { $.fn.wl_Date.methods.disable.call(this); } } else { } if (opts) $.extend($this.data('wl_Date'), opts); }); }; $.fn.wl_Date.defaults = { value: null, mousewheel: true }; $.fn.wl_Date.version = '1.0'; $.fn.wl_Date.methods = { disable: function () { var $this = $(this); //disable the datepicker $this.datepicker('disable'); $this.data('wl_Date').disabled = true; }, enable: function () { var $this = $(this); //enable the datepicker $this.datepicker('enable'); $this.data('wl_Date').disabled = false; }, next: function () { //select next day $.fn.wl_Date.methods.changeDay.call(this, 1); }, prev: function () { //select previous day $.fn.wl_Date.methods.changeDay.call(this, -1); }, changeDay: function (delta) { var $this = $(this), _current = $this.datepicker('getDate') || new Date(); //set day to currentday + delta _current.setDate(_current.getDate() + delta); $this.datepicker('setDate', _current); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Date.defaults[key] !== undefined || $.fn.wl_Date.defaults[key] == null) { $this.data('wl_Date')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Date.js
JavaScript
oos
3,978
/*----------------------------------------------------------------------*/ /* Set some Standards /* This file not required! It just demonstrate how you can define /* standards in one configuration file /*----------------------------------------------------------------------*/ var config = { tooltip :{ gravity: 'nw', fade: false, opacity: 1, offset: 0 } }; //wrap them because of some jQuery Elements $(document).ready(function() { if($.fn.wl_Alert) $.fn.wl_Alert.defaults = { speed: 500, sticky: false, onBeforeClose: function (element) {}, onClose: function (element) {} }; if($.fn.wl_Autocomplete) $.fn.wl_Autocomplete.defaults = { //check http://jqueryui.com/demos/autocomplete/ for all options }; if($.fn.wl_Breadcrump) $.fn.wl_Breadcrump.defaults = { start: 0, numbers: false, allownextonly: false, disabled: false, connect: null, onChange: function () {} }; if($.fn.wl_Calendar) $.fn.wl_Calendar.defaults = { //check http://arshaw.com/fullcalendar/ for all options }; if($.fn.wl_Chart) $.fn.wl_Chart.defaults = { width: null, height: 300, hideTable: true, tableBefore: false, data: {}, stack: false, type: 'lines', points: null, shadowSize: 2, fill: null, fillColor: null, lineWidth: null, legend: true, legendPosition: "ne", // or "nw" or "se" or "sw" tooltip: true, tooltipGravity: 'n', tooltipPattern: function (value, legend, label, id, itemobj) { return "value is " + value + " from " + legend + " at " + label + " (" + id + ")"; }, //tooltipPattern: "value is %1 from %2 at %3 (%4)", //also possible orientation: 'horizontal', colors: ['#b2e7b2', '#f0b7b7', '#b5f0f0', '#e8e8b3', '#efb7ef', '#bbb6f0'], flot: {}, onClick: function (value, legend, label, id, itemobj) {} }; if($.fn.wl_Color) $.fn.wl_Color.defaults = { mousewheel: true, onChange: function (hsb, rgb) {} }; if($.fn.wl_Date) $.fn.wl_Date.defaults = { value: null, mousewheel: true, //some datepicker standards dayNames : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], dayNamesMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], dayNamesShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], firstDay: 0, nextText: 'next', prevText: 'prev', currentText: 'Today', showWeek: true, dateFormat: 'mm/dd/yy' }; if($.confirm) $.confirm.defaults = { text:{ header: 'Please confirm', ok: 'Yes', cancel: 'No' } }; if($.prompt) $.prompt.defaults = { text:{ header: 'Please prompt', ok: 'OK', cancel: 'Cancel' } }; if($.alert) $.alert.defaults = { nativ: false, resizable: false, modal: true, text:{ header: 'Notification', ok: 'OK' } }; if($.fn.wl_Editor) $.fn.wl_Editor.defaults = { css: 'css/light/editor.css', buttons: 'bold|italic|underline|strikeThrough|justifyLeft|justifyCenter|justifyRight|justifyFull|highlight|colorpicker|indent|outdent|subscript|superscript|undo|redo|insertOrderedList|insertUnorderedList|insertHorizontalRule|createLink|insertImage|h1|h2|h3|h4|h5|h6|paragraph|rtl|ltr|cut|copy|paste|increaseFontSize|decreaseFontSize|html|code|removeFormat|insertTable', initialContent: '' }; if($.fn.wl_File) $.fn.wl_File.defaults = { url: 'upload.php', autoUpload: true, paramName: 'files', multiple: false, allowedExtensions: ['jpg','jpeg','gif','png','doc','zip','docx','txt','pdf'], maxNumberOfFiles: 0, maxFileSize: 0, minFileSize: 0, sequentialUploads: false, dragAndDrop: true, formData: {}, text: { ready: 'ready', cancel: 'cancel', remove: 'remove', uploading: 'uploading...', done: 'done', start: 'start upload', add_files: 'add files', cancel_all: 'cancel upload', remove_all: 'remove all' }, onAdd: function (e, data) {}, onDelete:function(files){}, onCancel:function(file){}, onSend: function (e, data) {}, onDone: function (e, data) {}, onFinish: function (e, data) {}, onFail: function (e, data) {}, onAlways: function (e, data) {}, onProgress: function (e, data) {}, onProgressAll: function (e, data) {}, onStart: function (e) {}, onStop: function (e) {}, onChange: function (e, data) {}, onDrop: function (e, data) {}, onDragOver: function (e) {}, onFileError: function (error, fileobj) { $.msg('file is not allowed: ' + fileobj.name, { header: error.msg + ' (' + error.code + ')' }); } }; if($.fn.wl_Fileexplorer) $.fn.wl_Fileexplorer.defaults = { url: 'elfinder/php/connector.php', toolbar: [ ['back', 'reload', 'open', 'select', 'quicklook', 'info', 'rename', 'copy', 'cut', 'paste', 'rm', 'mkdir', 'mkfile', 'upload', 'duplicate', 'edit', 'archive', 'extract', 'resize', 'icons', 'list', 'help'] ] }; if($.fn.wl_Form) $.fn.wl_Form.defaults = { submitButton: 'button.submit', resetButton: 'button.reset', method: 'post', action: null, ajax: true, serialize: false, parseQuery: true, dataType: 'text', status: true, sent: false, confirmSend: true, text: { required: 'This field is required', valid: 'This field is invalid', password: 'This password is to short', passwordmatch: 'This password doesn\'t match', fileinqueue: 'There is at least one file in the queue', incomplete: 'Please fill out the form correctly!', send: 'send form...', sendagain: 'send again?', success: 'form sent!', error: 'error while sending!', parseerror: 'Can\'t unserialize query string:\n %e' }, tooltip: { gravity: 'nw' }, onRequireError: function (element) {}, onValidError: function (element) {}, onPasswordError: function (element) {}, onFileError: function (element) {}, onBeforePrepare: function () {}, onBeforeSubmit: function (data) {}, onReset: function () {}, onComplete: function (textStatus, jqXHR) {}, onError: function (textStatus, error, jqXHR) {}, onSuccess: function (data, textStatus, jqXHR) {} }; if($.fn.wl_Gallery) $.fn.wl_Gallery.defaults = { group: 'wl_gallery', editBtn: true, deleteBtn: true, fancybox: {}, onEdit: function (element, href, title) {}, onDelete: function (element, href, title) {}, onMove: function (element, href, title, newOrder) {} }; if($.fn.wl_Multiselect) $.fn.wl_Multiselect.defaults = { height: 200, items: [], selected: [], showUsed: false, searchfield: true, onAdd: function (values) {}, onRemove: function (values) {}, onSelect: function (values) {}, onUnselect: function (values) {}, onSort: function (values) {} }; if($.fn.wl_Number) $.fn.wl_Number.defaults = { step: 1, decimals: 0, start: 0, min: null, max: null, mousewheel: true, onChange: function (value) {}, onError: function (value) {} }; if($.fn.wl_Password) $.fn.wl_Password.defaults = { confirm: true, showStrength: true, words: ['too short', 'bad', 'medium', 'good', 'very good', 'excellent'], minLength: 3, text: { confirm: 'please confirm', nomatch: 'password doesn\'t match' } }; if($.fn.wl_Slider) $.fn.wl_Slider.defaults = { min: 0, max: 100, step: 1, animate: false, disabled: false, orientation: 'horizontal', range: false, mousewheel: true, connect: null, tooltip: false, tooltipGravity: ['s','w'], tooltipPattern: "%n", onSlide: function (value) {}, onChange: function (value) {} }; if($.fn.wl_Time) $.fn.wl_Time.defaults = { step: 5, timeformat: 24, roundtime: true, time: null, value: null, mousewheel: true, onDateChange: function (offset) {}, onHourChange: function (offset) {}, onChange: function (value) {} }; if($.fn.wl_Valid) $.fn.wl_Valid.defaults = { errorClass: 'error', instant: true, regex: /.*/, minLength: 0, onChange: function ($this, value) {}, onError: function ($this, value) {} }; if($.fn.wl_Mail) $.fn.wl_Mail.defaults = { regex: /^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$|(\[?(\d{1,3}\.){3}\d{1,3}\]?)$/i, onChange: function (element, value) { element.val(value.toLowerCase()); } }; if($.fn.wl_URL) $.fn.wl_URL.defaults = { regex: /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w]))*\.+(([\w#!:.?+=&%@!\-\/]))?/, instant: false, onChange: function (element, value) { if (value != '' && !/^(ftp|http|https):\/\//.test(value)) element.val('http://' + value).trigger('change.wl_Valid'); } }; if($.fn.wl_Widget) $.fn.wl_Widget.defaults = { collapsed: false, load: null, reload: false, removeContent: true, collapsible: true, sortable: true, text: { loading: 'loading...', reload: 'reload', collapse: 'collapse widget', expand: 'expand widget' }, onDrag: function () {}, onDrop: function () {}, onExpand: function () {}, onCollapse: function () {} }; });
08102013project
trunk/CMS/Scripts/plugins/config.js
JavaScript
oos
8,823
$(document).ready(function () { /** * WYSIWYG - jQuery plugin 0.97 * (0.97.2 - From infinity) * * Copyright (c) 2008-2009 Juan M Martinez, 2010-2011 Akzhan Abdulin and all contributors * https://github.com/akzhan/jwysiwyg * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /*jslint browser: true, forin: true */ (function ($) { "use strict"; /* Wysiwyg namespace: private properties and methods */ var console = window.console ? window.console : { log: $.noop, error: function (msg) { $.error(msg); } }; var supportsProp = (('prop' in $.fn) && ('removeProp' in $.fn)); function Wysiwyg() { this.controls = { bold: { groupIndex: 0, visible: false, tags: ["b", "strong"], css: { fontWeight: "bold" }, tooltip: "Bold", hotkey: { "ctrl": 1, "key": 66 } }, copy: { groupIndex: 8, visible: false, tooltip: "Copy" }, colorpicker: { visible: false, groupIndex: 1, tooltip: "Colorpicker", exec: function() { $.wysiwyg.controls.colorpicker.init(this); } }, createLink: { groupIndex: 6, visible: false, exec: function () { var self = this; if ($.wysiwyg.controls && $.wysiwyg.controls.link) { $.wysiwyg.controls.link.init(this); } else if ($.wysiwyg.autoload) { $.wysiwyg.autoload.control("wysiwyg.link.js", function () { self.controls.createLink.exec.apply(self); }); } else { console.error("$.wysiwyg.controls.link not defined. You need to include wysiwyg.link.js file"); } }, tags: ["a"], tooltip: "Create link" }, cut: { groupIndex: 8, visible: false, tooltip: "Cut" }, decreaseFontSize: { groupIndex: 9, visible: false, tags: ["small"], tooltip: "Decrease font size", exec: function () { this.decreaseFontSize(); } }, h1: { groupIndex: 7, visible: false, className: "h1", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h1>" : "h1", tags: ["h1"], tooltip: "Header 1" }, h2: { groupIndex: 7, visible: false, className: "h2", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h2>" : "h2", tags: ["h2"], tooltip: "Header 2" }, h3: { groupIndex: 7, visible: false, className: "h3", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h3>" : "h3", tags: ["h3"], tooltip: "Header 3" }, h4: { groupIndex: 7, visible: false, className: "h4", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h4>" : "h4", tags: ["h4"], tooltip: "Header 4" }, h5: { groupIndex: 7, visible: false, className: "h5", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h5>" : "h5", tags: ["h5"], tooltip: "Header 5" }, h6: { groupIndex: 7, visible: false, className: "h6", command: ($.browser.msie || $.browser.safari || $.browser.opera) ? "FormatBlock" : "heading", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<h6>" : "h6", tags: ["h6"], tooltip: "Header 6" }, highlight: { tooltip: "Highlight", className: "highlight", groupIndex: 1, visible: false, css: { backgroundColor: "rgb(255, 255, 102)" }, exec: function () { var command, node, selection, args; if ($.browser.msie || $.browser.safari) { command = "backcolor"; } else { command = "hilitecolor"; } if ($.browser.msie) { node = this.getInternalRange().parentElement(); } else { selection = this.getInternalSelection(); node = selection.extentNode || selection.focusNode; while (node.style === undefined) { node = node.parentNode; if (node.tagName && node.tagName.toLowerCase() === "body") { return; } } } if (node.style.backgroundColor === "rgb(255, 255, 102)" || node.style.backgroundColor === "#ffff66") { args = "#ffffff"; } else { args = "#ffff66"; } this.editorDoc.execCommand(command, false, args); } }, html: { groupIndex: 10, visible: false, exec: function () { var elementHeight; if (this.options.resizeOptions && $.fn.resizable) { elementHeight = this.element.height(); } if (this.viewHTML) { this.setContent(this.original.value); $(this.original).hide(); this.editor.show(); if (this.options.resizeOptions && $.fn.resizable) { // if element.height still the same after frame was shown if (elementHeight === this.element.height()) { this.element.height(elementHeight + this.editor.height()); } this.element.resizable($.extend(true, { alsoResize: this.editor }, this.options.resizeOptions)); } this.ui.toolbar.find("li").each(function () { var li = $(this); if (li.hasClass("html")) { li.removeClass("active"); } else { li.removeClass('disabled'); } }); } else { this.saveContent(); $(this.original).css({ width: this.element.outerWidth() - 6, height: this.element.height() - this.ui.toolbar.height() - 6, resize: "none" }).show(); this.editor.hide(); if (this.options.resizeOptions && $.fn.resizable) { // if element.height still the same after frame was hidden if (elementHeight === this.element.height()) { this.element.height(this.ui.toolbar.height()); } this.element.resizable("destroy"); } this.ui.toolbar.find("li").each(function () { var li = $(this); if (li.hasClass("html")) { li.addClass("active"); } else { if (false === li.hasClass("fullscreen")) { li.removeClass("active").addClass('disabled'); } } }); } this.viewHTML = !(this.viewHTML); }, tooltip: "View source code" }, increaseFontSize: { groupIndex: 9, visible: false, tags: ["big"], tooltip: "Increase font size", exec: function () { this.increaseFontSize(); } }, insertImage: { groupIndex: 6, visible: false, exec: function () { var self = this; if ($.wysiwyg.controls && $.wysiwyg.controls.image) { $.wysiwyg.controls.image.init(this); } else if ($.wysiwyg.autoload) { $.wysiwyg.autoload.control("wysiwyg.image.js", function () { self.controls.insertImage.exec.apply(self); }); } else { console.error("$.wysiwyg.controls.image not defined. You need to include wysiwyg.image.js file"); } }, tags: ["img"], tooltip: "Insert image" }, insertOrderedList: { groupIndex: 5, visible: false, tags: ["ol"], tooltip: "Insert Ordered List" }, insertTable: { groupIndex: 6, visible: false, exec: function () { var self = this; if ($.wysiwyg.controls && $.wysiwyg.controls.table) { $.wysiwyg.controls.table(this); } else if ($.wysiwyg.autoload) { $.wysiwyg.autoload.control("wysiwyg.table.js", function () { self.controls.insertTable.exec.apply(self); }); } else { console.error("$.wysiwyg.controls.table not defined. You need to include wysiwyg.table.js file"); } }, tags: ["table"], tooltip: "Insert table" }, insertUnorderedList: { groupIndex: 5, visible: false, tags: ["ul"], tooltip: "Insert Unordered List" }, italic: { groupIndex: 0, visible: false, tags: ["i", "em"], css: { fontStyle: "italic" }, tooltip: "Italic", hotkey: { "ctrl": 1, "key": 73 } }, justifyLeft: { visible: false, groupIndex: 1, css: { textAlign: "left" }, tooltip: "Justify Left" }, justifyCenter: { groupIndex: 1, visible: false, tags: ["center"], css: { textAlign: "center" }, tooltip: "Justify Center" }, justifyRight: { groupIndex: 1, visible: false, css: { textAlign: "right" }, tooltip: "Justify Right" }, justifyFull: { groupIndex: 1, visible: false, css: { textAlign: "justify" }, tooltip: "Justify Full" }, ltr: { groupIndex: 9, visible: false, exec: function () { var p = this.dom.getElement("p"); if (!p) { return false; } $(p).attr("dir", "ltr"); return true; }, tooltip: "Left to Right" }, rtl: { groupIndex: 9, visible: false, exec: function () { var p = this.dom.getElement("p"); if (!p) { return false; } $(p).attr("dir", "rtl"); return true; }, tooltip: "Right to Left" }, indent: { groupIndex: 2, visible: false, tooltip: "Indent" }, outdent: { groupIndex: 2, visible: false, tooltip: "Outdent" }, insertHorizontalRule: { groupIndex: 5, visible: false, tags: ["hr"], tooltip: "Insert Horizontal Rule" }, paragraph: { groupIndex: 7, visible: false, className: "paragraph", command: "FormatBlock", "arguments": ($.browser.msie || $.browser.safari || $.browser.opera) ? "<p>" : "p", tags: ["p"], tooltip: "Paragraph" }, paste: { groupIndex: 8, visible: false, tooltip: "Paste" }, undo: { groupIndex: 4, visible: false, tooltip: "Undo" }, redo: { groupIndex: 4, visible: false, tooltip: "Redo" }, removeFormat: { groupIndex: 10, visible: false, exec: function () { this.removeFormat(); }, tooltip: "Remove formatting" }, underline: { groupIndex: 0, visible: false, tags: ["u"], css: { textDecoration: "underline" }, tooltip: "Underline", hotkey: { "ctrl": 1, "key": 85 } }, strikeThrough: { groupIndex: 0, visible: false, tags: ["s", "strike"], css: { textDecoration: "line-through" }, tooltip: "Strike-through" }, subscript: { groupIndex: 3, visible: false, tags: ["sub"], tooltip: "Subscript" }, superscript: { groupIndex: 3, visible: false, tags: ["sup"], tooltip: "Superscript" }, code: { visible: false, groupIndex: 6, tooltip: "Code snippet", exec: function () { var range = this.getInternalRange(), common = $(range.commonAncestorContainer), $nodeName = range.commonAncestorContainer.nodeName.toLowerCase(); if (common.parent("code").length) { common.unwrap(); } else { if ($nodeName !== "body") { common.wrap("<code/>"); } } } }, cssWrap: { visible: false, groupIndex: 6, tooltip: "CSS Wrapper", exec: function () { $.wysiwyg.controls.cssWrap.init(this); } } }; this.defaults = { html: '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>INITIAL_CONTENT</body></html>', debug: false, controls: {}, css: {}, events: {}, autoGrow: false, autoSave: true, brIE: true, // http://code.google.com/p/jwysiwyg/issues/detail?id=15 formHeight: 270, formWidth: 440, iFrameClass: null, initialContent: "<p>Initial content</p>", maxHeight: 10000, // see autoGrow maxLength: 0, messages: { nonSelection: "Select the text you wish to link" }, toolbarHtml: '<ul role="menu" class="toolbar"></ul>', removeHeadings: false, replaceDivWithP: false, resizeOptions: false, rmUnusedControls: false, // https://github.com/akzhan/jwysiwyg/issues/52 rmUnwantedBr: true, // http://code.google.com/p/jwysiwyg/issues/detail?id=11 tableFiller: null, initialMinHeight: null, controlImage: { forceRelativeUrls: false }, controlLink: { forceRelativeUrls: false }, plugins: { // placeholder for plugins settings autoload: false, i18n: false, rmFormat: { rmMsWordMarkup: false } } }; this.availableControlProperties = ["arguments", "callback", "className", "command", "css", "custom", "exec", "groupIndex", "hotkey", "icon", "tags", "tooltip", "visible"]; this.editor = null; this.editorDoc = null; this.element = null; this.options = {}; this.original = null; this.savedRange = null; this.timers = []; this.validKeyCodes = [8, 9, 13, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46]; this.isDestroyed = false; this.dom = { // DOM related properties and methods ie: { parent: null // link to dom }, w3c: { parent: null // link to dom } }; this.dom.parent = this; this.dom.ie.parent = this.dom; this.dom.w3c.parent = this.dom; this.ui = {}; // UI related properties and methods this.ui.self = this; this.ui.toolbar = null; this.ui.initialHeight = null; // ui.grow this.dom.getAncestor = function (element, filterTagName) { filterTagName = filterTagName.toLowerCase(); while (element && "body" !== element.tagName.toLowerCase()) { if (filterTagName === element.tagName.toLowerCase()) { return element; } element = element.parentNode; } return null; }; this.dom.getElement = function (filterTagName) { var dom = this; if (window.getSelection) { return dom.w3c.getElement(filterTagName); } else { return dom.ie.getElement(filterTagName); } }; this.dom.ie.getElement = function (filterTagName) { var dom = this.parent, selection = dom.parent.getInternalSelection(), range = selection.createRange(), element; if ("Control" === selection.type) { // control selection if (1 === range.length) { element = range.item(0); } else { // multiple control selection return null; } } else { element = range.parentElement(); } return dom.getAncestor(element, filterTagName); }; this.dom.w3c.getElement = function (filterTagName) { var dom = this.parent, range = dom.parent.getInternalRange(), element; if (!range) { return null; } element = range.commonAncestorContainer; if (3 === element.nodeType) { element = element.parentNode; } // if startContainer not Text, Comment, or CDATASection element then // startOffset is the number of child nodes between the start of the // startContainer and the boundary point of the Range if (element === range.startContainer) { element = element.childNodes[range.startOffset]; } return dom.getAncestor(element, filterTagName); }; this.ui.addHoverClass = function () { $(this).addClass("wysiwyg-button-hover"); }; this.ui.appendControls = function () { var ui = this, self = this.self, controls = self.parseControls(), hasVisibleControls = true, // to prevent separator before first item groups = [], controlsByGroup = {}, i, currentGroupIndex, // jslint wants all vars at top of function iterateGroup = function (controlName, control) { if (control.groupIndex && currentGroupIndex !== control.groupIndex) { currentGroupIndex = control.groupIndex; hasVisibleControls = false; } if (!control.visible) { return; } if (!hasVisibleControls) { ui.appendItemSeparator(); hasVisibleControls = true; } if (control.custom) { ui.appendItemCustom(controlName, control); } else { ui.appendItem(controlName, control); } }; $.each(controls, function (name, c) { var index = "empty"; if (undefined !== c.groupIndex) { if ("" === c.groupIndex) { index = "empty"; } else { index = c.groupIndex; } } if (undefined === controlsByGroup[index]) { groups.push(index); controlsByGroup[index] = {}; } controlsByGroup[index][name] = c; }); groups.sort(function (a, b) { if ("number" === typeof (a) && typeof (a) === typeof (b)) { return (a - b); } else { a = a.toString(); b = b.toString(); if (a > b) { return 1; } if (a === b) { return 0; } return -1; } }); if (0 < groups.length) { // set to first index in groups to proper placement of separator currentGroupIndex = groups[0]; } for (i = 0; i < groups.length; i += 1) { $.each(controlsByGroup[groups[i]], iterateGroup); } }; this.ui.appendItem = function (name, control) { var self = this.self, className = control.className || control.command || name || "empty", tooltip = control.tooltip || control.command || name || ""; return $('<li role="menuitem" unselectable="on">' + (className) + "</li>").addClass(className).attr("title", tooltip).hover(this.addHoverClass, this.removeHoverClass).click(function () { if ($(this).hasClass("disabled")) { return false; } self.triggerControl.apply(self, [name, control]); this.blur(); self.ui.returnRange(); self.ui.focus(); return true; }).appendTo(self.ui.toolbar); }; this.ui.appendItemCustom = function (name, control) { var self = this.self, tooltip = control.tooltip || control.command || name || ""; if (control.callback) { $(window).bind("trigger-" + name + ".wysiwyg", control.callback); } return $('<li role="menuitem" unselectable="on" style="background: url(\'' + control.icon + '\') no-repeat;"></li>').addClass("custom-command-" + name).addClass("wysiwyg-custom-command").addClass(name).attr("title", tooltip).hover(this.addHoverClass, this.removeHoverClass).click(function () { if ($(this).hasClass("disabled")) { return false; } self.triggerControl.apply(self, [name, control]); this.blur(); self.ui.returnRange(); self.ui.focus(); self.triggerControlCallback(name); return true; }).appendTo(self.ui.toolbar); }; this.ui.appendItemSeparator = function () { var self = this.self; return $('<li role="separator" class="separator"></li>').appendTo(self.ui.toolbar); }; this.autoSaveFunction = function () { this.saveContent(); }; this.ui.checkTargets = function (element) { var self = this.self; $.each(self.options.controls, function (name, control) { var className = control.className || control.command || name || "empty", tags, elm, css, el, checkActiveStatus = function (cssProperty, cssValue) { var handler; if ("function" === typeof (cssValue)) { handler = cssValue; if (handler(el.css(cssProperty).toString().toLowerCase(), self)) { self.ui.toolbar.find("." + className).addClass("active"); } } else { if (el.css(cssProperty).toString().toLowerCase() === cssValue) { self.ui.toolbar.find("." + className).addClass("active"); } } }; if ("fullscreen" !== className) { self.ui.toolbar.find("." + className).removeClass("active"); } if (control.tags || (control.options && control.options.tags)) { tags = control.tags || (control.options && control.options.tags); elm = element; while (elm) { if (elm.nodeType !== 1) { break; } if ($.inArray(elm.tagName.toLowerCase(), tags) !== -1) { self.ui.toolbar.find("." + className).addClass("active"); } elm = elm.parentNode; } } if (control.css || (control.options && control.options.css)) { css = control.css || (control.options && control.options.css); el = $(element); while (el) { if (el[0].nodeType !== 1) { break; } $.each(css, checkActiveStatus); el = el.parent(); } } }); }; this.ui.designMode = function () { var attempts = 3, self = this.self, runner; runner = function (attempts) { if ("on" === self.editorDoc.designMode) { if (self.timers.designMode) { window.clearTimeout(self.timers.designMode); } // IE needs to reget the document element (this.editorDoc) after designMode was set if (self.innerDocument() !== self.editorDoc) { self.ui.initFrame(); } return; } try { self.editorDoc.designMode = "on"; } catch (e) {} attempts -= 1; if (attempts > 0) { self.timers.designMode = window.setTimeout(function () { runner(attempts); }, 100); } }; runner(attempts); }; this.destroy = function () { this.isDestroyed = true; var i, $form = this.element.closest("form"); for (i = 0; i < this.timers.length; i += 1) { window.clearTimeout(this.timers[i]); } // Remove bindings $form.unbind(".wysiwyg"); this.element.remove(); $.removeData(this.original, "wysiwyg"); $(this.original).show(); return this; }; this.getRangeText = function () { var r = this.getInternalRange(); if (r.toString) { r = r.toString(); } else if (r.text) { // IE r = r.text; } return r; }; //not used? this.execute = function (command, arg) { if (typeof (arg) === "undefined") { arg = null; } this.editorDoc.execCommand(command, false, arg); }; this.extendOptions = function (options) { var controls = {}; /** * If the user set custom controls, we catch it, and merge with the * defaults controls later. */ if ("object" === typeof options.controls) { controls = options.controls; delete options.controls; } options = $.extend(true, {}, this.defaults, options); options.controls = $.extend(true, {}, controls, this.controls, controls); if (options.rmUnusedControls) { $.each(options.controls, function (controlName) { if (!controls[controlName]) { delete options.controls[controlName]; } }); } return options; }; this.ui.focus = function () { var self = this.self; self.editor.get(0).contentWindow.focus(); return self; }; this.ui.returnRange = function () { var self = this.self, sel; if (self.savedRange !== null) { if (window.getSelection) { //non IE and there is already a selection sel = window.getSelection(); if (sel.rangeCount > 0) { sel.removeAllRanges(); } try { sel.addRange(self.savedRange); } catch (e) { console.error(e); } } else if (window.document.createRange) { // non IE and no selection window.getSelection().addRange(self.savedRange); } else if (window.document.selection) { //IE self.savedRange.select(); } self.savedRange = null; } }; this.increaseFontSize = function () { if ($.browser.mozilla || $.browser.opera) { this.editorDoc.execCommand('increaseFontSize', false, null); } else if ($.browser.safari) { var newNode = this.editorDoc.createElement('big'); this.getInternalRange().surroundContents(newNode); } else { console.error("Internet Explorer?"); } }; this.decreaseFontSize = function () { if ($.browser.mozilla || $.browser.opera) { this.editorDoc.execCommand('decreaseFontSize', false, null); } else if ($.browser.safari) { var newNode = this.editorDoc.createElement('small'); this.getInternalRange().surroundContents(newNode); } else { console.error("Internet Explorer?"); } }; this.getContent = function () { if (this.viewHTML) { this.setContent(this.original.value); } return this.events.filter('getContent', this.editorDoc.body.innerHTML); }; /** * A jWysiwyg specific event system. * * Example: * * $("#editor").getWysiwyg().events.bind("getContent", function (orig) { * return "<div id='content'>"+orgi+"</div>"; * }); * * This makes it so that when ever getContent is called, it is wrapped in a div#content. */ this.events = { _events: {}, /** * Similar to jQuery's bind, but for jWysiwyg only. */ bind: function (eventName, callback) { if (typeof (this._events.eventName) !== "object") { this._events[eventName] = []; } this._events[eventName].push(callback); }, /** * Similar to jQuery's trigger, but for jWysiwyg only. */ trigger: function (eventName, args) { if (typeof (this._events.eventName) === "object") { var editor = this.editor; $.each(this._events[eventName], function (k, v) { if (typeof (v) === "function") { v.apply(editor, args); } }); } }, /** * This "filters" `originalText` by passing it as the first argument to every callback * with the name `eventName` and taking the return value and passing it to the next function. * * This function returns the result after all the callbacks have been applied to `originalText`. */ filter: function (eventName, originalText) { if (typeof (this._events[eventName]) === "object") { var editor = this.editor, args = Array.prototype.slice.call(arguments, 1); $.each(this._events[eventName], function (k, v) { if (typeof (v) === "function") { originalText = v.apply(editor, args); } }); } return originalText; } }; this.getElementByAttributeValue = function (tagName, attributeName, attributeValue) { var i, value, elements = this.editorDoc.getElementsByTagName(tagName); for (i = 0; i < elements.length; i += 1) { value = elements[i].getAttribute(attributeName); if ($.browser.msie) { /** IE add full path, so I check by the last chars. */ value = value.substr(value.length - attributeValue.length); } if (value === attributeValue) { return elements[i]; } } return false; }; this.getInternalRange = function () { var selection = this.getInternalSelection(); if (!selection) { return null; } if (selection.rangeCount && selection.rangeCount > 0) { // w3c return selection.getRangeAt(0); } else if (selection.createRange) { // ie return selection.createRange(); } return null; }; this.getInternalSelection = function () { // firefox: document.getSelection is deprecated if (this.editor.get(0).contentWindow) { if (this.editor.get(0).contentWindow.getSelection) { return this.editor.get(0).contentWindow.getSelection(); } if (this.editor.get(0).contentWindow.selection) { return this.editor.get(0).contentWindow.selection; } } if (this.editorDoc.getSelection) { return this.editorDoc.getSelection(); } if (this.editorDoc.selection) { return this.editorDoc.selection; } return null; }; this.getRange = function () { var selection = this.getSelection(); if (!selection) { return null; } if (selection.rangeCount && selection.rangeCount > 0) { // w3c selection.getRangeAt(0); } else if (selection.createRange) { // ie return selection.createRange(); } return null; }; this.getSelection = function () { return (window.getSelection) ? window.getSelection() : window.document.selection; }; // :TODO: you can type long string and letters will be hidden because of overflow this.ui.grow = function () { var self = this.self, innerBody = $(self.editorDoc.body), innerHeight = $.browser.msie ? innerBody[0].scrollHeight : innerBody.height() + 2 + 20, // 2 - borders, 20 - to prevent content jumping on grow minHeight = self.ui.initialHeight, height = Math.max(innerHeight, minHeight); height = Math.min(height, self.options.maxHeight); self.editor.attr("scrolling", height < self.options.maxHeight ? "no" : "auto"); // hide scrollbar firefox innerBody.css("overflow", height < self.options.maxHeight ? "hidden" : ""); // hide scrollbar chrome self.editor.get(0).height = height; return self; }; this.init = function (element, options) { var self = this, $form = $(element).closest("form"), newX = element.width || element.clientWidth || 0, newY = element.height || element.clientHeight || 0; this.options = this.extendOptions(options); this.original = element; this.ui.toolbar = $(this.options.toolbarHtml); if ($.browser.msie && parseInt($.browser.version, 10) < 8) { this.options.autoGrow = false; } if (newX === 0 && element.cols) { newX = (element.cols * 8) + 21; } if (newY === 0 && element.rows) { newY = (element.rows * 16) + 16; } this.editor = $(window.location.protocol === "https:" ? '<iframe src="javascript:false;"></iframe>' : "<iframe></iframe>").attr("frameborder", "0"); if (this.options.iFrameClass) { this.editor.addClass(this.options.iFrameClass); } else { this.editor.css({ minHeight: (newY - 6).toString() + "px", // fix for issue 12 ( http://github.com/akzhan/jwysiwyg/issues/issue/12 ) width: (newX > 50) ? (newX - 8).toString() + "px" : "" }); if ($.browser.msie && parseInt($.browser.version, 10) < 7) { this.editor.css("height", newY.toString() + "px"); } } /** * http://code.google.com/p/jwysiwyg/issues/detail?id=96 */ this.editor.attr("tabindex", $(element).attr("tabindex")); this.element = $("<div/>").addClass("wysiwyg"); if (!this.options.iFrameClass) { this.element.css({ width: (newX > 0) ? newX.toString() + "px" : "100%" }); } $(element).hide().before(this.element); this.viewHTML = false; /** * @link http://code.google.com/p/jwysiwyg/issues/detail?id=52 */ this.initialContent = $(element).val(); this.ui.initFrame(); if (this.options.resizeOptions && $.fn.resizable) { this.element.resizable($.extend(true, { alsoResize: this.editor }, this.options.resizeOptions)); } if (this.options.autoSave) { $form.bind("submit.wysiwyg", function () { self.autoSaveFunction(); }); } $form.bind("reset.wysiwyg", function () { self.resetFunction(); }); }; this.ui.initFrame = function () { var self = this.self, stylesheet, growHandler, saveHandler; self.ui.appendControls(); self.element.append(self.ui.toolbar).append($("<div><!-- --></div>").css({ clear: "both" })).append(self.editor); self.editorDoc = self.innerDocument(); if (self.isDestroyed) { return null; } self.ui.designMode(); self.editorDoc.open(); self.editorDoc.write( self.options.html /** * @link http://code.google.com/p/jwysiwyg/issues/detail?id=144 */ .replace(/INITIAL_CONTENT/, function () { return self.wrapInitialContent(); })); self.editorDoc.close(); $.wysiwyg.plugin.bind(self); $(self.editorDoc).trigger("initFrame.wysiwyg"); $(self.editorDoc).bind("click.wysiwyg", function (event) { self.ui.checkTargets(event.target ? event.target : event.srcElement); }); /** * @link http://code.google.com/p/jwysiwyg/issues/detail?id=20 */ $(self.original).focus(function () { if ($(this).filter(":visible")) { return; } self.ui.focus(); }); $(self.editorDoc).keydown(function (event) { var emptyContentRegex; if (event.keyCode === 8) { // backspace emptyContentRegex = /^<([\w]+)[^>]*>(<br\/?>)?<\/\1>$/; if (emptyContentRegex.test(self.getContent())) { // if content is empty event.stopPropagation(); // prevent remove single empty tag return false; } } return true; }); if (!$.browser.msie) { $(self.editorDoc).keydown(function (event) { var controlName; /* Meta for Macs. tom@punkave.com */ if (event.ctrlKey || event.metaKey) { for (controlName in self.controls) { if (self.controls[controlName].hotkey && self.controls[controlName].hotkey.ctrl) { if (event.keyCode === self.controls[controlName].hotkey.key) { self.triggerControl.apply(self, [controlName, self.controls[controlName]]); return false; } } } } return true; }); } else if (self.options.brIE) { $(self.editorDoc).keydown(function (event) { if (event.keyCode === 13) { var rng = self.getRange(); rng.pasteHTML("<br/>"); rng.collapse(false); rng.select(); return false; } return true; }); } if (self.options.plugins.rmFormat.rmMsWordMarkup) { $(self.editorDoc).bind("keyup.wysiwyg", function (event) { if (event.ctrlKey || event.metaKey) { // CTRL + V (paste) if (86 === event.keyCode) { if ($.wysiwyg.rmFormat) { if ("object" === typeof (self.options.plugins.rmFormat.rmMsWordMarkup)) { $.wysiwyg.rmFormat.run(self, { rules: { msWordMarkup: self.options.plugins.rmFormat.rmMsWordMarkup } }); } else { $.wysiwyg.rmFormat.run(self, { rules: { msWordMarkup: { enabled: true } } }); } } } } }); } if (self.options.autoSave) { $(self.editorDoc).keydown(function () { self.autoSaveFunction(); }).keyup(function () { self.autoSaveFunction(); }).mousedown(function () { self.autoSaveFunction(); }).bind($.support.noCloneEvent ? "input.wysiwyg" : "paste.wysiwyg", function () { self.autoSaveFunction(); }); } if (self.options.autoGrow) { if (self.options.initialMinHeight !== null) { self.ui.initialHeight = self.options.initialMinHeight; } else { self.ui.initialHeight = $(self.editorDoc).height(); } $(self.editorDoc.body).css("border", "1px solid white"); // cancel margin collapsing growHandler = function () { self.ui.grow(); }; $(self.editorDoc).keyup(growHandler); $(self.editorDoc).bind("editorRefresh.wysiwyg", growHandler); // fix when content height > textarea height self.ui.grow(); } if (self.options.css) { if (String === self.options.css.constructor) { if ($.browser.msie) { stylesheet = self.editorDoc.createStyleSheet(self.options.css); $(stylesheet).attr({ "media": "all" }); } else { stylesheet = $("<link/>").attr({ "href": self.options.css, "media": "all", "rel": "stylesheet", "type": "text/css" }); $(self.editorDoc).find("head").append(stylesheet); } } else { self.timers.initFrame_Css = window.setTimeout(function () { $(self.editorDoc.body).css(self.options.css); }, 0); } } if (self.initialContent.length === 0) { if ("function" === typeof (self.options.initialContent)) { self.setContent(self.options.initialContent()); } else { self.setContent(self.options.initialContent); } } if (self.options.maxLength > 0) { $(self.editorDoc).keydown(function (event) { if ($(self.editorDoc).text().length >= self.options.maxLength && $.inArray(event.which, self.validKeyCodes) === -1) { event.preventDefault(); } }); } // Support event callbacks $.each(self.options.events, function (key, handler) { $(self.editorDoc).bind(key + ".wysiwyg", function (event) { // Trigger event handler, providing the event and api to // support additional functionality. handler.apply(self.editorDoc, [event, self]); }); }); // restores selection properly on focus if ($.browser.msie) { // Event chain: beforedeactivate => focusout => blur. // Focusout & blur fired too late to handle internalRange() in dialogs. // When clicked on input boxes both got range = null $(self.editorDoc).bind("beforedeactivate.wysiwyg", function () { self.savedRange = self.getInternalRange(); }); } else { $(self.editorDoc).bind("blur.wysiwyg", function () { self.savedRange = self.getInternalRange(); }); } $(self.editorDoc.body).addClass("wysiwyg"); if (self.options.events && self.options.events.save) { saveHandler = self.options.events.save; $(self.editorDoc).bind("keyup.wysiwyg", saveHandler); $(self.editorDoc).bind("change.wysiwyg", saveHandler); if ($.support.noCloneEvent) { $(self.editorDoc).bind("input.wysiwyg", saveHandler); } else { $(self.editorDoc).bind("paste.wysiwyg", saveHandler); $(self.editorDoc).bind("cut.wysiwyg", saveHandler); } } /** * XHTML5 {@link https://github.com/akzhan/jwysiwyg/issues/152} */ if (self.options.xhtml5 && self.options.unicode) { var replacements = { ne: 8800, le: 8804, para: 182, xi: 958, darr: 8595, nu: 957, oacute: 243, Uacute: 218, omega: 969, prime: 8242, pound: 163, igrave: 236, thorn: 254, forall: 8704, emsp: 8195, lowast: 8727, brvbar: 166, alefsym: 8501, nbsp: 160, delta: 948, clubs: 9827, lArr: 8656, Omega: 937, Auml: 196, cedil: 184, and: 8743, plusmn: 177, ge: 8805, raquo: 187, uml: 168, equiv: 8801, laquo: 171, rdquo: 8221, Epsilon: 917, divide: 247, fnof: 402, chi: 967, Dagger: 8225, iacute: 237, rceil: 8969, sigma: 963, Oslash: 216, acute: 180, frac34: 190, lrm: 8206, upsih: 978, Scaron: 352, part: 8706, exist: 8707, nabla: 8711, image: 8465, prop: 8733, zwj: 8205, omicron: 959, aacute: 225, Yuml: 376, Yacute: 221, weierp: 8472, rsquo: 8217, otimes: 8855, kappa: 954, thetasym: 977, harr: 8596, Ouml: 214, Iota: 921, ograve: 242, sdot: 8901, copy: 169, oplus: 8853, acirc: 226, sup: 8835, zeta: 950, Iacute: 205, Oacute: 211, crarr: 8629, Nu: 925, bdquo: 8222, lsquo: 8216, apos: 39, Beta: 914, eacute: 233, egrave: 232, lceil: 8968, Kappa: 922, piv: 982, Ccedil: 199, ldquo: 8220, Xi: 926, cent: 162, uarr: 8593, hellip: 8230, Aacute: 193, ensp: 8194, sect: 167, Ugrave: 217, aelig: 230, ordf: 170, curren: 164, sbquo: 8218, macr: 175, Phi: 934, Eta: 919, rho: 961, Omicron: 927, sup2: 178, euro: 8364, aring: 229, Theta: 920, mdash: 8212, uuml: 252, otilde: 245, eta: 951, uacute: 250, rArr: 8658, nsub: 8836, agrave: 224, notin: 8713, ndash: 8211, Psi: 936, Ocirc: 212, sube: 8838, szlig: 223, micro: 181, not: 172, sup1: 185, middot: 183, iota: 953, ecirc: 234, lsaquo: 8249, thinsp: 8201, sum: 8721, ntilde: 241, scaron: 353, cap: 8745, atilde: 227, lang: 10216, __replacement: 65533, isin: 8712, gamma: 947, Euml: 203, ang: 8736, upsilon: 965, Ntilde: 209, hearts: 9829, Alpha: 913, Tau: 932, spades: 9824, dagger: 8224, THORN: 222, "int": 8747, lambda: 955, Eacute: 201, Uuml: 220, infin: 8734, rlm: 8207, Aring: 197, ugrave: 249, Egrave: 200, Acirc: 194, rsaquo: 8250, ETH: 208, oslash: 248, alpha: 945, Ograve: 210, Prime: 8243, mu: 956, ni: 8715, real: 8476, bull: 8226, beta: 946, icirc: 238, eth: 240, prod: 8719, larr: 8592, ordm: 186, perp: 8869, Gamma: 915, reg: 174, ucirc: 251, Pi: 928, psi: 968, tilde: 732, asymp: 8776, zwnj: 8204, Agrave: 192, deg: 176, AElig: 198, times: 215, Delta: 916, sim: 8764, Otilde: 213, Mu: 924, uArr: 8657, circ: 710, theta: 952, Rho: 929, sup3: 179, diams: 9830, tau: 964, Chi: 935, frac14: 188, oelig: 339, shy: 173, or: 8744, dArr: 8659, phi: 966, iuml: 239, Lambda: 923, rfloor: 8971, iexcl: 161, cong: 8773, ccedil: 231, Icirc: 206, frac12: 189, loz: 9674, rarr: 8594, cup: 8746, radic: 8730, frasl: 8260, euml: 235, OElig: 338, hArr: 8660, Atilde: 195, Upsilon: 933, there4: 8756, ouml: 246, oline: 8254, Ecirc: 202, yacute: 253, auml: 228, permil: 8240, sigmaf: 962, iquest: 191, empty: 8709, pi: 960, Ucirc: 219, supe: 8839, Igrave: 204, yen: 165, rang: 10217, trade: 8482, lfloor: 8970, minus: 8722, Zeta: 918, sub: 8834, epsilon: 949, yuml: 255, Sigma: 931, Iuml: 207, ocirc: 244 }; self.events.bind("getContent", function (text) { return text.replace(/&(?:amp;)?(?!amp|lt|gt|quot)([a-z][a-z0-9]*);/gi, function (str, p1) { if (!replacements[p1]) { p1 = p1.toLowerCase(); if (!replacements[p1]) { p1 = "__replacement"; } } var num = replacements[p1]; /* Numeric return if ever wanted: return replacements[p1] ? "&#"+num+";" : ""; */ return String.fromCharCode(num); }); }); } }; this.innerDocument = function () { var element = this.editor.get(0); if (element.nodeName.toLowerCase() === "iframe") { if (element.contentDocument) { // Gecko return element.contentDocument; } else if (element.contentWindow) { // IE return element.contentWindow.document; } if (this.isDestroyed) { return null; } console.error("Unexpected error in innerDocument"); /* return ( $.browser.msie ) ? document.frames[element.id].document : element.contentWindow.document // contentDocument; */ } return element; }; this.insertHtml = function (szHTML) { var img, range; if (!szHTML || szHTML.length === 0) { return this; } if ($.browser.msie) { this.ui.focus(); this.editorDoc.execCommand("insertImage", false, "#jwysiwyg#"); img = this.getElementByAttributeValue("img", "src", "#jwysiwyg#"); if (img) { $(img).replaceWith(szHTML); } } else { if ($.browser.mozilla) { // @link https://github.com/akzhan/jwysiwyg/issues/50 if (1 === $(szHTML).length) { range = this.getInternalRange(); range.deleteContents(); range.insertNode($(szHTML).get(0)); } else { this.editorDoc.execCommand("insertHTML", false, szHTML); } } else { if (!this.editorDoc.execCommand("insertHTML", false, szHTML)) { this.editor.focus(); /* :TODO: place caret at the end if (window.getSelection) { } else { } this.editor.focus(); */ this.editorDoc.execCommand("insertHTML", false, szHTML); } } } this.saveContent(); return this; }; this.parseControls = function () { var self = this; $.each(this.options.controls, function (controlName, control) { $.each(control, function (propertyName) { if (-1 === $.inArray(propertyName, self.availableControlProperties)) { throw controlName + '["' + propertyName + '"]: property "' + propertyName + '" not exists in Wysiwyg.availableControlProperties'; } }); }); if (this.options.parseControls) { return this.options.parseControls.call(this); } return this.options.controls; }; this.removeFormat = function () { if ($.browser.msie) { this.ui.focus(); } if (this.options.removeHeadings) { this.editorDoc.execCommand("formatBlock", false, "<p>"); // remove headings } this.editorDoc.execCommand("removeFormat", false, null); this.editorDoc.execCommand("unlink", false, null); if ($.wysiwyg.rmFormat && $.wysiwyg.rmFormat.enabled) { if ("object" === typeof (this.options.plugins.rmFormat.rmMsWordMarkup)) { $.wysiwyg.rmFormat.run(this, { rules: { msWordMarkup: this.options.plugins.rmFormat.rmMsWordMarkup } }); } else { $.wysiwyg.rmFormat.run(this, { rules: { msWordMarkup: { enabled: true } } }); } } return this; }; this.ui.removeHoverClass = function () { $(this).removeClass("wysiwyg-button-hover"); }; this.resetFunction = function () { this.setContent(this.initialContent); }; this.saveContent = function () { if (this.viewHTML) { return; // no need } if (this.original) { var content, newContent; content = this.getContent(); if (this.options.rmUnwantedBr) { content = content.replace(/<br\/?>$/, ""); } if (this.options.replaceDivWithP) { newContent = $("<div/>").addClass("temp").append(content); newContent.children("div").each(function () { var element = $(this), p = element.find("p"), i; if (0 === p.length) { p = $("<p></p>"); if (this.attributes.length > 0) { for (i = 0; i < this.attributes.length; i += 1) { p.attr(this.attributes[i].name, element.attr(this.attributes[i].name)); } } p.append(element.html()); element.replaceWith(p); } }); content = newContent.html(); } $(this.original).val(content); if (this.options.events && this.options.events.save) { this.options.events.save.call(this); } } return this; }; this.setContent = function (newContent) { this.editorDoc.body.innerHTML = newContent; this.saveContent(); return this; }; this.triggerControl = function (name, control) { var cmd = control.command || name, args = control["arguments"] || []; if (control.exec) { control.exec.apply(this); } else { this.ui.focus(); this.ui.withoutCss(); // when click <Cut>, <Copy> or <Paste> got "Access to XPConnect service denied" code: "1011" // in Firefox untrusted JavaScript is not allowed to access the clipboard try { this.editorDoc.execCommand(cmd, false, args); } catch (e) { console.error(e); } } if (this.options.autoSave) { this.autoSaveFunction(); } }; this.triggerControlCallback = function (name) { $(window).trigger("trigger-" + name + ".wysiwyg", [this]); }; this.ui.withoutCss = function () { var self = this.self; if ($.browser.mozilla) { try { self.editorDoc.execCommand("styleWithCSS", false, false); } catch (e) { try { self.editorDoc.execCommand("useCSS", false, true); } catch (e2) {} } } return self; }; this.wrapInitialContent = function () { var content = this.initialContent, found = content.match(/<\/?p>/gi); if (!found) { return "<p>" + content + "</p>"; } else { // :TODO: checking/replacing } return content; }; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg = { messages: { noObject: "Something goes wrong, check object" }, /** * Custom control support by Alec Gorge ( http://github.com/alecgorge ) */ addControl: function (object, name, settings) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"), customControl = {}, toolbar; if (!oWysiwyg) { return this; } customControl[name] = $.extend(true, { visible: true, custom: true }, settings); $.extend(true, oWysiwyg.options.controls, customControl); // render new toolbar toolbar = $(oWysiwyg.options.toolbarHtml); oWysiwyg.ui.toolbar.replaceWith(toolbar); oWysiwyg.ui.toolbar = toolbar; oWysiwyg.ui.appendControls(); }); }, clear: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.setContent(""); }); }, console: console, // let our console be available for extensions destroy: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.destroy(); }); }, "document": function (object) { // no chains because of return var oWysiwyg = object.data("wysiwyg"); if (!oWysiwyg) { return undefined; } return $(oWysiwyg.editorDoc); }, getContent: function (object) { // no chains because of return var oWysiwyg = object.data("wysiwyg"); if (!oWysiwyg) { return undefined; } return oWysiwyg.getContent(); }, init: function (object, options) { return object.each(function () { var opts = $.extend(true, {}, options), obj; // :4fun: // remove this textarea validation and change line in this.saveContent function // $(this.original).val(content); to $(this.original).html(content); // now you can make WYSIWYG editor on h1, p, and many more tags if (("textarea" !== this.nodeName.toLowerCase()) || $(this).data("wysiwyg")) { return; } obj = new Wysiwyg(); obj.init(this, opts); $.data(this, "wysiwyg", obj); $(obj.editorDoc).trigger("afterInit.wysiwyg"); }); }, insertHtml: function (object, szHTML) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.insertHtml(szHTML); }); }, plugin: { listeners: {}, bind: function (Wysiwyg) { var self = this; $.each(this.listeners, function (action, handlers) { var i, plugin; for (i = 0; i < handlers.length; i += 1) { plugin = self.parseName(handlers[i]); $(Wysiwyg.editorDoc).bind(action + ".wysiwyg", { plugin: plugin }, function (event) { $.wysiwyg[event.data.plugin.name][event.data.plugin.method].apply($.wysiwyg[event.data.plugin.name], [Wysiwyg]); }); } }); }, exists: function (name) { var plugin; if ("string" !== typeof (name)) { return false; } plugin = this.parseName(name); if (!$.wysiwyg[plugin.name] || !$.wysiwyg[plugin.name][plugin.method]) { return false; } return true; }, listen: function (action, handler) { var plugin; plugin = this.parseName(handler); if (!$.wysiwyg[plugin.name] || !$.wysiwyg[plugin.name][plugin.method]) { return false; } if (!this.listeners[action]) { this.listeners[action] = []; } this.listeners[action].push(handler); return true; }, parseName: function (name) { var elements; if ("string" !== typeof (name)) { return false; } elements = name.split("."); if (2 > elements.length) { return false; } return { name: elements[0], method: elements[1] }; }, register: function (data) { if (!data.name) { console.error("Plugin name missing"); } $.each($.wysiwyg, function (pluginName) { if (pluginName === data.name) { console.error("Plugin with name '" + data.name + "' was already registered"); } }); $.wysiwyg[data.name] = data; return true; } }, removeFormat: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.removeFormat(); }); }, save: function (object) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.saveContent(); }); }, selectAll: function (object) { var oWysiwyg = object.data("wysiwyg"), oBody, oRange, selection; if (!oWysiwyg) { return this; } oBody = oWysiwyg.editorDoc.body; if (window.getSelection) { selection = oWysiwyg.getInternalSelection(); selection.selectAllChildren(oBody); } else { oRange = oBody.createTextRange(); oRange.moveToElementText(oBody); oRange.select(); } }, setContent: function (object, newContent) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } oWysiwyg.setContent(newContent); }); }, triggerControl: function (object, controlName) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"); if (!oWysiwyg) { return this; } if (!oWysiwyg.controls[controlName]) { console.error("Control '" + controlName + "' not exists"); } oWysiwyg.triggerControl.apply(oWysiwyg, [controlName, oWysiwyg.controls[controlName]]); }); }, support: { prop: supportsProp }, utils: { extraSafeEntities: [ ["<", ">", "'", '"', " "], [32] ], encodeEntities: function (str) { var self = this, aStr, aRet = []; if (this.extraSafeEntities[1].length === 0) { $.each(this.extraSafeEntities[0], function (i, ch) { self.extraSafeEntities[1].push(ch.charCodeAt(0)); }); } aStr = str.split(""); $.each(aStr, function (i) { var iC = aStr[i].charCodeAt(0); if ($.inArray(iC, self.extraSafeEntities[1]) && (iC < 65 || iC > 127 || (iC > 90 && iC < 97))) { aRet.push('&#' + iC + ';'); } else { aRet.push(aStr[i]); } }); return aRet.join(''); } } }; $.fn.wysiwyg = function (method) { var args = arguments, plugin; if ("undefined" !== typeof $.wysiwyg[method]) { // set argument object to undefined args = Array.prototype.concat.call([args[0]], [this], Array.prototype.slice.call(args, 1)); return $.wysiwyg[method].apply($.wysiwyg, Array.prototype.slice.call(args, 1)); } else if ("object" === typeof method || !method) { Array.prototype.unshift.call(args, this); return $.wysiwyg.init.apply($.wysiwyg, args); } else if ($.wysiwyg.plugin.exists(method)) { plugin = $.wysiwyg.plugin.parseName(method); args = Array.prototype.concat.call([args[0]], [this], Array.prototype.slice.call(args, 1)); return $.wysiwyg[plugin.name][plugin.method].apply($.wysiwyg[plugin.name], Array.prototype.slice.call(args, 1)); } else { console.error("Method '" + method + "' does not exist on jQuery.wysiwyg.\nTry to include some extra controls or plugins"); } }; $.fn.getWysiwyg = function () { return $.data(this, "wysiwyg"); }; })(jQuery); /** * Controls: Image plugin * * Depends on jWYSIWYG */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.image.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.image = { init: function (Wysiwyg) { var self = this, elements, dialog, formImageHtml, dialogReplacements, key, translation, img = { alt: "", self: Wysiwyg.dom.getElement("img"), // link to element node src: "http://", title: "" }; dialogReplacements = { legend: "Insert Image", preview: "Preview", url: "URL", title: "Title", description: "Description", width: "Width", height: "Height", original: "Original W x H", "float": "Float", floatNone: "None", floatLeft: "Left", floatRight: "Right", submit: "Insert Image", loading: "loading", reset: "Cancel" }; formImageHtml = '<form class="wysiwyg" title="{legend}">' + '<img src="" alt="{preview}" width="100%"><br>' + '{url}: <input type="text" name="src" value=""><br>' + '{title}: <input type="text" name="imgtitle" value=""><br>' + '{description}: <input type="text" name="description" value=""><br>' + '{width} x {height}: <input type="text" name="width" value="" class="width integer"> x <input type="text" name="height" value="" class="height integer"><br>' + '{float}: <select name="float">' + '<option value="">{floatNone}</option>' + '<option value="left">{floatLeft}</option>' + '<option value="right">{floatRight}</option></select></label><hr>' + '<button class="button" id="wysiwyg_submit">{submit}</button> ' + '<button class="button" id="wysiwyg_reset">{reset}</button></form>'; for (key in dialogReplacements) { if ($.wysiwyg.i18n) { translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs.image"); if (translation === dialogReplacements[key]) { // if not translated search in dialogs translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs"); } dialogReplacements[key] = translation; } formImageHtml = formImageHtml.replace("{" + key + "}", dialogReplacements[key]); } if (img.self) { img.src = img.self.src ? img.self.src : ""; img.alt = img.self.alt ? img.self.alt : ""; img.title = img.self.title ? img.self.title : ""; img.width = img.self.width ? img.self.width : ""; img.height = img.self.height ? img.self.height : ""; img.asp = img.width / img.width; } elements = $(formImageHtml); elements = self.makeForm(elements, img); dialog = elements.appendTo("body"); dialog.dialog({ modal: true, resizable: false, open: function (ev, ui) { $("#wysiwyg_submit", dialog).click(function (e) { self.processInsert(dialog.container, Wysiwyg, img); $(dialog).dialog("close"); return false; }); $("#wysiwyg_reset", dialog).click(function (e) { $(dialog).dialog("close"); return false; }); $('fieldset', dialog).click(function (e) { e.stopPropagation(); }); $("select, input[type=text]", dialog).uniform(); $('.width', dialog).wl_Number({ step: 10, onChange: function (value) { $('.height', dialog).val(Math.ceil(value / (img.asp || 1))); } }); $('.height', dialog).wl_Number({ step: 10, onChange: function (value) { $('.width', dialog).val(Math.floor(value * (img.asp || 1))); } }); $('input[name="src"]', dialog).wl_URL(); }, close: function (ev, ui) { dialog.dialog("destroy"); dialog.remove(); } }); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); }, processInsert: function (context, Wysiwyg, img) { var image, url = $('input[name="src"]', context).val(), title = $('input[name="imgtitle"]', context).val(), description = $('input[name="description"]', context).val(), width = $('input[name="width"]', context).val(), height = $('input[name="height"]', context).val(), styleFloat = $('select[name="float"]', context).val(), style = [], found, baseUrl; if (Wysiwyg.options.controlImage.forceRelativeUrls) { baseUrl = window.location.protocol + "//" + window.location.hostname; if (0 === url.indexOf(baseUrl)) { url = url.substr(baseUrl.length); } } if (img.self) { // to preserve all img attributes $(img.self).attr("src", url).attr("title", title).attr("alt", description).css("float", styleFloat); if (width.toString().match(/^[0-9]+(px|%)?$/)) { $(img.self).css("width", width); } else { $(img.self).css("width", ""); } if (height.toString().match(/^[0-9]+(px|%)?$/)) { $(img.self).css("height", height); } else { $(img.self).css("height", ""); } Wysiwyg.saveContent(); } else { found = width.toString().match(/^[0-9]+(px|%)?$/); if (found) { if (found[1]) { style.push("width: " + width + ";"); } else { style.push("width: " + width + "px;"); } } found = height.toString().match(/^[0-9]+(px|%)?$/); if (found) { if (found[1]) { style.push("height: " + height + ";"); } else { style.push("height: " + height + "px;"); } } if (styleFloat.length > 0) { style.push("float: " + styleFloat + ";"); } if (style.length > 0) { style = ' style="' + style.join(" ") + '"'; } image = "<img src='" + url + "' title='" + title + "' alt='" + description + "'" + style + "/>"; Wysiwyg.insertHtml(image); } }, makeForm: function (form, img) { form.find("input[name=src]").val(img.src); form.find("input[name=imgtitle]").val(img.title); form.find("input[name=description]").val(img.alt); form.find('input[name="width"]').val(img.width); form.find('input[name="height"]').val(img.height); form.find('img').attr("src", img.src); img.asp = img.width / img.height; form.find("input[name=src]").bind("change", function () { var image = new Image(); var text = $('#wysiwyg_submit', form).find('span').text(); form.find('img').removeAttr("src"); $('#wysiwyg_submit', form).prop('disabled', true).find('span').text('wait...'); image.onload = function () { form.find('img').attr("src", image.src); img.asp = image.width / image.height; form.find('input[name="width"]').val(image.width); form.find('input[name="height"]').val(image.height); $('#wysiwyg_submit', form).find('span').text(text); $('#wysiwyg_submit', form).prop('disabled', false); }; image.src = this.value; }); return form; } }; $.wysiwyg.insertImage = function (object, url, attributes) { return object.each(function () { var Wysiwyg = $(this).data("wysiwyg"), image, attribute; if (!Wysiwyg) { return this; } if (!url || url.length === 0) { return this; } if ($.browser.msie) { Wysiwyg.ui.focus(); } if (attributes) { Wysiwyg.editorDoc.execCommand("insertImage", false, "#jwysiwyg#"); image = Wysiwyg.getElementByAttributeValue("img", "src", "#jwysiwyg#"); if (image) { image.src = url; for (attribute in attributes) { if (attributes.hasOwnProperty(attribute)) { image.setAttribute(attribute, attributes[attribute]); } } } } else { Wysiwyg.editorDoc.execCommand("insertImage", false, url); } Wysiwyg.saveContent(); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); return this; }); }; })(jQuery); /** * Controls: Table plugin * * Depends on jWYSIWYG */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.table.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } var insertTable = function (colCount, rowCount, filler) { if (isNaN(rowCount) || isNaN(colCount) || rowCount === null || colCount === null) { return; } var i, j, html = ['<table border="1" style="width: 100%;"><tbody>']; colCount = parseInt(colCount, 10); rowCount = parseInt(rowCount, 10); if (filler === null) { filler = "&nbsp;"; } filler = "<td>" + filler + "</td>"; for (i = rowCount; i > 0; i -= 1) { html.push("<tr>"); for (j = colCount; j > 0; j -= 1) { html.push(filler); } html.push("</tr>"); } html.push("</tbody></table>"); return this.insertHtml(html.join("")); }; /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.table = function (Wysiwyg) { var dialog, colCount, rowCount, formTableHtml, formTextLegend = "Insert table", formTextCols = "Count of columns", formTextRows = "Count of rows", formTextSubmit = "Insert table", formTextReset = "Cancel"; if ($.wysiwyg.i18n) { formTextLegend = $.wysiwyg.i18n.t(formTextLegend, "dialogs.table"); formTextCols = $.wysiwyg.i18n.t(formTextCols, "dialogs.table"); formTextRows = $.wysiwyg.i18n.t(formTextRows, "dialogs.table"); formTextSubmit = $.wysiwyg.i18n.t(formTextSubmit, "dialogs.table"); formTextReset = $.wysiwyg.i18n.t(formTextReset, "dialogs"); } formTableHtml = '<form class="wysiwyg" title="' + formTextLegend + '">' + formTextCols + ': <input type="text" name="colCount" value="3" class="integer" ><br>' + formTextRows + ': <input type="text" name="rowCount" value="3" class="integer" ><hr>' + '<button class="button" id="wysiwyg_submit">' + formTextSubmit + '</button> ' + '<button class="button" id="wysiwyg_reset">' + formTextReset + '</button></form>'; if (!Wysiwyg.insertTable) { Wysiwyg.insertTable = insertTable; } dialog = $(formTableHtml).appendTo("body"); dialog.dialog({ modal: true, resizable: false, open: function (event, ui) { $("#wysiwyg_submit", dialog).click(function (e) { e.preventDefault(); rowCount = $('input[name="rowCount"]', dialog).val(); colCount = $('input[name="colCount"]', dialog).val(); Wysiwyg.insertTable(colCount, rowCount, Wysiwyg.defaults.tableFiller); $(dialog).dialog("close"); }); $("#wysiwyg_reset", dialog).click(function (e) { e.preventDefault(); $(dialog).dialog("close"); }); $("select, input[type=text]", dialog).uniform(); $('.integer', dialog).wl_Number(); }, close: function (event, ui) { dialog.dialog("destroy"); dialog.remove(); } }); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); }; $.wysiwyg.insertTable = function (object, colCount, rowCount, filler) { return object.each(function () { var Wysiwyg = $(this).data("wysiwyg"); if (!Wysiwyg.insertTable) { Wysiwyg.insertTable = insertTable; } if (!Wysiwyg) { return this; } Wysiwyg.insertTable(colCount, rowCount, filler); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); return this; }); }; })(jQuery); /** * Controls: Link plugin * * Depends on jWYSIWYG * * By: Esteban Beltran (academo) <sergies@gmail.com> */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.link.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.link = { init: function (Wysiwyg) { var self = this, elements, dialog, url, a, selection, formLinkHtml, formTextLegend, formTextUrl, formTextTitle, formTextTarget, formTextSubmit, formTextReset, baseUrl; formTextLegend = "Insert Link"; formTextUrl = "Link URL"; formTextTitle = "Link Title"; formTextTarget = "Link Target"; formTextSubmit = "Insert Link"; formTextReset = "Cancel"; if ($.wysiwyg.i18n) { formTextLegend = $.wysiwyg.i18n.t(formTextLegend, "dialogs.link"); formTextUrl = $.wysiwyg.i18n.t(formTextUrl, "dialogs.link"); formTextTitle = $.wysiwyg.i18n.t(formTextTitle, "dialogs.link"); formTextTarget = $.wysiwyg.i18n.t(formTextTarget, "dialogs.link"); formTextSubmit = $.wysiwyg.i18n.t(formTextSubmit, "dialogs.link"); formTextReset = $.wysiwyg.i18n.t(formTextReset, "dialogs"); } formLinkHtml = '<form class="wysiwyg" title="' + formTextLegend + '">' + formTextUrl + ': <input type="text" name="linkhref" value="">' + formTextTitle + ': <input type="text" name="linktitle" value="">' + formTextTarget + ': <input type="text" name="linktarget" value=""><hr>' + '<button class="button" id="wysiwyg_submit">' + formTextSubmit + '</button> ' + '<button class="button" id="wysiwyg_reset">' + formTextReset + '</button></form>'; a = { self: Wysiwyg.dom.getElement("a"), // link to element node href: "http://", title: "", target: "" }; if (a.self) { a.href = a.self.href ? a.self.href : a.href; a.title = a.self.title ? a.self.title : ""; a.target = a.self.target ? a.self.target : ""; } elements = $(formLinkHtml); elements.find("input[name=linkhref]").val(a.href); elements.find("input[name=linktitle]").val(a.title); elements.find("input[name=linktarget]").val(a.target); if ($.browser.msie) { dialog = elements.appendTo(Wysiwyg.editorDoc.body); } else { dialog = elements.appendTo("body"); } dialog.dialog({ modal: true, resizable: false, open: function (ev, ui) { $("#wysiwyg_submit", dialog).click(function (e) { e.preventDefault(); var url = $('input[name="linkhref"]', dialog).val(), title = $('input[name="linktitle"]', dialog).val(), target = $('input[name="linktarget"]', dialog).val(), baseUrl; if (Wysiwyg.options.controlLink.forceRelativeUrls) { baseUrl = window.location.protocol + "//" + window.location.hostname; if (0 === url.indexOf(baseUrl)) { url = url.substr(baseUrl.length); } } if (a.self) { if ("string" === typeof (url)) { if (url.length > 0) { // to preserve all link attributes $(a.self).attr("href", url).attr("title", title).attr("target", target); } else { $(a.self).replaceWith(a.self.innerHTML); } } } else { if ($.browser.msie) { Wysiwyg.ui.returnRange(); } //Do new link element selection = Wysiwyg.getRangeText(); img = Wysiwyg.dom.getElement("img"); if ((selection && selection.length > 0) || img) { if ($.browser.msie) { Wysiwyg.ui.focus(); } if ("string" === typeof (url)) { if (url.length > 0) { Wysiwyg.editorDoc.execCommand("createLink", false, url); } else { Wysiwyg.editorDoc.execCommand("unlink", false, null); } } a.self = Wysiwyg.dom.getElement("a"); $(a.self).attr("href", url).attr("title", title); /** * @url https://github.com/akzhan/jwysiwyg/issues/16 */ $(a.self).attr("target", target); } else if (Wysiwyg.options.messages.nonSelection) { $.dialog(Wysiwyg.options.messages.nonSelection); } } Wysiwyg.saveContent(); $(dialog).dialog("close"); }); $("#wysiwyg_reset", dialog).click(function (e) { e.preventDefault(); $(dialog).dialog("close"); }); $("select, input", dialog).uniform(); $('input[name="linkhref"]', dialog).wl_URL(); }, close: function (ev, ui) { dialog.dialog("destroy"); dialog.remove(); } }); $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); } }; $.wysiwyg.createLink = function (object, url) { return object.each(function () { var oWysiwyg = $(this).data("wysiwyg"), selection; if (!oWysiwyg) { return this; } if (!url || url.length === 0) { return this; } selection = oWysiwyg.getRangeText(); if (selection && selection.length > 0) { if ($.browser.msie) { oWysiwyg.ui.focus(); } oWysiwyg.editorDoc.execCommand("unlink", false, null); oWysiwyg.editorDoc.execCommand("createLink", false, url); } else if (oWysiwyg.options.messages.nonSelection) { window.alert(oWysiwyg.options.messages.nonSelection); } }); }; })(jQuery); /** * Controls: Element CSS Wrapper plugin * * Depends on jWYSIWYG * * By Yotam Bar-On (https://github.com/tudmotu) */ (function ($) { if (undefined === $.wysiwyg) { throw "wysiwyg.cssWrap.js depends on $.wysiwyg"; } /* For core enhancements #143 $.wysiwyg.ui.addControl("cssWrap", { visible : false, groupIndex: 6, tooltip: "CSS Wrapper", exec: function () { $.wysiwyg.controls.cssWrap.init(this); } } */ if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.cssWrap = { init: function (Wysiwyg) { var self = this, formWrapHtml, key, translation, dialogReplacements = { legend: "Wrap Element", wrapperType: "Wrapper Type", ID: "ID", "class": "Class", wrap: "Wrap", unwrap: "Unwrap", cancel: "Cancel" }; formWrapHtml = '<form class="wysiwyg" title="{legend}"><fieldset>' + '{wrapperType}: <select name="type"><option value="span">Span</option><option value="div">Div</option></select><br>' + '{ID}: <input name="id" type="text"><br>' + '{class}: <input name="class" type="text" ><hr>' + '<button class="cssWrap-unwrap" style="display:none;">{unwrap}</button> ' + '<button class="cssWrap-submit">{wrap}</button> ' + '<button class="cssWrap-cancel">{cancel}</button></fieldset></form>'; for (key in dialogReplacements) { if ($.wysiwyg.i18n) { translation = $.wysiwyg.i18n.t(dialogReplacements[key]); if (translation === dialogReplacements[key]) { // if not translated search in dialogs translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs"); } dialogReplacements[key] = translation; } formWrapHtml = formWrapHtml.replace("{" + key + "}", dialogReplacements[key]); } if (!$(".wysiwyg-dialog-wrapper").length) { $(formWrapHtml).appendTo("body"); $("form.wysiwyg").dialog({ modal: true, resizable: false, open: function (ev, ui) { $this = $(this); var range = Wysiwyg.getInternalRange(), common; // We make sure that there is some selection: if (range) { if ($.browser.msie) { Wysiwyg.ui.focus(); } common = $(range.commonAncestorContainer); } else { alert("You must select some elements before you can wrap them."); $this.dialog("close"); return 0; } var $nodeName = range.commonAncestorContainer.nodeName.toLowerCase(); // If the selection is already a .wysiwygCssWrapper, then we want to change it and not double-wrap it. if (common.parent(".wysiwygCssWrapper").length) { alert(common.parent(".wysiwygCssWrapper").get(0).nodeName.toLowerCase()); $this.find("select[name=type]").val(common.parent(".wysiwygCssWrapper").get(0).nodeName.toLowerCase()); $this.find("select[name=type]").attr("disabled", "disabled"); $this.find("input[name=id]").val(common.parent(".wysiwygCssWrapper").attr("id")); $this.find("input[name=class]").val(common.parent(".wysiwygCssWrapper").attr("class").replace('wysiwygCssWrapper ', '')); // Add the "unwrap" button: $("form.wysiwyg").find(".cssWrap-unwrap").show(); $("form.wysiwyg").find(".cssWrap-unwrap").click(function (e) { e.preventDefault(); if ($nodeName !== "body") { common.unwrap(); } $this.dialog("close"); return 1; }); } // Submit button. $("form.wysiwyg").find(".cssWrap-submit").click(function (e) { e.preventDefault(); var $wrapper = $("form.wysiwyg").find("select[name=type]").val(); var $id = $("form.wysiwyg").find("input[name=id]").val(); var $class = $("form.wysiwyg").find("input[name=class]").val(); if ($nodeName !== "body") { // If the selection is already a .wysiwygCssWrapper, then we want to change it and not double-wrap it. if (common.parent(".wysiwygCssWrapper").length) { common.parent(".wysiwygCssWrapper").attr("id", $class); common.parent(".wysiwygCssWrapper").attr("class", $class); } else { common.wrap('<' + $wrapper + ' id="' + $id + '" class="' + "wysiwygCssWrapper " + $class + '"/>'); } } else { // Currently no implemntation for if $nodeName == 'body'. } $this.dialog("close"); }); // Cancel button. $("form.wysiwyg").find(".cssWrap-cancel").click(function (e) { e.preventDefault(); $this.dialog("close"); return 1; }); $("form.wysiwyg").find("select, input[type=text]").uniform(); }, close: function () { $(this).dialog("destroy"); $(this).remove(); } }); Wysiwyg.saveContent(); } $(Wysiwyg.editorDoc).trigger("editorRefresh.wysiwyg"); return 1; } } })(jQuery); /** * Controls: Colorpicker plugin * * Depends on jWYSIWYG, wl_Color Plugin */ (function ($) { "use strict"; if (undefined === $.wysiwyg) { throw "wysiwyg.colorpicker.js depends on $.wysiwyg"; } if (!$.wysiwyg.controls) { $.wysiwyg.controls = {}; } /* * Wysiwyg namespace: public properties and methods */ $.wysiwyg.controls.colorpicker = { modalOpen: false, init: function (Wysiwyg) { if ($.wysiwyg.controls.colorpicker.modalOpen === true) { return false; } else { $.wysiwyg.controls.colorpicker.modalOpen = true; } var self = this, elements, dialog, colorpickerHtml, dialogReplacements, key, translation; dialogReplacements = { legend: "Colorpicker", color: "Color", submit: "Apply", cancel: "Cancel" }; colorpickerHtml = '<form class="wysiwyg" title="{legend}">' + '{color}: <input type="text" class="color" id="wysiwyg_colorpicker" name="wysiwyg_colorpicker" value=""><hr>' + '<button id="wysiwyg_colorpicker-submit">{submit}</button> ' + '<button id="wysiwyg_colorpicker-cancel">{cancel}</button></form>'; for (key in dialogReplacements) { if ($.wysiwyg.i18n) { translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs.colorpicker"); if (translation === dialogReplacements[key]) { // if not translated search in dialogs translation = $.wysiwyg.i18n.t(dialogReplacements[key], "dialogs"); } dialogReplacements[key] = translation; } colorpickerHtml = colorpickerHtml.replace("{" + key + "}", dialogReplacements[key]); } elements = $(colorpickerHtml); dialog = elements.appendTo("body"); dialog.dialog({ modal: true, resizable: false, open: function (event, ui) { if ($.browser.msie) { Wysiwyg.ui.returnRange(); } var selection = Wysiwyg.getRangeText(), content = Wysiwyg.getContent(), color = '', regexp = /#([a-fA-F0-9]{3,6})/; if (content.match(regexp)) { regexp.exec(content); color = RegExp.$1; } else { regexp = /rgb\((\d+), (\d+), (\d+)\)/; if (content.match(regexp)) { regexp.exec(content); var r = RegExp.$1, g = RegExp.$2, b = RegExp.$3; color = parseInt(r).toString(16) + parseInt(g).toString(16) + parseInt(b).toString(16); } } $('#wysiwyg_colorpicker').val('#' + color).wl_Color(); $("#wysiwyg_colorpicker-submit").click(function (e) { e.preventDefault(); var color = $('#wysiwyg_colorpicker').val(); if ($.browser.msie) { Wysiwyg.ui.returnRange(); Wysiwyg.ui.focus(); } if (color) Wysiwyg.editorDoc.execCommand('ForeColor', false, color); Wysiwyg.saveContent(); $(dialog).dialog("close"); return false; }); $("#wysiwyg_colorpicker-cancel").click(function (e) { e.preventDefault(); if ($.browser.msie) { Wysiwyg.ui.returnRange(); } $(dialog).dialog("close"); return false; }); }, close: function (event, ui) { $.wysiwyg.controls.colorpicker.modalOpen = false; dialog.dialog("destroy"); dialog.remove(); } }); } }; })(jQuery); });
08102013project
trunk/CMS/Scripts/plugins/editor.js
JavaScript
oos
84,874
/*----------------------------------------------------------------------*/ /* wl_Multiselect v 1.3 by revaxarts.com /* description: Makes a Multiselector out of a select input /* dependency: jQuery UI /*----------------------------------------------------------------------*/ $.fn.wl_Multiselect = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Multiselect.methods[method]) { return $.fn.wl_Multiselect.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Multiselect')) { var opts = $.extend({}, $this.data('wl_Multiselect'), method); } else { var opts = $.extend({}, $.fn.wl_Multiselect.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Multiselect')) { $this.data('wl_Multiselect', {}); //Hide the native input $this.hide(); //insert the required HTML $('<div class="comboselectbox"><div class="combowrap"><ul class="comboselect"></ul></div><div class="comboselectbuttons"><a class="add btn"></a><a class="addall btn"></a><a class="removeall btn"></a><a class="remove btn"></a></div><div class="combowrap"><ul class="comboselect"></ul></div></div>').insertAfter($this); } else { } var $box = $this.next('.comboselectbox'), $add = $box.find('a.add'), $remove = $box.find('a.remove'), $addall = $box.find('a.addall'), $removeall = $box.find('a.removeall'), $lists = $box.find('.comboselect'), $i = $([]); var name = $this.attr('name'), j = 0, selected = searchresult = []; opts.pool = $lists.eq(0), opts.selection = $lists.eq(1); //add searchfield and its actions if(opts.searchfield){ $searchfield = $('<input>') .bind('keyup.wl_Multiselect', function(){ var term = new RegExp($(this).val(), 'i'); console.log(opts.pool.find('li')); $.each(opts.pool.find('li').not('.used'), function(i, el){ var _el = $(el), _val = _el.data('value')+_el.data('name'); if(term.test(_val)){ _el.removeClass('hidden'); }else{ _el.addClass('hidden'); } }); }).prependTo($box.addClass('searchable').find('.combowrap').eq(0)); } //append a '[]' if isn't set (required for multiple values if (!/\[\]$/.test(name)) $this.attr('name', name + '[]'); //set the height of the box $box.height(opts.height); //if items ar sett append them to the native input if (opts.items.length) { if (opts.selected.length && !$.isArray(opts.selected)) opts.selected = [opts.selected]; $.each(opts.items, function (i, data) { var name, value, selected = ''; if (typeof data == 'object') { name = data.name; value = data.value; } else { name = value = data; } if (opts.selected.length && $.inArray(value, opts.selected) != -1) selected = ' selected'; $i = $i.add($('<option value="' + value + '"' + selected + '>' + name + '</option>')); }); $i.appendTo($this); } //refresh the positions if a change is triggered $this.bind('change.wl_Multiselect', function () { refreshPositions(); }); //clear them opts.items = []; opts.selected = []; //and iterate thru all native options $.each($this.find('option'), function (i, e) { var _this = $(this), name = _this.text(), value = _this.val(); var item = $('<li><a>' + name + '</a></li>').append('<a class="add"></a>').data({ 'pos': i, 'value': value, 'name': name, 'native': _this }).appendTo(opts.pool); opts.items[value] = item; //if it's selected we need it in the selection list if (_this.is(':selected')) { opts.selected.push(value); item.clone(true).data({ 'pos': j++ }).attr('data-value', value).append('<a class="remove"></a>').appendTo(opts.selection).find('.add').remove(); item.data('native').prop('selected', true); item.addClass('used'); if (!opts.showUsed) item.hide(); } }); //Bind click events to the buttons in the middle $add.bind('click.wl_Multiselect', function () { var selection = $.map(opts.pool.find('li.selected'), function (el) { return $(el).data('value'); }); if(opts.searchfield) $searchfield.focus(); $this.wl_Multiselect('select', selection); }); $remove.bind('click.wl_Multiselect', function () { var selection = $.map(opts.selection.find('li.selected'), function (el) { return $(el).data('value'); }); $this.wl_Multiselect('unselect', selection); }); $addall.bind('click.wl_Multiselect', function () { var selection = $.map(opts.pool.find('li').not('.hidden'), function (el) { return $(el).data('value'); }); if(opts.searchfield) $searchfield.val('').trigger('keyup').focus(); $this.wl_Multiselect('select', selection); }); $removeall.bind('click.wl_Multiselect', function () { var selection = $.map(opts.selection.find('li'), function (el) { return $(el).data('value'); }); $this.wl_Multiselect('unselect', selection); }); //Bind events to the elements opts.pool.delegate('li', 'click.wl_Multiselect', { 'list': opts.pool }, clickHandler).delegate('li', 'dblclick.wl_Multiselect', function () { $this.wl_Multiselect('select', $(this).data('value')); }).delegate('a.add', 'click.wl_Multiselect', function () { $this.wl_Multiselect('select', $(this).parent().data('value')); }).disableSelection(); opts.selection.delegate('li', 'click.wl_Multiselect', { 'list': opts.selection }, clickHandler).delegate('a.remove', 'click.wl_Multiselect', function () { $this.wl_Multiselect('unselect', $(this).parent().data('value')); }); //make the selection list sortable opts.selection.sortable({ containment: opts.selection, distance: 20, handle: 'a:first', forcePlaceholderSize: true, forceHelperSize: true, update: function () { refreshPositions(); opts.onSort.call($this[0], $this.data('wl_Multiselect').selected); }, items: 'li' }); //function to refresh positions. simple add a position to the element and sort the native select list function refreshPositions() { var li = opts.pool.find('li').not('.used'), selected = []; $.each(li, function (i) { $(this).data('pos', i); }); li = opts.selection.find('li'); $.each(li, function (i) { var _this = $(this); _this.data('pos', i); opts.items[_this.data('value')].data('native').appendTo($this); selected.push(_this.data('value')); }); $this.data('wl_Multiselect').selected = selected; } //the click handle simulates a native click behaviour on the elements function clickHandler(event) { var _this = $(this), selected = event.data.list.find('li.selected'); //stop when the clicked element is used if (_this.hasClass('used')) return false; //remove the selected class if it's a normal click if (!event.shiftKey && !event.ctrlKey) selected.removeClass('selected'); //shift clicks selects from selected to previous selected element if (event.shiftKey) { var first, second, items = event.data.list.find('li').not('.used'); if (_this.data('pos') > event.data.list.data('last')) { first = event.data.list.data('last'); second = _this.data('pos'); } else { first = _this.data('pos'); second = event.data.list.data('last'); } for (var i = first; i <= second; i++) { items.eq(i).addClass('selected'); } event.data.list.data('last', second); //a normal click (or with ctrl key) select the current one } else { event.data.list.data('last', _this.data('pos')); _this.toggleClass('selected'); } return false; } if (opts) $.extend($this.data('wl_Multiselect'), opts); }); }; $.fn.wl_Multiselect.defaults = { height: 200, items: [], selected: [], showUsed: false, searchfield: true, onAdd: function (values) {}, onRemove: function (values) {}, onSelect: function (values) {}, onUnselect: function (values) {}, onSort: function (values) {} }; $.fn.wl_Multiselect.version = '1.3'; $.fn.wl_Multiselect.methods = { add: function (items, select) { var $this = $(this), opts = $this.data('wl_Multiselect'), i = opts.itemsum || 0, _items = {}; //make an object from the input if (typeof items != 'object') { _items[items] = items; } else if ($.isArray(items)) { for (var i = 0; i < items.length; i++) { _items[items[i]] = items[i]; } } else { _items = items; } //iterate thru all _items $.each(_items, function (value, name) { //make native items var _native = $('<option value="' + value + '">' + name + '</option>').appendTo($this); //and elements var item = $('<li><a>' + name + '</a></li>').append('<a class="add"></a>').data({ 'pos': i++, 'native': _native, 'name': name, 'value': value }).appendTo(opts.pool); //store info in the object $this.data('wl_Multiselect').items[value] = item; if (select) $this.wl_Multiselect('select', value); }); //trigger the callback function opts.onAdd.call($this[0], $.map(_items, function (k, v) { return k; })); }, remove: function (values) { var $this = $(this), opts = $this.data('wl_Multiselect'); if (values && !$.isArray(values)) { values = [values]; } //unselect all values before $this.wl_Multiselect('unselect', values); if(values){ //remove all elements + native options $.each(values, function (i, value) { var item = opts.items[value]; item.data('native').remove(); item.remove(); delete opts.items[value]; $this.data('wl_Multiselect').items = opts.items; }); } //trigger a change $this.trigger('change.wl_Multiselect'); //trigger the callback function opts.onRemove.call($this[0], values); }, select: function (values) { var $this = $(this), opts = $this.data('wl_Multiselect'); if (values && !$.isArray(values)) { values = [values]; } if(values){ //add elements to the selection list and select the native option $.each(values, function (i, value) { var item = opts.items[value]; if (item.hasClass('used')) return; item.removeClass('selected').clone(true).attr('data-value', value).append('<a class="remove"></a>').appendTo(opts.selection).find('.add').remove(); item.data('native').prop('selected', true); item.addClass('used'); if (!opts.showUsed) item.addClass('hidden'); }); } //trigger a change $this.trigger('change.wl_Multiselect'); //trigger the callback function opts.onSelect.call($this[0], values); }, unselect: function (values) { var $this = $(this), opts = $this.data('wl_Multiselect'); if (values && !$.isArray(values)) { values = [values]; } var li = opts.selection.find('li'); if(values){ //remove elements from the selection list and select the native option $.each(values, function (i, value) { var item = opts.items[value]; if (!item.hasClass('used')) return; item.data('native').prop('selected', false); li.filter('[data-value="' + value + '"]').remove(); item.removeClass('used'); if (!opts.showUsed) item.removeClass('hidden'); }); } //trigger a change $this.trigger('change.wl_Multiselect'); //trigger the callback function opts.onUnselect.call($this[0], values); }, clear: function () { var $this = $(this), opts = $this.data('wl_Multiselect'); //unselect all seleted $this.wl_Multiselect('unselect', opts.selected); //trigger a change $this.trigger('change.wl_Multiselect'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Multiselect.defaults[key] !== undefined) { $this.data('wl_Multiselect')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Multiselect.js
JavaScript
oos
12,493
/*----------------------------------------------------------------------*/ /* wl_Time v 1.1 by revaxarts.com /* description: makes a timefield out of an input field /* dependency: jQuery Datepicker, mousewheel plugin, $.leadingZero /*----------------------------------------------------------------------*/ $.fn.wl_Time = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Time.methods[method]) { return $.fn.wl_Time.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Time')) { var opts = $.extend({}, $this.data('wl_Time'), method); } else { var opts = $.extend({}, $.fn.wl_Time.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Time')) { $this.data('wl_Time', {}); $this.bind({ 'mousewheel.wl_Time': function (event, delta) { var opts = $this.data('wl_Time') || opts; if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) delta = (delta < 0) ? -1 : 1; //scroll thru hours if shift key is pressed if (event.shiftKey) delta *= 60 / opts.step; $.fn.wl_Time.methods.change.call($this[0], delta); } }, 'change.wl_Time': function () { var opts = $this.data('wl_Time') || opts; //correct input value $.fn.wl_Time.methods.correct.call($this[0]); //print it $.fn.wl_Time.methods.printTime.call($this[0]); //callback opts.onChange.call($this[0], opts.time); } //for 12h format ad a little span after the input and set length to 5 (hh:mm) }).after('<span class="timeformat"/>').attr('maxlength', 5); //is connected to a datepicker if (opts.connect !== null) { var _date = $('#' + opts.connect), _oldcallback = opts.onDateChange; //set a callback if the time reaches another date _callback = function (offset) { var current = new Date(_date.datepicker('getDate')).getTime(); if (current) _date.datepicker('setDate', new Date(current + (864e5 * offset))); _oldcallback.call($this[0], offset); }; opts.onDateChange = _callback; } //value is set and has to get translated (self-explanatory) if (opts.value) { var now = new Date().getTime(), date; switch (opts.value) { case 'now': date = new Date(now); break; default: //if a valid number add them as days to the date field if (!isNaN(opts.value)) date = new Date(now + (60000 * (opts.value % 60))); } //set the time (hh:mm) opts.time = $.leadingZero(date.getHours()) + ':' + $.leadingZero(date.getMinutes()); //write it into the input $this.val(opts.time); } } else { } if (opts) $.extend($this.data('wl_Time'), opts); //save value if already set if($this.val().match(/\d\d:\d\d/)){ $this.data('wl_Time').time = $this.val(); //correct input value $.fn.wl_Time.methods.printTime.call($this[0]); } }); }; $.fn.wl_Time.defaults = { step: 5, timeformat: 24, roundtime: true, time: null, value: null, mousewheel: true, onDateChange: function (offset) {}, onHourChange: function (offset) {}, onChange: function (value) {} }; $.fn.wl_Time.version = '1.1'; $.fn.wl_Time.methods = { change: function (delta) { var $this = $(this), opts = $this.data('wl_Time'), _current = new Date('2010/01/01 ' + ($this.data('wl_Time').time || '00:00')), _new = new Date(_current.getTime() + (delta * $this.data('wl_Time').step * 60000)), _hours = _new.getHours(), _minutes = _new.getMinutes(); //round the time on a mousewheel if (opts.roundtime) { _minutes -= (_minutes % $this.data('wl_Time').step); } //save time $this.data('wl_Time').time = $.leadingZero(_hours) + ':' + $.leadingZero(_minutes); //and print it $.fn.wl_Time.methods.printTime.call(this); //callbacks opts.onChange.call(this, $this.data('wl_Time').time); if (Math.abs(_current.getMinutes() - _minutes) == (60 - opts.step)) { opts.onHourChange.call(this, (_hours - _current.getHours())); } if (Math.abs(_current.getHours() - _hours) == (23)) { opts.onDateChange.call(this, (_hours) ? -1 : 1); } }, printTime: function () { var $this = $(this), opts = $this.data('wl_Time'), time = opts.time; if (time) { time = time.split(':'); //calculate the 12h format if (opts.timeformat == 12) { $this.val($.leadingZero(((time[0] % 12 == 0) ? 12 : time[0] % 12)) + ':' + $.leadingZero(time[1])).next().html((time[0] / 12 >= 1) ? 'pm' : 'am'); //or set the 24h format } else { $this.val($.leadingZero(time[0]) + ':' + $.leadingZero(time[1])); } } }, correct: function () { var $this = $(this), val = $this.val(), time; //no value => stop if (val == '') return; //it is not hh:mm format if (!/^\d+:\d+$/.test(val)) { //convert the input (read the docs for more details) if (val.length == 1) { val = "0" + val + ":00"; } else if (val.length == 2) { val = val + ":00"; } else if (val.length == 3) { val = val.substr(0, 2) + ":" + val.substr(2, 3) + "0"; } else if (val.length == 4) { val = val.substr(0, 2) + ":" + val.substr(2, 4); } } time = val.split(':'); //value is wrong or out of range if (!/\d\d:\d\d$/.test(val) && val != "" || time[0] > 23 || time[1] > 59) { $this.val('00:00').focus().select(); $this.data('wl_Time').time = '00:00'; $.fn.wl_Time.methods.printTime.call(this); //value is a time } else { //save it $this.data('wl_Time').time = val; //print it $.fn.wl_Time.methods.printTime.call(this); } }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Time.defaults[key] !== undefined || $.fn.wl_Time.defaults[key] == null) { $this.data('wl_Time')[key] = value; $this.trigger('change.wl_Time'); } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Time.js
JavaScript
oos
6,579
$(document).ready(function () { var $body = $('body'), $content = $('#content'), $form = $content.find('#loginform'); //IE doen't like that fadein if (!$.browser.msie) $body.fadeTo(0, 0.0).delay(500).fadeTo(1000, 1); $("input").uniform(); $("input[name='UserName']").focus(); $form.wl_Form({ status: false, onBeforeSubmit: function (data) { $form.wl_Form('set', 'sent', false); if (data.UserName && data.Password) { return true; } else { $.wl_Alert('Please provide something!', 'info', '#content'); return false; } }, onSuccess: function (data, textStatus, jqXHR) { if (typeof data == 'string') data = JSON.parse(data); if (data.Success) { window.location.href = data.RedirectUrl; } else { $.wl_Alert(data.Message, 'info', '#content'); } } }); });
08102013project
trunk/CMS/Scripts/plugins/login.js
JavaScript
oos
1,073
/*----------------------------------------------------------------------*/ /* wl_Autocomplete v 1.0 by revaxarts.com /* description: extends the jQuery Autocomplete Function /* dependency: jQUery UI Autocomplete, parseData function /*----------------------------------------------------------------------*/ $.fn.wl_Autocomplete = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Autocomplete.methods[method]) { return $.fn.wl_Autocomplete.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Autocomplete')) { var opts = $.extend({}, $this.data('wl_Autocomplete'), method); } else { var opts = $.extend({}, $.fn.wl_Autocomplete.defaults, method, $this.data()); } } else { try { return $this.autocomplete(method, args[1], args[2]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Autocomplete')) { $this.data('wl_Autocomplete', {}); //if source is a function use the returning value of that function if ($.isFunction(window[opts.source])) { opts.source = window[opts.source].call(this); } //if it is an string it must be an array to parse (typeof '[1,2,3]' === 'string') if (typeof opts.source === 'string') { opts.source = $.parseData(opts.source, true); } //call the jQueryUI autocomplete plugin $this.autocomplete(opts); } else { } if (opts) $.extend($this.data('wl_Autocomplete'), opts); }); }; $.fn.wl_Autocomplete.defaults = { //check http://jqueryui.com/demos/autocomplete/ for all options }; $.fn.wl_Autocomplete.version = '1.0'; $.fn.wl_Autocomplete.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Autocomplete.defaults[key] !== undefined || $.fn.wl_Autocomplete.defaults[key] == null) { $this.data('wl_Autocomplete')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Autocomplete.js
JavaScript
oos
2,354
/*----------------------------------------------------------------------*/ /* wl_Calendar v 1.0 by revaxarts.com /* description: makes a Calendar /* dependency: fullcalendar plugin (calendar.js) /*----------------------------------------------------------------------*/ $.fn.wl_Calendar = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Calendar.methods[method]) { return $.fn.wl_Calendar.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Calendar')) { var opts = $.extend({}, $this.data('wl_Calendar'), method); } else { var opts = $.extend({}, $.fn.wl_Calendar.defaults, method, $this.data()); } } else { try { return $this.fullCalendar(method, args[1], args[2], args[3], args[4]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Calendar')) { $this.data('wl_Calendar', {}); //we need to use the jquery UI Theme opts.theme = true; //some shorties for the header, you can add more easily switch (opts.header) { case 'small': opts.header = { left: 'title', right: 'prev,next' }; break; case 'small-today': opts.header = { left: 'title', right: 'prev,today,next' }; break; default: } //call the fullCalendar plugin $this.fullCalendar(opts); } else { } if (opts) $.extend($this.data('wl_Calendar'), opts); }); }; $.fn.wl_Calendar.defaults = {}; $.fn.wl_Calendar.version = '1.0'; $.fn.wl_Calendar.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Calendar.defaults[key] !== undefined || $.fn.wl_Calendar.defaults[key] == null) { $this.data('wl_Calendar')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Calendar.js
JavaScript
oos
2,236
/*----------------------------------------------------------------------*/ /* wl_Dialog v 1.1 by revaxarts.com /* description: handles alert boxes, prompt boxes and confirm boxes and /* message boxes /* contains 4 plugins /* dependency: jquery UI Dialog /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Confirm Dialog /* like the native confirm method /*----------------------------------------------------------------------*/ $.confirm = function (text, callback, cancelcallback) { var options = $.extend(true, {}, $.alert.defaults, $.confirm.defaults); //nativ behaviour if (options.nativ) { if (result = confirm(unescape(text))) { if ($.isFunction(callback)) callback.call(this); } else { if ($.isFunction(cancelcallback)) cancelcallback.call(this); } return; } //the callbackfunction var cb = function () { if ($.isFunction(callback)) callback.call(this); $(this).dialog('close'); $('#wl_dialog').remove(); }, //the callbackfunction on cancel ccb = function () { if ($.isFunction(cancelcallback)) cancelcallback.call(this); $(this).dialog('close'); $('#wl_dialog').remove(); }; //set some options options = $.extend({}, { buttons: [{ text: options.text.ok, click: cb }, { text: options.text.cancel, click: ccb }] }, options); //use the dialog return $.alert(unescape(text), options); }; $.confirm.defaults = { text: { header: 'Please confirm', ok: 'Yes', cancel: 'No' } }; /*----------------------------------------------------------------------*/ /* Prompt Dialog /* like the native prompt method /*----------------------------------------------------------------------*/ $.prompt = function (text, value, callback, cancelcallback) { var options = $.extend(true, {}, $.alert.defaults, $.prompt.defaults); //nativ behaviour if (options.nativ) { var val = prompt(unescape($.trim(text)), unescape(value)); if ($.isFunction(callback) && val !== null) { callback.call(this, val); } else { if ($.isFunction(cancelcallback)) cancelcallback.call(this); } return; } //the callbackfunction var cb = function (value) { if ($.isFunction(callback)) callback.call(this, value); $(this).dialog('close'); $('#wl_dialog').remove(); }, //the callbackfunction on cancel ccb = function () { if ($.isFunction(cancelcallback)) cancelcallback.call(this); $(this).dialog('close'); $('#wl_dialog').remove(); }; //set some options options = $.extend({}, { buttons: [{ text: options.text.ok, click: function () { cb.call(this, $('#wl_promptinputfield').val()); } }, { text: options.text.cancel, click: ccb }], open: function () { $('#wl_promptinputfield').focus().select(); $('#wl_promptinputfield').uniform(); $('#wl_promptinputform').bind('submit', function (event) { event.preventDefault(); cb.call(this, $('#wl_promptinputfield').val()); $(this).parent().dialog('close'); $('#wl_dialog').remove(); }); } }, options); //use the dialog return $.alert('<p>' + unescape(text) + '</p><form id="wl_promptinputform"><input id="wl_promptinputfield" name="wl_promptinputfield" value="' + unescape(value) + '"></form>', options); }; $.prompt.defaults = { text: { header: 'Please prompt', ok: 'OK', cancel: 'Cancel' } }; /*----------------------------------------------------------------------*/ /* Alert Dialog /* like the native alert method /*----------------------------------------------------------------------*/ $.alert = function (content, options) { //if no options it is a normal dialog if (!options) { var options = $.extend(true, {}, { buttons: [{ text: $.alert.defaults.text.ok, click: function () { $(this).dialog('close'); $('#wl_dialog').remove(); } }] }, $.alert.defaults); } //nativ behaviour if (options.nativ) { alert(content); return; } //create a container var container = $('<div/>', { id: 'wl_dialog' }).appendTo('body'); //set a header if (options.text.header) { container.attr('title', options.text.header); } //fill the container container.html(content.replace(/\n/g, '<br>')); //display the dialog container.dialog(options); return{ close:function(callback){ container.dialog('close'); container.remove(); if($.isFunction(callback)) callback.call(this); }, setHeader:function(text){ this.set('title',text); }, setBody:function(html){ container.html(html); }, set:function(option, value){ container.dialog("option", option, value); } } }; $.alert.defaults = { nativ: false, resizable: false, modal: true, text: { header: 'Notification', ok: 'OK' } }; /*----------------------------------------------------------------------*/ /* Message Function /*----------------------------------------------------------------------*/ $.msg = function (content, options) { //get the options var options = $.extend({}, $.msg.defaults, options); var container = $('#wl_msg'),msgbox; //the container doen't exists => create it if (!container.length) { container = $('<div/>', { id: 'wl_msg' }).appendTo('body').data('msgcount', 0); var topoffset = parseInt(container.css('top'), 10); //bind some events to it container.bind('mouseenter', function () { container.data('pause', true); }).bind('mouseleave', function () { container.data('pause', false); }); container.delegate('.msg-close', 'click', function () { container.data('pause', false); close($(this).parent()); }); container.delegate('.msg-box-close', 'click', function () { container.fadeOutSlide(options.fadeTime); }); //bind the scroll event $(window).unbind('scroll.wl_msg').bind('scroll.wl_msg', function () { var pos = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; if (pos > topoffset) { (window.navigator.standalone === undefined) ? container.css({ position: 'fixed', top: 10 }) : container.css({ top: pos + 10 }); } else { (window.navigator.standalone === undefined) ? container.removeAttr('style') : container.css({ top: topoffset }); } }).trigger('scroll.wl_msg'); } //stop if no content is set if(!content)return false; //count of displayed messages var count = container.data('msgcount'); function getHTML(content, headline) { return '<div class="msg-box"><h3>' + (headline || '') + '</h3><a class="msg-close">close</a><div class="msg-content">' + content.replace('\n', '<br>') + '</div></div>'; } function create() { msgbox = $(getHTML(content, options.header)), closeall = $('.msg-box-close'); //we have some messages allready if (count) { //No close all button if (!closeall.length) { msgbox.appendTo(container); $('<div class="msg-box-close">close all</div>').appendTo(container).fadeInSlide(options.fadeTime); //Close all button } else { msgbox.insertBefore(closeall); } //first message } else { msgbox.appendTo(container); } //fade it in nicely msgbox.fadeInSlide(options.fadeTime); //add the count of the messages to the container container.data('msgcount', ++count); //outclose it only if it's not sticky if (!options.sticky) { close(msgbox, options.live); } } function close(item, delay, callback) { if ($.isFunction(delay)){ callback = delay; delay = 0; }else if(!delay){ delay = 0; } setTimeout(function () { //if the mouse isn't over the container if (!container.data('pause')) { item.fadeOutSlide(options.fadeTime, function () { var count = $('.msg-box').length; if (count < 2 && $('.msg-box-close').length) { $('.msg-box-close').fadeOutSlide(options.fadeTime); } container.data('msgcount', count); if($.isFunction(callback)) callback.call(item); }) //try again... } else { close(item, delay); } }, delay); } //create the messsage create(); return { close:function(callback){ close(msgbox,callback); }, setHeader:function(text){ msgbox.find('h3').eq(0).text(text); }, setBody:function(html){ msgbox.find('.msg-content').eq(0).html(html); }, closeAll:function(callback){ container.fadeOutSlide(options.fadeTime, function(){ if($.isFunction(callback)) callback.call(this); }); } } }; $.msg.defaults = { header: null, live: 5000, topoffset: 90, fadeTime: 500, sticky: false }; //initial call to prevent IE to jump to the top $(document).ready(function() {$.msg(false);});
08102013project
trunk/CMS/Scripts/plugins/wl_Dialog.js
JavaScript
oos
9,009
/*----------------------------------------------------------------------*/ /* wl_Color v 1.0 by revaxarts.com /* description: Makes a colorpicker on an input field /* dependency: miniColors Plugin /*----------------------------------------------------------------------*/ $.fn.wl_Color = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($.fn.wl_Color.methods[method]) { return $.fn.wl_Color.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Color')) { var opts = $.extend({}, $this.data('wl_Color'), method); } else { var opts = $.extend({}, $.fn.wl_Color.defaults, method, $this.data()); } } else { try { return $this.miniColors(method, args[1]); } catch (e) { $.error('Method "' + method + '" does not exist'); } } if (!$this.data('wl_Color')) { $this.data('wl_Color', {}); //bind the mouswheel event $this.bind('mousewheel.wl_Color', function (event, delta) { if (opts.mousewheel) { event.preventDefault(); //delta must be 1 or -1 (different on macs and with shiftkey pressed) var delta = (delta < 0) ? -1 : 1, hsb = $this.data('hsb'); //saturation with shift key if(event.shiftKey){ hsb.s -= delta*2; hsb.s = Math.round(Math.max(0,Math.min(100,hsb.s))); //hue with alt key }else if(event.altKey && event.shiftKey){ hsb.h += delta*5; hsb.h = Math.round(hsb.h); //brightness without additional key }else{ hsb.b += delta*2; hsb.b = Math.round(Math.max(0,Math.min(100,hsb.b))); } $this.miniColors('value',hsb); $this.trigger('change.wl_Color'); } }); //call the miniColors plugin with extra options $this.miniColors($.extend({}, { change: function (hex, rgb) { $(this).trigger('change.wl_Color'); } }), opts).trigger('keyup.miniColors'); //bind a change event to the evet field for the callback $this.bind('change.wl_Color', function () { var val = $(this).val(); if (val && !/^#/.test(val)) val = '#'+val; $(this).val(val); opts.onChange.call($this[0], $(this).data('hsb'), val); }) //hex values have 7 chars with # .attr('maxlength',7); //prepend a '#' if not set var val = $this.val(); if (val && !/^#/.test($this.val())) { $this.val('#' + val.substr(0,6)); } } else { } if (opts) $.extend($this.data('wl_Color'), opts); }); }; $.fn.wl_Color.defaults = { mousewheel: true, onChange: function (hsb, rgb) {} }; $.fn.wl_Color.version = '1.0'; $.fn.wl_Color.methods = { destroy: function () { var $this = $(this); //destroy them $this.removeData('wl_Color'); $this.miniColors('destroy'); }, set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Color.defaults[key] !== undefined) { $this.data('wl_Color')[key] = value; } else if (key == 'value') { $this.val(value).trigger('keyup.miniColors'); } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Color.js
JavaScript
oos
3,506
/*----------------------------------------------------------------------*/ /* wl_Password v 1.0.1 by revaxarts.com /* description: handles password fields /* dependency: none /*----------------------------------------------------------------------*/ $.fn.wl_Password = function (method) { var args = arguments; return this.each(function () { var $this = $(this); if ($this.data('wl_Password') && $this.data('wl_Password').confirmfield) { return; } if ($.fn.wl_Password.methods[method]) { return $.fn.wl_Password.methods[method].apply(this, Array.prototype.slice.call(args, 1)); } else if (typeof method === 'object' || !method) { if ($this.data('wl_Password')) { var opts = $.extend({}, $this.data('wl_Password'), method); } else { var opts = $.extend({}, $.fn.wl_Password.defaults, method, $this.data()); } } else { $.error('Method "' + method + '" does not exist'); } if (!$this.data('wl_Password')) { $this.data('wl_Password', {}); //The strnghtmeter var $strength = $('<div/>', { 'class': 'passwordstrength' }).appendTo($this.parent()).hide(); //if confirm field if (opts.confirm) { //clone the password field and append it after the field or after the strengthmeter. Hide it opts.connect = this.id + '_confirm'; var $confirm = $($this.addClass('password').clone()).attr({ 'id': opts.connect, 'name': opts.connect }).appendTo($this.parent()).removeAttr('required').hide(); $confirm.data('wl_Password', { confirmfield: true }); } $this.bind({ //focus triggers a keyup 'focus.wl_Password': function () { $this.trigger('keyup.wl_Password'); }, //blur sets the strengthmeter 'blur.wl_Password': function () { var opts = $this.data('wl_Password') || opts; if ($this.val()) { if (opts.confirm && !$confirm.val()) $strength.text(opts.text.confirm); } else { $strength.hide(); if (opts.confirm) $confirm.hide(); } }, 'keyup.wl_Password': function () { var opts = $this.data('wl_Password') || opts; //if value is set if ($this.val()) { //show optional confirm field if (opts.confirm) $confirm.show(); //get the strength of the current value var _strength = getStrength($this.val(), opts.minLength); //show optional strengthmeter if (opts.showStrength) { $strength.show(); $strength.attr('class', 'passwordstrength').addClass('s_' + _strength).text(opts.words[_strength]); } //add strength to the DOM element $this.data('wl_Password').strength = _strength; //hide siblings if no value is set } else { if (opts.showStrength) $strength.hide(); if (opts.confirm) $confirm.val('').hide(); } } }); //bind only when confirmation and strengthmeter is active if (opts.confirm && opts.showStrength) { $confirm.bind('keyup.wl_Password', function () { var opts = $this.data('wl_Password') || opts; if (!$confirm.val()) { //confirm text $strength.text(opts.text.confirm); } else if ($confirm.val() != $this.val()) { //password doesn't match $strength.text(opts.text.nomatch); } else { //password match => show strength $strength.text(opts.words[$this.data('wl_Password').strength]); } }); } //calculates the strenght of a password //must return a value between 0 and 5 //value is the password function getStrength(value, minLength) { var score = 0; if (value.length < minLength) { return score } else { score = Math.min(15, (score + (value.length) * 2)); } if (value.match(/[a-z]/)) score += 1; if (value.match(/[A-Z]/)) score += 5; if (value.match(/\d+/)) score += 5; if (value.match(/(.*[0-9].*[0-9].*[0-9])/)) score += 7; if (value.match(/.[!,@,#,$,%,^,&,*,?,_,~]/)) score += 5; if (value.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 7; if (value.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) score += 2; if (value.match(/([a-zA-Z])/) && value.match(/([0-9])/)) score += 3; if (value.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/)) score += 3; return Math.min(5, Math.ceil(score / 10)); } } else { } if (opts) $.extend($this.data('wl_Password'), opts); }); }; $.fn.wl_Password.defaults = { confirm: true, showStrength: true, words: ['too short', 'bad', 'medium', 'good', 'very good', 'excellent'], minLength: 3, text: { confirm: 'please confirm', nomatch: 'password doesn\'t match' } }; $.fn.wl_Password.version = '1.0.1'; $.fn.wl_Password.methods = { set: function () { var $this = $(this), options = {}; if (typeof arguments[0] === 'object') { options = arguments[0]; } else if (arguments[0] && arguments[1] !== undefined) { options[arguments[0]] = arguments[1]; } $.each(options, function (key, value) { if ($.fn.wl_Password.defaults[key] !== undefined || $.fn.wl_Password.defaults[key] == null) { $this.data('wl_Password')[key] = value; } else { $.error('Key "' + key + '" is not defined'); } }); } };
08102013project
trunk/CMS/Scripts/plugins/wl_Password.js
JavaScript
oos
5,405
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CMS.Controllers { public class HomeController : Controller { [Authorize] public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } } }
08102013project
trunk/CMS/Controllers/HomeController.cs
C#
oos
380
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.Security; using CMS.Models; namespace CMS.Controllers { public class AccountController : Controller { // // GET: /Account/LogOn public ActionResult LogOn() { if (Request.IsAuthenticated) { return RedirectToAction("Index", "Home"); } else return View(); } // // POST: /Account/LogOn [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Json(new { Success = true, Message = "Đăng nhập thành công.", RedirectUrl = returnUrl }); } else { return Json(new { Success = true, Message = "Đăng nhập thành công.", RedirectUrl = "/" }); } } else { return Json(new { Success = false, Message = "The user name or password provided is incorrect.", RedirectUrl = "" }); } } // If we got this far, something failed, redisplay form return Json(new { Success = false, Message = "The user name or password provided is incorrect.", RedirectUrl = "" }); } // // GET: /Account/LogOff public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("LogOn"); } // // GET: /Account/Register [Authorize] public ActionResult Register() { return View(); } // // POST: /Account/Register [Authorize] [HttpPost] public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ChangePassword [Authorize] public ActionResult ChangePassword() { return View(); } // // POST: /Account/ChangePassword [Authorize] [HttpPost] public ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { // ChangePassword will throw an exception rather // than return false in certain failure scenarios. bool changePasswordSucceeded; try { MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */); changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword); } catch (Exception) { changePasswordSucceeded = false; } if (changePasswordSucceeded) { return RedirectToAction("ChangePasswordSuccess"); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ChangePasswordSuccess public ActionResult ChangePasswordSuccess() { return View(); } #region Status Codes private static string ErrorCodeToString(MembershipCreateStatus createStatus) { // See http://go.microsoft.com/fwlink/?LinkID=177550 for // a full list of status codes. switch (createStatus) { case MembershipCreateStatus.DuplicateUserName: return "User name already exists. Please enter a different user name."; case MembershipCreateStatus.DuplicateEmail: return "A user name for that e-mail address already exists. Please enter a different e-mail address."; case MembershipCreateStatus.InvalidPassword: return "The password provided is invalid. Please enter a valid password value."; case MembershipCreateStatus.InvalidEmail: return "The e-mail address provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidAnswer: return "The password retrieval answer provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidQuestion: return "The password retrieval question provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidUserName: return "The user name provided is invalid. Please check the value and try again."; case MembershipCreateStatus.ProviderError: return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; case MembershipCreateStatus.UserRejected: return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; default: return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; } } #endregion } }
08102013project
trunk/CMS/Controllers/AccountController.cs
C#
oos
7,209
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Web.Mvc; using System.Web.Security; namespace CMS.Models { public class ChangePasswordModel { [Required] [DataType(DataType.Password)] [Display(Name = "Current password")] public string OldPassword { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New password")] public string NewPassword { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm new password")] [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } public class LogOnModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } public class RegisterModel { [Required] [Display(Name = "User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [Display(Name = "Email address")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } } }
08102013project
trunk/CMS/Models/AccountModels.cs
C#
oos
2,122
<%@ Application Codebehind="Global.asax.cs" Inherits="CMS.MvcApplication" Language="C#" %>
08102013project
trunk/CMS/Global.asax
ASP.NET
oos
95
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CMS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("CMS")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("345cb851-5d8e-4ca4-8901-040cd7a2b5e0")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
08102013project
trunk/CMS/Properties/AssemblyInfo.cs
C#
oos
1,395
/*----------------------------------------------------------------------*/ /* bg/01.png http://ptrn.it/iglrOa /* bg/02.png http://ptrn.it/ldfM3q /* bg/03.png http://ptrn.it/jJseqP /* bg/04.png http://ptrn.it/mkP0FP /* bg/05.png http://ptrn.it/mntuwU /* bg/06.png http://ptrn.it/kj7OMC /* bg/07.png http://ptrn.it/l9Ehl8 /* bg/08.png http://ptrn.it/lOwe5N /* bg/09.png http://ptrn.it/muLiXq /* bg/10.png http://ptrn.it/mjwbxK /* bg/11.png http://ptrn.it/kq6NGq /* bg/12.png http://ptrn.it/ilzOva /* bg/13.png http://ptrn.it/jNcpdS /* bg/14.png http://ptrn.it/iVpjzW /*----------------------------------------------------------------------*/ .bg01{background-image:url(images/bg/01.png);} .bg02{background-image:url(images/bg/02.png);} .bg03{background-image:url(images/bg/03.png);} .bg04{background-image:url(images/bg/04.png);} .bg05{background-image:url(images/bg/05.png);} .bg06{background-image:url(images/bg/06.png);} .bg07{background-image:url(images/bg/07.png);} .bg08{background-image:url(images/bg/08.png);} .bg09{background-image:url(images/bg/09.png);} .bg10{background-image:url(images/bg/10.png);} .bg11{background-image:url(images/bg/11.png);} .bg12{background-image:url(images/bg/12.png);} .bg13{background-image:url(images/bg/13.png);} .bg14{background-image:url(images/bg/14.png);} /*----------------------------------------------------------------------*/ /* Reset /*----------------------------------------------------------------------*/ html,body,div,span,applet,object,iframe,input,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{ margin:0; padding:0; border:0; outline:0; font-weight:100; font-style:inherit; font-size:100%; font-family:inherit; vertical-align:baseline; } *{ -webkit-text-size-adjust:none; -webkit-tap-highlight-color:rgba(0,0,0,0); } /*----------------------------------------------------------------------*/ /* Font Declaration /*----------------------------------------------------------------------*/ html, textarea, input, input[type=submit], button, a.btn, span, div.alert p, header{ font-family:'PT Sans', sans-serif; } code, pre{ font-family:"Courier New", Courier, monospace; } blockquote{ font-family:Georgia, "Times New Roman", Times, serif; } /*----------------------------------------------------------------------*/ /* General Section /*----------------------------------------------------------------------*/ html, body, textarea, input { font-size:12px; -webkit-text-size-adjust:none; } html{ background-attachment:fixed; overflow-y:scroll; } a{ text-decoration:none; cursor:pointer;} a:hover { text-decoration:underline; } a, a:hover, a:visited, a:link {color:#000;} ::-moz-selection{ text-shadow:none; } ::selection { text-shadow:none; } header, footer, nav, section{ display:block; } h1, h2, h3, h4, h5, h6{ font-weight:100; } h1 { font-size:28px; line-height:32px; margin-top:22px; } h2 { font-size:24px; line-height:26px; } h3 { font-size:20px; line-height:24px; } h4 { font-size:18px; line-height:22px; } h5 { font-size:16px; line-height:22px; } h6 { font-size:14px; line-height:20px; } h1 span{ font-size:14px; line-height:14px; } h2 span{ font-size:12px; line-height:12px; } h3 span{ font-size:10px; line-height:10px; } p, ul, ol, pre{ margin-bottom:18px; line-height:18px; font-size:12px; } blockquote{ font-size:16px; font-style:italic; border-left:5px solid; padding:0 18px; margin:36px; } li{ margin-left:18px; } hr { display:block; height:0px; line-height:0px; border:0; border-top:1px solid; border-bottom:1px solid; margin:16px 0; float:none; clear:both; padding:0; } strong{ font-weight:700; } em{ font-style:italic; } img{ border:0; } .small{ font-size:10px; } .field-validation-error{color:Red;} /*----------------------------------------------------------------------*/ /* Pageoptions /*----------------------------------------------------------------------*/ #pageoptions{ position:relative; overflow:hidden; width:auto; padding:0; min-height:20px; } #pageoptions h1, #pageoptions h2,#pageoptions h3, #pageoptions h4, #pageoptions h5, #pageoptions h6{ } #pageoptions ul{ overflow:hidden; margin:0; padding:1px 6px; } #pageoptions ul li{ float:right; list-style:none; padding:0; margin:0; margin-left:1px; } #pageoptions ul li a{ text-decoration:none; padding:0 8px 6px; -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } #pageoptions ul li a:hover, #pageoptions ul li a.active{ } #pageoptions > div{ position:absolute; left:15px; right:15px; padding:15px; overflow:hidden; min-height:400px; -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } #pageoptions div li{ float:none; } /*----------------------------------------------------------------------*/ /* Tables /*----------------------------------------------------------------------*/ table{ width:100%; border-collapse:collapse; margin-bottom:18px; } table td, table th{ border:1px solid; padding:6px 3px; text-align:center; } table th{ font-weight:700; } div.chart .legend table{ border:0; width:auto; } div.chart{ max-width:100%; margin-bottom:18px; } div.chart .legend table td{ vertical-align:middle; text-align:center; } div.chart .legend table td.legendColorBox{ opacity:0.6; filter:Alpha(opacity=60); } table.documentation{ } table.documentation th, table.documentation td{ text-align:left; } /*----------------------------------------------------------------------*/ /* Header /*----------------------------------------------------------------------*/ header{ position:relative; border-top:1px solid; z-index:10; -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } #logo{ height:60px; padding:0px; margin-left:15px; width:160px; border:0; -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; background:url(images/cms-logo.png) left center no-repeat; } #logo, #logo a{ font-weight:700; font-size:20px; text-decoration:none; text-indent:-99999px; } #logo a{ } #header{ height:60px; position:absolute; top:0; left:240px; right:0; border:0; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } #header ul{ width:75%; height:46px; float:left; margin:0; } #header ul li{ list-style:none; margin:0; } #header ul li ul{ width:100%; height:auto; float:none; padding:18px 0; margin:0; } #header ul li ul li{ border:1px solid; position:relative; float:left; margin:0 10px 0 0; display:block; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } #header ul li ul li a{ padding:2px 20px 4px 20px; font-size:14px; display:block; border-top:1px solid; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } #header ul li ul li a:hover{ text-decoration:none; } #header ul li ul li a:active, #header ul li ul li a.active{ border:0; padding:4px 20px 3px 20px; } #header ul li ul li:active, #header ul li ul li.active{ } #header ul li ul li ul{ display:none; padding:0; -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } #header ul li ul li ul.shown{ display:block; } #header ul li ul li ul li{ margin:0; max-width:180px; border-left:0; border-right:0; border:0; border-top:1px solid; float:none; -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } #header ul li ul li ul li a{ -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } #header ul li ul li ul li:last-child, #header ul li ul li ul li:last-child a{ -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } #header ul li ul li span{ font-family:sans-serif; display:block; position:absolute; right:-12px; top:-12px; font-size:10px; line-height:10px; font-weight:700; padding:4px 4px 5px; text-align:center; min-width:10px; z-index:100; border:1px solid; cursor:pointer; -webkit-border-radius:36px; -moz-border-radius:36px; border-radius:36px; } #searchbox{ float:right; margin:17px 10px 17px 0; padding:0; border:1px solid; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } form#searchform{ width:90px; padding:0; border:0; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } form#searchform input#search{ -webkit-appearance:none !important; padding:3px 0; font-size:14px; width:100%; text-align:center; border:0; border-top:1px solid; margin:0; font-style:normal; } form#searchform input#search.load{ background-repeat:no-repeat !important; background-position:100% 50% !important; } form#searchform input::-webkit-search-decoration, form#searchform input::-webkit-search-cancel-button, form#searchform input::-webkit-search-results-button, form#searchform input::-webkit-search-results-decoration { display:none; } /* Live Search /*---------------------------------------------------------------------*/ form#searchform input#search:focus{ border:0; padding:4px 0 3px; } ul#searchboxresult{ margin:0; position:absolute; overflow:hidden; height:auto; right:10px; top:50px; width:250px; border-top:1px solid; margin:0; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; display:none; z-index:250; } ul#searchboxresult li{ } ul#searchboxresult li a{ padding:8px; font-size:12px; display:block; border:1px solid; border-left:0; border-right:0; background-repeat:no-repeat; background-position:12px 10px; display:block; overflow:hidden; height:50px; line-height:17px; } ul#searchboxresult li a:hover{ text-decoration:none; } ul#searchboxresult li a.noresult{ padding:12px; height:auto; text-align:center; font-size:14px; } ul#searchboxresult li a img{ float:left; margin-right:6px; } /*----------------------------------------------------------------------*/ /* Navigation /*----------------------------------------------------------------------*/ nav{ border-right:0px solid; border-left:1px solid; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } nav ul{ border-top:1px solid; margin:0; -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } nav ul li{ list-style:none; padding:0; margin:0; background-repeat:no-repeat; background-position:-9999px; } nav ul li a{ display:block; padding-right:0; } nav ul li a span{ padding:12px 40px 11px; font-size:14px; display:block; border:1px solid; border-left:0; border-right:0; background-repeat:no-repeat; background-position:12px 10px; white-space:nowrap; } nav ul li a:hover{ text-decoration:none; cursor:pointer; padding-right:0px; } nav ul li a:active, nav ul li a.active{ padding-right:0px; padding-bottom:0px; background-repeat:repeat-x; background-position:left center; filter:none; } nav ul li a:active span, nav ul li a.active span{ border-bottom:0; padding:12px 40px 12px; } nav ul li ul{ border:0; margin-right:10px; margin-left:10px; display:none; margin-bottom:10px; } nav ul li ul li:first-child a{ } nav ul li ul li:last-child, nav ul li ul li:last-child a, nav ul li ul li:last-child a span{ -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } nav ul li ul li{ -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } nav ul li ul li a{ padding-right:0; -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } nav ul li ul li a span{ border:0; font-size:12px; line-height:12px; border-top:1px solid #ddd; padding-top:6px; padding-bottom:6px; padding-left:15px; background-position:-9999px; -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } nav ul li ul li:first-child a span{ } nav ul li ul li a:active, nav ul li ul li a.active{ } nav ul li ul li a:active span, nav ul li ul li a.active span{ background-position:-9999px; padding-top:6px; padding-bottom:6px; padding-left:15px; } /*----------------------------------------------------------------------*/ /* Content /*----------------------------------------------------------------------*/ #content{ border:0; padding:15px 5px 15px 230px; margin:0; min-height:600px; border:1px solid; overflow:visible; -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } .bgsample{ border:1px solid; float:left; margin:8px; padding:27px 30px; } /*----------------------------------------------------------------------*/ /* Gallery /*----------------------------------------------------------------------*/ .gallery{ border:1px solid; padding:3px; overflow:auto; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .widget .gallery{ padding:0; border:0; } .gallery .sortable_placeholder{ margin:4px; } .gallery li{ margin:4px; position:relative; list-style:none; float:left; padding:8px; border:1px solid; overflow:hidden; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .gallery li > a{ display:block; margin:0; padding:0; height:116px; width:116px; background-position:center center; background-repeat:no-repeat; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .gallery li img{ position:relative; } .gallery li span{ position:absolute; top:140px; left:0; display:block; height:132px; width:132px; padding-top:4px; border-top:1px solid; } .gallery li > a span a{ /* position:relative; */ display:block; padding-left:24px; margin:2px 16px; background-position:center left; background-repeat:no-repeat; height:20px; } .gallery li a span a.edit{ } .gallery li a span a.delete{ } /*----------------------------------------------------------------------*/ /* Breadcrumb /*----------------------------------------------------------------------*/ .breadcrumb{ margin-bottom:20px; display:block; overflow:hidden; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .breadcrumb.disabled{ opacity:0.8; filter:Alpha(opacity=80); } .breadcrumb li{ float:left; margin:0; list-style:none; max-width:280px; } .breadcrumb li:first-child{ margin-left:0px; } .breadcrumb li a{ padding:10px 35px 5px 30px; font-size:14px; display:block; font-weight:700; margin-left:-20px; border:1px solid; border-left:0; background-repeat:no-repeat; background-position:0px 0px; height:25px; text-decoration:none; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .breadcrumb li a span{ padding:4px 9px; height:20px; background-repeat:no-repeat; background-position:-2px -2px; display:block; text-indent:-9999px; } .breadcrumb li a.previous span{ opacity:0.6; filter:Alpha(opacity=60); } .breadcrumb li a.previous:hover span{ opacity:1; filter:none; } .breadcrumb li:first-child a{ border-left:1px solid; background-position:-20px 0px; margin-left:0px; padding-left:20px; } .breadcrumb li:last-child a{ padding-right:20px; } .breadcrumb li a.previous{ background-position:0px -129px; } .breadcrumb.disabled li a.previous:hover{ background-position:0px -129px; } .breadcrumb li:first-child a.previous{ background-position:-20px -129px; } .breadcrumb.disabled li:first-child a.previous:hover{ background-position:-20px -129px; } .breadcrumb li a:hover{ background-position:0px -43px; } .breadcrumb.disabled li a:hover{ background-position:0px 0px; } .breadcrumb li:first-child a:hover{ background-position:-20px -43px; } .breadcrumb.disabled li:first-child a:hover{ background-position:-20px 0px; } .breadcrumb li a:active, .breadcrumb li a.active, .breadcrumb.disabled li a.active:hover{ background-position:0px -86px; } .breadcrumb li:first-child a:active, .breadcrumb li:first-child a.active, .breadcrumb.disabled li:first-child a.active:hover{ background-position:-20px -86px; } /*----------------------------------------------------------------------*/ /* Message Box /*----------------------------------------------------------------------*/ #wl_msg{ position:absolute; top:90px; right:25px; z-index:15; width:300px; } #wl_msg .msg-box:first-child{ -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } #wl_msg .msg-box:last-child{ -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } #wl_msg .msg-box, #wl_msg .msg-box-close{ border:1px solid; margin-bottom:4px; display:none; } #wl_msg .msg-box-close{ text-align:center; cursor:pointer; -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } #wl_msg .msg-box-close:hover{ } #wl_msg .msg-box h3, #wl_msg .msg-close{ height:28px; } #wl_msg .msg-box h3{ border-bottom:1px solid; font-size:14px; width:264px; line-height:30px; padding-left:8px; margin:0; float:left; } #wl_msg .msg-close{ border-left:1px solid; border-bottom:1px solid; display:block; float:right; width:25px; line-height:1px; padding:0; text-indent:-9999px; background-position:50% 50%; background-repeat:no-repeat; } #wl_msg .msg-close:hover{ } #wl_msg .msg-content{ clear:both; padding:10px; } /*----------------------------------------------------------------------*/ /* Alert Boxes /*----------------------------------------------------------------------*/ div.alert{ border:1px solid; margin-bottom:15px; cursor:pointer; background-repeat:no-repeat; background-position:7px 8px; padding:10px 10px 10px 35px; font-size:14px; font-weight:700; margin:0; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } div.alert code{ background:none; border:0; } form div.alert{ margin:15px 4px; } div.alert:hover{ border:1px solid; } div.alert a{ font-size:14px; font-weight:700; } /*----------------------------------------------------------------------*/ /* Buttons /*----------------------------------------------------------------------*/ button, a.btn, .button, .dataTables_paginate span.paginate_button, .dataTables_paginate span.paginate_active{ border:1px solid; position:relative; padding:9px 12px; display:inline-block; cursor:pointer; background-repeat:no-repeat; background-position:4px 5px; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; text-decoration:none; font-size:11px; font-weight:700; outline:0 none; text-align:center; text-transform:uppercase; margin:2px; min-height:22px; min-width:8px; white-space:pre-line; vertical-align:baseline; } button.small, a.btn.small, .button.small{ min-height:14px; line-height:14px; font-size:10px; padding:4px 7px; } button.big, a.btn.big, .button.big{ font-size:14px; padding:12px 16px; } button.icon, a.btn.icon, .button.icon{ padding-left:27px; } button.small.icon, a.btn.small.icon, .button.small.icon{ padding-left:23px; background-position:0 -2px; } button.big.icon, a.btn.big.icon, .button.big.icon{ padding-left:27px; background-position:-0 8px; } a.btn.nt, button.nt, .button.nt{ background-position:50% 50%; text-indent:-9999px; } a.btn.small.nt, button.small.nt, .button.small.nt{ padding-left:12px; padding-right:12px; } button{ } a.btn{ line-height:18px; min-height:18px; } button:hover, a.btn:hover, .button:hover{ } button:active, a.btn:active, .button:active, .dataTables_paginate span.paginate_active{ top:1px; } /*----------------------------------------------------------------------*/ /* Form Elements /*----------------------------------------------------------------------*/ fieldset{ padding:15px; } pre{ white-space:pre-wrap; white-space:-moz-pre-wrap; white-space:-pre-wrap; white-space:-o-pre-wrap; word-wrap:break-word; padding:12px 15px; line-height:18px; } pre, code{ font-size:11px; padding:1px 2px; border:1px solid; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } pre code{ display:block; border:0; } input,textarea{ width:99%; border:1px solid; padding:4px 2px; margin:0 1px; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } input.g1,input.g2,input.g3,input.g4,input.g5,input.g6,input.g7,input.g8,input.g9,input.g10,input.g11,input.g12, textarea.g1,textarea.g2,textarea.g3,textarea.g4,textarea.g5,textarea.g6,textarea.g7,textarea.g8,textarea.g9,textarea.g10,textarea.g11,textarea.g12 { margin-left:0; padding:6px 2px; min-height:auto; } input.placeholder,textarea.placeholder{ font-style:italic; } input:focus,textarea:focus{ outline:none; } select optgroup, select option{ font-style:normal; border:0; } select option{ border:1px solid; padding:3px; } input[type=submit], input[type=checkbox], input[type=radio], input[type=button], button{ width:auto !important; } input[type=submit]{ min-height:33px; } form{ border:1px solid; padding:4px; margin-bottom:18px; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } form:last-child{ margin-bottom:0; } .widget form{ border:0; } form .wl_formstatus{ padding-left:18px; } form fieldset{ padding:0; margin:4px; border:1px solid; border-bottom:0; margin-top:18px; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } form fieldset:first-child{ margin-top:4px; } form label{ border-top:1px solid; display:block; font-size:16px; margin:0; padding:15px 10px; font-weight:700; -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } form label span{ font-size:12px; } form span.required{ padding:0 4px; font-size:10px; background-repeat:no-repeat; background-position:left bottom; } form input, form textarea{ padding:6px 2px; font-size:13px; } form fieldset > section{ width:100%; border-top:1px solid; border-bottom:1px solid; float:left; padding:0; margin:0; } form fieldset > section:first-child{ -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } form fieldset > section:last-child{ -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } form fieldset > section > div{ padding:15px 1%; width:78%; float:right; border-left:1px solid; height:100%; min-height:100%; } form fieldset > section > div > div{ float:none; clear:both; width:auto; } form fieldset > section > div div.date{ max-width:230px; } form fieldset > section.error > label{ text-shadow:none; font-weight:700; } form fieldset > section > div span{ font-size:11px; } form fieldset > section.error{ border-bottom:1px solid; } form fieldset > section.error > label{ text-shadow:none; font-weight:700; } form fieldset > section label{ border:0; cursor:pointer; font-size:13px; font-weight:100; float:left; background:none; filter:none; margin:0; width:16%; padding-left:2px; margin-left:8px; text-align:left; } form fieldset > section > div > div.selector{ } form fieldset > section > div > div.selector span{ height:32px; } form fieldset > section > div > div.selector select{ height:32px; cursor:pointer; } form fieldset > section > div > div.checker, form fieldset > section > div > div.radio{ display:inline-block; margin:0; line-height:1; float:none; } form fieldset > section > div > div.checker span, form fieldset > section > div > div.radio span{ display:inline-block; height:22px; width:22px; float:none; } form fieldset > section > div > div.checker span input, form fieldset > section > div > div.radio span input{ display:inline; width:22px; height:22px; min-width:22px; min-height:22px; margin:0; padding:0; cursor:pointer; } form fieldset > section > div label{ position:relative; width:auto; margin:0; padding:0; display:inline-block; float:none; top:-5px; font-size:11px; line-height:1.5; -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } form fieldset > section label span{ font-size:10px; } form div input{ } textarea{ min-height:70px; resize:none; overflow:auto; } input.date{ width:80px; } input[type=password], input.password{ width:150px; } div.passwordstrength{ font-size:12px; padding:5px 3px; text-align:center; width:150px; margin:3px 1px; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } div.passwordstrength.s_1{} div.passwordstrength.s_2{} div.passwordstrength.s_3{} div.passwordstrength.s_4{} div.passwordstrength.s_5{} input.time{ width:35px; text-align:center; } span.timeformat{ font-size:11px; padding-left:1px; } input.integer, input.decimal{ width:60px; text-align:right; } input.color{ width:60px; } /*----------------------------------------------------------------------*/ /* jQuery Checkbox /*----------------------------------------------------------------------*/ .jquery-checkbox, .jquery-checkbox span { display: inline; font-size: 16px; line-height: 16px; cursor: pointer;} .jquery-checkbox span.checkboxplaceholder { vertical-align:baseline; padding:2px 12px 0px; line-height:8px; background-repeat:no-repeat; } .jquery-checkbox span.checkboxplaceholder { background-image:url(dark/images/checkbox.png); } .jquery-checkbox.checkbox span.checkboxplaceholder{ background-position: 0px 0px; } .jquery-checkbox.checkbox .hover span.checkboxplaceholder{ background-position: 0px -26px; } .jquery-checkbox.checkbox .hover.pressed span.checkboxplaceholder{ background-position: 0px -51px; } .jquery-checkbox.checkbox.checked span.checkboxplaceholder{ background-position: 0px -77px; } .jquery-checkbox.checkbox.checked .hover span.checkboxplaceholder { background-position: 0px -102px; } .jquery-checkbox.checkbox.checked .hover.pressed span.checkboxplaceholder { background-position: 0px -128px; } .jquery-checkbox.checkbox .disabled span.checkboxplaceholder{ background-position: 0px -153px !important; cursor:auto; } .jquery-checkbox.checkbox.checked .disabled span.checkboxplaceholder{ background-position: 0px -179px !important; cursor:auto; } .jquery-checkbox.radio span.checkboxplaceholder{ background-position: -26px 0px; } .jquery-checkbox.radio .hover span.checkboxplaceholder{ background-position: -26px -26px; } .jquery-checkbox.radio .hover.pressed span.checkboxplaceholder{ background-position: -26px -51px; } .jquery-checkbox.radio.checked span.checkboxplaceholder{ background-position: -26px -77px; } .jquery-checkbox.radio.checked .hover span.checkboxplaceholder { background-position: -26px -102px; } .jquery-checkbox.radio.checked .hover.pressed span.checkboxplaceholder { background-position: -26px -128px; } .jquery-checkbox.radio .disabled span.checkboxplaceholder{ background-position: -26px -153px !important; cursor:auto; } .jquery-checkbox.radio.checked .disabled span.checkboxplaceholder{ background-position: -26px -179px !important; cursor:auto; } /*----------------------------------------------------------------------*/ /* File Upload /*----------------------------------------------------------------------*/ div.fileuploadui{ padding:0 5px; margin-bottom:5px; } div.fileuploadui a{ margin-right:10px; font-size:11px; display:inline !important; } ul.fileuploadpool{ display:block; clear:both; margin-bottom:5px; border:1px solid; z-index:1; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; min-height:68px; min-width:138px; overflow:hidden; padding:4px; } ul.fileuploadpool.drop{ } ul.fileuploadpool.single{ width:138px; } ul.fileuploadpool li{ font-size:11px; list-style-type:none; float:left; border:1px solid; margin:4px; padding:4px; height:50px; width:120px; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; -webkit-animation-name: showfile;-moz-animation-name: showfile;animation-name: showfile; -webkit-animation-duration: 0.2s;-moz-animation-duration: 0.2s;animation-duration: 0.2s; -webkit-animation-direction: alternate;-moz-animation-direction: alternate;animation-direction: alternate; -webkit-animation-timing-function: ease-out;-moz-animation-timing-function: ease-out;animation-timing-function: ease-out; } @-webkit-keyframes showfile { from { -webkit-transform: scale(0);} to {-webkit-transform: scale(1.0); } } @-moz-keyframes showfile { from { -webkit-transform: scale(0);} to {-webkit-transform: scale(1.0); } } @keyframes showfile { from { -webkit-transform: scale(0);} to {-webkit-transform: scale(1.0); } } ul.fileuploadpool li.error{ text-shadow:none; } ul.fileuploadpool li .name{ display:block; height:20px; overflow:hidden; white-space:nowrap; line-height:22px; } ul.fileuploadpool li a{ display:block; height:24px; width:24px; text-indent:-9999px; float:right; } ul.fileuploadpool li a:hover{ text-decoration:none; } ul.fileuploadpool li a.cancel{ } ul.fileuploadpool li a.remove{ } ul.fileuploadpool li .progress{ display:block; line-height:1px; height:3px; width:0%; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } ul.fileuploadpool li.success .progress{ } /*----------------------------------------------------------------------*/ /* Comboselect /*----------------------------------------------------------------------*/ div.comboselectbox{ display:block; clear:both; min-height:100px; } div.comboselectbox div.combowrap{ -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; float:left; border:1px solid; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; max-width:42%; width:200px; height:99%; padding:1% 1% 0 0; } div.comboselectbox ul.comboselect{ overflow:auto; height:99%; } div.comboselectbox.searchable div.combowrap:first-child ul.comboselect{ height:79%; } div.comboselectbox.searchable div.combowrap:first-child input{ margin:1% 2% 2% 2%; width:96%; } div.comboselectbox ul.comboselect li{ display:block; margin:0; list-style-type:none; float:left; border:1px solid; margin:1px 6% 1px 2%; width:92%; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } div.comboselectbox ul.comboselect li.hidden{ display:none; } div.comboselectbox ul.comboselect li a{ font-size:11px; padding:3px; float:left; width:75%; cursor:pointer; text-decoration:none; cursor:pointer; } div.comboselectbox ul.comboselect.ui-sortable li.selected a{ cursor:n-resize; } div.comboselectbox ul.comboselect li a.add, div.comboselectbox ul.comboselect li a.remove{ float:right; display:block; width:18px; height:18px; text-indent:-9999px; background-position:center center; background-repeat:no-repeat; cursor:pointer; } div.comboselectbox ul.comboselect li.used a{ text-decoration:line-through; } div.comboselectbox ul.comboselect li.selected{ } div.comboselectbox div.comboselectbuttons{ max-width:9%; height:99%; width:30px; float:left; padding:0 3px; } div.comboselectbox div.comboselectbuttons a{ padding:3px; line-height:20px; font-size:20px; width:18px; height:18px; margin:0 2px; background-position:center center; background-repeat:no-repeat; display:inline-block; } div.comboselectbox div.comboselectbuttons a.add{ } div.comboselectbox div.comboselectbuttons a.remove{ } div.comboselectbox div.comboselectbuttons a.addall{ } div.comboselectbox div.comboselectbuttons a.removeall{ } @media screen and (max-width:700px){ div.comboselectbox div.combowrap{ max-width:98%; width:98%; height:40%; float:none; } div.comboselectbox.searchable div.combowrap:first-child ul.comboselect{ height:40%; } div.comboselectbox div.comboselectbuttons{ text-align:center; max-width:98%; width:98%; float:none; height:30px; } } /*----------------------------------------------------------------------*/ /* Widgets /*----------------------------------------------------------------------*/ .widget{ margin-bottom:15px; border:1px solid; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .widget > div{ margin:2px; padding:15px 6px 2px; border:1px solid; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .widget > div > img{ -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .widget > div.ui-widget{ width:99%; padding:0; } .widget .ui-widget-header{ overflow:hidden; } .widget h3{ margin:0; } .widget:hover{ border:1px solid; } .widget.ui-sortable-helper{ } .widget h3.handle{ position:relative; font-size:14px !important; border-top:1px solid; border-bottom:1px solid; padding:8px 10px; margin:0; line-height:18px; margin-bottom:1px; cursor:pointer; -webkit-border-top-left-radius:4px; -moz-border-radius-topleft:4px; border-top-left-radius:4px; -webkit-border-top-right-radius:4px; -moz-border-radius-topright:4px; border-top-right-radius:4px; } .widget.sortable h3.handle{ cursor:move; } .widget h3.handle:hover{ } .widget h3.handle.red{ } .widget h3.handle.green{ } .widget h3.handle.blue{ } .widget h3.handle.yellow{ } .widget h3.handle .collapse, .widget h3.handle .reload{ position:absolute; right:8px; top:5px; display:block; height:24px; width:24px; background-repeat:no-repeat; background-position:center center; display:none; } .widget h3.handle .reload{ right:30px; } .widget h3.handle a:first-child{ right:8px; } .widget:hover h3.handle .collapse, .widget.loading h3.handle .reload, .widget:hover h3.handle .reload{ display:block; } .widget h3.handle .collapse{ } .widget h3.handle .icon{ margin-top:-3px; margin-left:-4px; height:24px; width:24px; display:inline-block; float:left; background-position:center; } .widget.collapsed{ border-bottom:1px solid; } .widget.collapsed h3.handle{ border-bottom:0; -webkit-border-bottom-right-radius:4px; -moz-border-radius-bottomright:4px; border-bottom-right-radius:4px; } .widget.collapsed h3.handle .collapse{ } .widget.number-widget > div ul{ overflow:auto; } .widget.number-widget > div ul li{ display:block; margin:0; list-style:none; border-top:1px dotted; padding:14px 10px 4px; margin:0; } .widget.number-widget > div ul li:first-child{ border-top:0; } .widget.number-widget > div ul li a{ font-size:12px; display:block; } .widget.number-widget > div ul li a:hover{ text-decoration:none; } .widget.number-widget ul li a span{ text-align:right; display:inline-block; width:80px; font-size:32px; font-weight:700; letter-spacing:-0.05em; padding:2px 6px 2px 0; } .sortable_placeholder{ margin-bottom:15px; border:1px solid; z-index:1; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } /*----------------------------------------------------------------------*/ /* Footer /*----------------------------------------------------------------------*/ footer{ } /*----------------------------------------------------------------------*/ /* width /*----------------------------------------------------------------------*/ .w_5{ width:5% !important; } .w_10{ width:10% !important; } .w_15{ width:15% !important; } .w_20{ width:20% !important; } .w_25{ width:25% !important; } .w_30{ width:30% !important; } .w_33{ width:33% !important; } .w_35{ width:35% !important; } .w_40{ width:40% !important; } .w_45{ width:45% !important; } .w_50{ width:50% !important; } .w_55{ width:55% !important; } .w_60{ width:60% !important; } .w_65{ width:65% !important; } .w_66{ width:66% !important; } .w_70{ width:70% !important; } .w_75{ width:75% !important; } .w_80{ width:80% !important; } .w_85{ width:85% !important; } .w_90{ width:90% !important; } .w_95{ width:95% !important; } .w_5p{ width:5px !important; } .w_10p{ width:10px !important; } .w_15p{ width:15px !important; } .w_20p{ width:20px !important; } .w_25p{ width:25px !important; } .w_30p{ width:30px !important; } .w_35p{ width:35px !important; } .w_40p{ width:40px !important; } .w_45p{ width:45px !important; } .w_50p{ width:50px !important; } .w_55p{ width:55px !important; } .w_60p{ width:60px !important; } .w_65p{ width:65px !important; } .w_70p{ width:70px !important; } .w_75p{ width:75px !important; } .w_80p{ width:80px !important; } .w_85p{ width:85px !important; } .w_90p{ width:90px !important; } .w_95p{ width:95px !important; } .w_100p{ width:100px !important; } .w_105p{ width:105px !important; } .w_110p{ width:110px !important; } .w_115p{ width:115px !important; } .w_120p{ width:120px !important; } .w_125p{ width:125px !important; } .w_130p{ width:130px !important; } .w_135p{ width:135px !important; } .w_140p{ width:140px !important; } .w_145p{ width:145px !important; } .w_150p{ width:150px !important; } .w_155p{ width:155px !important; } .w_160p{ width:160px !important; } .w_165p{ width:165px !important; } .w_170p{ width:170px !important; } .w_175p{ width:175px !important; } .w_180p{ width:180px !important; } .w_185p{ width:185px !important; } .w_190p{ width:190px !important; } .w_195p{ width:195px !important; } .w_200p{ width:200px !important; } .fl{ float:left !important; } .fr{ float:right !important; } .l{ text-align:left; } .c{ text-align:center; } .j{ text-align:justify; } .r{ text-align:right; } /*----------------------------------------------------------------------*/ /* Clear Floats /*----------------------------------------------------------------------*/ /* http://sonspring.com/journal/clearing-floats */ .clear { clear:both; display:block; overflow:hidden; visibility:hidden; width:0; height:0; } /* http://perishablepress.com/press/2008/02/05/lessons-learned-concerning-the-clearfix-css-hack */ .clearfix:after { clear:both; content:' '; display:block; font-size:0; line-height:0; visibility:hidden; width:0; height:0; } .clearfix { display:inline-block; } * html .clearfix { height:1%; } .clearfix { display:block; } /*----------------------------------------------------------------------*/ /* Grid System (based on the 960 Grid System (http://960.gs) /*----------------------------------------------------------------------*/ .g1,.g2,.g3,.g4,.g5,.g6,.g7,.g8,.g9,.g10,.g11,.g12 { display:inline; float:left; margin-left:1%; margin-right:1%; padding:9px 0; min-height:10px; } .alpha{margin-left:0;} .omega{margin-right:0;} .g1{width:6.333%;} .g2{width:14.667%;} .g3{width:23.0%;} .g4{width:31.333%;} .g5{width:39.667%;} .g6{width:48.0%;} .g7{width:56.333%;} .g8{width:64.667%;} .g9{width:73.0%;} .g10{width:81.333%;} .g11{width:89.667%;} .g12{width:98.0%;} .p1{padding-left:8.333%;} .p2{padding-left:16.667%;} .p3{padding-left:25.0%;} .p4{padding-left:33.333%;} .p5{padding-left:41.667%;} .p6{padding-left:50.0%;} .p7{padding-left:58.333%;} .p8{padding-left:66.667%;} .p9{padding-left:75.0%;} .p10{padding-left:83.333%;} .p11{padding-left:91.667%;} .s1{padding-right:8.333%;} .s2{padding-right:16.667%;} .s3{padding-right:25.0%;} .s4{padding-right:33.333%;} .s5{padding-right:41.667%;} .s6{padding-right:50.0%;} .s7{padding-right:58.333%;} .s8{padding-right:66.667%;} .s9{padding-right:75.0%;} .s10{padding-right:83.333%;} .s11{padding-right:91.667%;} .ps1{left:8.333%;} .ps2{left:16.667%;} .ps3{left:25.0%;} .ps4{left:33.333%;} .ps5{left:41.667%;} .ps6{left:50.0%;} .ps7{left:58.333%;} .ps8{left:66.667%;} .ps9{left:75.0%;} .ps10{left:83.333%;} .ps11{left:91.667%;} .pl1{left:-8.333%;} .pl2{left:-16.667%;} .pl3{left:-25.0%;} .pl4{left:-33.333%;} .pl5{left:-41.667%;} .pl6{left:-50.0%;} .pl7{left:-58.333%;} .pl8{left:-66.667%;} .pl9{left:-75.0%;} .pl10{left:-83.333%;} .pl11{left:-91.667%;} /*----------------------------------------------------------------------*/ /* Layout /*----------------------------------------------------------------------*/ body{ margin:0 15px; } header{ height:60px; z-index:2; } nav{ position:absolute; width:216px; z-index:2; } #content{ overflow:hidden; left:0px; right:0px; top:0px; z-index:1; } footer{ padding:5px; text-align:right; } /*----------------------------------------------------------------------*/ /* Login /*----------------------------------------------------------------------*/ body#login{ position:static; left:auto; right:auto; width:350px; margin:120px auto; padding:2%; } body#login #content{ min-height:50px; padding:8px; } body#login form label{ padding:0; margin:0; width:100%; } body#login form section{ width:100%; } body#login form section div{ width:90%; float:none; padding:0 4% 6px 4%; border:0; } body#login form section > div{ width:90% !important; } body#login form section div input{ width:100% !important; } body#login form section div input#remember{ width:auto !important; } body#login form section div.checker{ width:auto !important; padding:0; margin:0; } body#login form section label{ padding:3% 2% 1%; width:90% !important; float:none; } body#login form section label.checkbox div{ width:10px; padding:0; margin:0; } body#login form section div label{ width:80% !important; } body#login form section a{ /*float:right;*/ } body#login header h2{border:0;height:24px;padding:18px 0 18px 15px;} /*----------------------------------------------------------------------*/ /* Wizard /*----------------------------------------------------------------------*/ body#wizard{ position:static; left:auto; right:auto; width:500px; margin:120px auto; padding:0; } body#wizard #content{ min-height:50px; padding:8px; } /*----------------------------------------------------------------------*/ /* Error Page /*----------------------------------------------------------------------*/ body#error{ position:static; left:auto; right:auto; width:400px; margin:120px auto; padding:0; } body#error #content{ min-height:50px; padding:8px; } body#error #content h1{ font-size:116px; font-weight:700; line-height:0.7em; letter-spacing:-9px; } body#error #content h2{ float:right; } /*----------------------------------------------------------------------*/ /* Media Queries /*----------------------------------------------------------------------*/ /* For very large screens increes the margins*/ @media screen and (min-width:1281px) { body{ margin-left:10%; margin-right:10%; } } /* Move the Headernav to a drop down menu to the right */ @media screen and (max-width:960px) { #header ul#headernav li ul, #header ul#headernav li ul.collapsed{ display:none; } #header ul#headernav li ul.shown{ display:block !important; } #header ul#headernav{ border-left:1px solid; position:relative; float:right; height:60px; width:60px; cursor:pointer; background-repeat:no-repeat; background-position:center center; } #header ul#headernav li ul{ position:absolute; right:0; width:170px; padding:0; margin:0; top:60px; } #header ul#headernav li ul li{ float:none; margin:0; border-bottom:0; border-top:0; } #header ul#headernav li ul li a{ padding:10px; } #header ul#headernav li ul li:last-child{ border-bottom:1px solid; } #header ul#headernav li ul span{ right:5px; top:10px; } #header ul#headernav li ul li ul{ position:relative; top:0; padding:0; display:none; padding-bottom:6%; z-index:20; width:99%; } #header ul#headernav li ul li ul.shown{ display:block; } #header ul#headernav li ul li ul li{ margin:0 6%; } #header ul#headernav li ul li ul li a{ font-size:12px; padding:5px; } .g1,.g2,.g3,.g4,.g5,.g6 { padding:0; width:48.0%; } .g7,.g8,.g9,.g10,.g11,.g12 { padding:0; width:98%; } #header ul li ul li,#header ul li ul li a, #header ul#headernav li ul li ul{ -webkit-border-radius:0; -moz-border-radius:0; border-radius:0; } #header ul li ul li:last-child,#header ul li ul li:last-child a{ -webkit-border-bottom-left-radius:4px; -moz-border-radius-bottomleft:4px; border-bottom-left-radius:4px; } } @media screen and (max-width:900px) and (min-width:701px) { form fieldset > section > div{ width:69%; } form fieldset > section label{ width:24%; } } /* For more smaller Screens (iPad) */ @media screen and (max-width:700px) { header #search,header #searchbox{ max-width:100px; } form label{ padding:10px 1%; } form fieldset > section{ padding-bottom:8px; } form fieldset > section > label{ left:0; right:0; width:98%; margin:0; float:none; padding:1%; padding-bottom:8px; } form fieldset > section > div{ float:none; width:98%; padding:4px; border:0; } .g1,.g2,.g3,.g4,.g5,.g6,.g7,.g8,.g9,.g10,.g11,.g12 { width:98%; } } @media screen and (max-width:800px) and (min-width:481px) { nav{ width:150px; } nav ul li a span{ font-size:12px; } nav ul li ul{ margin-left:10px; margin-right:10px; } nav ul li ul li a span{ padding-right:4px; } #content{ padding:15px 0 15px 160px; } } /* iPhone and real small devicces */ @media screen and (max-width:480px) { body#login{ position:static; left:auto; right:auto; width:96%; margin:10px auto; padding:0; } body#login #content{ padding:0; padding-top:20px; width:99%; } body#login form{ border:0; } body#login form section label{ border:0; } body#login fieldset{ margin:0px; } body#login form > section a{ margin:10px 4%; float:left; } #pageoptions > div{ left:2px; right:2px; padding:15px; } header #searchbox{ display:none; max-width:40px; } header #searchbox input{ max-width:40px; } header ul#searchboxresult{ display:none !important; } body{ width:96%; margin:1%; } body, header, nav, #content{ -webkit-box-shadow:none; -moz-box-shadow:none; box-shadow:none; } #header{ } #logo{ width:100%; } #logo, header, #content{ width:100%; } nav, nav ul, nav ul li, nav ul li a, nav ul li a span, nav ul li a:active span, nav ul li a.active span{ margin:0; padding:0; } nav ul li a:active span, nav ul li a.active span{ border-top:1px solid; background-position:center center; } nav{ border-top:1px solid; position:static; width:98%; margin:0 1%; } nav ul li{ width:44px; display:inline-block; margin-left:-2px; margin-right:-2px; } nav ul li a span{ border-left:1px solid; border-bottom:0; height:40px; text-indent:-9999px; background-position:center center; } nav ul li:first-child a span{ border-left:0; } nav ul li ul{ position:absolute; left:0; margin:0; z-index:15; background:none; width:98%; margin:0 1%; } nav ul li ul li{ display:block; width:100%; } nav ul li ul li a span{ height:20px; text-indent:0; } #content{ padding:0; } form{ padding:0; margin:0; } form input, form textarea{ font-size:14px; max-width:96%; } #wl_msg{ right:5px; left:5px; width:auto; } .g1,.g2,.g3,.g4,.g5,.g6,.g7,.g8,.g9,.g10,.g11,.g12 { width:100%; margin:0; min-height:0; } } /*----------------------------------------------------------------------*/ /* jQuery UI mods /*----------------------------------------------------------------------*/ .ui-tabs .ui-tabs-nav li{ margin:0 2px 0 0 !important; } .ui-tabs .ui-tabs-nav, .ui-tabs{ padding:0 !important; } .ui-widget{ padding:0 !important; } .ui-widget-header{ border:0 !important; border-top:1px solid !important; border-bottom:1px solid !important; background-repeat:repeat !important; margin:0 !important; } .ui-widget-header a, .ui-accordion-header a, .ui-datepicker-title .ui-datepicker-month, .ui-datepicker-title .ui-datepicker-year{ font-size:14px !important; } .ui-state-default a{ border-top:1px solid !important; -webkit-border-radius:4px !important; -moz-border-radius:4px !important; border-radius:4px !important; } .ui-tabs .ui-tabs-panel { padding:0 !important; } .ui-tabs .ui-tabs-panel p { margin:1em 1.3em !important; } .ui-tabs .ui-tabs-selected{ border-bottom:0; } .ui-accordion-content p{ margin:0 !important; } .ui-accordion .ui-accordion-header{ margin-top:0 !important; } .ui-datepicker .ui-widget-header{ padding:4px !important; } .ui-widget-overlay{ background-repeat:repeat !important; } .ui-slider-range.ui-widget-header{ background-position:center !important; border:0 !important; } .ui-slider-horizontal .ui-slider-handle{ top:-5px !important; min-height:22px; min-width:18px; margin-left:-10px !important; cursor:pointer !important; } .ui-slider-vertical{ float:left; } .ui-slider-vertical .ui-slider-handle{ left:-5px !important; min-height:18px; min-width:22px; margin-bottom:-10px !important; cursor:pointer !important; } .ui-slider{ min-height:14px; min-width:14px; border:1px solid; background-repeat:repeat !important; margin:10px; } .ui-slider .ui-slider-handle{ background-repeat:no-repeat !important; z-index:1 !important; position:relative; } .ui-slider-horizontal .ui-slider-handle{ background-position:right center !important; } .ui-slider-vertical .ui-slider-handle{ background-position:left center !important; } .ui-slider-range{ -webkit-border-radius:4px !important; -moz-border-radius:4px !important; border-radius:4px !important; }
08102013project
trunk/CMS/Content/themes/base/style.css
CSS
oos
52,755
/*----------------------------------------------------------------------*/ /* This stylesheet is for IE 7 and IE8 /* Selectors with *:first-child+html is for IE 7 only /*----------------------------------------------------------------------*/ body{ } nav{ border-right:1px solid; } header{ filter:none !important; background-image:url(images/header_bg.png) !important; background-repeat:repeat-x; } #header ul li ul li ul li{ width:160px; margin:0; padding:0; } #header ul li ul li ul li a{ width:120px; margin:0; } form#searchform{ padding:0; margin:0; border:0; } form#searchform input#search{ border-left:0; border-right:0; border-bottom:0; margin:0 !important; } /*----------------------------------------------------------------------*/ /* Buttons /*----------------------------------------------------------------------*/ a.btn{ padding:0 12px; line-height:30px; min-height:32px; min-width:8px; background-position:4px 4px; } button{ min-width:auto; min-height:auto; } *:first-child+html button{ line-height:30px; padding:0; } button.big{ } a.btn.big{ height:10px; padding:3px 16px; padding-left:23px; } *:first-child+html button.icon{ padding-left:13px; } button.icon, a.btn.icon{ background-position:3px 2px; padding-left:27px; } *:first-child+html a.btn.big{ height:10px; padding:3px 23px; } *:first-child+html button.small{ height:20px; line-height:30px; padding:3px; padding-top:0; line-height:15px; padding:0; } *:first-child+html button.small.icon{ height:22px; line-height:10px; padding:3px; padding-left:7px; background-position:0 -4px; } a.btn.big.icon{ height:10px; padding:3px 20px; padding-left:23px; } *:first-child+html button.big.icon{ height:40px; background-position:6px 4px; padding-left:14px; } *:first-child+html a.btn.big.icon{ background-position:6px 4px; padding-left:32px; } div.checker, div.radio{ clear:none; } form fieldset > section > div > div.checker, form fieldset > section > div > div.radio{ padding:0; overflow:hidden; left:4px; margin-right:4px; zoom:1; *display:inline; } *:first-child+html form fieldset > section > div > div.checker, *:first-child+html form fieldset > section > div > div.radio{ top:4px; zoom:1; *display:inline; } *:first-child+html form fieldset > section > div > div.checker span, *:first-child+html form fieldset > section > div > div.radio span{ padding:0; zoom:1; *display:inline; } *:first-child+html form fieldset > section > div label{ position:static; } *:first-child+html ul.fileuploadpool li a{ margin-top:-14px; } *:first-child+html form{ padding:8px; } *:first-child+html form .wl_formstatus, *:first-child+html form .timeformat, *:first-child+html form .miniColors-trigger{ position:relative; top:-8px; } *:first-child+html div.comboselectbox ul.comboselect li{ width:86%; margin-right:0; } *:first-child+html div.comboselectbox div.comboselectbuttons a{ display:block; } /*----------------------------------------------------------------------*/ /* jQuery Checkbox /*----------------------------------------------------------------------*/ *:first-child+html .jquery-checkbox span.checkboxplaceholder{ display:inline-block; vertical-align:bottom; } /*----------------------------------------------------------------------*/ /* Widgets /*----------------------------------------------------------------------*/ *:first-child+html .widget h3.handle.icon{ padding-left:30px; } *:first-child+html .widget h3.handle .icon{ margin-top:-30px; margin-left:4px; } /*----------------------------------------------------------------------*/ /* Breadcrumb /*----------------------------------------------------------------------*/ .breadcrumb li a{ padding:10px 30px 5px 25px; } .breadcrumb li.last a{ padding-right:13px; }
08102013project
trunk/CMS/Content/themes/base/ie.css
CSS
oos
3,963
/* * FullCalendar v1.5.1 Stylesheet * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Sat Apr 9 14:09:51 2011 -0700 * */ .fc { direction: ltr; text-align: left; } .fc table { border-collapse: collapse; border-spacing: 0; } html .fc, .fc table { font-size: 1em; } .fc td, .fc th { padding: 0; vertical-align: top; } /* Header ------------------------------------------------------------------------*/ .fc-header { background:none; margin:0; } .fc-header td { white-space: nowrap; border:0; } .fc-header-left { width: 25%; text-align: left; } .fc-header-center { text-align: center; } .fc-header-right { width: 25%; text-align: right; } .fc-header-title { display: inline-block; vertical-align: top; } .fc-header-title h2 { margin-top: 0; white-space: nowrap; } .fc .fc-header-space { padding-left: 10px; } .fc-header .fc-button { margin-bottom: 1em; vertical-align: top; } /* buttons edges butting together */ .fc-header .fc-button { margin-right: -1px; } .fc-header .fc-corner-right { margin-right: 1px; /* back to normal */ } .fc-header .ui-corner-right { margin-right: 0; /* back to normal */ } /* button layering (for border precedence) */ .fc-header .fc-state-hover, .fc-header .ui-state-hover { z-index: 2; } .fc-header .fc-state-down { z-index: 3; } .fc-header .fc-state-active, .fc-header .ui-state-active { z-index: 4; } /* Content ------------------------------------------------------------------------*/ .fc-content { clear: both; } .fc-view { width: 100%; /* needed for view switching (when view is absolute) */ overflow: hidden; } /* Cell Styles ------------------------------------------------------------------------*/ .fc-widget-header, /* <th>, usually */ .fc-widget-content { /* <td>, usually */ border: 1px solid #ccc; } .fc-state-highlight { /* <td> today cell */ /* TODO: add .fc-today to <th> */ background: #ffc; } .fc-cell-overlay { /* semi-transparent rectangle while dragging */ background: #9cf; opacity: .2; filter: alpha(opacity=20); /* for IE */ } /* Buttons ------------------------------------------------------------------------*/ .fc-button { position: relative; display: inline-block; cursor: pointer; } .fc-state-default { /* non-theme */ border-style: solid; border-width: 1px 0; } .fc-button-inner { position: relative; float: left; overflow: hidden; } .fc-state-default .fc-button-inner { /* non-theme */ border-style: solid; border-width: 0 1px; } .fc-button-content { position: relative; float: left; height: 1.9em; line-height: 1.9em; padding: 0 .6em; white-space: nowrap; } /* icon (for jquery ui) */ .fc-button-content .fc-icon-wrap { position: relative; float: left; top: 50%; } .fc-button-content .ui-icon { position: relative; float: left; margin-top: -50%; *margin-top: 0; *top: -50%; } /* gloss effect */ .fc-state-default .fc-button-effect { position: absolute; top: 50%; left: 0; } .fc-state-default .fc-button-effect span { position: absolute; top: -100px; left: 0; width: 500px; height: 100px; border-width: 100px 0 0 1px; border-style: solid; border-color: #fff; background: #444; opacity: .09; filter: alpha(opacity=9); } /* button states (determines colors) */ .fc-state-default, .fc-state-default .fc-button-inner { border-style: solid; border-color: #ccc #bbb #aaa; background: #F3F3F3; color: #000; } .fc-state-hover, .fc-state-hover .fc-button-inner { border-color: #999; } .fc-state-down, .fc-state-down .fc-button-inner { border-color: #555; background: #777; } .fc-state-active, .fc-state-active .fc-button-inner { border-color: #555; background: #777; color: #fff; } .fc-state-disabled, .fc-state-disabled .fc-button-inner { color: #999; border-color: #ddd; } .fc-state-disabled { cursor: default; } .fc-state-disabled .fc-button-effect { display: none; } /* Global Event Styles ------------------------------------------------------------------------*/ .fc-event { border-style: solid; border-width: 0; font-size: 0.9em; cursor: default; padding:0; } a.fc-event, .fc-event-draggable { cursor: pointer; } a.fc-event { text-decoration: none; } .fc-rtl .fc-event { text-align: right; } .fc-event-skin { background-image:url(../images/bg/08.png); border-color: #ddd; /* default BORDER color */ background-color: #ddd; /* default BACKGROUND color */ color: #444; /* default TEXT color */ text-decoration:none; border-top-color:#fff; } .red .fc-event-skin{ border-color:#F0B7B7; background-color:#F0B7B7; } .green .fc-event-skin{ border-color:#B2E7B2; background-color:#B2E7B2; } .yellow .fc-event-skin{ border-color:#E8E8B3; background-color:#E8E8B3; } .blue .fc-event-skin{ border-color:#B5F0F0; background-color:#B5F0F0; } .fc-event-inner { position: relative; width: 100%; height: 100%; border-style: solid; border-width: 0; overflow: hidden; } .fc-event-time, .fc-event-title { padding: 0 1px; } .fc .ui-resizable-handle { /*** TODO: don't use ui-resizable anymore, change class ***/ display: block; position: absolute; z-index: 99999; overflow: hidden; /* hacky spaces (IE6/7) */ font-size: 300%; /* */ line-height: 50%; /* */ } /* Horizontal Events ------------------------------------------------------------------------*/ .fc-event-hori { border-width: 1px 0; margin-bottom: 1px; } /* resizable */ .fc-event-hori .ui-resizable-e { top: 0 !important; /* importants override pre jquery ui 1.7 styles */ right: -3px !important; width: 7px !important; height: 100% !important; cursor: e-resize; } .fc-event-hori .ui-resizable-w { top: 0 !important; left: -3px !important; width: 7px !important; height: 100% !important; cursor: w-resize; } .fc-event-hori .ui-resizable-handle { _padding-bottom: 14px; /* IE6 had 0 height */ } /* Fake Rounded Corners (for buttons and events) ------------------------------------------------------------*/ .fc-corner-left { margin-left: 1px; } .fc-corner-left .fc-button-inner, .fc-corner-left .fc-event-inner { margin-left: -1px; } .fc-corner-right { margin-right: 1px; } .fc-corner-right .fc-button-inner, .fc-corner-right .fc-event-inner { margin-right: -1px; } .fc-corner-top { margin-top: 1px; } .fc-corner-top .fc-event-inner { margin-top: -1px; } .fc-corner-bottom { margin-bottom: 1px; } .fc-corner-bottom .fc-event-inner { margin-bottom: -1px; } /* Fake Rounded Corners SPECIFICALLY FOR EVENTS -----------------------------------------------------------------*/ .fc-corner-left .fc-event-inner { border-left-width: 1px; } .fc-corner-right .fc-event-inner { border-right-width: 1px; } .fc-corner-top .fc-event-inner { border-top-width: 1px; } .fc-corner-bottom .fc-event-inner { border-bottom-width: 1px; } /* Reusable Separate-border Table ------------------------------------------------------------*/ table.fc-border-separate { border-collapse: separate; } .fc-border-separate th, .fc-border-separate td { border-width: 1px 0 0 1px; } .fc-border-separate th.fc-last, .fc-border-separate td.fc-last { border-right-width: 1px; } .fc-border-separate tr.fc-last th, .fc-border-separate tr.fc-last td { border-bottom-width: 1px; } .fc-border-separate tbody tr.fc-first td, .fc-border-separate tbody tr.fc-first th { border-top-width: 0; } /* Month View, Basic Week View, Basic Day View ------------------------------------------------------------------------*/ .fc-grid th { text-align: center; } .fc-grid .fc-day-number { float: right; padding: 0 2px; } .fc-grid .fc-other-month .fc-day-number { opacity: 0.3; filter: alpha(opacity=30); /* for IE */ /* opacity with small font can sometimes look too faded might want to set the 'color' property instead making day-numbers bold also fixes the problem */ } .fc-grid .fc-day-content { clear: both; padding: 2px 2px 1px; /* distance between events and day edges */ } /* event styles */ .fc-grid .fc-event-time { font-weight: bold; } /* right-to-left */ .fc-rtl .fc-grid .fc-day-number { float: left; } .fc-rtl .fc-grid .fc-event-time { float: right; } /* Agenda Week View, Agenda Day View ------------------------------------------------------------------------*/ .fc-agenda table { border-collapse: separate; } .fc-agenda-days th { text-align: center; } .fc-agenda .fc-agenda-axis { width: 50px; padding: 0 4px; vertical-align: middle; text-align: right; white-space: nowrap; font-weight: normal; } .fc-agenda .fc-day-content { padding: 2px 2px 1px; } /* make axis border take precedence */ .fc-agenda-days .fc-agenda-axis { border-right-width: 1px; } .fc-agenda-days .fc-col0 { border-left-width: 0; } /* all-day area */ .fc-agenda-allday th { border-width: 0 1px; } .fc-agenda-allday .fc-day-content { min-height: 34px; /* TODO: doesnt work well in quirksmode */ _height: 34px; } /* divider (between all-day and slots) */ .fc-agenda-divider-inner { height: 2px; overflow: hidden; } .fc-widget-header .fc-agenda-divider-inner { background: #eee; } /* slot rows */ .fc-agenda-slots th { border-width: 1px 1px 0; } .fc-agenda-slots td { border-width: 1px 0 0; background: none; } .fc-agenda-slots td div { height: 20px; } .fc-agenda-slots tr.fc-slot0 th, .fc-agenda-slots tr.fc-slot0 td { border-top-width: 0; } .fc-agenda-slots tr.fc-minor th, .fc-agenda-slots tr.fc-minor td { border-top-style: dotted; } .fc-agenda-slots tr.fc-minor th.ui-widget-header { *border-top-style: solid; /* doesn't work with background in IE6/7 */ } /* Vertical Events ------------------------------------------------------------------------*/ .fc-event-vert { border-width: 0 1px; } .fc-event-vert .fc-event-head, .fc-event-vert .fc-event-content { position: relative; z-index: 2; width: 100%; overflow: hidden; } .fc-event-vert .fc-event-time { white-space: nowrap; font-size: 10px; } .fc-event-vert .fc-event-bg { /* makes the event lighter w/ a semi-transparent overlay */ position: absolute; z-index: 1; top: 0; left: 0; width: 100%; height: 100%; background: #fff; opacity: .3; filter: alpha(opacity=30); } .fc .ui-draggable-dragging .fc-event-bg, /* TODO: something nicer like .fc-opacity */ .fc-select-helper .fc-event-bg { display: none\9; /* for IE6/7/8. nested opacity filters while dragging don't work */ } /* resizable */ .fc-event-vert .ui-resizable-s { bottom: 0 !important; /* importants override pre jquery ui 1.7 styles */ width: 100% !important; height: 8px !important; overflow: hidden !important; line-height: 8px !important; font-size: 11px !important; font-family: monospace; text-align: center; cursor: s-resize; } .fc-agenda .ui-resizable-resizing { /* TODO: better selector */ _overflow: hidden; }
08102013project
trunk/CMS/Content/themes/base/light/jquery.fullcalendar.css
CSS
oos
11,800
/*----------------------------------------------------------------------*/ /* This is the styling of the html container /*----------------------------------------------------------------------*/ @import 'http://fonts.googleapis.com/css?family=PT+Sans:regular,bold'; /*----------------------------------------------------------------------*/ /* Reset /*----------------------------------------------------------------------*/ html,body,div,span,applet,object,iframe,input,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{ margin:0; padding:0; border:0; outline:0; font-weight:100; font-style:inherit; font-size:100%; font-family:inherit; vertical-align:baseline; } *{ -webkit-text-size-adjust:none; -webkit-tap-highlight-color:rgba(0,0,0,0); } /*----------------------------------------------------------------------*/ /* Font Declaration /*----------------------------------------------------------------------*/ html{ font-family:'PT Sans', sans-serif; } code, pre{ font-family:"Courier New", Courier, monospace; } html, body { margin:0; cursor:text; margin:6px 2px; line-height:18px; font-size:13px; color:#6F6F6F; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } html{ margin:0; background-color:#FFFFFF; height:100%; min-height:100%; -webkit-box-shadow:inset 0px 1px 3px rgba(0, 0, 0, 0.2); -moz-box-shadow:inset 0px 1px 3px rgba(0, 0, 0, 0.2); box-shadow:inset 0px 1px 3px rgba(0, 0, 0, 0.2); } em{ font-style:italic; } strong, b{ font-weight:700; } big{ font-size:larger; } small{ font-size:smaller; } ::-moz-selection{ background:#bada55; color:#FFFFFF; text-shadow:none; } ::selection { background:#bada55; color:#FFFFFF; text-shadow:none; } a { color:#bada55; } h1, h2, h3, h4, h5, h6{ font-weight:700; color:#777; } h1{ font-size:30px; margin:9px 0; line-height:36px; } h2{ font-size:20px; margin:9px 0 7px; line-height:18px; } h3{ font-size:18px; margin:12px 0 6px; line-height:18px; } h4{ font-size:16px; font-weight:100; margin:15px 0 3px; } h5{ font-size:14px; margin:18px 0 2px; } h6{ font-size:14px; font-weight:100; margin:18px 0 2px; } p, ul, ol{ margin-top:9px; margin-bottom:9px; line-height:18px; font-size:12px; } ul, ol{ margin-left:18px; list-style-type:square; } table{ width:100%; border-collapse:collapse; margin-bottom:18px; background-image:url(images/paper_02.png); } table td{ border:1px solid; border-color:#DDDDDD #E7E7E7 #DDDDDD #E7E7E7; padding:6px 3px; text-align:center; }
08102013project
trunk/CMS/Content/themes/base/light/editor.css
CSS
oos
2,822
/* * File: demo_table.css * CVS: $Id$ * Description: CSS descriptions for DataTables demo pages * Author: Allan Jardine * Created: Tue May 12 06:47:22 BST 2009 * Modified: $Date$ by $Author$ * Language: CSS * Project: DataTables * * Copyright 2009 Allan Jardine. All Rights Reserved. * * *************************************************************************** * DESCRIPTION * * The styles given here are suitable for the demos that are used with the standard DataTables * distribution (see www.datatables.net). You will most likely wish to modify these styles to * meet the layout requirements of your site. * * Common issues: * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * no conflict between the two pagination types. If you want to use full_numbers pagination * ensure that you either have "example_alt_pagination" as a body class name, or better yet, * modify that selector. * Note that the path used for Images is relative. All images are by default located in * ../images/ - relative to this CSS file. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables features */ .dataTables_wrapper { position: relative; min-height: 302px; clear: both; _height: 302px; zoom: 1; /* Feeling sorry for IE */ } .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } .dataTables_length { float:left; width: 40%; vertical-align:top; } .dataTables_length label { height:40px; line-height:10px; vertical-align:top; display:inline-block; } .dataTable_length .selector{ margin-top:20px; } .dataTables_filter { width: 50%; float: right; text-align: right; } .datatable{ clear:both; } .dataTables_filter input{ width:auto; margin-bottom:4px; } .dataTables_info { width: 60%; float: left; } .dataTables_paginate { width: 44px; * width: 50px; float: right; text-align: right; } /* Pagination nested */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; width: 19px; margin-left: 3px; float: left; } .paginate_disabled_previous { background-image: url(../images/icons/dark/triangle_left.png); } .paginate_enabled_previous { background-image: url(../images/icons/dark/triangle_left.png); } .paginate_disabled_next { background-image: url(../images/icons/dark/triangle_right.png); } .paginate_enabled_next { background-image: url(../images/icons/dark/triangle_right.png); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables display */ table.display { margin: 0 auto; clear: both; width: 100%; /* Note Firefox 3.5 and before have a bug with border-collapse * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) * border-spacing: 0; is one possible option. Conditional-css.com is * useful for this kind of thing * * Further note IE 6/7 has problems when calculating widths with border width. * It subtracts one px relative to the other browsers from the first column, and * adds one to the end... * * If you want that effect I'd suggest setting a border-top/left on th/td's and * then filling in the gaps with other borders. */ } table.display thead th { padding: 3px 18px 3px 10px; border-bottom: 1px solid black; font-weight: bold; cursor: pointer; * cursor: hand; } table.display tfoot th { padding: 3px 18px 3px 10px; border-top: 1px solid black; font-weight: bold; } table.display tr.heading2 td { border-bottom: 1px solid #aaa; } table.display td { padding: 3px 10px; } table.display td.center { text-align: center; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables sorting */ .sorting_asc { background: url(../images/icons/dark/triangle_up.png) no-repeat center right; } .sorting_desc { background: url(../images/icons/dark/triangle_down.png) no-repeat center right; } .sorting { background: url(../images/icons/dark/triangle_up_down.png) no-repeat center right; } .sorting_asc_disabled { background: url(../images/icons/dark/triangle_up.png) no-repeat center right; } .sorting_desc_disabled { background: url(../images/icons/dark/triangle_down.png) no-repeat center right; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables row classes */ /* #f0a8a8 #f0cccc red /* #a2e8a2 #c5e8c5 green /* #e8e8a2 #e8e8c5 yellow /* #a8f0f0 #ccf0f0 blue /* #f0a8f0 #f0ccf0 pink /* #aea8f0 #cfccf0 purple */ table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeC { background-color: #ddddff; } table.display tr.even.gradeC { background-color: #eeeeff; } table.display tr.odd.gradeX { background-color: #ffdddd; } table.display tr.even.gradeX { background-color: #ffeeee; } table.display tr.odd.gradeU { background-color: #ddd; } table.display tr.even.gradeU { background-color: #eee; } tr.odd { background-color: #f6f6f6; } tr.even { background-color: #ffffff; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Misc */ .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; } .top, .bottom { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } .top .dataTables_info { float: none; } .clear { clear: both; } .dataTables_empty { text-align: center; } tfoot input { margin: 0.5em 0; width: 100%; color: #444; } tfoot input.search_init { color: #999; } td.group { background-color: #d1cfd0; border-bottom: 2px solid #A19B9E; border-top: 2px solid #A19B9E; } td.details { background-color: #d1cfd0; border: 2px solid #A19B9E; } .example_alt_pagination div.dataTables_info { width: 40%; } .paging_full_numbers { width: 400px; height: 22px; line-height: 22px; } .paging_full_numbers span.paginate_button, .paging_full_numbers span.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; } .paging_full_numbers span.paginate_button { background-color: #ddd; } .paging_full_numbers span.paginate_button:hover { background-color: #ccc; } .paging_full_numbers span.paginate_active { background-color: #99B3FF; } table.display tr.even.row_selected td { background-color: #B0BED9; } table.display tr.odd.row_selected td { background-color: #9FAFD1; } /* * Sorting classes for columns */ /* For the standard odd/even */ tr.odd td.sorting_1 { background-color: #D3D6FF; } tr.odd td.sorting_2 { background-color: #DADCFF; } tr.odd td.sorting_3 { background-color: #E0E2FF; } tr.even td.sorting_1 { background-color: #EAEBFF; } tr.even td.sorting_2 { background-color: #F2F3FF; } tr.even td.sorting_3 { background-color: #F9F9FF; } /* For the Conditional-CSS grading rows */ /* Colour calculations (based off the main row colours) Level 1: dd > c4 ee > d5 Level 2: dd > d1 ee > e2 */ tr.odd.gradeA td.sorting_1 { background-color: #a2e8a2; } tr.odd.gradeA td.sorting_2 { background-color: #d1ffd1; } tr.odd.gradeA td.sorting_3 { background-color: #d1ffd1; } tr.even.gradeA td.sorting_1 { background-color: #c5e8c5; } tr.even.gradeA td.sorting_2 { background-color: #e2ffe2; } tr.even.gradeA td.sorting_3 { background-color: #e2ffe2; } tr.odd.gradeC td.sorting_1 { background-color: #c4c4ff; } tr.odd.gradeC td.sorting_2 { background-color: #d1d1ff; } tr.odd.gradeC td.sorting_3 { background-color: #d1d1ff; } tr.even.gradeC td.sorting_1 { background-color: #d5d5ff; } tr.even.gradeC td.sorting_2 { background-color: #e2e2ff; } tr.even.gradeC td.sorting_3 { background-color: #e2e2ff; } tr.odd.gradeX td.sorting_1 { background-color: #ffc4c4; } tr.odd.gradeX td.sorting_2 { background-color: #ffd1d1; } tr.odd.gradeX td.sorting_3 { background-color: #ffd1d1; } tr.even.gradeX td.sorting_1 { background-color: #f0a8a8; } tr.even.gradeX td.sorting_2 { background-color: #f0cccc; } tr.even.gradeX td.sorting_3 { background-color: #ffe2e2; } tr.odd.gradeU td.sorting_1 { background-color: #c4c4c4; } tr.odd.gradeU td.sorting_2 { background-color: #d1d1d1; } tr.odd.gradeU td.sorting_3 { background-color: #d1d1d1; } tr.even.gradeU td.sorting_1 { background-color: #d5d5d5; } tr.even.gradeU td.sorting_2 { background-color: #e2e2e2; } tr.even.gradeU td.sorting_3 { background-color: #e2e2e2; } /* * Row highlighting example */ .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { background-color: #ECFFB3; } .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { background-color: #E6FF99; } .ex_highlight_row #example tr.even:hover { background-color: #ECFFB3; } .ex_highlight_row #example tr.even:hover td.sorting_1 { background-color: #DDFF75; } .ex_highlight_row #example tr.even:hover td.sorting_2 { background-color: #E7FF9E; } .ex_highlight_row #example tr.even:hover td.sorting_3 { background-color: #E2FF89; } .ex_highlight_row #example tr.odd:hover { background-color: #E6FF99; } .ex_highlight_row #example tr.odd:hover td.sorting_1 { background-color: #D6FF5C; } .ex_highlight_row #example tr.odd:hover td.sorting_2 { background-color: #E0FF84; } .ex_highlight_row #example tr.odd:hover td.sorting_3 { background-color: #DBFF70; } /* * KeyTable */ table.KeyTable td { border: 3px solid transparent; } table.KeyTable td.focus { border: 3px solid #3366FF; } table.display tr.gradeA { background-color: #eeffee; } table.display tr.gradeC { background-color: #ddddff; } table.display tr.gradeX { background-color: #ffdddd; } table.display tr.gradeU { background-color: #ddd; } div.box { height: 100px; padding: 10px; overflow: auto; border: 1px solid #8080FF; background-color: #E5E5FF; }
08102013project
trunk/CMS/Content/themes/base/light/jquery.datatables.css
CSS
oos
10,755
/*----------------------------------------------------------------------*/ /* Tipsy Tooltips /*----------------------------------------------------------------------*/ .tipsy-north {background-position:top center;} .tipsy-south {background-position:bottom center;} .tipsy-east {background-position:right center;} .tipsy-west {background-position:left center;} .tipsy { padding:5px; font-size:11px; position:absolute; z-index:100000; } .tipsy-inner { padding:4px 8px; border-top:1px solid #aaa; text-shadow:0px -1px 0px #000; color:#fff; max-width:220px; text-align:left; background-image:url(../images/bg/08.png); background-color:#333; background-color:rgba(24,24,24,0.9); -webkit-box-shadow:inset 0px 7px 5px rgba(255, 255, 255, 0.1); -moz-box-shadow:inset 0px 7px 5px rgba(255, 255, 255, 0.1); box-shadow:inset 0px 7px 5px rgba(255, 255, 255, 0.3); text-align:center; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .tipsy-outer { border:1px solid #333; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .tipsy-arrow { position:absolute; background-repeat:no-repeat; background-image:url(images/tipsy.gif); width:9px; height:5px; } .tipsy-n .tipsy-arrow { top:0; left:50%; margin-left:-4px; } .tipsy-nw .tipsy-arrow { top:0; left:10px; } .tipsy-ne .tipsy-arrow { top:0; right:10px; } .tipsy-s .tipsy-arrow { bottom:0; left:50%; margin-left:-4px; background-position:bottom left; } .tipsy-sw .tipsy-arrow { bottom:0; left:10px; background-position:bottom left; } .tipsy-se .tipsy-arrow { bottom:0; right:10px; background-position:bottom left; } .tipsy-e .tipsy-arrow { top:50%; margin-top:-4px; right:0; width:5px; height:9px; background-position:top right; } .tipsy-w .tipsy-arrow { top:50%; margin-top:-4px; left:0; width:5px; height:9px; }
08102013project
trunk/CMS/Content/themes/base/light/jquery.tipsy.css
CSS
oos
1,881
.miniColors-trigger { height: 22px; width: 22px; background: url(images/minicolor/trigger.png) center no-repeat; vertical-align: middle; margin: 0 .25em; display: inline-block; outline: none; } .miniColors-selector { position: absolute; width: 175px; height: 150px; background: #FFF; border: solid 1px #BBB; -moz-box-shadow: 0 0 6px rgba(0, 0, 0, .25); -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, .25); box-shadow: 0 0 6px rgba(0, 0, 0, .25); -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; padding: 5px; z-index: 999999; } .miniColors-selector.black { background: #000; border-color: #000; } .miniColors-colors { position: absolute; top: 5px; left: 5px; width: 150px; height: 150px; background: url(images/minicolor/gradient.png) center no-repeat; cursor: crosshair; } .miniColors-hues { position: absolute; top: 5px; left: 160px; width: 20px; height: 150px; background: url(images/minicolor/rainbow.png) center no-repeat; cursor: crosshair; cursor:pointer; } .miniColors-colorPicker { position: absolute; width: 11px; height: 11px; background: url(images/minicolor/circle.gif) center no-repeat; } .miniColors-huePicker { position: absolute; left: -3px; width: 26px; height: 3px; background: url(images/minicolor/line.gif) center no-repeat; }
08102013project
trunk/CMS/Content/themes/base/light/jquery.miniColors.css
CSS
oos
1,383
textarea.html{ max-width:100%; } div.wysiwyg{ border:1px solid; border-color:#CCC #E7E7E7 #FFF; border-radius:4px; max-width:100%; moz-border-radius:4px; padding:1%; webkit-border-radius:4px; } #content form div.wysiwyg{ border:0; padding:0; } div.wysiwyg *{ margin:0; padding:0; } div.wysiwyg ul.toolbar li.jwysiwyg-custom-command{ overflow:hidden; } div.wysiwyg ul.toolbar{ background-image:url(images/paper_01.png); background-repeat:repeat; border-bottom:1px solid #FFF; border-radius:4px; border-top:1px solid #AAA; float:left; margin-bottom:4px; moz-border-radius:4px; padding:0; webkit-border-radius:4px; width:99%; } div.wysiwyg ul.toolbar li{ background-color:#f0f0f0; background-position:-96px -120px; border-radius:4px; clear:none; float:left; list-style:none; margin:1px 2px 4px 0; moz-border-radius:4px; moz-user-select:none; padding:0; user-select:none; webkit-border-radius:4px; webkit-user-select:none; } div.wysiwyg ul.toolbar li.separator{ border-left:1px solid #ccc; border-right:1px solid #fff; height:22px; margin:1px 4px; width:0; } div.wysiwyg ul.toolbar li{ background:url(images/editor/buttons.png) no-repeat -96px -80px; border:0; cursor:pointer; display:block; filter:alpha(opacity=75); height:24px; margin:0; padding:1px; opacity:0.75; text-indent:-5000px; width:24px; } div.wysiwyg ul.toolbar li.wysiwyg-button-hover,div.wysiwyg ul.toolbar li.active{ background-color:#fff; border:1px solid; padding:0; border-color:#CCC; filter:alpha(opacity=100); opacity:1; } div.wysiwyg ul.toolbar li.active{ background-color:#ddd; margin:0; } div.wysiwyg ul.toolbar li.disabled,div.wysiwyg ul.toolbar li.wysiwyg-button-hover.disabled,div.wysiwyg ul.toolbar li.active.disabled{ border:0 none transparent; cursor:auto; filter:alpha(opacity=50); opacity:0.5; padding:1px; } div.wysiwyg ul.toolbar li.bold{ background-position:0 -24px; } div.wysiwyg ul.toolbar li.italic{ background-position:-24px -24px; } div.wysiwyg ul.toolbar li.strikeThrough{ background-position:-48px -24px; } div.wysiwyg ul.toolbar li.underline{ background-position:-72px -24px; } div.wysiwyg ul.toolbar li.highlight{ background-position:-72px -144px; } div.wysiwyg ul.toolbar li.justifyLeft{ background-position:0 0; } div.wysiwyg ul.toolbar li.justifyCenter{ background-position:-24px 0; } div.wysiwyg ul.toolbar li.justifyRight{ background-position:-48px 0; } div.wysiwyg ul.toolbar li.justifyFull{ background-position:-72px 0; } div.wysiwyg ul.toolbar li.indent{ background-position:-96px 0; } div.wysiwyg ul.toolbar li.outdent{ background-position:-120px 0; } div.wysiwyg ul.toolbar li.subscript{ background-position:-96px -24px; } div.wysiwyg ul.toolbar li.superscript{ background-position:-120px -24px; } div.wysiwyg ul.toolbar li.undo{ background-position:0 -96px; } div.wysiwyg ul.toolbar li.redo{ background-position:-24px -96px; } div.wysiwyg ul.toolbar li.insertOrderedList{ background-position:-48px -72px; } div.wysiwyg ul.toolbar li.insertUnorderedList{ background-position:-24px -72px; } div.wysiwyg ul.toolbar li.insertHorizontalRule{ background-position:0 -72px; } div.wysiwyg ul.toolbar li.h1{ background-position:0 -48px; } div.wysiwyg ul.toolbar li.h2{ background-position:-24px -48px; } div.wysiwyg ul.toolbar li.h3{ background-position:-48px -48px; } div.wysiwyg ul.toolbar li.h4{ background-position:-72px -48px; } div.wysiwyg ul.toolbar li.h5{ background-position:-96px -48px; } div.wysiwyg ul.toolbar li.h6{ background-position:-120px -48px; } div.wysiwyg ul.toolbar li.paragraph{ background-position:0 -144px; } div.wysiwyg ul.toolbar li.colorpicker{ background-position:-24px -96px; } div.wysiwyg ul.toolbar li.fullscreen{ background-position:-32px -96px; } div.wysiwyg ul.toolbar li.cut{ background-position:-48px -96px; } div.wysiwyg ul.toolbar li.copy{ background-position:-72px -96px; } div.wysiwyg ul.toolbar li.paste{ background-position:-96px -96px; } div.wysiwyg ul.toolbar li.insertTable{ background-position:-96px -72px; } div.wysiwyg ul.toolbar li.increaseFontSize{ background-position:-24px -120px; } div.wysiwyg ul.toolbar li.decreaseFontSize{ background-position:-48px -120px; } div.wysiwyg ul.toolbar li.createLink{ background-position:-120px -72px; } div.wysiwyg ul.toolbar li.insertImage{ background-position:-120px -120px; } div.wysiwyg ul.toolbar li.html{ background-position:-72px -72px; } div.wysiwyg ul.toolbar li.removeFormat{ background-position:-120px -96px; } div.wysiwyg ul.toolbar li.ltr{ background-position:-24px -144px; } div.wysiwyg ul.toolbar li.rtl{ background-position:-48px -144px; } div.wysiwyg ul.toolbar li.empty{ background-position:-96px -120px; } div.wysiwyg ul.toolbar li.code{ background-position:-96px -144px; } div.wysiwyg ul.toolbar li.cssWrap{ background-position:-120px -144px; } div.wysiwyg ul.toolbar li.colorpicker{ background-position:0 -168px; } div.wysiwyg-dialogRow{ float:left; font-size:16px; width:100%; } div.wysiwyg iframe{ background-color:#FFF; border:1px solid #bbb; border-radius:4px; clear:left; display:block; margin:0; moz-border-radius:4px; padding:0; webkit-border-radius:4px; width:100%; } form.wysiwyg input.width,form.wysiwyg input.height,form.wysiwyg input.integer{ margin:2px 0; text-align:right; width:30px; } form.wysiwyg select{ width:60px; }
08102013project
trunk/CMS/Content/themes/base/light/jquery.wysiwyg.css
CSS
oos
5,604
/* file manager window */ .el-finder { width:100%; min-width:400px; border:1px solid #ccc; background-color:#eee; border-radius:4px; -moz-border-radius:4px; -webkit-border-radius:4px; } .el-finder-undocked { position:absolute; min-width:400px; border:1px solid #ccc; padding:5px; } /* error messages */ .el-finder-err { padding: 15px; text-align:center; background: #2e2e33; color: #f1f1f1; border-radius:4px; -moz-border-radius:4px; -webkit-border-radius:4px; } /* disabled */ .el-finder-disabled .el-finder-toolbar li, .el-finder-disabled .el-finder-nav, .el-finder-disabled .el-finder-cwd { opacity:0.35; filter:Alpha(Opacity=35); } .el-finder .el-finder-droppable { background-color:#99ccff; } .el-finder .ui-selected { background-color:#ccc; } .el-finder input { margin:0; padding:0; outline:none; border:1px solid #ccc; } /************************************/ /* toolbar */ /************************************/ .el-finder-toolbar ul { padding:5px 7px; margin:0; list-style:none; } .el-finder-toolbar ul li { display: -moz-inline-stack; display: inline-block; zoom: 1; *display: inline; vertical-align: top; height:22px; width:23px; margin:0 2px; padding:0; background:url(images/elfinder/toolbar.png) no-repeat; border:1px solid #ccc; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; } .el-finder-toolbar ul li.delim { border:none; width:3px; background-position: 1px -610px; } .el-finder-toolbar ul li.el-finder-tb-hover { border:1px solid #fff; background-color:#ccc; } .el-finder-toolbar ul li.disabled { opacity:0.35; filter:Alpha(Opacity=35); } .el-finder-toolbar ul li.archive { background-position: 0px -583px; } .el-finder-toolbar ul li.extract { background-position: 0px -583px; } .el-finder-toolbar ul li.back { background-position: 0px -169px; } .el-finder-toolbar ul li.reload { background-position: 0px -190px; } .el-finder-toolbar ul li.select { background-position: 0px -214px; } .el-finder-toolbar ul li.open { background-position: 0px -235px; } .el-finder-toolbar ul li.mkdir { background-position: 0px -258px; } .el-finder-toolbar ul li.mkfile { background-position: 0px -280px; } .el-finder-toolbar ul li.upload { background-position: 0px -305px; } .el-finder-toolbar ul li.duplicate { background-position: 0px -705px; } .el-finder-toolbar ul li.rm { background-position: 0px -330px; } .el-finder-toolbar ul li.copy { background-position: 0px -356px; } .el-finder-toolbar ul li.cut { background-position: 0px -631px; } .el-finder-toolbar ul li.paste { background-position: 0px -380px; } .el-finder-toolbar ul li.rename { background-position: 0px -407px; } .el-finder-toolbar ul li.edit { background-position: 0px -435px; } .el-finder-toolbar ul li.info { background-position: 0px -463px; } .el-finder-toolbar ul li.help { background-position: 0px -487px; } .el-finder-toolbar ul li.icons { background-position: 0px -537px; } .el-finder-toolbar ul li.list { background-position: 0px -557px; } .el-finder-toolbar ul li.uncompress { background-position: 0px -583px; } .el-finder-toolbar ul li.resize { background-position: 0px -655px; } .el-finder-toolbar ul li.quicklook { background-position: 0px -726px; } .el-finder-dock-button { width:19px; height:19px; float:right; margin: 2px; border:1px solid #ccc; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; background:url(images/elfinder/toolbar.png) 2px -705px no-repeat; } .ui-dialog .el-finder-dock-button { background-position:2px -681px; } .el-finder-dock-button-hover { background-color:#ccc; border:1px solid #fff; } /**********************************************************/ /* workzone, container for navigation and current folder */ /**********************************************************/ .el-finder-workzone { background:url(images/paper_02.png); border-top:1px solid #ccc; border-bottom:1px solid #ccc; position:relative; } .el-finder-spinner { position:absolute; top:37%; left:37%; width:250px; height:50px; background:transparent url(images/loading.gif) 50% 50% no-repeat; display:none; } /* error in workzone */ .el-finder-workzone p.el-finder-err { display:none; position:absolute; left:37%; top:20px; } /* navigation and current directory */ .el-finder-nav, .el-finder-cwd { height:350px; overflow:auto; padding:3px 1px; } /************************************/ /* navigation */ /************************************/ .el-finder-nav { float:left; width : 200px; background:url(images/paper_01.png); } .el-finder-nav .ui-resizable-e { right:0; } /* folders tree */ .el-finder-nav ul { list-style:none; margin:0; padding:0; } .el-finder-nav ul li { clear:both; } ul.el-finder-tree, ul.el-finder-places { margin-bottom:1em; } .el-finder-nav ul li ul { margin-left:12px; } .el-finder-nav ul div { width:12px; height:20px; float:left; margin-right:23px; } .el-finder-nav a, .el-finder-nav div.collapsed { background-image:url(images/elfinder/toolbar.png); background-repeat:no-repeat; } .el-finder-nav div.collapsed { background-position: -5px 5px; } .el-finder-nav div.expanded { background-position: -5px -10px; } .el-finder-nav a { display: block; white-space:nowrap; line-height:20px; color:#444; cursor:default; text-decoration:none; outline:none; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; background-position: 8px -56px; } .el-finder-nav a.dropbox { background-position: 8px -80px; } .el-finder-nav a.readonly { background-position: 8px -104px; } .el-finder-nav a.noaccess { background-position: 8px -750px; } .el-finder-nav a.selected { background-color:#ccc; background-position: 8px -128px; } .el-finder-nav a.el-finder-tree-root { background-position: 10px -30px; font-weight:bold; } .el-finder-nav a.el-finder-places-root { background-position: 8px -148px; font-weight:bold; } .el-finder-nav ul.el-finder-tree .el-finder-droppable { background-position: 8px -237px; } /***********************************/ /* current working directory */ /************************************/ .el-finder-cwd { border-left:1px solid #ccc; padding:3px; } /********** view: icons ************/ .el-finder-cwd div { width: 81px; display: -moz-inline-stack; display: inline-block; vertical-align: top; zoom: 1; *display: inline; margin:0 3px 3px 0; padding:1px 0; text-align:center; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; color:#6f6f6f; background-color:transparent; } .el-finder-cwd p, .el-finder-ql p { width:48px; height:48px; margin:1px auto; padding:0; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; background: url(images/elfinder/icons-big.png) -1px 1px no-repeat; } /* mimetypes */ .directory p { background-position: 0 -45px; } .application p { background-position: -1px -134px; } .audio p { background-position: -1px -1082px; } .image p { background-position: -1px -1132px; } .text p, .x-empty p { background-position: -1px -524px; } .video p { background-position: -1px -1032px; } /* images */ .gif p { background-position: 0 -1183px; } .jpeg p { background-position: 0 -1234px; } .vnd-adobe-photoshop p, .postscript p { background-position: 0 -1132px; } /* video */ .ogg p { background-position: -1px -1032px; } /* audio */ .ogm p { background-position: -1px -1082px; } /* texts */ .rtf p, .rtfd p { background-position: 0 -573px; } .javascript p, .x-javascript p { background-position: 0 -184px; } .x-c p, .css p, .x-sql p, .x-python p, .x-java-source p { background-position: 0 -624px; } .html p { background-position: 0 -777px; } .x-java p { background-position: 0 -827px; } .x-php p { background-position: 0 -726px; } .x-perl p { background-position: 0 -675px; } .x-ruby p { background-position: 0 -877px; } .x-shellscript p { background-position: 0 -930px; } /* applications */ .vnd-ms-office p, .msword p, .vnd-ms-word p, .vnd-oasis-opendocument-text p { background-position: -1px -232px; } .ms-excel p, .vnd-ms-excel p, .vnd-oasis-opendocument-spreadsheet p { background-position: -1px -330px; } .vnd-ms-powerpoint p, .vnd-oasis-opendocument-presentation p { background-position: -1px -380px; } .pdf p { background-position: -1px -282px; } .xml p { background-position: 0 -980px; } .x-shockwave-flash p { background-position: 0 -1032px; } .x-sh p { background-position: 0 -930px; } /* archives */ .x-bzip p, .x-bzip2 p, .zip p, .x-rar p, .x-rar-compressed p, .x-tar p, .x-7z-compressed p { background-position: -1px -430px; } .x-gzip p { background-position: -1px -477px; } .el-finder-cwd div.el-finder-droppable p { background-position: 0 -87px; } .el-finder-cwd label { display:block; font-size:11px; line-height:13px; padding:0 1px; margin:0; height:25px; overflow:hidden; cursor:default; } .el-finder-cwd div input { background:#fff; width:81px; margin-left:-2px; outline:none; border:1px solid #ccc; text-align:center; } .el-finder-cwd div em { float:left; margin-top:-40px; margin-left:9px; width:15px; height:16px; background:url(images/elfinder/icons-big.png) -17px -1290px no-repeat; } .el-finder-cwd div em.dropbox { float:right; margin-right:9px; background-position: 0 -1290px; } .el-finder-cwd div em.noread { float:right; margin-right:9px; background-position: 0 -1415px; } .el-finder-cwd div em.readonly { float:right; margin-right:9px; background-position: -34px -1287px; } .el-finder-cwd div em.noaccess { float:right; margin-right:9px; background-position: 0 -1415px; } /********** view: list ************/ .el-finder-cwd table { width:100%; /* *width:99%;*/ border-collapse: collapse; border-spacing: 0; border:1px solid #ccc; border-top:0 solid; border-left:0 solid; margin:-3px -3px; } .el-finder-cwd table tr { background:transparent; } .el-finder-cwd table tr.el-finder-row-odd { background-color:#eee; } .el-finder-cwd table tr.ui-selected { background-color:#c1c1c1; } .el-finder-cwd table th, .el-finder-cwd table td { padding:3px 5px; border-left:1px solid #444444; cursor:default; white-space:nowrap; text-align:left; } .el-finder-cwd table th { text-align:left; } .el-finder-cwd table td.icon { width:24px; } .el-finder-cwd table p { width:24px; height:16px; margin:0; padding:0; background:url(images/elfinder/icons-small.png) 4px 0 no-repeat; } .el-finder-cwd table .size { text-align:right; } tr.directory p { background-position:4px -16px; } tr.text p { background-position:5px -34px; } tr.image p { background-position:4px -51px; } tr.audio p { background-position:4px -70px; } tr.video p { background-position:5px -89px; } tr.application p { background-position:4px -108px; } /* text */ tr.html p { background-position:5px -188px; } tr.javascript p, tr.x-javascript p, tr.css p, tr.x-sql p, tr.xml p, tr.x-python p, tr.x-java-source p, tr.x-perl p, tr.x-ruby p { background-position:5px -228px; } tr.x-php p { background-position:5px -247px; } tr.x-c p { background-position:5px -208px; } tr.x-shellscript p, tr.x-sh p { background-position:5px -168px; } tr.rtf p, tr.rtfd p { background-position:5px -148px; } /* application */ tr.x-shockwave-flash p { background-position:4px -266px; } tr.pdf p { background-position:4px -285px; } tr.vnd-ms-office p { background-position:4px -325px; } tr.msword p, tr.vnd-oasis-opendocument-text p, tr.vnd-ms-word p { background-position:4px -346px; } tr.vnd-ms-excel p, tr.ms-excel p, tr.vnd-oasis-opendocument-spreadsheet { background-position:4px -365px; } tr.vnd-ms-powerpoint p, tr.vnd-oasis-opendocument-presentation { background-position:4px -385px; } /* archives */ tr.x-tar p, tr.x-gzip p, tr.x-bzip p, tr.x-bzip2 p, tr.zip p, tr.x-rar p, tr.x-rar-compressed p, tr.x-7z-compressed p { background-position:4px -305px; } tr.el-finder-droppable td.icon p { background-position:5px -450px; } .el-finder-cwd table td p em { float:left; width:10px; height:12px; margin-top:5px; background:url(images/elfinder/icons-small.png) 0px -405px no-repeat; } .el-finder-cwd table p em.readonly { background-position:0px -433px; } .el-finder-cwd table p em.dropbox { background-position:0px -418px; } .el-finder-cwd table p em.noread, .el-finder-cwd table p em.noaccess { background-position:0px -470px; } /************************************/ /* statusbar */ /************************************/ .el-finder-statusbar { height:20px; } .el-finder-stat, .el-finder-path, .el-finder-sel { padding:3px 9px 1px 9px; color:#555; } /* current directory path */ .el-finder-path { float:left; } /* number folders/files in current directory and size */ .el-finder-stat { float:right; } /* info about selected files */ .el-finder-sel { text-align:center; } /************************************/ /* dialog window */ /************************************/ .el-finder-dialog form p, .el-finder-dialog .ui-tabs p { margin:.5em; } .el-finder-dialog .ui-dialog-titlebar { padding: .2em .1em .1em .8em; } .el-finder-dialog .ui-dialog-buttonpane { padding: .1em 1em .1em .4em; font-size:.9em; } .el-finder-dialog .ui-dialog-content { padding:5px; } .el-finder-dialog hr { border:0; border-bottom: 1px #ccc solid; clear:both } .el-finder-dialog ul { margin-top:0; } .el-finder-dialog a { outline: none;} .el-finder-dialog textarea { width:100%; height:400px; outline:none; border:1px solid #ccc; } .ui-state-error { margin: 5px 0; padding:.5em; clear:both; } .el-finder-dialog .ui-state-error .ui-icon { float: left; margin-right: .3em; } .el-finder-add-field { cursor:pointer; } .el-finder-add-field span { float:left; margin-right:.7em; } .el-finder-dialog table { width : 100%; } .el-finder-dialog table td { padding:2px 5px; } .el-finder-dialog .ui-tabs div { padding:0 .5em; } .el-finder-dialog .ui-tabs-nav li a { padding:.2em 1em; } /************************************/ /* contextmenu */ /************************************/ .el-finder-contextmenu { position:absolute; width:200px; background:#fff; cursor:default; border:1px solid #ccc; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; padding:5px 0; } .el-finder-contextmenu div { position:relative; display:block; margin:0; padding:4px 29px 4px 29px; white-space:nowrap; font:12px trebuchet ms,lucida grande,verdana,sans-serif; background:url(images/elfinder/toolbar.png) 0 0 no-repeat; } .el-finder-contextmenu span { float:right; width:9px; height:18px; margin-right:-27px; background:url(images/elfinder/toolbar.png) -4px 5px no-repeat; } .el-finder-contextmenu div.el-finder-contextmenu-sub { position:absolute; top:0; display:none; margin:0; padding:5px 0; background:#fff; border:1px solid #ccc; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; } .el-finder-contextmenu div.reload { background-position: 5px -192px; } .el-finder-contextmenu div.select { background-position: 5px -214px; } .el-finder-contextmenu div.open { background-position: 6px -235px; } .el-finder-contextmenu div.mkdir { background-position: 6px -258px; } .el-finder-contextmenu div.mkfile { background-position: 6px -280px; } .el-finder-contextmenu div.upload { background-position: 5px -305px; } .el-finder-contextmenu div.rm { background-position: 5px -330px; } .el-finder-contextmenu div.copy { background-position: 5px -356px; } .el-finder-contextmenu div.cut { background-position: 5px -631px; } .el-finder-contextmenu div.duplicate { background-position: 5px -356px; } .el-finder-contextmenu div.paste { background-position: 5px -381px; } .el-finder-contextmenu div.rename { background-position: 5px -407px; } .el-finder-contextmenu div.edit { background-position: 6px -435px; } .el-finder-contextmenu div.info { background-position: 5px -462px; } .el-finder-contextmenu div.help { background-position: 5px -487px; } .el-finder-contextmenu div.icons { background-position: 5px -537px; } .el-finder-contextmenu div.list { background-position: 5px -557px; } .el-finder-contextmenu div.archive { background-position: 5px -583px; } .el-finder-contextmenu div.extract { background-position: 5px -583px; } .el-finder-contextmenu div.resize { background-position: 5px -655px; } .el-finder-contextmenu div.quicklook { background-position: 5px -727px; } .el-finder-contextmenu div.delim { margin:0; padding:0; height:1px; border-top:1px solid #eee; background:transparent; display:block; } .el-finder-contextmenu div.hover { background-color:#99ccff; } .el-finder-places { margin-top:.5em; } .el-finder-drag-helper { padding:0; cursor:move; zoom:1; } .el-finder-drag-helper div { border:0 solid; margin-left:-57px; } .el-finder-drag-copy { background:url(images/elfinder/toolbar.png) 0 -771px no-repeat; } .el-finder-drag-helper label { border:1px solid #ccc; background-color:#eee; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; } /************************************/ /* QuickLook */ /************************************/ .el-finder-ql { position:absolute; width:420px; height:auto; padding:12px 9px; text-align:center; border-radius:9px; -moz-border-radius:9px; -webkit-border-radius:9px; background:url(images/elfinder/ql.png); overflow: inherit !important; } /* toolbar */ .el-finder-ql div.el-finder-ql-drag-handle { height:18px; background-color:#777; margin:-12px -9px 12px -9px; padding:3px 0 0 19px; opacity:.8; text-align:center; white-space: nowrap; overflow:hidden; -moz-border-radius-topleft:9px; -moz-border-radius-topright:9px; -webkit-border-top-left-radius: 9px; -webkit-border-top-right-radius: 9px; border-top-left-radius: 9px; border-top-right-radius: 9px; } /* close button */ .el-finder-ql div.el-finder-ql-drag-handle span { float:left; margin:0 19px 0 -15px; } /* title in tolbar */ .el-finder-ql div.el-finder-ql-drag-handle strong { line-height:18px; margin-left:-17px; color:#fff; } .el-finder-ql div.el-finder-ql-media { width:100%; padding:0; } .el-finder-ql div.el-finder-ql-content { width:100%; font:.82em/1.3em trebuchet ms,lucida grande,verdana,sans-serif; padding:5px 0; overflow:hidden; } .el-finder-ql div.el-finder-ql-content span, .el-finder-ql div.el-finder-ql-content a { display:block; color: #fff; } /* text files preview */ .el-finder-ql iframe { background:#fff; width:100%; height:315px; padding:0; margin:0; border:none; outline:none; } /* images preview */ .el-finder-ql img { margin:0 auto; border:1px solid #fff; } /* button help */ .el-finder-help-std { background: url(images/elfinder/icons-big.png) 0 -1315px no-repeat; width:48px; height:48px; float:right; } .el-finder-logo { background: url(images/elfinder/icons-big.png) 0 -1365px no-repeat; width:48px; height:48px; float:left; }
08102013project
trunk/CMS/Content/themes/base/light/jquery.elfinder.css
CSS
oos
20,467
/*----------------------------------------------------------------------*/ /* colors /* #f0a8a8 #f0cccc red /* #a2e8a2 #c5e8c5 green /* #e8e8a2 #e8e8c5 yellow /* #a8f0f0 #ccf0f0 blue /* #f0a8f0 #f0ccf0 pink /* #aea8f0 #cfccf0 purple /* /* contrast color #bada55 /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Imports /*----------------------------------------------------------------------*/ @import 'jquery-ui.css'; @import 'jquery.miniColors.css'; @import 'jquery.tipsy.css'; @import 'jquery.uniform.css'; @import 'jquery.wysiwyg.css'; @import 'jquery.fullcalendar.css'; @import 'jquery.elfinder.css'; @import 'jquery.fancybox.css'; @import 'jquery.datatables.css'; /*----------------------------------------------------------------------*/ /* General Section /*----------------------------------------------------------------------*/ html, body, textarea, input { color:#6f6f6f; } html{ background-color:#ffffff; background-image:url(images/paper_02.png); } a, a:hover, a:visited, a:link {color:#3f3f3f;} ::-moz-selection{ background:#bada55; color:#ffffff; text-shadow:none; } ::selection { background:#bada55; color:#ffffff; text-shadow:none; } nav ul li a span{ background-image:url(../images/icons/dark/arrow_right.png); } h1, h2, h3, h4, h5, h6{ text-shadow:0 1px 0 #ffffff; color:#777777; } h1{ text-shadow:0 2px 0 #ffffff; } h1 span{ text-shadow:0 1px 0 #ffffff; } blockquote{ border-color:#999999; color:#999999; } hr { border-top-color:#e1e1e1; border-bottom-color:#ffffff; } /*----------------------------------------------------------------------*/ /* jQuery UI mods /*----------------------------------------------------------------------*/ .ui-widget-header a, .ui-accordion-header a{ color:#444444; text-shadow:0 0 1px #FFFFFF; } .ui-widget-header{ border-top-color:#FFFFFF !important; border-bottom-color:#AAAAAA !important; margin:0; } .ui-widget-overlay{ background-image:url(images/paper_02.png); background-color:#333333; } .ui-state-default a{ border-top-color:#FFFFFF !important; } .ui-slider-range.ui-widget-header{ background-color:#333333; background-image:url(../images/bg/01.png); } .ui-slider{ border-color:#AAAAAA !important; background-color:#f6f6f6; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.3); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.3); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.3); } .ui-slider .ui-slider-handle{ border-color:#AAAAAA !important; background-image:url(images/slider_handler.png); -webkit-box-shadow:0 1px 1px rgba(0, 0, 0, 0.1); -moz-box-shadow:0 0 3px rgba(0, 0, 0, 0.1); box-shadow:0 0 1px rgba(0, 0, 0, 0.1); } /*----------------------------------------------------------------------*/ /* Pageoptions /*----------------------------------------------------------------------*/ #pageoptions h1, #pageoptions h2,#pageoptions h3, #pageoptions h4, #pageoptions h5, #pageoptions h6{ text-shadow:0 2px 0 #000000; color:#f1f1f1; } #pageoptions ul li a{ color:#999999; } #pageoptions ul li a:hover, #pageoptions ul li a.active{ color:#f1f1f1; background-color:#2e2e33; } #pageoptions > div{ color:#f1f1f1; background-color:#2e2e33; -webkit-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.5); box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.5); } /*----------------------------------------------------------------------*/ /* Tables /*----------------------------------------------------------------------*/ table{ background-image:url(images/paper_01.png); } table td, table th{ border-color:#dddddd #e7e7e7 #dddddd #e7e7e7; } table thead tr,table tfoot tr, table th{ background-image:url(images/paper_02.png); } table th{ text-shadow:0 -1px 0 #ffffff; } /*----------------------------------------------------------------------*/ /* Header /*----------------------------------------------------------------------*/ header{ -webkit-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); -moz-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); border-top-color:#d7d7d7; background:#f3f3f3; /* the filter causes an overflow problem on IE9 http://stackoverflow.com/questions/3619383/internet-explorer-css-property-filter-ignores-overflowvisible filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#f1f1f1');*/ background:-webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#f1f1f1)); background:-moz-linear-gradient(top, #f6f6f6, #f1f1f1); background:-o-linear-gradient(top, #f6f6f6, #f1f1f1); border-left-color: #e1e1e1; border-left-width: 1px; border-left-style: solid; } #logo, #logo a{ text-shadow:0 -1px 0 #999999; color:#ffffff; } #header ul li ul li{ border-color:#d7d7d7 #c2c2c2 #c2c2c2 #d7d7d7; } #header ul li ul li a{ color:#353535; text-shadow:0px 1px 0 #ffffff; border-top-color:#ffffff; background:#f1f1f1; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f1f1f1', endColorstr='#e8e8e8'); background:-webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e8e8e8)); background:-moz-linear-gradient(top, #f1f1f1, #e8e8e8); background:-o-linear-gradient(top, #f1f1f1, #e8e8e8); } #header ul li ul li a:hover{ background:#f6f6f6; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#f1f1f1'); background:-webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#f1f1f1)); background:-moz-linear-gradient(top, #f6f6f6, #f1f1f1); background:-o-linear-gradient(top, #f6f6f6, #f1f1f1); } #header ul li ul li a:active, #header ul li ul li a.active{ -webkit-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.3); -moz-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.3); box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.3); background:#e8e8e8; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#e8e8e8', endColorstr='#e3e3e3'); background:-webkit-gradient(linear, left top, left bottom, from(#e8e8e8), to(#e3e3e3)); background:-moz-linear-gradient(top, #e8e8e8, #e3e3e3); background:-o-linear-gradient(top, #e8e8e8, #e3e3e3); } #header ul li ul li:active, #header ul li ul li.active{ } #header ul li ul li ul{ background-color:#2e2e33; } #header ul li ul li span{ background-color:#f0a8a8; color:#ffffff; border-color: #bbb; -webkit-box-shadow: inset 0px 2px 2px rgba(255,255,255, 0.4), inset 0px -2px 3px rgba(255,25,25, 0.4); -moz-box-shadow: inset 0px 2px 2px rgba(255,255,255, 0.4), inset 0px -2px 3px rgba(255,25,25, 0.4); box-shadow: inset 0px 2px 2px rgba(255,255,255, 0.4), inset 0px -2px 3px rgba(255,25,25, 0.4); } #header ul li ul li ul li{ border-color:#dddddd; } #searchbox{ border-color:#d7d7d7 #c2c2c2 #c2c2c2 #d7d7d7; } form#searchform input#search{ color:#353535; text-shadow:0px 1px 0 #ffffff; border-top-color:#ffffff; -webkit-box-shadow:none; -moz-box-shadow:none; box-shadow:none; background:#f1f1f1; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f1f1f1', endColorstr='#e8e8e8'); background:-webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e8e8e8)); background:-moz-linear-gradient(top, #f1f1f1, #e8e8e8); background:-o-linear-gradient(top, #f1f1f1, #e8e8e8); } form#searchform input#search:hover{ background:#f6f6f6; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#f1f1f1'); background:-webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#f1f1f1)); background:-moz-linear-gradient(top, #f6f6f6, #f1f1f1); background:-o-linear-gradient(top, #f6f6f6, #f1f1f1); } form#searchform input#search:focus{ -webkit-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.3); -moz-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.3); box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.3); background:#ffffff; filter:none; } form#searchform input#search.load{ background-image:url(images/loading.gif) !important; } /* Live Search /*---------------------------------------------------------------------*/ ul#searchboxresult{ border-top-color:#e1e1e1; -webkit-box-shadow:0px 0px 4px rgba(0, 0, 0, 0.1); -moz-box-shadow:0px 0px 4px rgba(0, 0, 0, 0.1); box-shadow:0px 0px 4px rgba(0, 0, 0, 0.1); } ul#searchboxresult li a{ border-color:#ffffff #f7f7f7 #dddddd #f7f7f7; background-color:#f7f7f7; } ul#searchboxresult li a:hover{ background-color:#f1f1f1; } /*----------------------------------------------------------------------*/ /* Navigation /*----------------------------------------------------------------------*/ nav{ border-right-color:#e1e1e1 !important; border-left-color:#e1e1e1; -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.1); -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.1); box-shadow:2px 2px 4px rgba(0, 0, 0, 0.1); } nav ul{ border-top-color:#e1e1e1; background-color:#2e2e33; } nav ul li{ background-image:none !important; } nav ul li a{ background:#f1f1f1; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f1f1f1', endColorstr='#e8e8e8'); background:-webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e8e8e8)); background:-moz-linear-gradient(top, #f1f1f1, #e8e8e8); background:-o-linear-gradient(top, #f1f1f1, #e8e8e8); } nav ul li a:hover{ background:#f6f6f6; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#f1f1f1'); background:-webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#f1f1f1)); background:-moz-linear-gradient(top, #f6f6f6, #f1f1f1); background:-o-linear-gradient(top, #f6f6f6, #f1f1f1); } nav ul li a span{ color:#353535; text-shadow:0px 1px 0 #ffffff; border-color:#ffffff #f7f7f7 #dddddd #f7f7f7; } nav ul li a:active, nav ul li a.active{ background-image:url(images/nav_active.png); background-repeat:repeat-x; background-color:#bada55; background-position:left center; filter:none; } nav ul li a:active span, nav ul li a.active span{ color:#ffffff; text-shadow:0px -1px 0 rgba(0,0,0,0.3); } nav ul li ul{ border-bottom-color:#dddddd; } nav ul li ul li{ background-image:none !important; } nav ul li ul li a{ } nav ul li ul li a span{ border-top-color:#dddddd; background-image:none !important; } /*----------------------------------------------------------------------*/ /* Content /*----------------------------------------------------------------------*/ #content{ -webkit-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); -moz-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); background-color:#eeeeee; background-image:url(images/paper_01.png); border-color:#ededed; } .bgsample{ border-color:#999999; -webkit-box-shadow:inset 0 0 2px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 0 2px rgba(0, 0, 0, 0.5); box-shadow:inset 0 0 2px rgba(0, 0, 0, 0.5); background-color:#ffffff; } /*----------------------------------------------------------------------*/ /* Breadcrumb /*----------------------------------------------------------------------*/ .breadcrumb li a{ color:#999999; text-shadow:0 1px 0 #ffffff; border-color:#eeeeee #dddddd #dddddd #dddddd; background-image:url(images/breadcrumb.png); } .breadcrumb li:first-child a{ border-left-color:#dddddd; } .breadcrumb li:last-child a{ } .breadcrumb.disabled li a:hover{ color:#999999; } .breadcrumb li a.previous{ color:#aaaaaa; } .breadcrumb.disabled li a.previous:hover{ color:#aaaaaa; } .breadcrumb li a:hover{ color:#777777; } .breadcrumb li a:active, .breadcrumb li a.active, .breadcrumb.disabled li a.active:hover{ color:#555555; text-shadow:0 0 1px #ffffff; } /*----------------------------------------------------------------------*/ /* Gallery /*----------------------------------------------------------------------*/ .gallery{ border-color:#CCCCCC #E7E7E7 #FFFFFF #E7E7E7; background-image:url(images/paper_02.png); } .gallery .sortable_placeholder{ background-color:#f6f6f6; background-image:url(images/paper_02.png); } .gallery li{ border-color:#FFFFFF #E7E7E7 #CCCCCC #E7E7E7; background-image:url(images/paper_01.png); } .gallery li > a{ background-image:url(images/loading.gif); } .gallery li img{ } .gallery li span{ background-color:#2e2e33; border-top-color:#666666; -webkit-box-shadow:0 -1px 0 #2e2e33; -moz-box-shadow:0 -1px 0 #2e2e33; box-shadow:0 -1px 0 #2e2e33; } .gallery li > a span a{ color:#ffffff; } .gallery li a span a.edit{ background-image:url(../images/icons/light/pencil.png); } .gallery li a span a.delete{ background-image:url(../images/icons/light/cross.png); } /*----------------------------------------------------------------------*/ /* Message Box /*----------------------------------------------------------------------*/ #wl_msg .msg-box, #wl_msg .msg-box-close{ border-color:#e1e1e1; color:#f1f1f1; background:#202020; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#202020', endColorstr='#151515'); background:-webkit-gradient(linear, left top, left bottom, from(#202020), to(#151515)); background:-moz-linear-gradient(top, #202020, #151515); background:-o-linear-gradient(top, #202020, #151515); } #wl_msg .msg-box-close{ } #wl_msg .msg-box-close:hover{ background-color:#e1e1e1; color:#2e2e33; } #wl_msg .msg-box h3, #wl_msg .msg-close{ color:#f1f1f1; text-shadow:0 1px 0 #111111; background:#202020; } #wl_msg .msg-box h3{ border-bottom-color:#555555; } #wl_msg .msg-close{ border-left-color:#555555; border-bottom-color:#555555; background-image:url(../images/icons/light/cross.png); } #wl_msg .msg-close:hover{ background-image:url(../images/icons/dark/cross.png); background-color:#e1e1e1; } #wl_msg .msg-content{ } /*----------------------------------------------------------------------*/ /* Alert Boxes /*----------------------------------------------------------------------*/ div.alert{ border-color:#c7c7c7 #b2b2b2 #b2b2b2 #c7c7c7; text-shadow:0 1px 0 rgba(255,255,255,0.4); color:#555; background-color:#e6e6e6; -webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.6), inset 0 2px 5px rgba(255, 255, 255, 0.5), inset 0 -2px 8px rgba(0, 0, 0, 0.1); -moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.6), inset 0 2px 5px rgba(255, 255, 255, 0.5), inset 0 -2px 8px rgba(0, 0, 0, 0.1); box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.5), inset 0 2px 5px rgba(255, 255, 255, 0.1), inset 0 -2px 8px rgba(0, 0, 0, 0.1); margin:9px 0; } div.alert:hover{ border-color:#b2b2b2; } div.alert a{ color:#777777; } div.alert a:hover{ color:#444444; } div.alert.red, div.alert.warning{ background-color:#f0a8a8; } div.alert.red:hover, div.alert.warning:hover{ background-color:#f0cccc; } div.alert.green, div.alert.success{ background-color:#a2e8a2; } div.alert.green:hover, div.alert.success:hover{ background-color:#c5e8c5; } div.alert.yellow, div.alert.note{ background-color:#e8e8a2; } div.alert.yellow:hover, div.alert.note:hover{ background-color:#e8e8c5; } div.alert.blue, div.alert.info{ background-color:#a8f0f0; } div.alert.blue:hover, div.alert.info:hover{ background-color:#ccf0f0; } div.alert.pink{ background-color:#f0a8f0; } div.alert.pink:hover{ background-color:#f0ccf0; } div.alert.purple{ background-color:#aea8f0; } div.alert.purple:hover{ background-color:#cfccf0; } div.alert.warning{ background-image:url(../images/icons/dark/alert.png); } div.alert.success{ background-image:url(../images/icons/dark/tick.png); } div.alert.note{ background-image:url(../images/icons/dark/light_bulb.png); } div.alert.info{ background-image:url(../images/icons/dark/information.png); } /*----------------------------------------------------------------------*/ /* Form Elements /*----------------------------------------------------------------------*/ pre{ -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.1); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.1); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.1); } pre, code{ background-image:url(images/paper_02.png); background-color:#f1f1f1; border-color:#bbbbbb; } pre code{ background-image:url(images/code_lines.png); } input,textarea{ background-color:#ffffff; border-color:#bbbbbb; } input.placeholder,textarea.placeholder{ color:#cccccc; } input.error{ color:#c49090; } input, textarea, input:invalid, input:required, textarea:required{ -webkit-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); } input:hover,input:focus,textarea:hover,textarea:focus{ -webkit-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2), 0 0 3px rgba(0, 0, 0, 0.2); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2), 0 0 3px rgba(0, 0, 0, 0.2); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2), 0 0 3px rgba(0, 0, 0, 0.2); } select optgroup, select option{ color:#555555; } select option{ border-color:#ffffff #f7f7f7 #dddddd #f7f7f7; } form{ border-color:#cccccc #e7e7e7 #ffffff #e7e7e7; background-image:url(images/paper_02.png); } form .wl_formstatus{ color:#990000; } form span.required{ background-image:url(images/required.png); } form fieldset{ border-color:#dddddd #e7e7e7 #bbbbbb #e7e7e7; } form label{ border-top-color:#ffffff; color:#444444; text-shadow:0 1px 0 #ffffff; background:#f1f1f1; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f1f1f1', endColorstr='#e8e8e8'); background:-webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e8e8e8)); background:-moz-linear-gradient(top, #f1f1f1, #e8e8e8); background:-o-linear-gradient(top, #f1f1f1, #e8e8e8); } form fieldset > section{ border-top-color:#ffffff; border-bottom-color:#e7e7e7; background:#f6f6f6; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#f1f1f1'); background:-webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#f1f1f1)); background:-moz-linear-gradient(top, #f6f6f6, #f1f1f1); background:-o-linear-gradient(top, #f6f6f6, #f1f1f1); } form fieldset > section > div{ border-left-color:#e7e7e7; } form fieldset > section > div span{ } form fieldset > section.error{ background:#f0cccc; border-bottom-color:#f0cccc; filter:none; } form fieldset > section.error > label{ text-shadow:none; } form fieldset > section label{ } div.passwordstrength{ text-shadow:0 1px 0 #dddddd; -webkit-box-shadow:inset 0 0 5px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 0 5px rgba(0, 0, 0, 0.5); box-shadow:inset 0 0 5px rgba(0, 0, 0, 0.5); } div.passwordstrength.s_1{background-color:#f0a8a8;} div.passwordstrength.s_2{background-color:#f0d2b5;} div.passwordstrength.s_3{background-color:#e8e8a2;} div.passwordstrength.s_4{background-color:#a8f0f0;} div.passwordstrength.s_5{background-color:#a2e8a2;} /*----------------------------------------------------------------------*/ /* jQuery Checkbox /*----------------------------------------------------------------------*/ .jquery-checkbox span.checkboxplaceholder { background-image:url(images/checkbox.png); } /*----------------------------------------------------------------------*/ /* File Upload /*----------------------------------------------------------------------*/ div.fileuploadui{ } div.fileuploadui a{ } ul.fileuploadpool{ border-color:#ffffff; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); } ul.fileuploadpool.drop{ background-image:url(images/dragndrop.png),url(images/paper_02.png); } ul.fileuploadpool.single{ } ul.fileuploadpool li{ border-color:#FFFFFF #E7E7E7 #CCCCCC #E7E7E7; background-color:#f6f6f6; } ul.fileuploadpool li.error{ background-color:#f0cccc; } ul.fileuploadpool li .name{ } ul.fileuploadpool li a{ } ul.fileuploadpool li a:hover{ } ul.fileuploadpool li a.cancel{ background-image:url(../images/icons/dark/cross.png); } ul.fileuploadpool li a.remove{ background-image:url(../images/icons/dark/cross.png); } ul.fileuploadpool li .progress{ background-color:#f0a8a8; background-image:url(images/upload.gif); } ul.fileuploadpool li.success .progress{ background-color:#a2e8a2; background-image:none; } /*----------------------------------------------------------------------*/ /* Comboselect /*----------------------------------------------------------------------*/ div.comboselectbox div.combowrap{ border-color:#FFFFFF #E7E7E7 #CCCCCC #E7E7E7; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); } div.comboselectbox ul.comboselect li{ border-color:#FFFFFF #E7E7E7 #CCCCCC #E7E7E7; background-color:#f6f6f6; } div.comboselectbox ul.comboselect li:hover a{ color:#111; } div.comboselectbox ul.comboselect li a.add{ background-image:url(../images/icons/dark/plus.png); } div.comboselectbox ul.comboselect li a.remove{ background-image:url(../images/icons/dark/cross.png); } div.comboselectbox ul.comboselect li.used a{ color:#ccc; } div.comboselectbox ul.comboselect li.selected{ background-color:#efefef; } div.comboselectbox div.comboselectbuttons a.add{ background-image:url(../images/icons/dark/triangle_right.png); } div.comboselectbox div.comboselectbuttons a.remove{ background-image:url(../images/icons/dark/triangle_left.png); } div.comboselectbox div.comboselectbuttons a.addall{ background-image:url(../images/icons/dark/triangle_double_right.png); } div.comboselectbox div.comboselectbuttons a.removeall{ background-image:url(../images/icons/dark/triangle_double_left.png); } @media screen and (max-width:700px){ div.comboselectbox div.comboselectbuttons a.add{ background-image:url(../images/icons/dark/triangle_down.png); } div.comboselectbox div.comboselectbuttons a.remove{ background-image:url(../images/icons/dark/triangle_up.png); } div.comboselectbox div.comboselectbuttons a.addall{ background-image:url(../images/icons/dark/triangle_double_down.png); } div.comboselectbox div.comboselectbuttons a.removeall{ background-image:url(../images/icons/dark/triangle_double_up.png); } } /*----------------------------------------------------------------------*/ /* Buttons /*----------------------------------------------------------------------*/ button, a.btn, .button .dataTables_paginate span.paginate_button, .dataTables_paginate span.paginate_active{ border-color:#c7c7c7 #b2b2b2 #b2b2b2 #c7c7c7; text-shadow:0 1px 0 rgba(255,255,255,0.7); color:#555555; background-color:#e6e6e6; -webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.6), inset 0 2px 5px rgba(255, 255, 255, 0.5), inset 0 -2px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.6), inset 0 2px 5px rgba(255, 255, 255, 0.5), inset 0 -2px 5px rgba(0, 0, 0, 0.1); box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.6), inset 0 2px 5px rgba(255, 255, 255, 0.5), inset 0 -2px 5px rgba(0, 0, 0, 0.1); } button.icon, a.btn.icon, .button.icon{ } button{ } a.btn{ } button:hover, a.btn:hover, .button:hover, .dataTables_paginate span.paginate_active:hover{ background-color:#f1f1f1; } button:active, a.btn:active, .button:active, .dataTables_paginate span.paginate_active{ background-color:#f1f1f1; border-color:#b2b2b2 #c7c7c7 #c7c7c7 #b2b2b2; -webkit-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.1); -moz-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.1); box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.1); } button.red, a.btn.red, .button.red{ background-color:#f0a8a8; } button.red:hover, a.btn.red:hover, .button.red:hover{ background-color:#f0cccc; } button.green, a.btn.green, .button.green{ background-color:#a2e8a2; } button.green:hover, a.btn.green:hover, .button.green:hover{ background-color:#c5e8c5; } button.yellow, a.btn.yellow, .button.yellow{ background-color:#e8e8a2; } button.yellow:hover, a.btn.yellow:hover, .button.yellow:hover{ background-color:#e8e8c5; } button.blue, a.btn.blue, .button.blue{ background-color:#a8f0f0; } button.blue:hover, a.btn.blue:hover, .button.blue:hover{ background-color:#ccf0f0; } button.pink, a.btn.pink, .button.pink{ background-color:#f0a8f0; } button.pink:hover, a.btn.pink:hover, .button.pink:hover{ background-color:#f0ccf0; } button.purple, a.btn.purple, .button.purple{ background-color:#aea8f0; } button.purple:hover, a.btn.purple:hover, .button.purple:hover{ background-color:#cfccf0; } /*----------------------------------------------------------------------*/ /* Widgets /*----------------------------------------------------------------------*/ .widget, .widget.loading{ background-color:#ffffff; border-color:#dddddd #efefef #f1f1f1 #efefef; background-image:url(images/paper_02.png); } .widget > div{ border-color:#dddddd #e7e7e7 #bbbbbb #e7e7e7; background-image:url(images/paper_01.png); } .widget > div.ui-widget{ background-image:none; } .widget:hover{ border-color:#cccccc; } .widget.ui-sortable-helper{ -webkit-box-shadow:0px 5px 6px rgba(0, 0, 0, 0.6); -moz-box-shadow:0px 5px 6px rgba(0, 0, 0, 0.6); box-shadow:0px 5px 6px rgba(0, 0, 0, 0.6); } .widget h3.handle{ color:#444444; text-shadow:0 0 1px #ffffff; border-top-color:#ffffff; border-bottom-color:#aaaaaa; background:#f1f1f1; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f1f1f1', endColorstr='#e8e8e8'); background:-webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e8e8e8)); background:-moz-linear-gradient(top, #f1f1f1, #e8e8e8); background:-o-linear-gradient(top, #f1f1f1, #e8e8e8); } .widget h3.handle:hover{ -webkit-box-shadow:inset 0 -3px 12px rgba(255, 255, 255, 0.5); -moz-box-shadow:inset 0 -3px 12px rgba(255, 255, 255, 0.5); box-shadow:inset 0 -3px 12px rgba(255, 255, 255, 0.5); background:#f6f6f6; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f6f6f6', endColorstr='#f1f1f1'); background:-webkit-gradient(linear, left top, left bottom, from(#f6f6f6), to(#f1f1f1)); background:-moz-linear-gradient(top, #f6f6f6, #f1f1f1); background:-o-linear-gradient(top, #f6f6f6, #f1f1f1); } .widget h3.handle .collapse{ background-image:url(../images/icons/dark/collapse.png); } .widget h3.handle .reload{ background-image:url(../images/icons/dark/refresh_3.png); } .widget.collapsed{ border-bottom-color:#aaaaaa; } .widget.collapsed h3.handle .collapse{ background-image:url(../images/icons/dark/expand.png); } .widget.loading h3.handle .reload{ background-image:url(images/loading.gif); } .widget.number-widget > div ul li{ border-top-color:#555555; } .widget.number-widget > div ul li a{ color:#555555; text-shadow:0 1px 0 #ffffff; } .widget.number-widget > div ul li a:hover{ color:#999999; } .widget.number-widget ul li a span{ } .sortable_placeholder{ border-color:#ffffff; background-color:#f6f6f6; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); } /*----------------------------------------------------------------------*/ /* Footer /*----------------------------------------------------------------------*/ footer{ color:#aaaaaa; } /* Move the Headernav to a drop down menu to the right */ @media screen and (max-width:960px) { #header ul#headernav{ background-image:url(../images/icons/dark/expand.png); border-left-color:#e7e7e7; } #header ul#headernav li ul li ul{ background-image:url(../images/bg/04.png); background-color:#2e2e33; } } /* iPhone and real small devicces */ @media screen and (max-width:480px) { nav ul li a:active span, nav ul li a.active span{ border-top-color:#ffffff; } nav{ border-top-color:#e1e1e1; } nav ul { background:#f1f1f1; } nav ul li a span{ border-left-color:#e1e1e1; } } /*----------------------------------------------------------------------*/ /* Icons /*----------------------------------------------------------------------*/ nav ul li.i_abacus a span, .i_abacus{ background-image: url(../images/icons/dark/abacus.png);} nav ul li.i_access_denied a span, .i_access_denied{ background-image: url(../images/icons/dark/access_denied.png);} nav ul li.i_address_book a span, .i_address_book{ background-image: url(../images/icons/dark/address_book.png);} nav ul li.i_admin_user a span, .i_admin_user{ background-image: url(../images/icons/dark/admin_user.png);} nav ul li.i_admin_user_2 a span, .i_admin_user_2{ background-image: url(../images/icons/dark/admin_user_2.png);} nav ul li.i_airplane a span, .i_airplane{ background-image: url(../images/icons/dark/airplane.png);} nav ul li.i_alarm a span, .i_alarm{ background-image: url(../images/icons/dark/alarm.png);} nav ul li.i_alarm_2 a span, .i_alarm_2{ background-image: url(../images/icons/dark/alarm_2.png);} nav ul li.i_alarm_clock a span, .i_alarm_clock{ background-image: url(../images/icons/dark/alarm_clock.png);} nav ul li.i_alert a span, .i_alert{ background-image: url(../images/icons/dark/alert.png);} nav ul li.i_android a span, .i_android{ background-image: url(../images/icons/dark/android.png);} nav ul li.i_application a span, .i_application{ background-image: url(../images/icons/dark/application.png);} nav ul li.i_archive a span, .i_archive{ background-image: url(../images/icons/dark/archive.png);} nav ul li.i_arrow_down a span, .i_arrow_down{ background-image: url(../images/icons/dark/arrow_down.png);} nav ul li.i_arrow_down_left a span, .i_arrow_down_left{ background-image: url(../images/icons/dark/arrow_down_left.png);} nav ul li.i_arrow_down_right a span, .i_arrow_down_right{ background-image: url(../images/icons/dark/arrow_down_right.png);} nav ul li.i_arrow_left a span, .i_arrow_left{ background-image: url(../images/icons/dark/arrow_left.png);} nav ul li.i_arrow_right a span, .i_arrow_right{ background-image: url(../images/icons/dark/arrow_right.png);} nav ul li.i_arrow_up a span, .i_arrow_up{ background-image: url(../images/icons/dark/arrow_up.png);} nav ul li.i_arrow_up_left a span, .i_arrow_up_left{ background-image: url(../images/icons/dark/arrow_up_left.png);} nav ul li.i_arrow_up_right a span, .i_arrow_up_right{ background-image: url(../images/icons/dark/arrow_up_right.png);} nav ul li.i_bag a span, .i_bag{ background-image: url(../images/icons/dark/bag.png);} nav ul li.i_balloons a span, .i_balloons{ background-image: url(../images/icons/dark/balloons.png);} nav ul li.i_bandaid a span, .i_bandaid{ background-image: url(../images/icons/dark/bandaid.png);} nav ul li.i_battery a span, .i_battery{ background-image: url(../images/icons/dark/battery.png);} nav ul li.i_battery_33 a span, .i_battery_33{ background-image: url(../images/icons/dark/battery_33.png);} nav ul li.i_battery_66 a span, .i_battery_66{ background-image: url(../images/icons/dark/battery_66.png);} nav ul li.i_battery_empty a span, .i_battery_empty{ background-image: url(../images/icons/dark/battery_empty.png);} nav ul li.i_battery_full a span, .i_battery_full{ background-image: url(../images/icons/dark/battery_full.png);} nav ul li.i_bended_arrow_down a span, .i_bended_arrow_down{ background-image: url(../images/icons/dark/bended_arrow_down.png);} nav ul li.i_bended_arrow_left a span, .i_bended_arrow_left{ background-image: url(../images/icons/dark/bended_arrow_left.png);} nav ul li.i_bended_arrow_right a span, .i_bended_arrow_right{ background-image: url(../images/icons/dark/bended_arrow_right.png);} nav ul li.i_bended_arrow_up a span, .i_bended_arrow_up{ background-image: url(../images/icons/dark/bended_arrow_up.png);} nav ul li.i_big_brush a span, .i_big_brush{ background-image: url(../images/icons/dark/big_brush.png);} nav ul li.i_blackberry a span, .i_blackberry{ background-image: url(../images/icons/dark/blackberry.png);} nav ul li.i_blocks_images a span, .i_blocks_images{ background-image: url(../images/icons/dark/blocks_images.png);} nav ul li.i_blu-ray a span, .i_blu-ray{ background-image: url(../images/icons/dark/blu-ray.png);} nav ul li.i_bluetooth a span, .i_bluetooth{ background-image: url(../images/icons/dark/bluetooth.png);} nav ul li.i_bluetooth_2 a span, .i_bluetooth_2{ background-image: url(../images/icons/dark/bluetooth_2.png);} nav ul li.i_book a span, .i_book{ background-image: url(../images/icons/dark/book.png);} nav ul li.i_book_large a span, .i_book_large{ background-image: url(../images/icons/dark/book_large.png);} nav ul li.i_books a span, .i_books{ background-image: url(../images/icons/dark/books.png);} nav ul li.i_breadcrumb a span, .i_breadcrumb{ background-image: url(../images/icons/dark/breadcrumb.png);} nav ul li.i_brush a span, .i_brush{ background-image: url(../images/icons/dark/brush.png);} nav ul li.i_buildings a span, .i_buildings{ background-image: url(../images/icons/dark/buildings.png);} nav ul li.i_bulls_eye a span, .i_bulls_eye{ background-image: url(../images/icons/dark/bulls_eye.png);} nav ul li.i_calculator a span, .i_calculator{ background-image: url(../images/icons/dark/calculator.png);} nav ul li.i_calendar a span, .i_calendar{ background-image: url(../images/icons/dark/calendar.png);} nav ul li.i_calendar_day a span, .i_calendar_day{ background-image: url(../images/icons/dark/calendar_day.png);} nav ul li.i_camera a span, .i_camera{ background-image: url(../images/icons/dark/camera.png);} nav ul li.i_camera_2 a span, .i_camera_2{ background-image: url(../images/icons/dark/camera_2.png);} nav ul li.i_car a span, .i_car{ background-image: url(../images/icons/dark/car.png);} nav ul li.i_cash_register a span, .i_cash_register{ background-image: url(../images/icons/dark/cash_register.png);} nav ul li.i_cassette a span, .i_cassette{ background-image: url(../images/icons/dark/cassette.png);} nav ul li.i_cat a span, .i_cat{ background-image: url(../images/icons/dark/cat.png);} nav ul li.i_cd a span, .i_cd{ background-image: url(../images/icons/dark/cd.png);} nav ul li.i_chair a span, .i_chair{ background-image: url(../images/icons/dark/chair.png);} nav ul li.i_chart a span, .i_chart{ background-image: url(../images/icons/dark/chart.png);} nav ul li.i_chart_2 a span, .i_chart_2{ background-image: url(../images/icons/dark/chart_2.png);} nav ul li.i_chart_3 a span, .i_chart_3{ background-image: url(../images/icons/dark/chart_3.png);} nav ul li.i_chart_4 a span, .i_chart_4{ background-image: url(../images/icons/dark/chart_4.png);} nav ul li.i_chart_5 a span, .i_chart_5{ background-image: url(../images/icons/dark/chart_5.png);} nav ul li.i_chart_6 a span, .i_chart_6{ background-image: url(../images/icons/dark/chart_6.png);} nav ul li.i_chart_7 a span, .i_chart_7{ background-image: url(../images/icons/dark/chart_7.png);} nav ul li.i_chart_8 a span, .i_chart_8{ background-image: url(../images/icons/dark/chart_8.png);} nav ul li.i_chemical a span, .i_chemical{ background-image: url(../images/icons/dark/chemical.png);} nav ul li.i_chrome a span, .i_chrome{ background-image: url(../images/icons/dark/chrome.png);} nav ul li.i_clipboard a span, .i_clipboard{ background-image: url(../images/icons/dark/clipboard.png);} nav ul li.i_clock a span, .i_clock{ background-image: url(../images/icons/dark/clock.png);} nav ul li.i_cloud a span, .i_cloud{ background-image: url(../images/icons/dark/cloud.png);} nav ul li.i_cloud_download a span, .i_cloud_download{ background-image: url(../images/icons/dark/cloud_download.png);} nav ul li.i_cloud_upload a span, .i_cloud_upload{ background-image: url(../images/icons/dark/cloud_upload.png);} nav ul li.i_cog a span, .i_cog{ background-image: url(../images/icons/dark/cog.png);} nav ul li.i_cog_2 a span, .i_cog_2{ background-image: url(../images/icons/dark/cog_2.png);} nav ul li.i_cog_3 a span, .i_cog_3{ background-image: url(../images/icons/dark/cog_3.png);} nav ul li.i_cog_4 a span, .i_cog_4{ background-image: url(../images/icons/dark/cog_4.png);} nav ul li.i_collapse a span, .i_collapse{ background-image: url(../images/icons/dark/collapse.png);} nav ul li.i_companies a span, .i_companies{ background-image: url(../images/icons/dark/companies.png);} nav ul li.i_compress a span, .i_compress{ background-image: url(../images/icons/dark/compress.png);} nav ul li.i_copy a span, .i_copy{ background-image: url(../images/icons/dark/copy.png);} nav ul li.i_coverflow a span, .i_coverflow{ background-image: url(../images/icons/dark/coverflow.png);} nav ul li.i_create_write a span, .i_create_write{ background-image: url(../images/icons/dark/create_write.png);} nav ul li.i_cross a span, .i_cross{ background-image: url(../images/icons/dark/cross.png);} nav ul li.i_cup a span, .i_cup{ background-image: url(../images/icons/dark/cup.png);} nav ul li.i_cursor a span, .i_cursor{ background-image: url(../images/icons/dark/cursor.png);} nav ul li.i_delicious a span, .i_delicious{ background-image: url(../images/icons/dark/delicious.png);} nav ul li.i_desk a span, .i_desk{ background-image: url(../images/icons/dark/desk.png);} nav ul li.i_digg a span, .i_digg{ background-image: url(../images/icons/dark/digg.png);} nav ul li.i_digg_2 a span, .i_digg_2{ background-image: url(../images/icons/dark/digg_2.png);} nav ul li.i_document a span, .i_document{ background-image: url(../images/icons/dark/document.png);} nav ul li.i_document_add a span, .i_document_add{ background-image: url(../images/icons/dark/document_add.png);} nav ul li.i_document_delete a span, .i_document_delete{ background-image: url(../images/icons/dark/document_delete.png);} nav ul li.i_documents a span, .i_documents{ background-image: url(../images/icons/dark/documents.png);} nav ul li.i_download a span, .i_download{ background-image: url(../images/icons/dark/download.png);} nav ul li.i_download_to_computer a span, .i_download_to_computer{ background-image: url(../images/icons/dark/download_to_computer.png);} nav ul li.i_dress a span, .i_dress{ background-image: url(../images/icons/dark/dress.png);} nav ul li.i_dribbble a span, .i_dribbble{ background-image: url(../images/icons/dark/dribbble.png);} nav ul li.i_dribbble_2 a span, .i_dribbble_2{ background-image: url(../images/icons/dark/dribbble_2.png);} nav ul li.i_dropbox a span, .i_dropbox{ background-image: url(../images/icons/dark/dropbox.png);} nav ul li.i_drupal a span, .i_drupal{ background-image: url(../images/icons/dark/drupal.png);} nav ul li.i_duplicate a span, .i_duplicate{ background-image: url(../images/icons/dark/duplicate.png);} nav ul li.i_dvd a span, .i_dvd{ background-image: url(../images/icons/dark/dvd.png);} nav ul li.i_eject a span, .i_eject{ background-image: url(../images/icons/dark/eject.png);} nav ul li.i_electricty_input a span, .i_electricty_input{ background-image: url(../images/icons/dark/electricty_input.png);} nav ul li.i_electricty_plug a span, .i_electricty_plug{ background-image: url(../images/icons/dark/electricty_plug.png);} nav ul li.i_empty a span, .i_empty{ background-image: url(../images/icons/dark/empty.png);} nav ul li.i_excel_document a span, .i_excel_document{ background-image: url(../images/icons/dark/excel_document.png);} nav ul li.i_excel_documents a span, .i_excel_documents{ background-image: url(../images/icons/dark/excel_documents.png);} nav ul li.i_exclamation a span, .i_exclamation{ background-image: url(../images/icons/dark/exclamation.png);} nav ul li.i_exit a span, .i_exit{ background-image: url(../images/icons/dark/exit.png);} nav ul li.i_expand a span, .i_expand{ background-image: url(../images/icons/dark/expand.png);} nav ul li.i_expose a span, .i_expose{ background-image: url(../images/icons/dark/expose.png);} nav ul li.i_expression_engine a span, .i_expression_engine{ background-image: url(../images/icons/dark/expression_engine.png);} nav ul li.i_eyedropper a span, .i_eyedropper{ background-image: url(../images/icons/dark/eyedropper.png);} nav ul li.i_facebook a span, .i_facebook{ background-image: url(../images/icons/dark/facebook.png);} nav ul li.i_facebook_like a span, .i_facebook_like{ background-image: url(../images/icons/dark/facebook_like.png);} nav ul li.i_fax a span, .i_fax{ background-image: url(../images/icons/dark/fax.png);} nav ul li.i_female a span, .i_female{ background-image: url(../images/icons/dark/female.png);} nav ul li.i_female_contour a span, .i_female_contour{ background-image: url(../images/icons/dark/female_contour.png);} nav ul li.i_file_cabinet a span, .i_file_cabinet{ background-image: url(../images/icons/dark/file_cabinet.png);} nav ul li.i_film a span, .i_film{ background-image: url(../images/icons/dark/film.png);} nav ul li.i_film_2 a span, .i_film_2{ background-image: url(../images/icons/dark/film_2.png);} nav ul li.i_filmcamera a span, .i_filmcamera{ background-image: url(../images/icons/dark/filmcamera.png);} nav ul li.i_finish_flag a span, .i_finish_flag{ background-image: url(../images/icons/dark/finish_flag.png);} nav ul li.i_firefox a span, .i_firefox{ background-image: url(../images/icons/dark/firefox.png);} nav ul li.i_flag a span, .i_flag{ background-image: url(../images/icons/dark/flag.png);} nav ul li.i_flag_2 a span, .i_flag_2{ background-image: url(../images/icons/dark/flag_2.png);} nav ul li.i_folder a span, .i_folder{ background-image: url(../images/icons/dark/folder.png);} nav ul li.i_folder_add a span, .i_folder_add{ background-image: url(../images/icons/dark/folder_add.png);} nav ul li.i_folder_closed a span, .i_folder_closed{ background-image: url(../images/icons/dark/folder_closed.png);} nav ul li.i_folder_delete a span, .i_folder_delete{ background-image: url(../images/icons/dark/folder_delete.png);} nav ul li.i_folder_download a span, .i_folder_download{ background-image: url(../images/icons/dark/folder_download.png);} nav ul li.i_folder_lock a span, .i_folder_lock{ background-image: url(../images/icons/dark/folder_lock.png);} nav ul li.i_folder_love a span, .i_folder_love{ background-image: url(../images/icons/dark/folder_love.png);} nav ul li.i_folder_upload a span, .i_folder_upload{ background-image: url(../images/icons/dark/folder_upload.png);} nav ul li.i_footprint a span, .i_footprint{ background-image: url(../images/icons/dark/footprint.png);} nav ul li.i_forward a span, .i_forward{ background-image: url(../images/icons/dark/forward.png);} nav ul li.i_fountain_pen a span, .i_fountain_pen{ background-image: url(../images/icons/dark/fountain_pen.png);} nav ul li.i_frames a span, .i_frames{ background-image: url(../images/icons/dark/frames.png);} nav ul li.i_fullscreen a span, .i_fullscreen{ background-image: url(../images/icons/dark/fullscreen.png);} nav ul li.i_globe a span, .i_globe{ background-image: url(../images/icons/dark/globe.png);} nav ul li.i_globe_2 a span, .i_globe_2{ background-image: url(../images/icons/dark/globe_2.png);} nav ul li.i_google_buzz a span, .i_google_buzz{ background-image: url(../images/icons/dark/google_buzz.png);} nav ul li.i_google_maps a span, .i_google_maps{ background-image: url(../images/icons/dark/google_maps.png);} nav ul li.i_graph a span, .i_graph{ background-image: url(../images/icons/dark/graph.png);} nav ul li.i_grid a span, .i_grid{ background-image: url(../images/icons/dark/grid.png);} nav ul li.i_hd a span, .i_hd{ background-image: url(../images/icons/dark/hd.png);} nav ul li.i_hd_2 a span, .i_hd_2{ background-image: url(../images/icons/dark/hd_2.png);} nav ul li.i_hd_3 a span, .i_hd_3{ background-image: url(../images/icons/dark/hd_3.png);} nav ul li.i_headphones a span, .i_headphones{ background-image: url(../images/icons/dark/headphones.png);} nav ul li.i_help a span, .i_help{ background-image: url(../images/icons/dark/help.png);} nav ul li.i_house a span, .i_house{ background-image: url(../images/icons/dark/house.png);} nav ul li.i_house_2 a span, .i_house_2{ background-image: url(../images/icons/dark/house_2.png);} nav ul li.i_ice_cream a span, .i_ice_cream{ background-image: url(../images/icons/dark/ice_cream.png);} nav ul li.i_ice_cream_2 a span, .i_ice_cream_2{ background-image: url(../images/icons/dark/ice_cream_2.png);} nav ul li.i_ichat a span, .i_ichat{ background-image: url(../images/icons/dark/ichat.png);} nav ul li.i_imac a span, .i_imac{ background-image: url(../images/icons/dark/imac.png);} nav ul li.i_image a span, .i_image{ background-image: url(../images/icons/dark/image.png);} nav ul li.i_image_2 a span, .i_image_2{ background-image: url(../images/icons/dark/image_2.png);} nav ul li.i_images a span, .i_images{ background-image: url(../images/icons/dark/images.png);} nav ul li.i_images_2 a span, .i_images_2{ background-image: url(../images/icons/dark/images_2.png);} nav ul li.i_inbox a span, .i_inbox{ background-image: url(../images/icons/dark/inbox.png);} nav ul li.i_incomming a span, .i_incomming{ background-image: url(../images/icons/dark/incomming.png);} nav ul li.i_information a span, .i_information{ background-image: url(../images/icons/dark/information.png);} nav ul li.i_ipad a span, .i_ipad{ background-image: url(../images/icons/dark/ipad.png);} nav ul li.i_iphone_3g a span, .i_iphone_3g{ background-image: url(../images/icons/dark/iphone_3g.png);} nav ul li.i_iphone_4 a span, .i_iphone_4{ background-image: url(../images/icons/dark/iphone_4.png);} nav ul li.i_ipod a span, .i_ipod{ background-image: url(../images/icons/dark/ipod.png);} nav ul li.i_ipod_nano a span, .i_ipod_nano{ background-image: url(../images/icons/dark/ipod_nano.png);} nav ul li.i_joomla a span, .i_joomla{ background-image: url(../images/icons/dark/joomla.png);} nav ul li.i_key a span, .i_key{ background-image: url(../images/icons/dark/key.png);} nav ul li.i_key_2 a span, .i_key_2{ background-image: url(../images/icons/dark/key_2.png);} nav ul li.i_ladys_purse a span, .i_ladys_purse{ background-image: url(../images/icons/dark/ladys_purse.png);} nav ul li.i_lamp a span, .i_lamp{ background-image: url(../images/icons/dark/lamp.png);} nav ul li.i_laptop a span, .i_laptop{ background-image: url(../images/icons/dark/laptop.png);} nav ul li.i_lastfm a span, .i_lastfm{ background-image: url(../images/icons/dark/lastfm.png);} nav ul li.i_lemonade_stand a span, .i_lemonade_stand{ background-image: url(../images/icons/dark/lemonade_stand.png);} nav ul li.i_light_bulb a span, .i_light_bulb{ background-image: url(../images/icons/dark/light_bulb.png);} nav ul li.i_link a span, .i_link{ background-image: url(../images/icons/dark/link.png);} nav ul li.i_link_2 a span, .i_link_2{ background-image: url(../images/icons/dark/link_2.png);} nav ul li.i_linux a span, .i_linux{ background-image: url(../images/icons/dark/linux.png);} nav ul li.i_list a span, .i_list{ background-image: url(../images/icons/dark/list.png);} nav ul li.i_list_image a span, .i_list_image{ background-image: url(../images/icons/dark/list_image.png);} nav ul li.i_list_images a span, .i_list_images{ background-image: url(../images/icons/dark/list_images.png);} nav ul li.i_loading_bar a span, .i_loading_bar{ background-image: url(../images/icons/dark/loading_bar.png);} nav ul li.i_locked a span, .i_locked{ background-image: url(../images/icons/dark/locked.png);} nav ul li.i_locked_2 a span, .i_locked_2{ background-image: url(../images/icons/dark/locked_2.png);} nav ul li.i_macos a span, .i_macos{ background-image: url(../images/icons/dark/macos.png);} nav ul li.i_magic_mouse a span, .i_magic_mouse{ background-image: url(../images/icons/dark/magic_mouse.png);} nav ul li.i_magnifying_glass a span, .i_magnifying_glass{ background-image: url(../images/icons/dark/magnifying_glass.png);} nav ul li.i_mail a span, .i_mail{ background-image: url(../images/icons/dark/mail.png);} nav ul li.i_male a span, .i_male{ background-image: url(../images/icons/dark/male.png);} nav ul li.i_male_contour a span, .i_male_contour{ background-image: url(../images/icons/dark/male_contour.png);} nav ul li.i_map a span, .i_map{ background-image: url(../images/icons/dark/map.png);} nav ul li.i_marker a span, .i_marker{ background-image: url(../images/icons/dark/marker.png);} nav ul li.i_maximize a span, .i_maximize{ background-image: url(../images/icons/dark/maximize.png);} nav ul li.i_medical_case a span, .i_medical_case{ background-image: url(../images/icons/dark/medical_case.png);} nav ul li.i_megaphone a span, .i_megaphone{ background-image: url(../images/icons/dark/megaphone.png);} nav ul li.i_microphone a span, .i_microphone{ background-image: url(../images/icons/dark/microphone.png);} nav ul li.i_mighty_mouse a span, .i_mighty_mouse{ background-image: url(../images/icons/dark/mighty_mouse.png);} nav ul li.i_minimize a span, .i_minimize{ background-image: url(../images/icons/dark/minimize.png);} nav ul li.i_minus a span, .i_minus{ background-image: url(../images/icons/dark/minus.png);} nav ul li.i_mobile_phone a span, .i_mobile_phone{ background-image: url(../images/icons/dark/mobile_phone.png);} nav ul li.i_mobypicture a span, .i_mobypicture{ background-image: url(../images/icons/dark/mobypicture.png);} nav ul li.i_money a span, .i_money{ background-image: url(../images/icons/dark/money.png);} nav ul li.i_money_2 a span, .i_money_2{ background-image: url(../images/icons/dark/money_2.png);} nav ul li.i_monitor a span, .i_monitor{ background-image: url(../images/icons/dark/monitor.png);} nav ul li.i_mouse a span, .i_mouse{ background-image: url(../images/icons/dark/mouse.png);} nav ul li.i_myspace a span, .i_myspace{ background-image: url(../images/icons/dark/myspace.png);} nav ul li.i_next a span, .i_next{ background-image: url(../images/icons/dark/next.png);} nav ul li.i_note_book a span, .i_note_book{ background-image: url(../images/icons/dark/note_book.png);} nav ul li.i_outgoing a span, .i_outgoing{ background-image: url(../images/icons/dark/outgoing.png);} nav ul li.i_pacman a span, .i_pacman{ background-image: url(../images/icons/dark/pacman.png);} nav ul li.i_pacman_ghost a span, .i_pacman_ghost{ background-image: url(../images/icons/dark/pacman_ghost.png);} nav ul li.i_paint_brush a span, .i_paint_brush{ background-image: url(../images/icons/dark/paint_brush.png);} nav ul li.i_pants a span, .i_pants{ background-image: url(../images/icons/dark/pants.png);} nav ul li.i_paperclip a span, .i_paperclip{ background-image: url(../images/icons/dark/paperclip.png);} nav ul li.i_paste a span, .i_paste{ background-image: url(../images/icons/dark/paste.png);} nav ul li.i_pause a span, .i_pause{ background-image: url(../images/icons/dark/pause.png);} nav ul li.i_paypal a span, .i_paypal{ background-image: url(../images/icons/dark/paypal.png);} nav ul li.i_paypal_2 a span, .i_paypal_2{ background-image: url(../images/icons/dark/paypal_2.png);} nav ul li.i_paypal_3 a span, .i_paypal_3{ background-image: url(../images/icons/dark/paypal_3.png);} nav ul li.i_pdf_document a span, .i_pdf_document{ background-image: url(../images/icons/dark/pdf_document.png);} nav ul li.i_pdf_documents a span, .i_pdf_documents{ background-image: url(../images/icons/dark/pdf_documents.png);} nav ul li.i_pencil a span, .i_pencil{ background-image: url(../images/icons/dark/pencil.png);} nav ul li.i_phone a span, .i_phone{ background-image: url(../images/icons/dark/phone.png);} nav ul li.i_phone_2 a span, .i_phone_2{ background-image: url(../images/icons/dark/phone_2.png);} nav ul li.i_phone_hook a span, .i_phone_hook{ background-image: url(../images/icons/dark/phone_hook.png);} nav ul li.i_piggy_bank a span, .i_piggy_bank{ background-image: url(../images/icons/dark/piggy_bank.png);} nav ul li.i_plane_suitecase a span, .i_plane_suitecase{ background-image: url(../images/icons/dark/plane_suitecase.png);} nav ul li.i_play a span, .i_play{ background-image: url(../images/icons/dark/play.png);} nav ul li.i_plixi a span, .i_plixi{ background-image: url(../images/icons/dark/plixi.png);} nav ul li.i_plus a span, .i_plus{ background-image: url(../images/icons/dark/plus.png);} nav ul li.i_post_card a span, .i_post_card{ background-image: url(../images/icons/dark/post_card.png);} nav ul li.i_power a span, .i_power{ background-image: url(../images/icons/dark/power.png);} nav ul li.i_powerpoint_document a span, .i_powerpoint_document{ background-image: url(../images/icons/dark/powerpoint_document.png);} nav ul li.i_powerpoint_documents a span, .i_powerpoint_documents{ background-image: url(../images/icons/dark/powerpoint_documents.png);} nav ul li.i_presentation a span, .i_presentation{ background-image: url(../images/icons/dark/presentation.png);} nav ul li.i_prev a span, .i_prev{ background-image: url(../images/icons/dark/prev.png);} nav ul li.i_preview a span, .i_preview{ background-image: url(../images/icons/dark/preview.png);} nav ul li.i_price_tag a span, .i_price_tag{ background-image: url(../images/icons/dark/price_tag.png);} nav ul li.i_price_tags a span, .i_price_tags{ background-image: url(../images/icons/dark/price_tags.png);} nav ul li.i_printer a span, .i_printer{ background-image: url(../images/icons/dark/printer.png);} nav ul li.i_question a span, .i_question{ background-image: url(../images/icons/dark/question.png);} nav ul li.i_radio a span, .i_radio{ background-image: url(../images/icons/dark/radio.png);} nav ul li.i_record a span, .i_record{ background-image: url(../images/icons/dark/record.png);} nav ul li.i_recycle a span, .i_recycle{ background-image: url(../images/icons/dark/recycle.png);} nav ul li.i_refresh a span, .i_refresh{ background-image: url(../images/icons/dark/refresh.png);} nav ul li.i_refresh_2 a span, .i_refresh_2{ background-image: url(../images/icons/dark/refresh_2.png);} nav ul li.i_refresh_3 a span, .i_refresh_3{ background-image: url(../images/icons/dark/refresh_3.png);} nav ul li.i_refresh_4 a span, .i_refresh_4{ background-image: url(../images/icons/dark/refresh_4.png);} nav ul li.i_repeat a span, .i_repeat{ background-image: url(../images/icons/dark/repeat.png);} nav ul li.i_rewind a span, .i_rewind{ background-image: url(../images/icons/dark/rewind.png);} nav ul li.i_robot a span, .i_robot{ background-image: url(../images/icons/dark/robot.png);} nav ul li.i_rss a span, .i_rss{ background-image: url(../images/icons/dark/rss.png);} nav ul li.i_ruler a span, .i_ruler{ background-image: url(../images/icons/dark/ruler.png);} nav ul li.i_ruler_2 a span, .i_ruler_2{ background-image: url(../images/icons/dark/ruler_2.png);} nav ul li.i_running_man a span, .i_running_man{ background-image: url(../images/icons/dark/running_man.png);} nav ul li.i_safari a span, .i_safari{ background-image: url(../images/icons/dark/safari.png);} nav ul li.i_scan_label a span, .i_scan_label{ background-image: url(../images/icons/dark/scan_label.png);} nav ul li.i_scissors a span, .i_scissors{ background-image: url(../images/icons/dark/scissors.png);} nav ul li.i_sd a span, .i_sd{ background-image: url(../images/icons/dark/sd.png);} nav ul li.i_sd_2 a span, .i_sd_2{ background-image: url(../images/icons/dark/sd_2.png);} nav ul li.i_sd_3 a span, .i_sd_3{ background-image: url(../images/icons/dark/sd_3.png);} nav ul li.i_settings a span, .i_settings{ background-image: url(../images/icons/dark/settings.png);} nav ul li.i_settings_2 a span, .i_settings_2{ background-image: url(../images/icons/dark/settings_2.png);} nav ul li.i_shopping_bag a span, .i_shopping_bag{ background-image: url(../images/icons/dark/shopping_bag.png);} nav ul li.i_shopping_basket a span, .i_shopping_basket{ background-image: url(../images/icons/dark/shopping_basket.png);} nav ul li.i_shopping_basket_2 a span, .i_shopping_basket_2{ background-image: url(../images/icons/dark/shopping_basket_2.png);} nav ul li.i_shopping_cart a span, .i_shopping_cart{ background-image: url(../images/icons/dark/shopping_cart.png);} nav ul li.i_shopping_cart_2 a span, .i_shopping_cart_2{ background-image: url(../images/icons/dark/shopping_cart_2.png);} nav ul li.i_shopping_cart_3 a span, .i_shopping_cart_3{ background-image: url(../images/icons/dark/shopping_cart_3.png);} nav ul li.i_shopping_cart_4 a span, .i_shopping_cart_4{ background-image: url(../images/icons/dark/shopping_cart_4.png);} nav ul li.i_shuffle a span, .i_shuffle{ background-image: url(../images/icons/dark/shuffle.png);} nav ul li.i_sign_post a span, .i_sign_post{ background-image: url(../images/icons/dark/sign_post.png);} nav ul li.i_skype a span, .i_skype{ background-image: url(../images/icons/dark/skype.png);} nav ul li.i_sleeveless_shirt a span, .i_sleeveless_shirt{ background-image: url(../images/icons/dark/sleeveless_shirt.png);} nav ul li.i_socks a span, .i_socks{ background-image: url(../images/icons/dark/socks.png);} nav ul li.i_sound a span, .i_sound{ background-image: url(../images/icons/dark/sound.png);} nav ul li.i_speech_bubble a span, .i_speech_bubble{ background-image: url(../images/icons/dark/speech_bubble.png);} nav ul li.i_speech_bubble_2 a span, .i_speech_bubble_2{ background-image: url(../images/icons/dark/speech_bubble_2.png);} nav ul li.i_speech_bubbles a span, .i_speech_bubbles{ background-image: url(../images/icons/dark/speech_bubbles.png);} nav ul li.i_speech_bubbles_2 a span, .i_speech_bubbles_2{ background-image: url(../images/icons/dark/speech_bubbles_2.png);} nav ul li.i_sport_shirt a span, .i_sport_shirt{ background-image: url(../images/icons/dark/sport_shirt.png);} nav ul li.i_stop a span, .i_stop{ background-image: url(../images/icons/dark/stop.png);} nav ul li.i_stop_watch a span, .i_stop_watch{ background-image: url(../images/icons/dark/stop_watch.png);} nav ul li.i_strategy a span, .i_strategy{ background-image: url(../images/icons/dark/strategy.png);} nav ul li.i_strategy_2 a span, .i_strategy_2{ background-image: url(../images/icons/dark/strategy_2.png);} nav ul li.i_stubleupon a span, .i_stubleupon{ background-image: url(../images/icons/dark/stubleupon.png);} nav ul li.i_suitecase a span, .i_suitecase{ background-image: url(../images/icons/dark/suitecase.png);} nav ul li.i_sweater a span, .i_sweater{ background-image: url(../images/icons/dark/sweater.png);} nav ul li.i_t-shirt a span, .i_t-shirt{ background-image: url(../images/icons/dark/t-shirt.png);} nav ul li.i_table a span, .i_table{ background-image: url(../images/icons/dark/table.png);} nav ul li.i_tag a span, .i_tag{ background-image: url(../images/icons/dark/tag.png);} nav ul li.i_tags a span, .i_tags{ background-image: url(../images/icons/dark/tags.png);} nav ul li.i_television a span, .i_television{ background-image: url(../images/icons/dark/television.png);} nav ul li.i_tick a span, .i_tick{ background-image: url(../images/icons/dark/tick.png);} nav ul li.i_timer a span, .i_timer{ background-image: url(../images/icons/dark/timer.png);} nav ul li.i_trashcan a span, .i_trashcan{ background-image: url(../images/icons/dark/trashcan.png);} nav ul li.i_trashcan_2 a span, .i_trashcan_2{ background-image: url(../images/icons/dark/trashcan_2.png);} nav ul li.i_travel_suitecase a span, .i_travel_suitecase{ background-image: url(../images/icons/dark/travel_suitecase.png);} nav ul li.i_tree a span, .i_tree{ background-image: url(../images/icons/dark/tree.png);} nav ul li.i_triangle_double_down a span, .i_triangle_double_down{ background-image: url(../images/icons/dark/triangle_double_down.png);} nav ul li.i_triangle_double_left a span, .i_triangle_double_left{ background-image: url(../images/icons/dark/triangle_double_left.png);} nav ul li.i_triangle_double_right a span, .i_triangle_double_right{ background-image: url(../images/icons/dark/triangle_double_right.png);} nav ul li.i_triangle_double_up a span, .i_triangle_double_up{ background-image: url(../images/icons/dark/triangle_double_up.png);} nav ul li.i_triangle_down a span, .i_triangle_down{ background-image: url(../images/icons/dark/triangle_down.png);} nav ul li.i_triangle_down_left a span, .i_triangle_down_left{ background-image: url(../images/icons/dark/triangle_down_left.png);} nav ul li.i_triangle_down_right a span, .i_triangle_down_right{ background-image: url(../images/icons/dark/triangle_down_right.png);} nav ul li.i_triangle_left a span, .i_triangle_left{ background-image: url(../images/icons/dark/triangle_left.png);} nav ul li.i_triangle_left_right a span, .i_triangle_left_right{ background-image: url(../images/icons/dark/triangle_left_right.png);} nav ul li.i_triangle_right a span, .i_triangle_right{ background-image: url(../images/icons/dark/triangle_right.png);} nav ul li.i_triangle_up a span, .i_triangle_up{ background-image: url(../images/icons/dark/triangle_up.png);} nav ul li.i_triangle_up_down a span, .i_triangle_up_down{ background-image: url(../images/icons/dark/triangle_up_down.png);} nav ul li.i_triangle_up_left a span, .i_triangle_up_left{ background-image: url(../images/icons/dark/triangle_up_left.png);} nav ul li.i_triangle_up_right a span, .i_triangle_up_right{ background-image: url(../images/icons/dark/triangle_up_right.png);} nav ul li.i_trolly a span, .i_trolly{ background-image: url(../images/icons/dark/trolly.png);} nav ul li.i_truck a span, .i_truck{ background-image: url(../images/icons/dark/truck.png);} nav ul li.i_tumbler a span, .i_tumbler{ background-image: url(../images/icons/dark/tumbler.png);} nav ul li.i_twitter a span, .i_twitter{ background-image: url(../images/icons/dark/twitter.png);} nav ul li.i_twitter_2 a span, .i_twitter_2{ background-image: url(../images/icons/dark/twitter_2.png);} nav ul li.i_typo a span, .i_typo{ background-image: url(../images/icons/dark/typo.png);} nav ul li.i_umbrella a span, .i_umbrella{ background-image: url(../images/icons/dark/umbrella.png);} nav ul li.i_under_construction a span, .i_under_construction{ background-image: url(../images/icons/dark/under_construction.png);} nav ul li.i_unlocked a span, .i_unlocked{ background-image: url(../images/icons/dark/unlocked.png);} nav ul li.i_upload a span, .i_upload{ background-image: url(../images/icons/dark/upload.png);} nav ul li.i_user a span, .i_user{ background-image: url(../images/icons/dark/user.png);} nav ul li.i_user_2 a span, .i_user_2{ background-image: url(../images/icons/dark/user_2.png);} nav ul li.i_user_comment a span, .i_user_comment{ background-image: url(../images/icons/dark/user_comment.png);} nav ul li.i_users a span, .i_users{ background-image: url(../images/icons/dark/users.png);} nav ul li.i_users_2 a span, .i_users_2{ background-image: url(../images/icons/dark/users_2.png);} nav ul li.i_v-card a span, .i_v-card{ background-image: url(../images/icons/dark/v-card.png);} nav ul li.i_v-card_2 a span, .i_v-card_2{ background-image: url(../images/icons/dark/v-card_2.png);} nav ul li.i_vault a span, .i_vault{ background-image: url(../images/icons/dark/vault.png);} nav ul li.i_vimeo a span, .i_vimeo{ background-image: url(../images/icons/dark/vimeo.png);} nav ul li.i_vimeo_2 a span, .i_vimeo_2{ background-image: url(../images/icons/dark/vimeo_2.png);} nav ul li.i_walking_man a span, .i_walking_man{ background-image: url(../images/icons/dark/walking_man.png);} nav ul li.i_wifi_signal a span, .i_wifi_signal{ background-image: url(../images/icons/dark/wifi_signal.png);} nav ul li.i_wifi_signal_2 a span, .i_wifi_signal_2{ background-image: url(../images/icons/dark/wifi_signal_2.png);} nav ul li.i_windows a span, .i_windows{ background-image: url(../images/icons/dark/windows.png);} nav ul li.i_winner_podium a span, .i_winner_podium{ background-image: url(../images/icons/dark/winner_podium.png);} nav ul li.i_wizard a span, .i_wizard{ background-image: url(../images/icons/dark/wizard.png);} nav ul li.i_word_document a span, .i_word_document{ background-image: url(../images/icons/dark/word_document.png);} nav ul li.i_word_documents a span, .i_word_documents{ background-image: url(../images/icons/dark/word_documents.png);} nav ul li.i_wordpress a span, .i_wordpress{ background-image: url(../images/icons/dark/wordpress.png);} nav ul li.i_wordpress_2 a span, .i_wordpress_2{ background-image: url(../images/icons/dark/wordpress_2.png);} nav ul li.i_youtube a span, .i_youtube{ background-image: url(../images/icons/dark/youtube.png);} nav ul li.i_youtube_2 a span, .i_youtube_2{ background-image: url(../images/icons/dark/youtube_2.png);} nav ul li.i_zip_file a span, .i_zip_file{ background-image: url(../images/icons/dark/zip_file.png);} nav ul li.i_zip_files a span, .i_zip_files{ background-image: url(../images/icons/dark/zip_files.png);}
08102013project
trunk/CMS/Content/themes/base/light/theme.css
CSS
oos
65,484
/* * FullCalendar v1.5.1 Stylesheet * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Sat Apr 9 14:09:51 2011 -0700 * */ .fc { direction: ltr; text-align: left; } .fc table { border-collapse: collapse; border-spacing: 0; } html .fc, .fc table { font-size: 1em; } .fc td, .fc th { padding: 0; vertical-align: top; } /* Header ------------------------------------------------------------------------*/ .fc-header { background:none; margin:0; } .fc-header td { white-space: nowrap; border:0; } .fc-header-left { width: 25%; text-align: left; } .fc-header-center { text-align: center; } .fc-header-right { width: 25%; text-align: right; } .fc-header-title { display: inline-block; vertical-align: top; } .fc-header-title h2 { margin-top: 0; white-space: nowrap; } .fc .fc-header-space { padding-left: 10px; } .fc-header .fc-button { margin-bottom: 1em; vertical-align: top; } /* buttons edges butting together */ .fc-header .fc-button { margin-right: -1px; } .fc-header .fc-corner-right { margin-right: 1px; /* back to normal */ } .fc-header .ui-corner-right { margin-right: 0; /* back to normal */ } /* button layering (for border precedence) */ .fc-header .fc-state-hover, .fc-header .ui-state-hover { z-index: 2; } .fc-header .fc-state-down { z-index: 3; } .fc-header .fc-state-active, .fc-header .ui-state-active { z-index: 4; } /* Content ------------------------------------------------------------------------*/ .fc-content { clear: both; } .fc-view { width: 100%; /* needed for view switching (when view is absolute) */ overflow: hidden; } /* Cell Styles ------------------------------------------------------------------------*/ .fc-widget-header, /* <th>, usually */ .fc-widget-content { /* <td>, usually */ border: 1px solid #ccc; } .fc-state-highlight { /* <td> today cell */ /* TODO: add .fc-today to <th> */ background: #ffc; } .fc-cell-overlay { /* semi-transparent rectangle while dragging */ background: #9cf; opacity: .2; filter: alpha(opacity=20); /* for IE */ } /* Buttons ------------------------------------------------------------------------*/ .fc-button { position: relative; display: inline-block; cursor: pointer; } .fc-state-default { /* non-theme */ border-style: solid; border-width: 1px 0; } .fc-button-inner { position: relative; float: left; overflow: hidden; } .fc-state-default .fc-button-inner { /* non-theme */ border-style: solid; border-width: 0 1px; } .fc-button-content { position: relative; float: left; height: 1.9em; line-height: 1.9em; padding: 0 .6em; white-space: nowrap; } /* icon (for jquery ui) */ .fc-button-content .fc-icon-wrap { position: relative; float: left; top: 50%; } .fc-button-content .ui-icon { position: relative; float: left; margin-top: -50%; *margin-top: 0; *top: -50%; } /* gloss effect */ .fc-state-default .fc-button-effect { position: absolute; top: 50%; left: 0; } .fc-state-default .fc-button-effect span { position: absolute; top: -100px; left: 0; width: 500px; height: 100px; border-width: 100px 0 0 1px; border-style: solid; border-color: #fff; background: #444; opacity: .09; filter: alpha(opacity=9); } /* button states (determines colors) */ .fc-state-default, .fc-state-default .fc-button-inner { border-style: solid; border-color: #ccc #bbb #aaa; background: #F3F3F3; color: #000; } .fc-state-hover, .fc-state-hover .fc-button-inner { border-color: #999; } .fc-state-down, .fc-state-down .fc-button-inner { border-color: #555; background: #777; } .fc-state-active, .fc-state-active .fc-button-inner { border-color: #555; background: #777; color: #fff; } .fc-state-disabled, .fc-state-disabled .fc-button-inner { color: #999; border-color: #ddd; } .fc-state-disabled { cursor: default; } .fc-state-disabled .fc-button-effect { display: none; } /* Global Event Styles ------------------------------------------------------------------------*/ .fc-event { border-style: solid; border-width: 0; font-size: 0.9em; cursor: default; padding:0; } a.fc-event, .fc-event-draggable { cursor: pointer; } a.fc-event { text-decoration: none; } .fc-rtl .fc-event { text-align: right; } .fc-event-skin { background-image:url(../images/bg/08.png); border-color: #ddd; /* default BORDER color */ background-color: #ddd; /* default BACKGROUND color */ color: #444; /* default TEXT color */ text-decoration:none; border-top-color:#fff; } .red .fc-event-skin{ border-color:#F0B7B7; background-color:#F0B7B7; } .green .fc-event-skin{ border-color:#B2E7B2; background-color:#B2E7B2; } .yellow .fc-event-skin{ border-color:#E8E8B3; background-color:#E8E8B3; } .blue .fc-event-skin{ border-color:#B5F0F0; background-color:#B5F0F0; } .fc-event-inner { position: relative; width: 100%; height: 100%; border-style: solid; border-width: 0; overflow: hidden; } .fc-event-time, .fc-event-title { padding: 0 1px; } .fc .ui-resizable-handle { /*** TODO: don't use ui-resizable anymore, change class ***/ display: block; position: absolute; z-index: 99999; overflow: hidden; /* hacky spaces (IE6/7) */ font-size: 300%; /* */ line-height: 50%; /* */ } /* Horizontal Events ------------------------------------------------------------------------*/ .fc-event-hori { border-width: 1px 0; margin-bottom: 1px; } /* resizable */ .fc-event-hori .ui-resizable-e { top: 0 !important; /* importants override pre jquery ui 1.7 styles */ right: -3px !important; width: 7px !important; height: 100% !important; cursor: e-resize; } .fc-event-hori .ui-resizable-w { top: 0 !important; left: -3px !important; width: 7px !important; height: 100% !important; cursor: w-resize; } .fc-event-hori .ui-resizable-handle { _padding-bottom: 14px; /* IE6 had 0 height */ } /* Fake Rounded Corners (for buttons and events) ------------------------------------------------------------*/ .fc-corner-left { margin-left: 1px; } .fc-corner-left .fc-button-inner, .fc-corner-left .fc-event-inner { margin-left: -1px; } .fc-corner-right { margin-right: 1px; } .fc-corner-right .fc-button-inner, .fc-corner-right .fc-event-inner { margin-right: -1px; } .fc-corner-top { margin-top: 1px; } .fc-corner-top .fc-event-inner { margin-top: -1px; } .fc-corner-bottom { margin-bottom: 1px; } .fc-corner-bottom .fc-event-inner { margin-bottom: -1px; } /* Fake Rounded Corners SPECIFICALLY FOR EVENTS -----------------------------------------------------------------*/ .fc-corner-left .fc-event-inner { border-left-width: 1px; } .fc-corner-right .fc-event-inner { border-right-width: 1px; } .fc-corner-top .fc-event-inner { border-top-width: 1px; } .fc-corner-bottom .fc-event-inner { border-bottom-width: 1px; } /* Reusable Separate-border Table ------------------------------------------------------------*/ table.fc-border-separate { border-collapse: separate; } .fc-border-separate th, .fc-border-separate td { border-width: 1px 0 0 1px; } .fc-border-separate th.fc-last, .fc-border-separate td.fc-last { border-right-width: 1px; } .fc-border-separate tr.fc-last th, .fc-border-separate tr.fc-last td { border-bottom-width: 1px; } .fc-border-separate tbody tr.fc-first td, .fc-border-separate tbody tr.fc-first th { border-top-width: 0; } /* Month View, Basic Week View, Basic Day View ------------------------------------------------------------------------*/ .fc-grid th { text-align: center; } .fc-grid .fc-day-number { float: right; padding: 0 2px; } .fc-grid .fc-other-month .fc-day-number { opacity: 0.3; filter: alpha(opacity=30); /* for IE */ /* opacity with small font can sometimes look too faded might want to set the 'color' property instead making day-numbers bold also fixes the problem */ } .fc-grid .fc-day-content { clear: both; padding: 2px 2px 1px; /* distance between events and day edges */ } /* event styles */ .fc-grid .fc-event-time { font-weight: bold; } /* right-to-left */ .fc-rtl .fc-grid .fc-day-number { float: left; } .fc-rtl .fc-grid .fc-event-time { float: right; } /* Agenda Week View, Agenda Day View ------------------------------------------------------------------------*/ .fc-agenda table { border-collapse: separate; } .fc-agenda-days th { text-align: center; } .fc-agenda .fc-agenda-axis { width: 50px; padding: 0 4px; vertical-align: middle; text-align: right; white-space: nowrap; font-weight: normal; } .fc-agenda .fc-day-content { padding: 2px 2px 1px; } /* make axis border take precedence */ .fc-agenda-days .fc-agenda-axis { border-right-width: 1px; } .fc-agenda-days .fc-col0 { border-left-width: 0; } /* all-day area */ .fc-agenda-allday th { border-width: 0 1px; } .fc-agenda-allday .fc-day-content { min-height: 34px; /* TODO: doesnt work well in quirksmode */ _height: 34px; } /* divider (between all-day and slots) */ .fc-agenda-divider-inner { height: 2px; overflow: hidden; } .fc-widget-header .fc-agenda-divider-inner { background: #eee; } /* slot rows */ .fc-agenda-slots th { border-width: 1px 1px 0; } .fc-agenda-slots td { border-width: 1px 0 0; background: none; } .fc-agenda-slots td div { height: 20px; } .fc-agenda-slots tr.fc-slot0 th, .fc-agenda-slots tr.fc-slot0 td { border-top-width: 0; } .fc-agenda-slots tr.fc-minor th, .fc-agenda-slots tr.fc-minor td { border-top-style: dotted; } .fc-agenda-slots tr.fc-minor th.ui-widget-header { *border-top-style: solid; /* doesn't work with background in IE6/7 */ } /* Vertical Events ------------------------------------------------------------------------*/ .fc-event-vert { border-width: 0 1px; } .fc-event-vert .fc-event-head, .fc-event-vert .fc-event-content { position: relative; z-index: 2; width: 100%; overflow: hidden; } .fc-event-vert .fc-event-time { white-space: nowrap; font-size: 10px; } .fc-event-vert .fc-event-bg { /* makes the event lighter w/ a semi-transparent overlay */ position: absolute; z-index: 1; top: 0; left: 0; width: 100%; height: 100%; background: #fff; opacity: .3; filter: alpha(opacity=30); } .fc .ui-draggable-dragging .fc-event-bg, /* TODO: something nicer like .fc-opacity */ .fc-select-helper .fc-event-bg { display: none\9; /* for IE6/7/8. nested opacity filters while dragging don't work */ } /* resizable */ .fc-event-vert .ui-resizable-s { bottom: 0 !important; /* importants override pre jquery ui 1.7 styles */ width: 100% !important; height: 8px !important; overflow: hidden !important; line-height: 8px !important; font-size: 11px !important; font-family: monospace; text-align: center; cursor: s-resize; } .fc-agenda .ui-resizable-resizing { /* TODO: better selector */ _overflow: hidden; }
08102013project
trunk/CMS/Content/themes/base/dark/jquery.fullcalendar.css
CSS
oos
11,800
/*----------------------------------------------------------------------*/ /* This is the styling of the html container /*----------------------------------------------------------------------*/ @import 'http://fonts.googleapis.com/css?family=PT+Sans:regular,bold'; /*----------------------------------------------------------------------*/ /* Reset /*----------------------------------------------------------------------*/ html,body,div,span,applet,object,iframe,input,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{ margin:0; padding:0; border:0; outline:0; font-weight:100; font-style:inherit; font-size:100%; font-family:inherit; vertical-align:baseline; } *{ -webkit-text-size-adjust:none; -webkit-tap-highlight-color:rgba(0,0,0,0); } /*----------------------------------------------------------------------*/ /* Font Declaration /*----------------------------------------------------------------------*/ html{ font-family:'PT Sans', sans-serif; } code, pre{ font-family:"Courier New", Courier, monospace; } html, body { margin:0; cursor:text; margin:6px 2px; line-height:18px; font-size:13px; color:#6F6F6F; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } html{ margin:0; background-color:#2e2e33; height:100%; min-height:100%; -webkit-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); } em{ font-style:italic; } strong, b{ font-weight:700; } big{ font-size:larger; } small{ font-size:smaller; } ::-moz-selection{ background:#287e84; color:#cacaca; text-shadow:none; } ::selection { background:#287e84; color:#cacaca; text-shadow:none; } a { color:#287e84; } h1, h2, h3, h4, h5, h6{ font-weight:700; color:#777; } h1{ font-size:30px; margin:9px 0; line-height:36px; } h2{ font-size:20px; margin:9px 0 7px; line-height:18px; } h3{ font-size:18px; margin:12px 0 6px; line-height:18px; } h4{ font-size:16px; font-weight:100; margin:15px 0 3px; } h5{ font-size:14px; margin:18px 0 2px; } h6{ font-size:14px; font-weight:100; margin:18px 0 2px; } p, ul, ol{ margin-top:9px; margin-bottom:9px; line-height:18px; font-size:12px; } ul, ol{ margin-left:18px; list-style-type:square; } table{ width:100%; border-collapse:collapse; margin-bottom:18px; background-image:url(images/paper_02.png); } table td{ border:1px solid; border-color:#DDDDDD #E7E7E7 #DDDDDD #E7E7E7; padding:6px 3px; text-align:center; }
08102013project
trunk/CMS/Content/themes/base/dark/editor.css
CSS
oos
2,816
/* * File: demo_table.css * CVS: $Id$ * Description: CSS descriptions for DataTables demo pages * Author: Allan Jardine * Created: Tue May 12 06:47:22 BST 2009 * Modified: $Date$ by $Author$ * Language: CSS * Project: DataTables * * Copyright 2009 Allan Jardine. All Rights Reserved. * * *************************************************************************** * DESCRIPTION * * The styles given here are suitable for the demos that are used with the standard DataTables * distribution (see www.datatables.net). You will most likely wish to modify these styles to * meet the layout requirements of your site. * * Common issues: * 'full_numbers' pagination - I use an extra selector on the body tag to ensure that there is * no conflict between the two pagination types. If you want to use full_numbers pagination * ensure that you either have "example_alt_pagination" as a body class name, or better yet, * modify that selector. * Note that the path used for Images is relative. All images are by default located in * ../images/ - relative to this CSS file. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables features */ .dataTables_wrapper { position: relative; min-height: 302px; clear: both; _height: 302px; zoom: 1; /* Feeling sorry for IE */ } .dataTables_processing { position: absolute; top: 50%; left: 50%; width: 250px; height: 30px; margin-left: -125px; margin-top: -15px; padding: 14px 0 2px 0; border: 1px solid #ddd; text-align: center; color: #999; font-size: 14px; background-color: white; } .dataTables_length { float:left; width: 40%; vertical-align:top; } .dataTables_length label { height:40px; line-height:10px; vertical-align:top; display:inline-block; } .dataTable_length .selector{ margin-top:20px; } .dataTables_filter { width: 50%; float: right; text-align: right; } .datatable{ clear:both; } .dataTables_filter input{ width:auto; margin-bottom:4px; } .dataTables_info { width: 60%; float: left; } .dataTables_paginate { width: 44px; * width: 50px; float: right; text-align: right; } /* Pagination nested */ .paginate_disabled_previous, .paginate_enabled_previous, .paginate_disabled_next, .paginate_enabled_next { height: 19px; width: 19px; margin-left: 3px; float: left; } .paginate_disabled_previous { background-image: url(../images/icons/dark/triangle_left.png); } .paginate_enabled_previous { background-image: url(../images/icons/dark/triangle_left.png); } .paginate_disabled_next { background-image: url(../images/icons/dark/triangle_right.png); } .paginate_enabled_next { background-image: url(../images/icons/dark/triangle_right.png); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables display */ table.display { margin: 0 auto; clear: both; width: 100%; /* Note Firefox 3.5 and before have a bug with border-collapse * ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 ) * border-spacing: 0; is one possible option. Conditional-css.com is * useful for this kind of thing * * Further note IE 6/7 has problems when calculating widths with border width. * It subtracts one px relative to the other browsers from the first column, and * adds one to the end... * * If you want that effect I'd suggest setting a border-top/left on th/td's and * then filling in the gaps with other borders. */ } table.display thead th { padding: 3px 18px 3px 10px; border-bottom: 1px solid black; font-weight: bold; cursor: pointer; * cursor: hand; } table.display tfoot th { padding: 3px 18px 3px 10px; border-top: 1px solid black; font-weight: bold; } table.display tr.heading2 td { border-bottom: 1px solid #aaa; } table.display td { padding: 3px 10px; } table.display td.center { text-align: center; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables sorting */ .sorting_asc { background: url(../images/icons/dark/triangle_up.png) no-repeat center right; } .sorting_desc { background: url(../images/icons/dark/triangle_down.png) no-repeat center right; } .sorting { background: url(../images/icons/dark/triangle_up_down.png) no-repeat center right; } .sorting_asc_disabled { background: url(../images/icons/dark/triangle_up.png) no-repeat center right; } .sorting_desc_disabled { background: url(../images/icons/dark/triangle_down.png) no-repeat center right; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * DataTables row classes */ table.display tr.odd.gradeA { background-color: #ddffdd; } table.display tr.even.gradeA { background-color: #eeffee; } table.display tr.odd.gradeC { background-color: #ddddff; } table.display tr.even.gradeC { background-color: #eeeeff; } table.display tr.odd.gradeX { background-color: #ffdddd; } table.display tr.even.gradeX { background-color: #ffeeee; } table.display tr.odd.gradeU { background-color: #ddd; } table.display tr.even.gradeU { background-color: #eee; } tr.odd { background-color: #2e2e33; } tr.even { background-color: #3333333; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Misc */ .dataTables_scroll { clear: both; } .dataTables_scrollBody { *margin-top: -1px; } .top, .bottom { padding: 15px; background-color: #F5F5F5; border: 1px solid #CCCCCC; } .top .dataTables_info { float: none; } .clear { clear: both; } .dataTables_empty { text-align: center; } tfoot input { margin: 0.5em 0; width: 100%; color: #444; } tfoot input.search_init { color: #999; } td.group { background-color: #d1cfd0; border-bottom: 2px solid #A19B9E; border-top: 2px solid #A19B9E; } td.details { background-color: #d1cfd0; border: 2px solid #A19B9E; } .example_alt_pagination div.dataTables_info { width: 40%; } .paging_full_numbers { width: 400px; height: 22px; line-height: 22px; } .paging_full_numbers span.paginate_button, .paging_full_numbers span.paginate_active { border: 1px solid #aaa; -webkit-border-radius: 5px; -moz-border-radius: 5px; padding: 2px 5px; margin: 0 3px; cursor: pointer; *cursor: hand; } .paging_full_numbers span.paginate_button { background-color: #ddd; } .paging_full_numbers span.paginate_button:hover { background-color: #ccc; } .paging_full_numbers span.paginate_active { background-color: #99B3FF; } table.display tr.even.row_selected td { background-color: #B0BED9; } table.display tr.odd.row_selected td { background-color: #9FAFD1; } /* * Sorting classes for columns */ /* For the standard odd/even */ tr.odd td.sorting_1 { background-color: #731717; } tr.odd td.sorting_2 { background-color: #357317; } tr.odd td.sorting_3 { background-color: #736e17; } tr.even td.sorting_1 { background-color: #8c1c1c; } tr.even td.sorting_2 { background-color: #418c1c; } tr.even td.sorting_3 { background-color: #8c871c; } /* For the Conditional-CSS grading rows */ /* Colour calculations (based off the main row colours) Level 1: dd > c4 ee > d5 Level 2: dd > d1 ee > e2 */ /* #731717 #8c1c1c red /* #357317 #418c1c green /* #736e17 #8c871c yellow /* #176d73 #1c858c blue /* #731771 #8c1c8b pink /* #491773 #581c8c purple */ tr.odd.gradeA td.sorting_1 { background-color: #357317; } tr.odd.gradeA td.sorting_2 { background-color: #d1ffd1; } tr.odd.gradeA td.sorting_3 { background-color: #d1ffd1; } tr.even.gradeA td.sorting_1 { background-color: #418c1c; } tr.even.gradeA td.sorting_2 { background-color: #e2ffe2; } tr.even.gradeA td.sorting_3 { background-color: #e2ffe2; } tr.odd.gradeC td.sorting_1 { background-color: #c4c4ff; } tr.odd.gradeC td.sorting_2 { background-color: #d1d1ff; } tr.odd.gradeC td.sorting_3 { background-color: #d1d1ff; } tr.even.gradeC td.sorting_1 { background-color: #d5d5ff; } tr.even.gradeC td.sorting_2 { background-color: #e2e2ff; } tr.even.gradeC td.sorting_3 { background-color: #e2e2ff; } tr.odd.gradeX td.sorting_1 { background-color: #ffc4c4; } tr.odd.gradeX td.sorting_2 { background-color: #ffd1d1; } tr.odd.gradeX td.sorting_3 { background-color: #ffd1d1; } tr.even.gradeX td.sorting_1 { background-color: #731717; } tr.even.gradeX td.sorting_2 { background-color: #8c1c1c; } tr.even.gradeX td.sorting_3 { background-color: #ffe2e2; } tr.odd.gradeU td.sorting_1 { background-color: #c4c4c4; } tr.odd.gradeU td.sorting_2 { background-color: #d1d1d1; } tr.odd.gradeU td.sorting_3 { background-color: #d1d1d1; } tr.even.gradeU td.sorting_1 { background-color: #d5d5d5; } tr.even.gradeU td.sorting_2 { background-color: #e2e2e2; } tr.even.gradeU td.sorting_3 { background-color: #e2e2e2; } /* * Row highlighting example */ .ex_highlight #example tbody tr.even:hover, #example tbody tr.even td.highlighted { background-color: #ECFFB3; } .ex_highlight #example tbody tr.odd:hover, #example tbody tr.odd td.highlighted { background-color: #E6FF99; } .ex_highlight_row #example tr.even:hover { background-color: #ECFFB3; } .ex_highlight_row #example tr.even:hover td.sorting_1 { background-color: #DDFF75; } .ex_highlight_row #example tr.even:hover td.sorting_2 { background-color: #E7FF9E; } .ex_highlight_row #example tr.even:hover td.sorting_3 { background-color: #E2FF89; } .ex_highlight_row #example tr.odd:hover { background-color: #E6FF99; } .ex_highlight_row #example tr.odd:hover td.sorting_1 { background-color: #D6FF5C; } .ex_highlight_row #example tr.odd:hover td.sorting_2 { background-color: #E0FF84; } .ex_highlight_row #example tr.odd:hover td.sorting_3 { background-color: #DBFF70; } /* * KeyTable */ table.KeyTable td { border: 3px solid transparent; } table.KeyTable td.focus { border: 3px solid #3366FF; } table.display tr.gradeA { background-color: #eeffee; } table.display tr.gradeC { background-color: #ddddff; } table.display tr.gradeX { background-color: #ffdddd; } table.display tr.gradeU { background-color: #ddd; } div.box { height: 100px; padding: 10px; overflow: auto; border: 1px solid #8080FF; background-color: #E5E5FF; }
08102013project
trunk/CMS/Content/themes/base/dark/jquery.datatables.css
CSS
oos
10,759
/*----------------------------------------------------------------------*/ /* Tipsy Tooltips /*----------------------------------------------------------------------*/ .tipsy-north {background-position:top center;} .tipsy-south {background-position:bottom center;} .tipsy-east {background-position:right center;} .tipsy-west {background-position:left center;} .tipsy { padding:5px; font-size:11px; position:absolute; z-index:100000; } .tipsy-inner { padding:4px 8px; border-top:1px solid #333; text-shadow:0 1px 0 #fff; color:#000; max-width:220px; text-align:left; background-image:url(../images/bg/08.png); background-color:#f1f1f1; background-color:rgba(241,241,241,0.9); -webkit-box-shadow:inset 0 7px 5px rgba(204, 204, 204, 0.1); -moz-box-shadow:inset 0 7px 5px rgba(204, 204, 204, 0.1); box-shadow:inset 0 7px 5px rgba(204, 204, 204, 0.3); text-align:center; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .tipsy-outer { border:0; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; } .tipsy-arrow { position:absolute; background-repeat:no-repeat; background-image:url(images/tipsy.gif); width:9px; height:5px; } .tipsy-n .tipsy-arrow { top:0; left:50%; margin-left:-4px; } .tipsy-nw .tipsy-arrow { top:0; left:10px; } .tipsy-ne .tipsy-arrow { top:0; right:10px; } .tipsy-s .tipsy-arrow { bottom:0; left:50%; margin-left:-4px; background-position:bottom left; } .tipsy-sw .tipsy-arrow { bottom:0; left:10px; background-position:bottom left; } .tipsy-se .tipsy-arrow { bottom:0; right:10px; background-position:bottom left; } .tipsy-e .tipsy-arrow { top:50%; margin-top:-4px; right:0; width:5px; height:9px; background-position:top right; } .tipsy-w .tipsy-arrow { top:50%; margin-top:-4px; left:0; width:5px; height:9px; }
08102013project
trunk/CMS/Content/themes/base/dark/jquery.tipsy.css
CSS
oos
1,863
.miniColors-trigger { height: 22px; width: 22px; background: url(images/minicolor/trigger.png) center no-repeat; vertical-align: middle; margin: 0 .25em; display: inline-block; outline: none; } .miniColors-selector { position: absolute; width: 175px; height: 150px; background: #2e2e33; border: solid 1px #333333; -moz-box-shadow: 0 0 6px rgba(0, 0, 0, .25); -webkit-box-shadow: 0 0 6px rgba(0, 0, 0, .25); box-shadow: 0 0 6px rgba(0, 0, 0, .25); -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; padding: 5px; z-index: 999999; } .miniColors-selector.black { background: #000; border-color: #000; } .miniColors-colors { position: absolute; top: 5px; left: 5px; width: 150px; height: 150px; background: url(images/minicolor/gradient.png) center no-repeat; cursor: crosshair; } .miniColors-hues { position: absolute; top: 5px; left: 160px; width: 20px; height: 150px; background: url(images/minicolor/rainbow.png) center no-repeat; cursor: crosshair; cursor:pointer; } .miniColors-colorPicker { position: absolute; width: 11px; height: 11px; background: url(images/minicolor/circle.gif) center no-repeat; } .miniColors-huePicker { position: absolute; left: -3px; width: 26px; height: 3px; background: url(images/minicolor/line.gif) center no-repeat; }
08102013project
trunk/CMS/Content/themes/base/dark/jquery.miniColors.css
CSS
oos
1,389
textarea.html{ max-width:100%; } div.wysiwyg{ border:1px solid; border-color:#CCC #E7E7E7 #FFF; border-radius:4px; max-width:100%; moz-border-radius:4px; padding:1%; webkit-border-radius:4px; } #content form div.wysiwyg{ border:0; padding:0; } div.wysiwyg *{ margin:0; padding:0; } div.wysiwyg ul.toolbar li.jwysiwyg-custom-command{ overflow:hidden; } div.wysiwyg ul.toolbar{ background-image:url(images/paper_01.png); background-repeat:repeat; border-bottom:1px solid #333333; border-radius:4px; border-top:1px solid #000000; float:left; margin-bottom:4px; moz-border-radius:4px; padding:0; webkit-border-radius:4px; width:99%; } div.wysiwyg ul.toolbar li{ background-color:#333333; background-position:-96px -120px; border-radius:4px; clear:none; float:left; list-style:none; margin:1px 2px 4px 0; moz-border-radius:4px; moz-user-select:none; padding:0; user-select:none; webkit-border-radius:4px; webkit-user-select:none; } div.wysiwyg ul.toolbar li.separator{ border-left:1px solid #1e1e1e; border-right:1px solid #2e2e33; height:22px; margin:1px 4px; width:0; } div.wysiwyg ul.toolbar li{ background:url(images/editor/buttons.png) no-repeat -96px -80px; border:0; cursor:pointer; display:block; filter:alpha(opacity=75); height:24px; margin:0; padding:1px; opacity:0.75; text-indent:-5000px; width:24px; } div.wysiwyg ul.toolbar li.wysiwyg-button-hover,div.wysiwyg ul.toolbar li.active{ background-color:#333333; border:1px solid; padding:0; border-color:#333333; filter:alpha(opacity=100); opacity:1; } div.wysiwyg ul.toolbar li.active{ background-color:#2e2e33; margin:0; } div.wysiwyg ul.toolbar li.disabled,div.wysiwyg ul.toolbar li.wysiwyg-button-hover.disabled,div.wysiwyg ul.toolbar li.active.disabled{ border:0 none transparent; cursor:auto; filter:alpha(opacity=50); opacity:0.5; padding:1px; } div.wysiwyg ul.toolbar li.bold{ background-position:0 -24px; } div.wysiwyg ul.toolbar li.italic{ background-position:-24px -24px; } div.wysiwyg ul.toolbar li.strikeThrough{ background-position:-48px -24px; } div.wysiwyg ul.toolbar li.underline{ background-position:-72px -24px; } div.wysiwyg ul.toolbar li.highlight{ background-position:-72px -144px; } div.wysiwyg ul.toolbar li.justifyLeft{ background-position:0 0; } div.wysiwyg ul.toolbar li.justifyCenter{ background-position:-24px 0; } div.wysiwyg ul.toolbar li.justifyRight{ background-position:-48px 0; } div.wysiwyg ul.toolbar li.justifyFull{ background-position:-72px 0; } div.wysiwyg ul.toolbar li.indent{ background-position:-96px 0; } div.wysiwyg ul.toolbar li.outdent{ background-position:-120px 0; } div.wysiwyg ul.toolbar li.subscript{ background-position:-96px -24px; } div.wysiwyg ul.toolbar li.superscript{ background-position:-120px -24px; } div.wysiwyg ul.toolbar li.undo{ background-position:0 -96px; } div.wysiwyg ul.toolbar li.redo{ background-position:-24px -96px; } div.wysiwyg ul.toolbar li.insertOrderedList{ background-position:-48px -72px; } div.wysiwyg ul.toolbar li.insertUnorderedList{ background-position:-24px -72px; } div.wysiwyg ul.toolbar li.insertHorizontalRule{ background-position:0 -72px; } div.wysiwyg ul.toolbar li.h1{ background-position:0 -48px; } div.wysiwyg ul.toolbar li.h2{ background-position:-24px -48px; } div.wysiwyg ul.toolbar li.h3{ background-position:-48px -48px; } div.wysiwyg ul.toolbar li.h4{ background-position:-72px -48px; } div.wysiwyg ul.toolbar li.h5{ background-position:-96px -48px; } div.wysiwyg ul.toolbar li.h6{ background-position:-120px -48px; } div.wysiwyg ul.toolbar li.paragraph{ background-position:0 -144px; } div.wysiwyg ul.toolbar li.colorpicker{ background-position:-24px -96px; } div.wysiwyg ul.toolbar li.fullscreen{ background-position:-32px -96px; } div.wysiwyg ul.toolbar li.cut{ background-position:-48px -96px; } div.wysiwyg ul.toolbar li.copy{ background-position:-72px -96px; } div.wysiwyg ul.toolbar li.paste{ background-position:-96px -96px; } div.wysiwyg ul.toolbar li.insertTable{ background-position:-96px -72px; } div.wysiwyg ul.toolbar li.increaseFontSize{ background-position:-24px -120px; } div.wysiwyg ul.toolbar li.decreaseFontSize{ background-position:-48px -120px; } div.wysiwyg ul.toolbar li.createLink{ background-position:-120px -72px; } div.wysiwyg ul.toolbar li.insertImage{ background-position:-120px -120px; } div.wysiwyg ul.toolbar li.html{ background-position:-72px -72px; } div.wysiwyg ul.toolbar li.removeFormat{ background-position:-120px -96px; } div.wysiwyg ul.toolbar li.ltr{ background-position:-24px -144px; } div.wysiwyg ul.toolbar li.rtl{ background-position:-48px -144px; } div.wysiwyg ul.toolbar li.empty{ background-position:-96px -120px; } div.wysiwyg ul.toolbar li.code{ background-position:-96px -144px; } div.wysiwyg ul.toolbar li.cssWrap{ background-position:-120px -144px; } div.wysiwyg ul.toolbar li.colorpicker{ background-position:0 -168px; } div.wysiwyg-dialogRow{ float:left; font-size:16px; width:100%; } div.wysiwyg iframe{ background-color:#2e2e33; border:1px solid #444444; border-radius:4px; clear:left; display:block; margin:0; moz-border-radius:4px; padding:0; webkit-border-radius:4px; width:100%; } form.wysiwyg input.width,form.wysiwyg input.height,form.wysiwyg input.integer{ margin:2px 0; text-align:right; width:30px; } form.wysiwyg select{ width:60px; }
08102013project
trunk/CMS/Content/themes/base/dark/jquery.wysiwyg.css
CSS
oos
5,631
/* file manager window */ .el-finder { width:100%; min-width:400px; border:1px solid #444444; background-color:#2e2e33; border-radius:4px; -moz-border-radius:4px; -webkit-border-radius:4px; } .el-finder-undocked { position:absolute; min-width:400px; border:1px solid #ccc; padding:5px; } /* error messages */ .el-finder-err { padding: 15px; text-align:center; background: #f1f1f1; color: #2e2e33; border-radius:4px; -moz-border-radius:4px; -webkit-border-radius:4px; } /* disabled */ .el-finder-disabled .el-finder-toolbar li, .el-finder-disabled .el-finder-nav, .el-finder-disabled .el-finder-cwd { opacity:0.35; filter:Alpha(Opacity=35); } .el-finder .el-finder-droppable { background-color:#99ccff; } .el-finder .ui-selected { background-color:#ccc; color:#2e2e33; } .el-finder input { margin:0; padding:0; outline:none; border:1px solid #ccc; } /************************************/ /* toolbar */ /************************************/ .el-finder-toolbar ul { padding:5px 7px; margin:0; list-style:none; } .el-finder-toolbar ul li { display: -moz-inline-stack; display: inline-block; zoom: 1; *display: inline; vertical-align: top; height:22px; width:23px; margin:0 2px; padding:0; background:url(images/elfinder/toolbar.png) no-repeat; border:1px solid #444444; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; } .el-finder-toolbar ul li.delim { border:none; width:3px; background-position: 1px -610px; } .el-finder-toolbar ul li.el-finder-tb-hover { border:1px solid #fff; background-color:#2e2e33; } .el-finder-toolbar ul li.disabled { opacity:0.35; filter:Alpha(Opacity=35); } .el-finder-toolbar ul li.archive { background-position: 0px -583px; } .el-finder-toolbar ul li.extract { background-position: 0px -583px; } .el-finder-toolbar ul li.back { background-position: 0px -169px; } .el-finder-toolbar ul li.reload { background-position: 0px -190px; } .el-finder-toolbar ul li.select { background-position: 0px -214px; } .el-finder-toolbar ul li.open { background-position: 0px -235px; } .el-finder-toolbar ul li.mkdir { background-position: 0px -258px; } .el-finder-toolbar ul li.mkfile { background-position: 0px -280px; } .el-finder-toolbar ul li.upload { background-position: 0px -305px; } .el-finder-toolbar ul li.duplicate { background-position: 0px -705px; } .el-finder-toolbar ul li.rm { background-position: 0px -330px; } .el-finder-toolbar ul li.copy { background-position: 0px -356px; } .el-finder-toolbar ul li.cut { background-position: 0px -631px; } .el-finder-toolbar ul li.paste { background-position: 0px -380px; } .el-finder-toolbar ul li.rename { background-position: 0px -407px; } .el-finder-toolbar ul li.edit { background-position: 0px -435px; } .el-finder-toolbar ul li.info { background-position: 0px -463px; } .el-finder-toolbar ul li.help { background-position: 0px -487px; } .el-finder-toolbar ul li.icons { background-position: 0px -537px; } .el-finder-toolbar ul li.list { background-position: 0px -557px; } .el-finder-toolbar ul li.uncompress { background-position: 0px -583px; } .el-finder-toolbar ul li.resize { background-position: 0px -655px; } .el-finder-toolbar ul li.quicklook { background-position: 0px -726px; } .el-finder-dock-button { width:19px; height:19px; float:right; margin: 2px; border:1px solid #ccc; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; background:url(images/elfinder/toolbar.png) 2px -705px no-repeat; } .ui-dialog .el-finder-dock-button { background-position:2px -681px; } .el-finder-dock-button-hover { background-color:#ccc; border:1px solid #222; } /**********************************************************/ /* workzone, container for navigation and current folder */ /**********************************************************/ .el-finder-workzone { background:url(images/paper_02.png); border-top:1px solid #444444; border-bottom:1px solid #444444; position:relative; } .el-finder-spinner { position:absolute; top:37%; left:37%; width:250px; height:50px; background:transparent url(images/loading.gif) 50% 50% no-repeat; display:none; } /* error in workzone */ .el-finder-workzone p.el-finder-err { display:none; position:absolute; left:37%; top:20px; } /* navigation and current directory */ .el-finder-nav, .el-finder-cwd { height:350px; overflow:auto; padding:3px 1px; } /************************************/ /* navigation */ /************************************/ .el-finder-nav { float:left; width : 200px; background:url(images/paper_01.png); } .el-finder-nav .ui-resizable-e { right:0; } /* folders tree */ .el-finder-nav ul { list-style:none; margin:0; padding:0; } .el-finder-nav ul li { clear:both; } ul.el-finder-tree, ul.el-finder-places { margin-bottom:1em; } .el-finder-nav ul li ul { margin-left:12px; } .el-finder-nav ul div { width:12px; height:20px; float:left; margin-right:23px; } .el-finder-nav a, .el-finder-nav div.collapsed { background-image:url(images/elfinder/toolbar.png); background-repeat:no-repeat; } .el-finder-nav div.collapsed { background-position: -5px 5px; } .el-finder-nav div.expanded { background-position: -5px -10px; } .el-finder-nav a { display: block; white-space:nowrap; line-height:20px; color:#c1c1c1; cursor:default; text-decoration:none; outline:none; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; background-position: 8px -56px; } .el-finder-nav a.dropbox { background-position: 8px -80px; } .el-finder-nav a.readonly { background-position: 8px -104px; } .el-finder-nav a.noaccess { background-position: 8px -750px; } .el-finder-nav a.selected { background-color:#ccc; background-position: 8px -128px; color:#2e2e33; } .el-finder-nav a.el-finder-tree-root { background-position: 10px -30px; font-weight:bold; } .el-finder-nav a.el-finder-places-root { background-position: 8px -148px; font-weight:bold; } .el-finder-nav ul.el-finder-tree .el-finder-droppable { background-position: 8px -237px; } /***********************************/ /* current working directory */ /************************************/ .el-finder-cwd { border-left:1px solid #444444; padding:3px; } /********** view: icons ************/ .el-finder-cwd div { width: 81px; display: -moz-inline-stack; display: inline-block; vertical-align: top; zoom: 1; *display: inline; margin:0 3px 3px 0; padding:1px 0; text-align:center; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; color:#c1c1c1; background-color:transparent; } .el-finder-cwd p, .el-finder-ql p { width:48px; height:48px; margin:1px auto; padding:0; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; background: url(images/elfinder/icons-big.png) -1px 1px no-repeat; } /* mimetypes */ .directory p { background-position: 0 -45px; } .application p { background-position: -1px -134px; } .audio p { background-position: -1px -1082px; } .image p { background-position: -1px -1132px; } .text p, .x-empty p { background-position: -1px -524px; } .video p { background-position: -1px -1032px; } /* images */ .gif p { background-position: 0 -1183px; } .jpeg p { background-position: 0 -1234px; } .vnd-adobe-photoshop p, .postscript p { background-position: 0 -1132px; } /* video */ .ogg p { background-position: -1px -1032px; } /* audio */ .ogm p { background-position: -1px -1082px; } /* texts */ .rtf p, .rtfd p { background-position: 0 -573px; } .javascript p, .x-javascript p { background-position: 0 -184px; } .x-c p, .css p, .x-sql p, .x-python p, .x-java-source p { background-position: 0 -624px; } .html p { background-position: 0 -777px; } .x-java p { background-position: 0 -827px; } .x-php p { background-position: 0 -726px; } .x-perl p { background-position: 0 -675px; } .x-ruby p { background-position: 0 -877px; } .x-shellscript p { background-position: 0 -930px; } /* applications */ .vnd-ms-office p, .msword p, .vnd-ms-word p, .vnd-oasis-opendocument-text p { background-position: -1px -232px; } .ms-excel p, .vnd-ms-excel p, .vnd-oasis-opendocument-spreadsheet p { background-position: -1px -330px; } .vnd-ms-powerpoint p, .vnd-oasis-opendocument-presentation p { background-position: -1px -380px; } .pdf p { background-position: -1px -282px; } .xml p { background-position: 0 -980px; } .x-shockwave-flash p { background-position: 0 -1032px; } .x-sh p { background-position: 0 -930px; } /* archives */ .x-bzip p, .x-bzip2 p, .zip p, .x-rar p, .x-rar-compressed p, .x-tar p, .x-7z-compressed p { background-position: -1px -430px; } .x-gzip p { background-position: -1px -477px; } .el-finder-cwd div.el-finder-droppable p { background-position: 0 -87px; } .el-finder-cwd label { display:block; font-size:11px; line-height:13px; padding:0 1px; margin:0; height:25px; overflow:hidden; cursor:default; } .el-finder-cwd div input { background:#fff; width:81px; margin-left:-2px; outline:none; border:1px solid #ccc; text-align:center; } .el-finder-cwd div em { float:left; margin-top:-40px; margin-left:9px; width:15px; height:16px; background:url(images/elfinder/icons-big.png) -17px -1290px no-repeat; } .el-finder-cwd div em.dropbox { float:right; margin-right:9px; background-position: 0 -1290px; } .el-finder-cwd div em.noread { float:right; margin-right:9px; background-position: 0 -1415px; } .el-finder-cwd div em.readonly { float:right; margin-right:9px; background-position: -34px -1287px; } .el-finder-cwd div em.noaccess { float:right; margin-right:9px; background-position: 0 -1415px; } /********** view: list ************/ .el-finder-cwd table { width:100%; /* *width:99%;*/ border-collapse: collapse; border-spacing: 0; border:1px solid #ccc; border-top:0 solid; border-left:0 solid; margin:-3px -3px; } .el-finder-cwd table tr { background:transparent; } .el-finder-cwd table tr.el-finder-row-odd { background-color:#2e2e33; } .el-finder-cwd table tr.ui-selected { background-color:#ccc; color:#2e2e33; } .el-finder-cwd table th, .el-finder-cwd table td { padding:3px 5px; border-left:1px solid #ccc; cursor:default; white-space:nowrap; text-align:left; } .el-finder-cwd table th { text-align:left; } .el-finder-cwd table td.icon { width:24px; } .el-finder-cwd table p { width:24px; height:16px; margin:0; padding:0; background:url(images/elfinder/icons-small.png) 4px 0 no-repeat; } .el-finder-cwd table .size { text-align:right; } tr.directory p { background-position:4px -16px; } tr.text p { background-position:5px -34px; } tr.image p { background-position:4px -51px; } tr.audio p { background-position:4px -70px; } tr.video p { background-position:5px -89px; } tr.application p { background-position:4px -108px; } /* text */ tr.html p { background-position:5px -188px; } tr.javascript p, tr.x-javascript p, tr.css p, tr.x-sql p, tr.xml p, tr.x-python p, tr.x-java-source p, tr.x-perl p, tr.x-ruby p { background-position:5px -228px; } tr.x-php p { background-position:5px -247px; } tr.x-c p { background-position:5px -208px; } tr.x-shellscript p, tr.x-sh p { background-position:5px -168px; } tr.rtf p, tr.rtfd p { background-position:5px -148px; } /* application */ tr.x-shockwave-flash p { background-position:4px -266px; } tr.pdf p { background-position:4px -285px; } tr.vnd-ms-office p { background-position:4px -325px; } tr.msword p, tr.vnd-oasis-opendocument-text p, tr.vnd-ms-word p { background-position:4px -346px; } tr.vnd-ms-excel p, tr.ms-excel p, tr.vnd-oasis-opendocument-spreadsheet { background-position:4px -365px; } tr.vnd-ms-powerpoint p, tr.vnd-oasis-opendocument-presentation { background-position:4px -385px; } /* archives */ tr.x-tar p, tr.x-gzip p, tr.x-bzip p, tr.x-bzip2 p, tr.zip p, tr.x-rar p, tr.x-rar-compressed p, tr.x-7z-compressed p { background-position:4px -305px; } tr.el-finder-droppable td.icon p { background-position:5px -450px; } .el-finder-cwd table td p em { float:left; width:10px; height:12px; margin-top:5px; background:url(images/elfinder/icons-small.png) 0px -405px no-repeat; } .el-finder-cwd table p em.readonly { background-position:0px -433px; } .el-finder-cwd table p em.dropbox { background-position:0px -418px; } .el-finder-cwd table p em.noread, .el-finder-cwd table p em.noaccess { background-position:0px -470px; } /************************************/ /* statusbar */ /************************************/ .el-finder-statusbar { height:20px; } .el-finder-stat, .el-finder-path, .el-finder-sel { padding:3px 9px 1px 9px; color:#c1c1c1; } /* current directory path */ .el-finder-path { float:left; } /* number folders/files in current directory and size */ .el-finder-stat { float:right; } /* info about selected files */ .el-finder-sel { text-align:center; } /************************************/ /* dialog window */ /************************************/ .el-finder-dialog form p, .el-finder-dialog .ui-tabs p { margin:.5em; } .el-finder-dialog .ui-dialog-titlebar { padding: .2em .1em .1em .8em; } .el-finder-dialog .ui-dialog-buttonpane { padding: .1em 1em .1em .4em; font-size:.9em; } .el-finder-dialog .ui-dialog-content { padding:5px; } .el-finder-dialog hr { border:0; border-bottom: 1px #ccc solid; clear:both } .el-finder-dialog ul { margin-top:0; } .el-finder-dialog a { outline: none;} .el-finder-dialog textarea { width:100%; height:400px; outline:none; border:1px solid #ccc; } .ui-state-error { margin: 5px 0; padding:.5em; clear:both; } .el-finder-dialog .ui-state-error .ui-icon { float: left; margin-right: .3em; } .el-finder-add-field { cursor:pointer; } .el-finder-add-field span { float:left; margin-right:.7em; } .el-finder-dialog table { width : 100%; } .el-finder-dialog table td { padding:2px 5px; } .el-finder-dialog .ui-tabs div { padding:0 .5em; } .el-finder-dialog .ui-tabs-nav li a { padding:.2em 1em; } /************************************/ /* contextmenu */ /************************************/ .el-finder-contextmenu { position:absolute; width:200px; background:#fff; cursor:default; border:1px solid #ccc; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; padding:5px 0; } .el-finder-contextmenu div { position:relative; display:block; margin:0; padding:4px 29px 4px 29px; white-space:nowrap; font:12px trebuchet ms,lucida grande,verdana,sans-serif; background:url(images/elfinder/toolbar.png) 0 0 no-repeat; } .el-finder-contextmenu span { float:right; width:9px; height:18px; margin-right:-27px; background:url(images/elfinder/toolbar.png) -4px 5px no-repeat; } .el-finder-contextmenu div.el-finder-contextmenu-sub { position:absolute; top:0; display:none; margin:0; padding:5px 0; background:#fff; border:1px solid #ccc; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; } .el-finder-contextmenu div.reload { background-position: 5px -192px; } .el-finder-contextmenu div.select { background-position: 5px -214px; } .el-finder-contextmenu div.open { background-position: 6px -235px; } .el-finder-contextmenu div.mkdir { background-position: 6px -258px; } .el-finder-contextmenu div.mkfile { background-position: 6px -280px; } .el-finder-contextmenu div.upload { background-position: 5px -305px; } .el-finder-contextmenu div.rm { background-position: 5px -330px; } .el-finder-contextmenu div.copy { background-position: 5px -356px; } .el-finder-contextmenu div.cut { background-position: 5px -631px; } .el-finder-contextmenu div.duplicate { background-position: 5px -356px; } .el-finder-contextmenu div.paste { background-position: 5px -381px; } .el-finder-contextmenu div.rename { background-position: 5px -407px; } .el-finder-contextmenu div.edit { background-position: 6px -435px; } .el-finder-contextmenu div.info { background-position: 5px -462px; } .el-finder-contextmenu div.help { background-position: 5px -487px; } .el-finder-contextmenu div.icons { background-position: 5px -537px; } .el-finder-contextmenu div.list { background-position: 5px -557px; } .el-finder-contextmenu div.archive { background-position: 5px -583px; } .el-finder-contextmenu div.extract { background-position: 5px -583px; } .el-finder-contextmenu div.resize { background-position: 5px -655px; } .el-finder-contextmenu div.quicklook { background-position: 5px -727px; } .el-finder-contextmenu div.delim { margin:0; padding:0; height:1px; border-top:1px solid #eee; background:transparent; display:block; } .el-finder-contextmenu div.hover { background-color:#99ccff; } .el-finder-places { margin-top:.5em; } .el-finder-drag-helper { padding:0; cursor:move; zoom:1; } .el-finder-drag-helper div { border:0 solid; margin-left:-57px; } .el-finder-drag-copy { background:url(images/elfinder/toolbar.png) 0 -771px no-repeat; } .el-finder-drag-helper label { border:1px solid #ccc; background-color:#eee; border-radius:5px; -moz-border-radius:5px; -webkit-border-radius:5px; } /************************************/ /* QuickLook */ /************************************/ .el-finder-ql { position:absolute; width:420px; height:auto; padding:12px 9px; text-align:center; border-radius:9px; -moz-border-radius:9px; -webkit-border-radius:9px; background:url(images/elfinder/ql.png); overflow: inherit !important; } /* toolbar */ .el-finder-ql div.el-finder-ql-drag-handle { height:18px; background-color:#777; margin:-12px -9px 12px -9px; padding:3px 0 0 19px; opacity:.8; text-align:center; white-space: nowrap; overflow:hidden; -moz-border-radius-topleft:9px; -moz-border-radius-topright:9px; -webkit-border-top-left-radius: 9px; -webkit-border-top-right-radius: 9px; border-top-left-radius: 9px; border-top-right-radius: 9px; } /* close button */ .el-finder-ql div.el-finder-ql-drag-handle span { float:left; margin:0 19px 0 -15px; } /* title in tolbar */ .el-finder-ql div.el-finder-ql-drag-handle strong { line-height:18px; margin-left:-17px; color:#fff; } .el-finder-ql div.el-finder-ql-media { width:100%; padding:0; } .el-finder-ql div.el-finder-ql-content { width:100%; font:.82em/1.3em trebuchet ms,lucida grande,verdana,sans-serif; padding:5px 0; overflow:hidden; } .el-finder-ql div.el-finder-ql-content span, .el-finder-ql div.el-finder-ql-content a { display:block; color: #fff; } /* text files preview */ .el-finder-ql iframe { background:#fff; width:100%; height:315px; padding:0; margin:0; border:none; outline:none; } /* images preview */ .el-finder-ql img { margin:0 auto; border:1px solid #fff; } /* button help */ .el-finder-help-std { background: url(images/elfinder/icons-big.png) 0 -1315px no-repeat; width:48px; height:48px; float:right; } .el-finder-logo { background: url(images/elfinder/icons-big.png) 0 -1365px no-repeat; width:48px; height:48px; float:left; }
08102013project
trunk/CMS/Content/themes/base/dark/jquery.elfinder.css
CSS
oos
20,542
/*----------------------------------------------------------------------*/ /* colors /* #731717 #8c1c1c red /* #357317 #418c1c green /* #736e17 #8c871c yellow /* #176d73 #1c858c blue /* #731771 #8c1c8b pink /* #491773 #581c8c purple /* /* contrast color #287e84 /*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/ /* Imports /*----------------------------------------------------------------------*/ @import 'jquery-ui.css'; @import 'jquery.miniColors.css'; @import 'jquery.tipsy.css'; @import 'jquery.uniform.css'; @import 'jquery.wysiwyg.css'; @import 'jquery.fullcalendar.css'; @import 'jquery.elfinder.css'; @import 'jquery.fancybox.css'; @import 'jquery.datatables.css'; /*----------------------------------------------------------------------*/ /* General Section /*----------------------------------------------------------------------*/ html, body, textarea, input { color:#c1c1c1; } html{ background-color:#2e2e33; background-image:url(images/paper_02.png); } a, a:hover, a:visited, a:link {color:#c0c0c0;} ::-moz-selection{ background:#287e84; color:#cacaca; text-shadow:none; } ::selection { background:#287e84; color:#cacaca; text-shadow:none; } nav ul li a span{ background-image:url(../images/icons/light/arrow_right.png); } h1, h2, h3, h4, h5, h6{ text-shadow:0 -1px 0 #000; color:#a8a8a8; } h1{ text-shadow:0 -1px 0 #000; } h1 span{ text-shadow:0 -1px 0 #000; } blockquote{ border-color:#666666; color:#666666; } hr { border-top-color:#1e1e1e; border-bottom-color:#2e2e33; } /*----------------------------------------------------------------------*/ /* jQuery UI mods /*----------------------------------------------------------------------*/ .ui-widget-header a, .ui-accordion-header a{ color:#bbbbbb; text-shadow:0 0 1px #2e2e33; } .ui-widget-header{ border-top-color:#2e2e33 !important; border-bottom-color:#555555 !important; margin:0; } .ui-widget-overlay{ background-image:url(images/paper_02.png); background-color:#cccccc; } .ui-state-default a{ border-top-color:#2e2e33 !important; } .ui-slider-range.ui-widget-header{ background-color:#e1e1e1; background-image:url(../images/bg/01.png); } .ui-slider{ border-color:#555555 !important; background-color:#2c2c2c; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.3); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.3); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.3); } .ui-slider .ui-slider-handle{ border-color:#555555 !important; background-image:url(images/slider_handler.png); -webkit-box-shadow:0 1px 1px rgba(0, 0, 0, 0.1); -moz-box-shadow:0 0 3px rgba(0, 0, 0, 0.1); box-shadow:0 0 1px rgba(0, 0, 0, 0.1); } /*----------------------------------------------------------------------*/ /* Pageoptions /*----------------------------------------------------------------------*/ #pageoptions h1, #pageoptions h2,#pageoptions h3, #pageoptions h4, #pageoptions h5, #pageoptions h6{ text-shadow:0 2px 0 #ffffff; color:#202020; } #pageoptions ul li a{ color:#f1f1f1; } #pageoptions ul li a:hover, #pageoptions ul li a.active{ color:#2e2e33; background-color:#ffffff; } #pageoptions > div{ color:#202020; background-color:#ffffff; -webkit-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.5); box-shadow:inset 0 2px 1px rgba(0, 0, 0, 0.5); } /*----------------------------------------------------------------------*/ /* Tables /*----------------------------------------------------------------------*/ table{ background-image:url(images/paper_01.png); } table td, table th{ border-color:#333333 #222222 #333333 #222222; } table thead tr,table tfoot tr, table th{ background-image:url(images/paper_02.png); } table th{ text-shadow:0 -1px 0 #2e2e33; } /*----------------------------------------------------------------------*/ /* Header /*----------------------------------------------------------------------*/ header{ -webkit-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); -moz-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); border-top-color:#3d3d3d; background:#2b2b2b; /* the filter causes an overflow problem on IE9 http://stackoverflow.com/questions/3619383/internet-explorer-css-property-filter-ignores-overflowvisible filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2c2c2c', endColorstr='#202020');*/ background:-webkit-gradient(linear, left top, left bottom, from(#2c2c2c), to(#202020)); background:-moz-linear-gradient(top, #2c2c2c, #202020); background:-o-linear-gradient(top, #2c2c2c, #202020); } #logo, #logo a{ text-shadow:0 -1px 0 #000; color:#2e2e33; } #header ul li ul li{ border-color:#2c2c2c #3d3d3d #3d3d3d #2c2c2c; } #header ul li ul li a{ color:#cacaca; text-shadow:0px 1px 0 #2e2e33; border-top-color:#555; background:#202020; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#202020', endColorstr='#151515'); background:-webkit-gradient(linear, left top, left bottom, from(#202020), to(#151515)); background:-moz-linear-gradient(top, #202020, #151515); background:-o-linear-gradient(top, #202020, #151515); } #header ul li ul li a:hover{ background:#2c2c2c; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2c2c2c', endColorstr='#202020'); background:-webkit-gradient(linear, left top, left bottom, from(#2c2c2c), to(#202020)); background:-moz-linear-gradient(top, #2c2c2c, #202020); background:-o-linear-gradient(top, #2c2c2c, #202020); } #header ul li ul li a:active, #header ul li ul li a.active{ -webkit-box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.3); -moz-box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.3); box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.3); background:#151515; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#151515', endColorstr='#1c1c1c'); background:-webkit-gradient(linear, left top, left bottom, from(#151515), to(#1c1c1c)); background:-moz-linear-gradient(top, #151515, #1c1c1c); background:-o-linear-gradient(top, #151515, #1c1c1c); } #header ul li ul li:active, #header ul li ul li.active{ } #header ul li ul li ul{ background-color:#a8a8a8; } #header ul li ul li span{ background-color:#731717; color:#ffffff; border-color: #333; -webkit-box-shadow: inset 0px 2px 2px rgba(255,255,255, 0.2), inset 0px -2px 3px rgba(255,25,25, 0.2); -moz-box-shadow: inset 0px 2px 2px rgba(255,255,255, 0.2), inset 0px -2px 3px rgba(255,25,25, 0.2); box-shadow: inset 0px 2px 2px rgba(255,255,255, 0.2), inset 0px -2px 3px rgba(255,25,25, 0.2); } #header ul li ul li ul li{ border-color:#222222; } #searchbox{ border-color:#2c2c2c #3d3d3d #3d3d3d #2c2c2c; } form#searchform input#search{ color:#cacaca; text-shadow:0px 1px 0 #2e2e33; border-top-color:#555555; -webkit-box-shadow:none; -moz-box-shadow:none; box-shadow:none; background:#202020; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#202020', endColorstr='#151515'); background:-webkit-gradient(linear, left top, left bottom, from(#202020), to(#151515)); background:-moz-linear-gradient(top, #202020, #151515); background:-o-linear-gradient(top, #202020, #151515); } form#searchform input#search:hover{ background:#2c2c2c; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2c2c2c', endColorstr='#202020'); background:-webkit-gradient(linear, left top, left bottom, from(#2c2c2c), to(#202020)); background:-moz-linear-gradient(top, #2c2c2c, #202020); background:-o-linear-gradient(top, #2c2c2c, #202020); } form#searchform input#search:focus{ -webkit-box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.3); -moz-box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.3); box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.3); background:#2e2e33; filter:none; } form#searchform input#search.load{ background-image:url(images/loading.gif) !important; } /* Live Search /*---------------------------------------------------------------------*/ ul#searchboxresult{ border-top-color:#121212; -webkit-box-shadow:0px 0px 4px rgba(0, 0, 0, 0.3); -moz-box-shadow:0px 0px 4px rgba(0, 0, 0, 0.3); box-shadow:0px 0px 4px rgba(0, 0, 0, 0.3); } ul#searchboxresult li a{ border-color:#2e2e33 #080808 #121212 #080808; background-color:#202020; } ul#searchboxresult li a:hover{ background-color:#2c2c2c; } /*----------------------------------------------------------------------*/ /* Navigation /*----------------------------------------------------------------------*/ nav{ border-right-color:#1e1e1e !important; border-left-color:#2e2e33; -webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.3); -moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.3); box-shadow:2px 2px 4px rgba(0, 0, 0, 0.3); } nav ul{ border-top-color:#121212; background-color:#a8a8a8; } nav ul li{ background-image:none !important; } nav ul li a{ background:#202020; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#202020', endColorstr='#151515'); background:-webkit-gradient(linear, left top, left bottom, from(#202020), to(#151515)); background:-moz-linear-gradient(top, #202020, #151515); background:-o-linear-gradient(top, #202020, #151515); } nav ul li a:hover{ background:#2c2c2c; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2c2c2c', endColorstr='#202020'); background:-webkit-gradient(linear, left top, left bottom, from(#2c2c2c), to(#202020)); background:-moz-linear-gradient(top, #2c2c2c, #202020); background:-o-linear-gradient(top, #2c2c2c, #202020); } nav ul li a span{ color:#cacaca; text-shadow:0 -1px 0 #000; border-color:#2e2e33 #080808 #121212 #080808; } nav ul li a:active, nav ul li a.active{ background-image:url(images/nav_active.png); background-repeat:repeat-x; background-color:#287e84; background-position:left center; filter:none; } nav ul li a:active span, nav ul li a.active span{ color:#cacaca; text-shadow:0px -1px 0 rgba(0,0,0,0.3); } nav ul li ul{ border-bottom-color:#222222; } nav ul li ul li{ background-image:none !important; } nav ul li ul li a{ } nav ul li ul li a span{ border-top-color:#222222; background-image:none !important; } /*----------------------------------------------------------------------*/ /* Content /*----------------------------------------------------------------------*/ #content{ -webkit-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); -moz-box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); box-shadow:3px 0 4px rgba(0, 0, 0, 0.1); background-color:#111111; background-image:url(images/paper_01.png); border-color:#121212 #2e2e33 #2e2e33 #2e2e33; } .bgsample{ border-color:#666666; -webkit-box-shadow:inset 0 0 2px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 0 2px rgba(0, 0, 0, 0.5); box-shadow:inset 0 0 2px rgba(0, 0, 0, 0.5); background-color:#2e2e33; } /*----------------------------------------------------------------------*/ /* Breadcrumb /*----------------------------------------------------------------------*/ .breadcrumb li a{ color:#666666; text-shadow:0 -1px 0 #000; border-color:#111111 #222222 #222222 #222222; background-image:url(images/breadcrumb.png); } .breadcrumb li:first-child a{ border-left-color:#111111; } .breadcrumb li:last-child a{ } .breadcrumb.disabled li a:hover{ color:#666666; } .breadcrumb li a.previous{ color:#555555; } .breadcrumb.disabled li a.previous:hover{ color:#555555; } .breadcrumb li a:hover{ color:#a8a8a8; } .breadcrumb li a:active, .breadcrumb li a.active, .breadcrumb.disabled li a.active:hover{ color:#aaaaaa; text-shadow:0 0 -1px #2e2e33; } /*----------------------------------------------------------------------*/ /* Gallery /*----------------------------------------------------------------------*/ .gallery{ border-color:#000000 #181818 #333333 #181818; background-image:url(images/paper_02.png); } .gallery .sortable_placeholder{ background-color:#2c2c2c; background-image:url(images/paper_02.png); } .gallery li{ border-color:#2e2e33 #181818 #333333 #181818; background-image:url(images/paper_01.png); } .gallery li > a{ background-image:url(images/loading.gif); } .gallery li img{ } .gallery li span{ background-color:#ffffff; border-top-color:#999999; -webkit-box-shadow:0 -1px 0 #ffffff; -moz-box-shadow:0 -1px 0 #ffffff; box-shadow:0 -1px 0 #ffffff; } .gallery li > a span a{ color:#2e2e33; } .gallery li a span a.edit{ background-image:url(../images/icons/dark/pencil.png); } .gallery li a span a.delete{ background-image:url(../images/icons/dark/cross.png); } /*----------------------------------------------------------------------*/ /* Message Box /*----------------------------------------------------------------------*/ #wl_msg .msg-box, #wl_msg .msg-box-close{ border-color:#1e1e1e; color:#202020; background:#f1f1f1; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f1f1f1', endColorstr='#e8e8e8'); background:-webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e8e8e8)); background:-moz-linear-gradient(top, #f1f1f1, #e8e8e8); background:-o-linear-gradient(top, #f1f1f1, #e8e8e8); } #wl_msg .msg-box-close{ } #wl_msg .msg-box-close:hover{ background-color:#1e1e1e; color:#ffffff; } #wl_msg .msg-box h3, #wl_msg .msg-close{ color:#202020; text-shadow:0 1px 0 #eeeeee; } #wl_msg .msg-box h3{ border-bottom-color:#aaaaaa; } #wl_msg .msg-close{ border-left-color:#aaaaaa; border-bottom-color:#aaaaaa; background-image:url(../images/icons/dark/cross.png); } #wl_msg .msg-close:hover{ background-image:url(../images/icons/light/cross.png); background-color:#202020; } #wl_msg .msg-content{ } /*----------------------------------------------------------------------*/ /* Alert Boxes /*----------------------------------------------------------------------*/ div.alert{ border-color:#2d2d2d #181818 #181818 #2d2d2d; text-shadow:0 -1px 0 rgba(0,0,0,0.2); color:#f1f1f1; background-color:#2e2e33; -webkit-box-shadow:inset 0 1px 0 rgba(204, 204, 204, 0.3), inset 0 2px 5px rgba(204, 204, 204, 0.2), inset 0 -2px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow:inset 0 1px 0 rgba(204, 204, 204, 0.3), inset 0 2px 5px rgba(204, 204, 204, 0.2), inset 0 -2px 5px rgba(0, 0, 0, 0.1); box-shadow:inset 0 1px 0 rgba(204, 204, 204, 0.3), inset 0 2px 5px rgba(204, 204, 204, 0.2), inset 0 -2px 5px rgba(0, 0, 0, 0.1); margin:9px 0; } div.alert:hover{ border-color:#2d2d2d; } div.alert a{ color:#a8a8a8; } div.alert a:hover{ color:#bbbbbb; } div.alert.red, div.alert.warning{ background-color:#731717; } div.alert.red:hover, div.alert.warning:hover{ background-color:#8c1c1c; } div.alert.green, div.alert.success{ background-color:#357317; } div.alert.green:hover, div.alert.success:hover{ background-color:#418c1c; } div.alert.yellow, div.alert.note{ background-color:#736e17; } div.alert.yellow:hover, div.alert.note:hover{ background-color:#8c871c; } div.alert.blue, div.alert.info{ background-color:#176d73; } div.alert.blue:hover, div.alert.info:hover{ background-color:#1c858c; } div.alert.pink{ background-color:#731771; } div.alert.pink:hover{ background-color:#8c1c8b; } div.alert.purple{ background-color:#491773; } div.alert.purple:hover{ background-color:#581c8c; } div.alert.warning{ background-image:url(../images/icons/light/alert.png); } div.alert.success{ background-image:url(../images/icons/light/tick.png); } div.alert.note{ background-image:url(../images/icons/light/light_bulb.png); } div.alert.info{ background-image:url(../images/icons/light/information.png); } /*----------------------------------------------------------------------*/ /* Form Elements /*----------------------------------------------------------------------*/ pre{ -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.8); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.8); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.8); } pre, code{ background-image:url(images/paper_02.png); background-color:#202020; border-color:#444444; } pre code{ background-image:url(images/code_lines.png); } input,textarea{ background-color:#2e2e33; border-color:#444444; } input.placeholder,textarea.placeholder{ color:#555555; } input.error{ color:#c49090; } input, textarea, input:invalid, input:required, textarea:required{ -webkit-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2); } input:hover,input:focus,textarea:hover,textarea:focus{ -webkit-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2), 0 0 3px rgba(0, 0, 0, 0.2); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2), 0 0 3px rgba(0, 0, 0, 0.2); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.2), 0 0 3px rgba(0, 0, 0, 0.2); } select optgroup, select option{ color:#555555; } select option{ border-color:#ffffff #f7f7f7 #dddddd #f7f7f7; } form{ border-color:#000000 #181818 #222222 #181818; background-image:url(images/paper_02.png); } form .wl_formstatus{ color:#731717; } form span.required{ background-image:url(images/required.png); } form fieldset{ border-color:#222222 #181818 #444444 #181818; } form label{ border-top-color:#2e2e33; color:#bbbbbb; text-shadow:0 1px 0 #2e2e33; background:#202020; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#202020', endColorstr='#151515'); background:-webkit-gradient(linear, left top, left bottom, from(#202020), to(#151515)); background:-moz-linear-gradient(top, #202020, #151515); background:-o-linear-gradient(top, #202020, #151515); } form fieldset > section{ border-top-color:#2e2e33; border-bottom-color:#181818; background:#2c2c2c; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2c2c2c', endColorstr='#202020'); background:-webkit-gradient(linear, left top, left bottom, from(#2c2c2c), to(#202020)); background:-moz-linear-gradient(top, #2c2c2c, #202020); background:-o-linear-gradient(top, #2c2c2c, #202020); } form fieldset > section > div{ border-left-color:#222222; } form fieldset > section > div span{ } form fieldset > section.error{ background:#8c1c1c; border-bottom-color:#8c1c1c; filter:none; } form fieldset > section.error > label{ text-shadow:none; } form fieldset > section label{ } div.passwordstrength{ text-shadow:0 1px 0 #222222; -webkit-box-shadow:inset 0 0 5px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 0 5px rgba(0, 0, 0, 0.5); box-shadow:inset 0 0 5px rgba(0, 0, 0, 0.5); } div.passwordstrength.s_1{background-color:#731717;} div.passwordstrength.s_2{background-color:#0f2d4a;} div.passwordstrength.s_3{background-color:#736e17;} div.passwordstrength.s_4{background-color:#176d73;} div.passwordstrength.s_5{background-color:#357317;} /*----------------------------------------------------------------------*/ /* jQuery Checkbox /*----------------------------------------------------------------------*/ .jquery-checkbox span.checkboxplaceholder { background-image:url(images/checkbox.png); } /*----------------------------------------------------------------------*/ /* File Upload /*----------------------------------------------------------------------*/ div.fileuploadui{ } div.fileuploadui a{ } ul.fileuploadpool{ border-color:#000000; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.8); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.8); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.8); } ul.fileuploadpool.drop{ background-image:url(images/dragndrop.png),url(images/paper_02.png); } ul.fileuploadpool.single{ } ul.fileuploadpool li{ border-color:#2e2e33 #181818 #333333 #181818; background-color:#202020; } ul.fileuploadpool li.error{ background-color:#8c1c1c; } ul.fileuploadpool li .name{ } ul.fileuploadpool li a{ } ul.fileuploadpool li a:hover{ } ul.fileuploadpool li a.cancel{ background-image:url(../images/icons/light/cross.png); } ul.fileuploadpool li a.remove{ background-image:url(../images/icons/light/cross.png); } ul.fileuploadpool li .progress{ background-color:#8c1c1c; background-image:url(images/upload.gif); } ul.fileuploadpool li.success .progress{ background-color:#418c1c; background-image:none; } /*----------------------------------------------------------------------*/ /* Comboselect /*----------------------------------------------------------------------*/ div.comboselectbox div.combowrap{ border-color:#2e2e33 #181818 #333333 #181818; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.8); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.8); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.8); } div.comboselectbox ul.comboselect li{ border-color:#2e2e33 #181818 #333333 #181818; background-color:#202020; } div.comboselectbox ul.comboselect li:hover a{ color:#fff; } div.comboselectbox ul.comboselect li a.add{ background-image:url(../images/icons/light/plus.png); } div.comboselectbox ul.comboselect li a.remove{ background-image:url(../images/icons/light/cross.png); } div.comboselectbox ul.comboselect li.used a{ color:#444; } div.comboselectbox ul.comboselect li.selected{ background-color:#404040; } div.comboselectbox div.comboselectbuttons a.add{ background-image:url(../images/icons/light/triangle_right.png); } div.comboselectbox div.comboselectbuttons a.remove{ background-image:url(../images/icons/light/triangle_left.png); } div.comboselectbox div.comboselectbuttons a.addall{ background-image:url(../images/icons/light/triangle_double_right.png); } div.comboselectbox div.comboselectbuttons a.removeall{ background-image:url(../images/icons/light/triangle_double_left.png); } @media screen and (max-width:700px){ div.comboselectbox div.comboselectbuttons a.add{ background-image:url(../images/icons/light/triangle_down.png); } div.comboselectbox div.comboselectbuttons a.remove{ background-image:url(../images/icons/light/triangle_up.png); } div.comboselectbox div.comboselectbuttons a.addall{ background-image:url(../images/icons/light/triangle_double_down.png); } div.comboselectbox div.comboselectbuttons a.removeall{ background-image:url(../images/icons/light/triangle_double_up.png); } } /*----------------------------------------------------------------------*/ /* Buttons /*----------------------------------------------------------------------*/ button, a.btn, .button, .dataTables_paginate span.paginate_button, .dataTables_paginate span.paginate_active{ border-color:#2d2d2d #181818 #181818 #2d2d2d; text-shadow:0 -1px 0 rgba(0,0,0,0.2); color:#f1f1f1; background-color:#222222; -webkit-box-shadow:inset 0 1px 0 rgba(204, 204, 204, 0.2), inset 0 2px 5px rgba(204, 204, 204, 0.1), inset 0 -2px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow:inset 0 1px 0 rgba(204, 204, 204, 0.2), inset 0 2px 5px rgba(204, 204, 204, 0.1), inset 0 -2px 5px rgba(0, 0, 0, 0.1); box-shadow:inset 0 1px 0 rgba(204, 204, 204, 0.2), inset 0 2px 5px rgba(204, 204, 204, 0.1), inset 0 -2px 5px rgba(0, 0, 0, 0.1); } button.icon, a.btn.icon, .button{ } button{ } a.btn{ } button:hover, a.btn:hover, .button:hover, .dataTables_paginate span.paginate_active:hover{ background-color:#333333; } button:active, a.btn:active, .button:active, .dataTables_paginate span.paginate_active{ background-color:#333333; border-color:#2d2d2d #181818 #181818 #2d2d2d; -webkit-box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.1); -moz-box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.1); box-shadow:inset 0 2px 1px rgba(204, 204, 204, 0.1); } button.red, a.btn.red, .button.red{ background-color:#731717; } button.red:hover, a.btn.red:hover, .button.red:hover{ background-color:#8c1c1c; } button.green, a.btn.green, .button.green{ background-color:#357317; } button.green:hover, a.btn.green:hover, .button.green:hover{ background-color:#418c1c; } button.yellow, a.btn.yellow, .button.yellow{ background-color:#736e17; } button.yellow:hover, a.btn.yellow:hover, .button.yellow:hover{ background-color:#8c871c; } button.blue, a.btn.blue, .button.blue{ background-color:#176d73; } button.blue:hover, a.btn.blue:hover, .button.blue:hover{ background-color:#1c858c; } button.pink, a.btn.pink, .button.pink{ background-color:#731771; } button.pink:hover, a.btn.pink:hover, .button.pink:hover{ background-color:#8c1c8b; } button.purple, a.btn.purple, .button.purple{ background-color:#491773; } button.purple:hover, a.btn.purple:hover, .button.purple:hover{ background-color:#581c8c; } /*----------------------------------------------------------------------*/ /* Widgets /*----------------------------------------------------------------------*/ .widget, .widget.loading{ background-color:#2e2e33; border-color:#555555 #2a2a2a #1e1e1e #2a2a2a; background-image:url(images/paper_02.png); } .widget > div{ border-color:#333333 #181818 #222222 #181818; background-image:url(images/paper_01.png); } .widget > div.ui-widget{ background-image:none; } .widget:hover{ border-color:#333333; } .widget.ui-sortable-helper{ -webkit-box-shadow:0px 5px 6px rgba(155, 155, 155, 0.1); -moz-box-shadow:0px 5px 6px rgba(155, 155, 155, 0.1); box-shadow:0px 5px 6px rgba(155, 155, 155, 0.1); } .widget h3.handle{ text-shadow:0 -1px 0 rgba(0,0,0,0.2); color:#f1f1f1; border-top-color:#2e2e33; border-bottom-color:#555555; background:#202020; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#202020', endColorstr='#151515'); background:-webkit-gradient(linear, left top, left bottom, from(#202020), to(#151515)); background:-moz-linear-gradient(top, #202020, #151515); background:-o-linear-gradient(top, #202020, #151515); } .widget h3.handle:hover{ -webkit-box-shadow:inset 0 -3px 12px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 -3px 12px rgba(0, 0, 0, 0.5); box-shadow:inset 0 -3px 12px rgba(0, 0, 0, 0.5); background:#2c2c2c; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#2c2c2c', endColorstr='#202020'); background:-webkit-gradient(linear, left top, left bottom, from(#2c2c2c), to(#202020)); background:-moz-linear-gradient(top, #2c2c2c, #202020); background:-o-linear-gradient(top, #2c2c2c, #202020); } .widget h3.handle .collapse{ background-image:url(../images/icons/light/collapse.png); } .widget h3.handle .reload{ background-image:url(../images/icons/light/refresh_3.png); } .widget.collapsed{ border-bottom-color:#555555; } .widget.collapsed h3.handle .collapse{ background-image:url(../images/icons/light/expand.png); } .widget.loading h3.handle .reload{ background-image:url(images/loading.gif); } .widget.number-widget > div ul li{ border-top-color:#aaaaaa; } .widget.number-widget > div ul li a{ color:#aaaaaa; text-shadow:0 1px 0 #2e2e33; } .widget.number-widget > div ul li a:hover{ color:#666666; } .widget.number-widget ul li a span{ } .sortable_placeholder{ border-color:#2e2e33; background-color:#2c2c2c; background-image:url(images/paper_02.png); -webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.5); -moz-box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); box-shadow:inset 0 1px 3px rgba(0, 0, 0, 0.5); } /*----------------------------------------------------------------------*/ /* Footer /*----------------------------------------------------------------------*/ footer{ color:#f1f1f1; } /* Move the Headernav to a drop down menu to the right */ @media screen and (max-width:960px) { #header ul#headernav{ background-image:url(../images/icons/light/expand.png); border-left-color:#181818; } #header ul#headernav li ul li ul{ background-image:url(../images/bg/04.png); background-color:#ffffff; } } /* iPhone and real small devicces */ @media screen and (max-width:480px) { nav ul li a:active span, nav ul li a.active span{ border-top-color:#2e2e33; } nav{ border-top-color:#1e1e1e; } nav ul { background:#202020; } nav ul li a span{ border-left-color:#1e1e1e; } } /*----------------------------------------------------------------------*/ /* Icons /*----------------------------------------------------------------------*/ nav ul li.i_abacus a span, .i_abacus{ background-image: url(../images/icons/light/abacus.png);} nav ul li.i_access_denied a span, .i_access_denied{ background-image: url(../images/icons/light/access_denied.png);} nav ul li.i_address_book a span, .i_address_book{ background-image: url(../images/icons/light/address_book.png);} nav ul li.i_admin_user a span, .i_admin_user{ background-image: url(../images/icons/light/admin_user.png);} nav ul li.i_admin_user_2 a span, .i_admin_user_2{ background-image: url(../images/icons/light/admin_user_2.png);} nav ul li.i_airplane a span, .i_airplane{ background-image: url(../images/icons/light/airplane.png);} nav ul li.i_alarm a span, .i_alarm{ background-image: url(../images/icons/light/alarm.png);} nav ul li.i_alarm_2 a span, .i_alarm_2{ background-image: url(../images/icons/light/alarm_2.png);} nav ul li.i_alarm_clock a span, .i_alarm_clock{ background-image: url(../images/icons/light/alarm_clock.png);} nav ul li.i_alert a span, .i_alert{ background-image: url(../images/icons/light/alert.png);} nav ul li.i_android a span, .i_android{ background-image: url(../images/icons/light/android.png);} nav ul li.i_application a span, .i_application{ background-image: url(../images/icons/light/application.png);} nav ul li.i_archive a span, .i_archive{ background-image: url(../images/icons/light/archive.png);} nav ul li.i_arrow_down a span, .i_arrow_down{ background-image: url(../images/icons/light/arrow_down.png);} nav ul li.i_arrow_down_left a span, .i_arrow_down_left{ background-image: url(../images/icons/light/arrow_down_left.png);} nav ul li.i_arrow_down_right a span, .i_arrow_down_right{ background-image: url(../images/icons/light/arrow_down_right.png);} nav ul li.i_arrow_left a span, .i_arrow_left{ background-image: url(../images/icons/light/arrow_left.png);} nav ul li.i_arrow_right a span, .i_arrow_right{ background-image: url(../images/icons/light/arrow_right.png);} nav ul li.i_arrow_up a span, .i_arrow_up{ background-image: url(../images/icons/light/arrow_up.png);} nav ul li.i_arrow_up_left a span, .i_arrow_up_left{ background-image: url(../images/icons/light/arrow_up_left.png);} nav ul li.i_arrow_up_right a span, .i_arrow_up_right{ background-image: url(../images/icons/light/arrow_up_right.png);} nav ul li.i_bag a span, .i_bag{ background-image: url(../images/icons/light/bag.png);} nav ul li.i_balloons a span, .i_balloons{ background-image: url(../images/icons/light/balloons.png);} nav ul li.i_bandaid a span, .i_bandaid{ background-image: url(../images/icons/light/bandaid.png);} nav ul li.i_battery a span, .i_battery{ background-image: url(../images/icons/light/battery.png);} nav ul li.i_battery_33 a span, .i_battery_33{ background-image: url(../images/icons/light/battery_33.png);} nav ul li.i_battery_66 a span, .i_battery_66{ background-image: url(../images/icons/light/battery_66.png);} nav ul li.i_battery_empty a span, .i_battery_empty{ background-image: url(../images/icons/light/battery_empty.png);} nav ul li.i_battery_full a span, .i_battery_full{ background-image: url(../images/icons/light/battery_full.png);} nav ul li.i_bended_arrow_down a span, .i_bended_arrow_down{ background-image: url(../images/icons/light/bended_arrow_down.png);} nav ul li.i_bended_arrow_left a span, .i_bended_arrow_left{ background-image: url(../images/icons/light/bended_arrow_left.png);} nav ul li.i_bended_arrow_right a span, .i_bended_arrow_right{ background-image: url(../images/icons/light/bended_arrow_right.png);} nav ul li.i_bended_arrow_up a span, .i_bended_arrow_up{ background-image: url(../images/icons/light/bended_arrow_up.png);} nav ul li.i_big_brush a span, .i_big_brush{ background-image: url(../images/icons/light/big_brush.png);} nav ul li.i_blackberry a span, .i_blackberry{ background-image: url(../images/icons/light/blackberry.png);} nav ul li.i_blocks_images a span, .i_blocks_images{ background-image: url(../images/icons/light/blocks_images.png);} nav ul li.i_blu-ray a span, .i_blu-ray{ background-image: url(../images/icons/light/blu-ray.png);} nav ul li.i_bluetooth a span, .i_bluetooth{ background-image: url(../images/icons/light/bluetooth.png);} nav ul li.i_bluetooth_2 a span, .i_bluetooth_2{ background-image: url(../images/icons/light/bluetooth_2.png);} nav ul li.i_book a span, .i_book{ background-image: url(../images/icons/light/book.png);} nav ul li.i_book_large a span, .i_book_large{ background-image: url(../images/icons/light/book_large.png);} nav ul li.i_books a span, .i_books{ background-image: url(../images/icons/light/books.png);} nav ul li.i_breadcrumb a span, .i_breadcrumb{ background-image: url(../images/icons/light/breadcrumb.png);} nav ul li.i_brush a span, .i_brush{ background-image: url(../images/icons/light/brush.png);} nav ul li.i_buildings a span, .i_buildings{ background-image: url(../images/icons/light/buildings.png);} nav ul li.i_bulls_eye a span, .i_bulls_eye{ background-image: url(../images/icons/light/bulls_eye.png);} nav ul li.i_calculator a span, .i_calculator{ background-image: url(../images/icons/light/calculator.png);} nav ul li.i_calendar a span, .i_calendar{ background-image: url(../images/icons/light/calendar.png);} nav ul li.i_calendar_day a span, .i_calendar_day{ background-image: url(../images/icons/light/calendar_day.png);} nav ul li.i_camera a span, .i_camera{ background-image: url(../images/icons/light/camera.png);} nav ul li.i_camera_2 a span, .i_camera_2{ background-image: url(../images/icons/light/camera_2.png);} nav ul li.i_car a span, .i_car{ background-image: url(../images/icons/light/car.png);} nav ul li.i_cash_register a span, .i_cash_register{ background-image: url(../images/icons/light/cash_register.png);} nav ul li.i_cassette a span, .i_cassette{ background-image: url(../images/icons/light/cassette.png);} nav ul li.i_cat a span, .i_cat{ background-image: url(../images/icons/light/cat.png);} nav ul li.i_cd a span, .i_cd{ background-image: url(../images/icons/light/cd.png);} nav ul li.i_chair a span, .i_chair{ background-image: url(../images/icons/light/chair.png);} nav ul li.i_chart a span, .i_chart{ background-image: url(../images/icons/light/chart.png);} nav ul li.i_chart_2 a span, .i_chart_2{ background-image: url(../images/icons/light/chart_2.png);} nav ul li.i_chart_3 a span, .i_chart_3{ background-image: url(../images/icons/light/chart_3.png);} nav ul li.i_chart_4 a span, .i_chart_4{ background-image: url(../images/icons/light/chart_4.png);} nav ul li.i_chart_5 a span, .i_chart_5{ background-image: url(../images/icons/light/chart_5.png);} nav ul li.i_chart_6 a span, .i_chart_6{ background-image: url(../images/icons/light/chart_6.png);} nav ul li.i_chart_7 a span, .i_chart_7{ background-image: url(../images/icons/light/chart_7.png);} nav ul li.i_chart_8 a span, .i_chart_8{ background-image: url(../images/icons/light/chart_8.png);} nav ul li.i_chemical a span, .i_chemical{ background-image: url(../images/icons/light/chemical.png);} nav ul li.i_chrome a span, .i_chrome{ background-image: url(../images/icons/light/chrome.png);} nav ul li.i_clipboard a span, .i_clipboard{ background-image: url(../images/icons/light/clipboard.png);} nav ul li.i_clock a span, .i_clock{ background-image: url(../images/icons/light/clock.png);} nav ul li.i_cloud a span, .i_cloud{ background-image: url(../images/icons/light/cloud.png);} nav ul li.i_cloud_download a span, .i_cloud_download{ background-image: url(../images/icons/light/cloud_download.png);} nav ul li.i_cloud_upload a span, .i_cloud_upload{ background-image: url(../images/icons/light/cloud_upload.png);} nav ul li.i_cog a span, .i_cog{ background-image: url(../images/icons/light/cog.png);} nav ul li.i_cog_2 a span, .i_cog_2{ background-image: url(../images/icons/light/cog_2.png);} nav ul li.i_cog_3 a span, .i_cog_3{ background-image: url(../images/icons/light/cog_3.png);} nav ul li.i_cog_4 a span, .i_cog_4{ background-image: url(../images/icons/light/cog_4.png);} nav ul li.i_collapse a span, .i_collapse{ background-image: url(../images/icons/light/collapse.png);} nav ul li.i_companies a span, .i_companies{ background-image: url(../images/icons/light/companies.png);} nav ul li.i_compress a span, .i_compress{ background-image: url(../images/icons/light/compress.png);} nav ul li.i_copy a span, .i_copy{ background-image: url(../images/icons/light/copy.png);} nav ul li.i_coverflow a span, .i_coverflow{ background-image: url(../images/icons/light/coverflow.png);} nav ul li.i_create_write a span, .i_create_write{ background-image: url(../images/icons/light/create_write.png);} nav ul li.i_cross a span, .i_cross{ background-image: url(../images/icons/light/cross.png);} nav ul li.i_cup a span, .i_cup{ background-image: url(../images/icons/light/cup.png);} nav ul li.i_cursor a span, .i_cursor{ background-image: url(../images/icons/light/cursor.png);} nav ul li.i_delicious a span, .i_delicious{ background-image: url(../images/icons/light/delicious.png);} nav ul li.i_desk a span, .i_desk{ background-image: url(../images/icons/light/desk.png);} nav ul li.i_digg a span, .i_digg{ background-image: url(../images/icons/light/digg.png);} nav ul li.i_digg_2 a span, .i_digg_2{ background-image: url(../images/icons/light/digg_2.png);} nav ul li.i_document a span, .i_document{ background-image: url(../images/icons/light/document.png);} nav ul li.i_document_add a span, .i_document_add{ background-image: url(../images/icons/light/document_add.png);} nav ul li.i_document_delete a span, .i_document_delete{ background-image: url(../images/icons/light/document_delete.png);} nav ul li.i_documents a span, .i_documents{ background-image: url(../images/icons/light/documents.png);} nav ul li.i_download a span, .i_download{ background-image: url(../images/icons/light/download.png);} nav ul li.i_download_to_computer a span, .i_download_to_computer{ background-image: url(../images/icons/light/download_to_computer.png);} nav ul li.i_dress a span, .i_dress{ background-image: url(../images/icons/light/dress.png);} nav ul li.i_dribbble a span, .i_dribbble{ background-image: url(../images/icons/light/dribbble.png);} nav ul li.i_dribbble_2 a span, .i_dribbble_2{ background-image: url(../images/icons/light/dribbble_2.png);} nav ul li.i_dropbox a span, .i_dropbox{ background-image: url(../images/icons/light/dropbox.png);} nav ul li.i_drupal a span, .i_drupal{ background-image: url(../images/icons/light/drupal.png);} nav ul li.i_duplicate a span, .i_duplicate{ background-image: url(../images/icons/light/duplicate.png);} nav ul li.i_dvd a span, .i_dvd{ background-image: url(../images/icons/light/dvd.png);} nav ul li.i_eject a span, .i_eject{ background-image: url(../images/icons/light/eject.png);} nav ul li.i_electricty_input a span, .i_electricty_input{ background-image: url(../images/icons/light/electricty_input.png);} nav ul li.i_electricty_plug a span, .i_electricty_plug{ background-image: url(../images/icons/light/electricty_plug.png);} nav ul li.i_empty a span, .i_empty{ background-image: url(../images/icons/light/empty.png);} nav ul li.i_excel_document a span, .i_excel_document{ background-image: url(../images/icons/light/excel_document.png);} nav ul li.i_excel_documents a span, .i_excel_documents{ background-image: url(../images/icons/light/excel_documents.png);} nav ul li.i_exclamation a span, .i_exclamation{ background-image: url(../images/icons/light/exclamation.png);} nav ul li.i_exit a span, .i_exit{ background-image: url(../images/icons/light/exit.png);} nav ul li.i_expand a span, .i_expand{ background-image: url(../images/icons/light/expand.png);} nav ul li.i_expose a span, .i_expose{ background-image: url(../images/icons/light/expose.png);} nav ul li.i_expression_engine a span, .i_expression_engine{ background-image: url(../images/icons/light/expression_engine.png);} nav ul li.i_eyedropper a span, .i_eyedropper{ background-image: url(../images/icons/light/eyedropper.png);} nav ul li.i_facebook a span, .i_facebook{ background-image: url(../images/icons/light/facebook.png);} nav ul li.i_facebook_like a span, .i_facebook_like{ background-image: url(../images/icons/light/facebook_like.png);} nav ul li.i_fax a span, .i_fax{ background-image: url(../images/icons/light/fax.png);} nav ul li.i_female a span, .i_female{ background-image: url(../images/icons/light/female.png);} nav ul li.i_female_contour a span, .i_female_contour{ background-image: url(../images/icons/light/female_contour.png);} nav ul li.i_file_cabinet a span, .i_file_cabinet{ background-image: url(../images/icons/light/file_cabinet.png);} nav ul li.i_film a span, .i_film{ background-image: url(../images/icons/light/film.png);} nav ul li.i_film_2 a span, .i_film_2{ background-image: url(../images/icons/light/film_2.png);} nav ul li.i_filmcamera a span, .i_filmcamera{ background-image: url(../images/icons/light/filmcamera.png);} nav ul li.i_finish_flag a span, .i_finish_flag{ background-image: url(../images/icons/light/finish_flag.png);} nav ul li.i_firefox a span, .i_firefox{ background-image: url(../images/icons/light/firefox.png);} nav ul li.i_flag a span, .i_flag{ background-image: url(../images/icons/light/flag.png);} nav ul li.i_flag_2 a span, .i_flag_2{ background-image: url(../images/icons/light/flag_2.png);} nav ul li.i_folder a span, .i_folder{ background-image: url(../images/icons/light/folder.png);} nav ul li.i_folder_add a span, .i_folder_add{ background-image: url(../images/icons/light/folder_add.png);} nav ul li.i_folder_closed a span, .i_folder_closed{ background-image: url(../images/icons/light/folder_closed.png);} nav ul li.i_folder_delete a span, .i_folder_delete{ background-image: url(../images/icons/light/folder_delete.png);} nav ul li.i_folder_download a span, .i_folder_download{ background-image: url(../images/icons/light/folder_download.png);} nav ul li.i_folder_lock a span, .i_folder_lock{ background-image: url(../images/icons/light/folder_lock.png);} nav ul li.i_folder_love a span, .i_folder_love{ background-image: url(../images/icons/light/folder_love.png);} nav ul li.i_folder_upload a span, .i_folder_upload{ background-image: url(../images/icons/light/folder_upload.png);} nav ul li.i_footprint a span, .i_footprint{ background-image: url(../images/icons/light/footprint.png);} nav ul li.i_forward a span, .i_forward{ background-image: url(../images/icons/light/forward.png);} nav ul li.i_fountain_pen a span, .i_fountain_pen{ background-image: url(../images/icons/light/fountain_pen.png);} nav ul li.i_frames a span, .i_frames{ background-image: url(../images/icons/light/frames.png);} nav ul li.i_fullscreen a span, .i_fullscreen{ background-image: url(../images/icons/light/fullscreen.png);} nav ul li.i_globe a span, .i_globe{ background-image: url(../images/icons/light/globe.png);} nav ul li.i_globe_2 a span, .i_globe_2{ background-image: url(../images/icons/light/globe_2.png);} nav ul li.i_google_buzz a span, .i_google_buzz{ background-image: url(../images/icons/light/google_buzz.png);} nav ul li.i_google_maps a span, .i_google_maps{ background-image: url(../images/icons/light/google_maps.png);} nav ul li.i_graph a span, .i_graph{ background-image: url(../images/icons/light/graph.png);} nav ul li.i_grid a span, .i_grid{ background-image: url(../images/icons/light/grid.png);} nav ul li.i_hd a span, .i_hd{ background-image: url(../images/icons/light/hd.png);} nav ul li.i_hd_2 a span, .i_hd_2{ background-image: url(../images/icons/light/hd_2.png);} nav ul li.i_hd_3 a span, .i_hd_3{ background-image: url(../images/icons/light/hd_3.png);} nav ul li.i_headphones a span, .i_headphones{ background-image: url(../images/icons/light/headphones.png);} nav ul li.i_help a span, .i_help{ background-image: url(../images/icons/light/help.png);} nav ul li.i_house a span, .i_house{ background-image: url(../images/icons/light/house.png);} nav ul li.i_house_2 a span, .i_house_2{ background-image: url(../images/icons/light/house_2.png);} nav ul li.i_ice_cream a span, .i_ice_cream{ background-image: url(../images/icons/light/ice_cream.png);} nav ul li.i_ice_cream_2 a span, .i_ice_cream_2{ background-image: url(../images/icons/light/ice_cream_2.png);} nav ul li.i_ichat a span, .i_ichat{ background-image: url(../images/icons/light/ichat.png);} nav ul li.i_imac a span, .i_imac{ background-image: url(../images/icons/light/imac.png);} nav ul li.i_image a span, .i_image{ background-image: url(../images/icons/light/image.png);} nav ul li.i_image_2 a span, .i_image_2{ background-image: url(../images/icons/light/image_2.png);} nav ul li.i_images a span, .i_images{ background-image: url(../images/icons/light/images.png);} nav ul li.i_images_2 a span, .i_images_2{ background-image: url(../images/icons/light/images_2.png);} nav ul li.i_inbox a span, .i_inbox{ background-image: url(../images/icons/light/inbox.png);} nav ul li.i_incomming a span, .i_incomming{ background-image: url(../images/icons/light/incomming.png);} nav ul li.i_information a span, .i_information{ background-image: url(../images/icons/light/information.png);} nav ul li.i_ipad a span, .i_ipad{ background-image: url(../images/icons/light/ipad.png);} nav ul li.i_iphone_3g a span, .i_iphone_3g{ background-image: url(../images/icons/light/iphone_3g.png);} nav ul li.i_iphone_4 a span, .i_iphone_4{ background-image: url(../images/icons/light/iphone_4.png);} nav ul li.i_ipod a span, .i_ipod{ background-image: url(../images/icons/light/ipod.png);} nav ul li.i_ipod_nano a span, .i_ipod_nano{ background-image: url(../images/icons/light/ipod_nano.png);} nav ul li.i_joomla a span, .i_joomla{ background-image: url(../images/icons/light/joomla.png);} nav ul li.i_key a span, .i_key{ background-image: url(../images/icons/light/key.png);} nav ul li.i_key_2 a span, .i_key_2{ background-image: url(../images/icons/light/key_2.png);} nav ul li.i_ladys_purse a span, .i_ladys_purse{ background-image: url(../images/icons/light/ladys_purse.png);} nav ul li.i_lamp a span, .i_lamp{ background-image: url(../images/icons/light/lamp.png);} nav ul li.i_laptop a span, .i_laptop{ background-image: url(../images/icons/light/laptop.png);} nav ul li.i_lastfm a span, .i_lastfm{ background-image: url(../images/icons/light/lastfm.png);} nav ul li.i_lemonade_stand a span, .i_lemonade_stand{ background-image: url(../images/icons/light/lemonade_stand.png);} nav ul li.i_light_bulb a span, .i_light_bulb{ background-image: url(../images/icons/light/light_bulb.png);} nav ul li.i_link a span, .i_link{ background-image: url(../images/icons/light/link.png);} nav ul li.i_link_2 a span, .i_link_2{ background-image: url(../images/icons/light/link_2.png);} nav ul li.i_linux a span, .i_linux{ background-image: url(../images/icons/light/linux.png);} nav ul li.i_list a span, .i_list{ background-image: url(../images/icons/light/list.png);} nav ul li.i_list_image a span, .i_list_image{ background-image: url(../images/icons/light/list_image.png);} nav ul li.i_list_images a span, .i_list_images{ background-image: url(../images/icons/light/list_images.png);} nav ul li.i_loading_bar a span, .i_loading_bar{ background-image: url(../images/icons/light/loading_bar.png);} nav ul li.i_locked a span, .i_locked{ background-image: url(../images/icons/light/locked.png);} nav ul li.i_locked_2 a span, .i_locked_2{ background-image: url(../images/icons/light/locked_2.png);} nav ul li.i_macos a span, .i_macos{ background-image: url(../images/icons/light/macos.png);} nav ul li.i_magic_mouse a span, .i_magic_mouse{ background-image: url(../images/icons/light/magic_mouse.png);} nav ul li.i_magnifying_glass a span, .i_magnifying_glass{ background-image: url(../images/icons/light/magnifying_glass.png);} nav ul li.i_mail a span, .i_mail{ background-image: url(../images/icons/light/mail.png);} nav ul li.i_male a span, .i_male{ background-image: url(../images/icons/light/male.png);} nav ul li.i_male_contour a span, .i_male_contour{ background-image: url(../images/icons/light/male_contour.png);} nav ul li.i_map a span, .i_map{ background-image: url(../images/icons/light/map.png);} nav ul li.i_marker a span, .i_marker{ background-image: url(../images/icons/light/marker.png);} nav ul li.i_maximize a span, .i_maximize{ background-image: url(../images/icons/light/maximize.png);} nav ul li.i_medical_case a span, .i_medical_case{ background-image: url(../images/icons/light/medical_case.png);} nav ul li.i_megaphone a span, .i_megaphone{ background-image: url(../images/icons/light/megaphone.png);} nav ul li.i_microphone a span, .i_microphone{ background-image: url(../images/icons/light/microphone.png);} nav ul li.i_mighty_mouse a span, .i_mighty_mouse{ background-image: url(../images/icons/light/mighty_mouse.png);} nav ul li.i_minimize a span, .i_minimize{ background-image: url(../images/icons/light/minimize.png);} nav ul li.i_minus a span, .i_minus{ background-image: url(../images/icons/light/minus.png);} nav ul li.i_mobile_phone a span, .i_mobile_phone{ background-image: url(../images/icons/light/mobile_phone.png);} nav ul li.i_mobypicture a span, .i_mobypicture{ background-image: url(../images/icons/light/mobypicture.png);} nav ul li.i_money a span, .i_money{ background-image: url(../images/icons/light/money.png);} nav ul li.i_money_2 a span, .i_money_2{ background-image: url(../images/icons/light/money_2.png);} nav ul li.i_monitor a span, .i_monitor{ background-image: url(../images/icons/light/monitor.png);} nav ul li.i_mouse a span, .i_mouse{ background-image: url(../images/icons/light/mouse.png);} nav ul li.i_myspace a span, .i_myspace{ background-image: url(../images/icons/light/myspace.png);} nav ul li.i_next a span, .i_next{ background-image: url(../images/icons/light/next.png);} nav ul li.i_note_book a span, .i_note_book{ background-image: url(../images/icons/light/note_book.png);} nav ul li.i_outgoing a span, .i_outgoing{ background-image: url(../images/icons/light/outgoing.png);} nav ul li.i_pacman a span, .i_pacman{ background-image: url(../images/icons/light/pacman.png);} nav ul li.i_pacman_ghost a span, .i_pacman_ghost{ background-image: url(../images/icons/light/pacman_ghost.png);} nav ul li.i_paint_brush a span, .i_paint_brush{ background-image: url(../images/icons/light/paint_brush.png);} nav ul li.i_pants a span, .i_pants{ background-image: url(../images/icons/light/pants.png);} nav ul li.i_paperclip a span, .i_paperclip{ background-image: url(../images/icons/light/paperclip.png);} nav ul li.i_paste a span, .i_paste{ background-image: url(../images/icons/light/paste.png);} nav ul li.i_pause a span, .i_pause{ background-image: url(../images/icons/light/pause.png);} nav ul li.i_paypal a span, .i_paypal{ background-image: url(../images/icons/light/paypal.png);} nav ul li.i_paypal_2 a span, .i_paypal_2{ background-image: url(../images/icons/light/paypal_2.png);} nav ul li.i_paypal_3 a span, .i_paypal_3{ background-image: url(../images/icons/light/paypal_3.png);} nav ul li.i_pdf_document a span, .i_pdf_document{ background-image: url(../images/icons/light/pdf_document.png);} nav ul li.i_pdf_documents a span, .i_pdf_documents{ background-image: url(../images/icons/light/pdf_documents.png);} nav ul li.i_pencil a span, .i_pencil{ background-image: url(../images/icons/light/pencil.png);} nav ul li.i_phone a span, .i_phone{ background-image: url(../images/icons/light/phone.png);} nav ul li.i_phone_2 a span, .i_phone_2{ background-image: url(../images/icons/light/phone_2.png);} nav ul li.i_phone_hook a span, .i_phone_hook{ background-image: url(../images/icons/light/phone_hook.png);} nav ul li.i_piggy_bank a span, .i_piggy_bank{ background-image: url(../images/icons/light/piggy_bank.png);} nav ul li.i_plane_suitecase a span, .i_plane_suitecase{ background-image: url(../images/icons/light/plane_suitecase.png);} nav ul li.i_play a span, .i_play{ background-image: url(../images/icons/light/play.png);} nav ul li.i_plixi a span, .i_plixi{ background-image: url(../images/icons/light/plixi.png);} nav ul li.i_plus a span, .i_plus{ background-image: url(../images/icons/light/plus.png);} nav ul li.i_post_card a span, .i_post_card{ background-image: url(../images/icons/light/post_card.png);} nav ul li.i_power a span, .i_power{ background-image: url(../images/icons/light/power.png);} nav ul li.i_powerpoint_document a span, .i_powerpoint_document{ background-image: url(../images/icons/light/powerpoint_document.png);} nav ul li.i_powerpoint_documents a span, .i_powerpoint_documents{ background-image: url(../images/icons/light/powerpoint_documents.png);} nav ul li.i_presentation a span, .i_presentation{ background-image: url(../images/icons/light/presentation.png);} nav ul li.i_prev a span, .i_prev{ background-image: url(../images/icons/light/prev.png);} nav ul li.i_preview a span, .i_preview{ background-image: url(../images/icons/light/preview.png);} nav ul li.i_price_tag a span, .i_price_tag{ background-image: url(../images/icons/light/price_tag.png);} nav ul li.i_price_tags a span, .i_price_tags{ background-image: url(../images/icons/light/price_tags.png);} nav ul li.i_printer a span, .i_printer{ background-image: url(../images/icons/light/printer.png);} nav ul li.i_question a span, .i_question{ background-image: url(../images/icons/light/question.png);} nav ul li.i_radio a span, .i_radio{ background-image: url(../images/icons/light/radio.png);} nav ul li.i_record a span, .i_record{ background-image: url(../images/icons/light/record.png);} nav ul li.i_recycle a span, .i_recycle{ background-image: url(../images/icons/light/recycle.png);} nav ul li.i_refresh a span, .i_refresh{ background-image: url(../images/icons/light/refresh.png);} nav ul li.i_refresh_2 a span, .i_refresh_2{ background-image: url(../images/icons/light/refresh_2.png);} nav ul li.i_refresh_3 a span, .i_refresh_3{ background-image: url(../images/icons/light/refresh_3.png);} nav ul li.i_refresh_4 a span, .i_refresh_4{ background-image: url(../images/icons/light/refresh_4.png);} nav ul li.i_repeat a span, .i_repeat{ background-image: url(../images/icons/light/repeat.png);} nav ul li.i_rewind a span, .i_rewind{ background-image: url(../images/icons/light/rewind.png);} nav ul li.i_robot a span, .i_robot{ background-image: url(../images/icons/light/robot.png);} nav ul li.i_rss a span, .i_rss{ background-image: url(../images/icons/light/rss.png);} nav ul li.i_ruler a span, .i_ruler{ background-image: url(../images/icons/light/ruler.png);} nav ul li.i_ruler_2 a span, .i_ruler_2{ background-image: url(../images/icons/light/ruler_2.png);} nav ul li.i_running_man a span, .i_running_man{ background-image: url(../images/icons/light/running_man.png);} nav ul li.i_safari a span, .i_safari{ background-image: url(../images/icons/light/safari.png);} nav ul li.i_scan_label a span, .i_scan_label{ background-image: url(../images/icons/light/scan_label.png);} nav ul li.i_scissors a span, .i_scissors{ background-image: url(../images/icons/light/scissors.png);} nav ul li.i_sd a span, .i_sd{ background-image: url(../images/icons/light/sd.png);} nav ul li.i_sd_2 a span, .i_sd_2{ background-image: url(../images/icons/light/sd_2.png);} nav ul li.i_sd_3 a span, .i_sd_3{ background-image: url(../images/icons/light/sd_3.png);} nav ul li.i_settings a span, .i_settings{ background-image: url(../images/icons/light/settings.png);} nav ul li.i_settings_2 a span, .i_settings_2{ background-image: url(../images/icons/light/settings_2.png);} nav ul li.i_shopping_bag a span, .i_shopping_bag{ background-image: url(../images/icons/light/shopping_bag.png);} nav ul li.i_shopping_basket a span, .i_shopping_basket{ background-image: url(../images/icons/light/shopping_basket.png);} nav ul li.i_shopping_basket_2 a span, .i_shopping_basket_2{ background-image: url(../images/icons/light/shopping_basket_2.png);} nav ul li.i_shopping_cart a span, .i_shopping_cart{ background-image: url(../images/icons/light/shopping_cart.png);} nav ul li.i_shopping_cart_2 a span, .i_shopping_cart_2{ background-image: url(../images/icons/light/shopping_cart_2.png);} nav ul li.i_shopping_cart_3 a span, .i_shopping_cart_3{ background-image: url(../images/icons/light/shopping_cart_3.png);} nav ul li.i_shopping_cart_4 a span, .i_shopping_cart_4{ background-image: url(../images/icons/light/shopping_cart_4.png);} nav ul li.i_shuffle a span, .i_shuffle{ background-image: url(../images/icons/light/shuffle.png);} nav ul li.i_sign_post a span, .i_sign_post{ background-image: url(../images/icons/light/sign_post.png);} nav ul li.i_skype a span, .i_skype{ background-image: url(../images/icons/light/skype.png);} nav ul li.i_sleeveless_shirt a span, .i_sleeveless_shirt{ background-image: url(../images/icons/light/sleeveless_shirt.png);} nav ul li.i_socks a span, .i_socks{ background-image: url(../images/icons/light/socks.png);} nav ul li.i_sound a span, .i_sound{ background-image: url(../images/icons/light/sound.png);} nav ul li.i_speech_bubble a span, .i_speech_bubble{ background-image: url(../images/icons/light/speech_bubble.png);} nav ul li.i_speech_bubble_2 a span, .i_speech_bubble_2{ background-image: url(../images/icons/light/speech_bubble_2.png);} nav ul li.i_speech_bubbles a span, .i_speech_bubbles{ background-image: url(../images/icons/light/speech_bubbles.png);} nav ul li.i_speech_bubbles_2 a span, .i_speech_bubbles_2{ background-image: url(../images/icons/light/speech_bubbles_2.png);} nav ul li.i_sport_shirt a span, .i_sport_shirt{ background-image: url(../images/icons/light/sport_shirt.png);} nav ul li.i_stop a span, .i_stop{ background-image: url(../images/icons/light/stop.png);} nav ul li.i_stop_watch a span, .i_stop_watch{ background-image: url(../images/icons/light/stop_watch.png);} nav ul li.i_strategy a span, .i_strategy{ background-image: url(../images/icons/light/strategy.png);} nav ul li.i_strategy_2 a span, .i_strategy_2{ background-image: url(../images/icons/light/strategy_2.png);} nav ul li.i_stubleupon a span, .i_stubleupon{ background-image: url(../images/icons/light/stubleupon.png);} nav ul li.i_suitecase a span, .i_suitecase{ background-image: url(../images/icons/light/suitecase.png);} nav ul li.i_sweater a span, .i_sweater{ background-image: url(../images/icons/light/sweater.png);} nav ul li.i_t-shirt a span, .i_t-shirt{ background-image: url(../images/icons/light/t-shirt.png);} nav ul li.i_table a span, .i_table{ background-image: url(../images/icons/light/table.png);} nav ul li.i_tag a span, .i_tag{ background-image: url(../images/icons/light/tag.png);} nav ul li.i_tags a span, .i_tags{ background-image: url(../images/icons/light/tags.png);} nav ul li.i_television a span, .i_television{ background-image: url(../images/icons/light/television.png);} nav ul li.i_tick a span, .i_tick{ background-image: url(../images/icons/light/tick.png);} nav ul li.i_timer a span, .i_timer{ background-image: url(../images/icons/light/timer.png);} nav ul li.i_trashcan a span, .i_trashcan{ background-image: url(../images/icons/light/trashcan.png);} nav ul li.i_trashcan_2 a span, .i_trashcan_2{ background-image: url(../images/icons/light/trashcan_2.png);} nav ul li.i_travel_suitecase a span, .i_travel_suitecase{ background-image: url(../images/icons/light/travel_suitecase.png);} nav ul li.i_tree a span, .i_tree{ background-image: url(../images/icons/light/tree.png);} nav ul li.i_triangle_double_down a span, .i_triangle_double_down{ background-image: url(../images/icons/light/triangle_double_down.png);} nav ul li.i_triangle_double_left a span, .i_triangle_double_left{ background-image: url(../images/icons/light/triangle_double_left.png);} nav ul li.i_triangle_double_right a span, .i_triangle_double_right{ background-image: url(../images/icons/light/triangle_double_right.png);} nav ul li.i_triangle_double_up a span, .i_triangle_double_up{ background-image: url(../images/icons/light/triangle_double_up.png);} nav ul li.i_triangle_down a span, .i_triangle_down{ background-image: url(../images/icons/light/triangle_down.png);} nav ul li.i_triangle_down_left a span, .i_triangle_down_left{ background-image: url(../images/icons/light/triangle_down_left.png);} nav ul li.i_triangle_down_right a span, .i_triangle_down_right{ background-image: url(../images/icons/light/triangle_down_right.png);} nav ul li.i_triangle_left a span, .i_triangle_left{ background-image: url(../images/icons/light/triangle_left.png);} nav ul li.i_triangle_left_right a span, .i_triangle_left_right{ background-image: url(../images/icons/light/triangle_left_right.png);} nav ul li.i_triangle_right a span, .i_triangle_right{ background-image: url(../images/icons/light/triangle_right.png);} nav ul li.i_triangle_up a span, .i_triangle_up{ background-image: url(../images/icons/light/triangle_up.png);} nav ul li.i_triangle_up_down a span, .i_triangle_up_down{ background-image: url(../images/icons/light/triangle_up_down.png);} nav ul li.i_triangle_up_left a span, .i_triangle_up_left{ background-image: url(../images/icons/light/triangle_up_left.png);} nav ul li.i_triangle_up_right a span, .i_triangle_up_right{ background-image: url(../images/icons/light/triangle_up_right.png);} nav ul li.i_trolly a span, .i_trolly{ background-image: url(../images/icons/light/trolly.png);} nav ul li.i_truck a span, .i_truck{ background-image: url(../images/icons/light/truck.png);} nav ul li.i_tumbler a span, .i_tumbler{ background-image: url(../images/icons/light/tumbler.png);} nav ul li.i_twitter a span, .i_twitter{ background-image: url(../images/icons/light/twitter.png);} nav ul li.i_twitter_2 a span, .i_twitter_2{ background-image: url(../images/icons/light/twitter_2.png);} nav ul li.i_typo a span, .i_typo{ background-image: url(../images/icons/light/typo.png);} nav ul li.i_umbrella a span, .i_umbrella{ background-image: url(../images/icons/light/umbrella.png);} nav ul li.i_under_construction a span, .i_under_construction{ background-image: url(../images/icons/light/under_construction.png);} nav ul li.i_unlocked a span, .i_unlocked{ background-image: url(../images/icons/light/unlocked.png);} nav ul li.i_upload a span, .i_upload{ background-image: url(../images/icons/light/upload.png);} nav ul li.i_user a span, .i_user{ background-image: url(../images/icons/light/user.png);} nav ul li.i_user_2 a span, .i_user_2{ background-image: url(../images/icons/light/user_2.png);} nav ul li.i_user_comment a span, .i_user_comment{ background-image: url(../images/icons/light/user_comment.png);} nav ul li.i_users a span, .i_users{ background-image: url(../images/icons/light/users.png);} nav ul li.i_users_2 a span, .i_users_2{ background-image: url(../images/icons/light/users_2.png);} nav ul li.i_v-card a span, .i_v-card{ background-image: url(../images/icons/light/v-card.png);} nav ul li.i_v-card_2 a span, .i_v-card_2{ background-image: url(../images/icons/light/v-card_2.png);} nav ul li.i_vault a span, .i_vault{ background-image: url(../images/icons/light/vault.png);} nav ul li.i_vimeo a span, .i_vimeo{ background-image: url(../images/icons/light/vimeo.png);} nav ul li.i_vimeo_2 a span, .i_vimeo_2{ background-image: url(../images/icons/light/vimeo_2.png);} nav ul li.i_walking_man a span, .i_walking_man{ background-image: url(../images/icons/light/walking_man.png);} nav ul li.i_wifi_signal a span, .i_wifi_signal{ background-image: url(../images/icons/light/wifi_signal.png);} nav ul li.i_wifi_signal_2 a span, .i_wifi_signal_2{ background-image: url(../images/icons/light/wifi_signal_2.png);} nav ul li.i_windows a span, .i_windows{ background-image: url(../images/icons/light/windows.png);} nav ul li.i_winner_podium a span, .i_winner_podium{ background-image: url(../images/icons/light/winner_podium.png);} nav ul li.i_wizard a span, .i_wizard{ background-image: url(../images/icons/light/wizard.png);} nav ul li.i_word_document a span, .i_word_document{ background-image: url(../images/icons/light/word_document.png);} nav ul li.i_word_documents a span, .i_word_documents{ background-image: url(../images/icons/light/word_documents.png);} nav ul li.i_wordpress a span, .i_wordpress{ background-image: url(../images/icons/light/wordpress.png);} nav ul li.i_wordpress_2 a span, .i_wordpress_2{ background-image: url(../images/icons/light/wordpress_2.png);} nav ul li.i_youtube a span, .i_youtube{ background-image: url(../images/icons/light/youtube.png);} nav ul li.i_youtube_2 a span, .i_youtube_2{ background-image: url(../images/icons/light/youtube_2.png);} nav ul li.i_zip_file a span, .i_zip_file{ background-image: url(../images/icons/light/zip_file.png);} nav ul li.i_zip_files a span, .i_zip_files{ background-image: url(../images/icons/light/zip_files.png);}
08102013project
trunk/CMS/Content/themes/base/dark/theme.css
CSS
oos
65,807
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace CMS { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
08102013project
trunk/CMS/Global.asax.cs
C#
oos
1,180
# Django settings for iphone12580 project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = '' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'w%4yt1@#$mqd$*_ip%1xhl+(mbg$+4i5qa5t#kp@ac5eyvp40d' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'iphone12580.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. '/Users/uc0079/iphone12580/templates' ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', )
12580iphone
trunk/settings.py
Python
bsd
2,829
from django.db import models # Create your models here.
12580iphone
trunk/coupon/models.py
Python
bsd
57
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.failUnlessEqual(1 + 1, 2) __test__ = {"doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True """}
12580iphone
trunk/coupon/tests.py
Python
bsd
514
# -*- coding: utf-8 -*- from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.shortcuts import render_to_response from django.core.paginator import Paginator,InvalidPage,EmptyPage def test(request): return HttpResponse("hello iphone") def index(request): return render_to_response("index.html",locals()) def dis_info(request): return render_to_response("discount.html",locals()) def hotel_info(request): return render_to_response("hotel_info.html",locals()) def flight_info(request): return render_to_response("flight_info.html",locals())
12580iphone
trunk/coupon/views.py
Python
bsd
595
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
12580iphone
trunk/.svn/text-base/manage.py.svn-base
Python
bsd
546
from django.conf.urls.defaults import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^iphone12580/', include('iphone12580.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^$','iphone12580.coupon.views.index'), (r'^discount','iphone12580.coupon.views.dis_info'), #优惠券信息 (r'^hotel','iphone12580.coupon.views.hotel_info'), #酒店信息 (r'^flight','iphone12580.coupon.views.flight_info') #机票信息 (r'^test/','iphone12580.coupon.views.test'), #临时测试 )
12580iphone
trunk/urls.py
Python
bsd
883
/*----------------------------- RESET STYLES -----------------------------*/ html, body, form, fieldset, p, div, h1, h2, h3, h4, h5, h6{ margin:0; padding:0; -webkit-text-size-adjust:none; } body{ font-size: 10px; } ul, li, ol, dl, dd, dt{ list-style:none; padding:0; margin:0; } a{ text-decoration:none; } /*----------------------------- BASIC PAGE STYLING -----------------------------*/ body{ background:#fff000; font-family: Helvetica; color:#999; } p{ font-size:12px; padding-bottom:8px; } a{ color:#fff000; text-decoration:none; } /*----------------------------- HEADINGS -----------------------------*/ h1{ display:block; width:112px; height:41px; background-image:url(images/logo.gif); text-indent:-5000px; } /*----------------------------- BASIC LAYOUT -----------------------------*/ #page_wrapper{ padding-top:20px; background:#000 url(images/page_background.gif) repeat-x; overflow:auto; }
12580iphone
trunk/templates/iphone.css
CSS
bsd
1,279
<!DOCTYPE HTML> <html lang="ru-RU"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> <link rel="apple-touch-icon" href="images/template/engage.png"/> <title>This is Title</title> </head> <body onorientationchange="updateOrientation();"> <div id="page_wrapper"> <h1>Engage Interactive</h1> <div id="content_left"> <p>You are now holding your phone to the left</p> </div> <div id="content_right"> <p>You are now holding your phone to the right</p> </div> <div id="content_normal"> <p>You are now holding your phone upright</p> </div> <div id="content_flipped"> <p>This doesn't work yet.</p> </div> </div> </body> </html>
12580iphone
trunk/templates/index.html
HTML
bsd
812
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
12580iphone
trunk/manage.py
Python
bsd
546
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.os.Looper; import android.util.Log; public class CacheableBitmapDrawable extends BitmapDrawable { static final String LOG_TAG = "CacheableBitmapDrawable"; // URL Associated with this Bitmap private final String mUrl; private BitmapLruCache.RecyclePolicy mRecyclePolicy; // Number of Views currently displaying bitmap private int mDisplayingCount; // Has it been displayed yet private boolean mHasBeenDisplayed; // Number of caches currently referencing the wrapper private int mCacheCount; // The CheckStateRunnable currently being delayed private Runnable mCheckStateRunnable; // Throwable which records the stack trace when we recycle private Throwable mStackTraceWhenRecycled; // Handler which may be used later private static final Handler sHandler = new Handler(Looper.getMainLooper()); CacheableBitmapDrawable(String url, Resources resources, Bitmap bitmap, BitmapLruCache.RecyclePolicy recyclePolicy) { super(resources, bitmap); mUrl = url; mRecyclePolicy = recyclePolicy; mDisplayingCount = 0; mCacheCount = 0; } @Override public void draw(Canvas canvas) { try { Bitmap bitmap = getBitmap(); if (bitmap != null && !bitmap.isRecycled()) super.draw(canvas); } catch (RuntimeException re) { // A RuntimeException has been thrown, probably due to a recycled // Bitmap. If we have // one, print the method stack when the recycle() call happened if (null != mStackTraceWhenRecycled) { mStackTraceWhenRecycled.printStackTrace(); } // Finally throw the original exception throw re; } } /** * @return Amount of heap size currently being used by {@code Bitmap} */ int getMemorySize() { int size = 0; final Bitmap bitmap = getBitmap(); if (null != bitmap && !bitmap.isRecycled()) { size = bitmap.getRowBytes() * bitmap.getHeight(); } return size; } /** * @return the URL associated with the BitmapDrawable */ public String getUrl() { return mUrl; } /** * Returns true when this wrapper has a bitmap and the bitmap has not been * recycled. * * @return true - if the bitmap has not been recycled. */ public synchronized boolean hasValidBitmap() { Bitmap bitmap = getBitmap(); return null != bitmap && !bitmap.isRecycled(); } /** * @return true - if the bitmap is currently being displayed by a * {@link CacheableImageView}. */ public synchronized boolean isBeingDisplayed() { return mDisplayingCount > 0; } /** * @return true - if the wrapper is currently referenced by a cache. */ public synchronized boolean isReferencedByCache() { return mCacheCount > 0; } /** * Used to signal to the Drawable whether it is being used or not. * * @param beingUsed * - true if being used, false if not. */ public synchronized void setBeingUsed(boolean beingUsed) { if (beingUsed) { mDisplayingCount++; mHasBeenDisplayed = true; } else { mDisplayingCount--; } checkState(); } /** * Used to signal to the wrapper whether it is being referenced by a cache * or not. * * @param added * - true if the wrapper has been added to a cache, false if * removed. */ synchronized void setCached(boolean added) { if (added) { mCacheCount++; } else { mCacheCount--; } checkState(); } private void cancelCheckStateCallback() { if (null != mCheckStateRunnable) { if (Constants.DEBUG) { Log.d(LOG_TAG, "Cancelling checkState() callback for: " + mUrl); } sHandler.removeCallbacks(mCheckStateRunnable); mCheckStateRunnable = null; } } /** * Calls {@link #checkState(boolean)} with default parameter of * <code>false</code>. */ private void checkState() { checkState(false); } /** * Checks whether the wrapper is currently referenced by a cache, and is * being displayed. If neither of those conditions are met then the bitmap * is ready to be recycled. Whether this happens now, or is delayed depends * on whether the Drawable has been displayed or not. * <ul> * <li>If it has been displayed, it is recycled straight away.</li> * <li>If it has not been displayed, and <code>ignoreBeenDisplayed</code> is * <code>false</code>, a call to <code>checkState(true)</code> is queued to * be called after a delay.</li> * <li>If it has not been displayed, and <code>ignoreBeenDisplayed</code> is * <code>true</code>, it is recycled straight away.</li> * </ul> * * @param ignoreBeenDisplayed * - Whether to ignore the 'has been displayed' flag when * deciding whether to recycle() now. * @see Constants#UNUSED_DRAWABLE_RECYCLE_DELAY_MS */ private synchronized void checkState(final boolean ignoreBeenDisplayed) { if (Constants.DEBUG) { Log.d(LOG_TAG, String.format( "checkState(). Been Displayed: %b, Displaying: %d, Caching: %d, URL: %s", mHasBeenDisplayed, mDisplayingCount, mCacheCount, mUrl)); } // If the policy doesn't let us recycle, return now if (!mRecyclePolicy.canRecycle()) { return; } // Cancel the callback, if one is queued. cancelCheckStateCallback(); // We're not being referenced or used anywhere if (mCacheCount <= 0 && mDisplayingCount <= 0 && hasValidBitmap()) { /** * If we have been displayed or we don't care whether we have been * or not, then recycle() now. Otherwise, we retry after a delay. */ if (mHasBeenDisplayed || ignoreBeenDisplayed) { if (Constants.DEBUG) { Log.d(LOG_TAG, "Recycling bitmap with url: " + mUrl); } // Record the current method stack just in case mStackTraceWhenRecycled = new Throwable( "Recycled Bitmap Method Stack"); getBitmap().recycle(); } else { if (Constants.DEBUG) { Log.d(LOG_TAG, "Unused Bitmap which hasn't been displayed, delaying recycle(): " + mUrl); } mCheckStateRunnable = new CheckStateRunnable(this); sHandler.postDelayed(mCheckStateRunnable, Constants.UNUSED_DRAWABLE_RECYCLE_DELAY_MS); } } } /** * Runnable which run a {@link CacheableBitmapDrawable#checkState(boolean) * checkState(false)} call. * * @author chrisbanes */ private static final class CheckStateRunnable extends WeakReferenceRunnable<CacheableBitmapDrawable> { public CheckStateRunnable(CacheableBitmapDrawable object) { super(object); } @Override public void run(CacheableBitmapDrawable object) { object.checkState(true); } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/CacheableBitmapDrawable.java
Java
art
7,454
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import android.support.v4.util.LruCache; import java.util.Map.Entry; import java.util.Set; final class BitmapMemoryLruCache extends LruCache<String, CacheableBitmapDrawable> { BitmapMemoryLruCache(int maxSize) { super(maxSize); } CacheableBitmapDrawable put(CacheableBitmapDrawable value) { if (null != value) { value.setCached(true); return put(value.getUrl(), value); } return null; } @Override protected int sizeOf(String key, CacheableBitmapDrawable value) { return value.getMemorySize(); } @Override protected void entryRemoved(boolean evicted, String key, CacheableBitmapDrawable oldValue, CacheableBitmapDrawable newValue) { // Notify the wrapper that it's no longer being cached oldValue.setCached(false); } void trimMemory() { final Set<Entry<String, CacheableBitmapDrawable>> values = snapshot().entrySet(); for (Entry<String, CacheableBitmapDrawable> entry : values) { CacheableBitmapDrawable value = entry.getValue(); if (null == value || !value.isBeingDisplayed()) { remove(entry.getKey()); } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/BitmapMemoryLruCache.java
Java
art
2,023
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; class Util { static long copy(File in, OutputStream out) throws IOException { return copy(new FileInputStream(in), out); } static long copy(InputStream in, File out) throws IOException { return copy(in, new FileOutputStream(out)); } static void saveBitmap(Bitmap bitmap, OutputStream out) { bitmap.compress(CompressFormat.PNG, 100, out); } /** * Pipe an InputStream to the given OutputStream <p /> Taken from Apache Commons IOUtils. */ private static long copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024 * 4]; long count = 0; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/Util.java
Java
art
1,866
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import java.lang.ref.WeakReference; abstract class WeakReferenceRunnable<T> implements Runnable { private final WeakReference<T> mObjectRef; public WeakReferenceRunnable(T object) { mObjectRef = new WeakReference<T>(object); } @Override public final void run() { T object = mObjectRef.get(); if (null != object) { run(object); } } public abstract void run(T object); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/WeakReferenceRunnable.java
Java
art
1,233
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; public class CacheableImageView extends ImageView { private static void onDrawableSet(Drawable drawable) { if (drawable instanceof CacheableBitmapDrawable) { ((CacheableBitmapDrawable) drawable).setBeingUsed(true); } } private static void onDrawableUnset(final Drawable drawable) { if (drawable instanceof CacheableBitmapDrawable) { ((CacheableBitmapDrawable) drawable).setBeingUsed(false); } } public CacheableImageView(Context context) { super(context); } public CacheableImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void setImageDrawable(Drawable drawable) { final Drawable previousDrawable = getDrawable(); // Set new Drawable super.setImageDrawable(drawable); if (drawable != previousDrawable) { onDrawableSet(drawable); onDrawableUnset(previousDrawable); } } @Override public void setImageResource(int resId) { final Drawable previousDrawable = getDrawable(); super.setImageResource(resId); onDrawableUnset(previousDrawable); } @Override public void setImageURI(Uri uri) { final Drawable previousDrawable = getDrawable(); super.setImageURI(uri); onDrawableUnset(previousDrawable); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); // Will cause displayed bitmap wrapper to be 'free-able' setImageDrawable(null); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/CacheableImageView.java
Java
art
2,552
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; class Constants { static boolean DEBUG = false; static String LOG_TAG = "BitmapCache"; static final int UNUSED_DRAWABLE_RECYCLE_DELAY_MS = 2000; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/Constants.java
Java
art
948
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; class Md5 { private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public static String encode(String string) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); return bytesToHexString(digest.digest(string.getBytes())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private static String bytesToHexString(byte[] bytes) { final char[] buf = new char[bytes.length * 2]; byte b; int c = 0; for (int i = 0, z = bytes.length; i < z; i++) { b = bytes[i]; buf[c++] = DIGITS[(b >> 4) & 0xf]; buf[c++] = DIGITS[b & 0xf]; } return new String(buf); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/Md5.java
Java
art
1,822
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package uk.co.senab.bitmapcache; import com.jakewharton.DiskLruCache; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Build; import android.os.Looper; import android.os.Process; import android.util.Log; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * A cache which can be set to use multiple layers of caching for Bitmap objects * in an Android app. Instances are created via a {@link Builder} instance, * which can be used to alter the settings of the resulting cache. * * <p> * Instances of this class should ideally be kept globally with the application, * for example in the {@link android.app.Application Application} object. You * should also use the bundled {@link CacheableImageView} wherever possible, as * the memory cache has a close relationship with it. * </p> * * <p> * Clients can call {@link #get(String)} to retrieve a cached value from the * given Url. This will check all available caches for the value. There are also * the {@link #getFromDiskCache(String, android.graphics.BitmapFactory.Options)} * and {@link #getFromMemoryCache(String)} which allow more granular access. * </p> * * <p> * There are a number of update methods. {@link #put(String, InputStream)} and * {@link #put(String, InputStream)} are the preferred versions of the method, * as they allow 1:1 caching to disk of the original content. <br /> * {@link #put(String, Bitmap)} should only be used if you can't get access to * the original InputStream. * </p> * * @author Chris Banes */ public class BitmapLruCache { /** * The recycle policy controls if the * {@link android.graphics.Bitmap#recycle()} is automatically called, when * it is no longer being used. To set this, use the * {@link Builder#setRecyclePolicy(uk.co.senab.bitmapcache.BitmapLruCache.RecyclePolicy) * Builder.setRecyclePolicy()} method. */ public static enum RecyclePolicy { /** * The Bitmap is never recycled automatically. */ DISABLED, /** * The Bitmap is only automatically recycled if running on a device API * v10 or earlier. */ PRE_HONEYCOMB_ONLY, /** * The Bitmap is always recycled when no longer being used. This is the * default. */ ALWAYS; boolean canRecycle() { switch (this) { case DISABLED: return false; case PRE_HONEYCOMB_ONLY: return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB; case ALWAYS: return true; } return false; } } // The number of seconds after the last edit that the Disk Cache should be // flushed static final int DISK_CACHE_FLUSH_DELAY_SECS = 5; /** * @throws IllegalStateException * if the calling thread is the main/UI thread. */ private static void checkNotOnMainThread() { if (Looper.myLooper() == Looper.getMainLooper()) { throw new IllegalStateException( "This method should not be called from the main/UI thread."); } } /** * The disk cache only accepts a reduced range of characters for the key * values. This method transforms the {@code url} into something accepted * from {@link DiskLruCache}. Currently we simply return a MD5 hash of the * url. * * @param url * - Key to be transformed * @return key which can be used for the disk cache */ private static String transformUrlForDiskCacheKey(String url) { return Md5.encode(url); } private File mTempDir; private Resources mResources; /** * Memory Cache Variables */ private BitmapMemoryLruCache mMemoryCache; private RecyclePolicy mRecyclePolicy; /** * Disk Cache Variables */ private DiskLruCache mDiskCache; // Variables which are only used when the Disk Cache is enabled private HashMap<String, ReentrantLock> mDiskCacheEditLocks; private ScheduledThreadPoolExecutor mDiskCacheFlusherExecutor; private DiskCacheFlushRunnable mDiskCacheFlusherRunnable; // Transient private ScheduledFuture<?> mDiskCacheFuture; BitmapLruCache(Context context) { if (null != context) { // Make sure we have the application context context = context.getApplicationContext(); mTempDir = context.getCacheDir(); mResources = context.getResources(); } } /** * Returns whether any of the enabled caches contain the specified URL. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * the URL to search for. * @return {@code true} if any of the caches contain the specified URL, * {@code false} otherwise. */ public boolean contains(String url) { return containsInMemoryCache(url) || containsInDiskCache(url); } /** * Returns whether the Disk Cache contains the specified URL. You should not * call this method from main/UI thread. * * @param url * the URL to search for. * @return {@code true} if the Disk Cache is enabled and contains the * specified URL, {@code false} otherwise. */ public boolean containsInDiskCache(String url) { if (null != mDiskCache) { checkNotOnMainThread(); try { return null != mDiskCache.get(transformUrlForDiskCacheKey(url)); } catch (IOException e) { e.printStackTrace(); } } return false; } /** * Returns whether the Memory Cache contains the specified URL. This method * is safe to be called from the main thread. * * @param url * the URL to search for. * @return {@code true} if the Memory Cache is enabled and contains the * specified URL, {@code false} otherwise. */ public boolean containsInMemoryCache(String url) { return null != mMemoryCache && null != mMemoryCache.get(url); } /** * Returns the value for {@code url}. This will check all caches currently * enabled. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * - String representing the URL of the image */ public CacheableBitmapDrawable get(String url) { return get(url, null); } /** * Returns the value for {@code url}. This will check all caches currently * enabled. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * - String representing the URL of the image * @param decodeOpts * - Options used for decoding the contents from the disk cache * only. */ public CacheableBitmapDrawable get(String url, BitmapFactory.Options decodeOpts) { CacheableBitmapDrawable result; // First try Memory Cache result = getFromMemoryCache(url); if (null == result) { // Memory Cache failed, so try Disk Cache result = getFromDiskCache(url, decodeOpts); } return result; } /** * Returns the value for {@code url} in the disk cache only. You should not * call this method from main/UI thread. * <p/> * If enabled, the result of this method will be cached in the memory cache. * <p /> * Unless you have a specific requirement to only query the disk cache, you * should call {@link #get(String)} instead. * * @param url * - String representing the URL of the image * @param decodeOpts * - Options used for decoding the contents from the disk cache. * @return Value for {@code url} from disk cache, or {@code null} if the * disk cache is not enabled. */ public CacheableBitmapDrawable getFromDiskCache(final String url, final BitmapFactory.Options decodeOpts) { CacheableBitmapDrawable result = null; if (null != mDiskCache) { checkNotOnMainThread(); try { final String key = transformUrlForDiskCacheKey(url); DiskLruCache.Snapshot snapshot = mDiskCache.get(key); if (null != snapshot) { // Try and decode bitmap Bitmap bitmap = BitmapFactory.decodeStream( snapshot.getInputStream(0), null, decodeOpts); if (null != bitmap) { result = new CacheableBitmapDrawable(url, mResources, bitmap, mRecyclePolicy); if (null != mMemoryCache) { mMemoryCache.put(result); } } else { // If we get here, the file in the cache can't be // decoded. Remove it and schedule a flush. mDiskCache.remove(key); scheduleDiskCacheFlush(); } } } catch (IOException e) { e.printStackTrace(); } } return result; } /** * Returns the value for {@code url} in the memory cache only. This method * is safe to be called from the main thread. * <p /> * You should check the result of this method before starting a threaded * call. * * @param url * - String representing the URL of the image * @return Value for {@code url} from memory cache, or {@code null} if the * disk cache is not enabled. */ public CacheableBitmapDrawable getFromMemoryCache(final String url) { CacheableBitmapDrawable result = null; if (null != mMemoryCache) { synchronized (mMemoryCache) { result = mMemoryCache.get(url); // If we get a value, but it has a invalid bitmap, remove it if (null != result && !result.hasValidBitmap()) { mMemoryCache.remove(url); result = null; } } } return result; } /** * @return true if the Disk Cache is enabled. */ public boolean isDiskCacheEnabled() { return null != mDiskCache; } /** * @return true if the Memory Cache is enabled. */ public boolean isMemoryCacheEnabled() { return null != mMemoryCache; } /** * Caches {@code bitmap} for {@code url} into all enabled caches. If the * disk cache is enabled, the bitmap will be compressed losslessly. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. * * @param url * - String representing the URL of the image. * @param bitmap * - Bitmap which has been decoded from {@code url}. * @return CacheableBitmapDrawable which can be used to display the bitmap. */ public CacheableBitmapDrawable put(final String url, final Bitmap bitmap) { CacheableBitmapDrawable d = new CacheableBitmapDrawable(url, mResources, bitmap, mRecyclePolicy); if (null != mMemoryCache) { mMemoryCache.put(d); Log.d("cache memory size", mMemoryCache.size() + ""); } if (null != mDiskCache) { checkNotOnMainThread(); final String key = transformUrlForDiskCacheKey(url); final ReentrantLock lock = getLockForDiskCacheEdit(key); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache.edit(key); Util.saveBitmap(bitmap, editor.newOutputStream(0)); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } return d; } /** * Caches resulting bitmap from {@code inputStream} for {@code url} into all * enabled caches. This version of the method should be preferred as it * allows the original image contents to be cached, rather than a * re-compressed version. * <p /> * The contents of the InputStream will be copied to a temporary file, then * the file will be decoded into a Bitmap. Providing the decode worked: * <ul> * <li>If the memory cache is enabled, the decoded Bitmap will be cached to * memory.</li> * <li>If the disk cache is enabled, the contents of the original stream * will be cached to disk.</li> * </ul> * <p/> * You should not call this method from the main/UI thread. * * @param url * - String representing the URL of the image * @param inputStream * - InputStream opened from {@code url} * @return CacheableBitmapDrawable which can be used to display the bitmap. */ public CacheableBitmapDrawable put(final String url, final InputStream inputStream) { return put(url, inputStream, null, true); } /** * Caches resulting bitmap from {@code inputStream} for {@code url} into all * enabled caches. This version of the method should be preferred as it * allows the original image contents to be cached, rather than a * re-compressed version. * <p /> * The contents of the InputStream will be copied to a temporary file, then * the file will be decoded into a Bitmap, using the optional * <code>decodeOpts</code>. Providing the decode worked: * <ul> * <li>If the memory cache is enabled, the decoded Bitmap will be cached to * memory.</li> * <li>If the disk cache is enabled, the contents of the original stream * will be cached to disk.</li> * </ul> * <p/> * You should not call this method from the main/UI thread. * * @param url * - String representing the URL of the image * @param inputStream * - InputStream opened from {@code url} * @param decodeOpts * - Options used for decoding. This does not affect what is * cached in the disk cache (if enabled). * @return CacheableBitmapDrawable which can be used to display the bitmap. */ public CacheableBitmapDrawable put(final String url, final InputStream inputStream, final BitmapFactory.Options decodeOpts, boolean cacheOnMemory) { checkNotOnMainThread(); // First we need to save the stream contents to a temporary file, so it // can be read multiple times File tmpFile = null; try { tmpFile = File.createTempFile("bitmapcache_", null, mTempDir); // Pipe InputStream to file Util.copy(inputStream, tmpFile); try { // Close the original InputStream inputStream.close(); } catch (IOException e) { // NO-OP - Ignore } } catch (IOException e) { e.printStackTrace(); } CacheableBitmapDrawable d = null; if (null != tmpFile) { // Try and decode File Bitmap bitmap = BitmapFactory.decodeFile(tmpFile.getAbsolutePath(), decodeOpts); if (null != bitmap) { d = new CacheableBitmapDrawable(url, mResources, bitmap, mRecyclePolicy); if (null != mMemoryCache && cacheOnMemory) { d.setCached(true); mMemoryCache.put(d.getUrl(), d); } if (null != mDiskCache) { final ReentrantLock lock = getLockForDiskCacheEdit(url); lock.lock(); try { DiskLruCache.Editor editor = mDiskCache .edit(transformUrlForDiskCacheKey(url)); Util.copy(tmpFile, editor.newOutputStream(0)); editor.commit(); } catch (IOException e) { e.printStackTrace(); } finally { lock.unlock(); scheduleDiskCacheFlush(); } } } // Finally, delete the temporary file tmpFile.delete(); } Log.d("cache memory size", mMemoryCache.size() + ""); return d; } /** * Removes the entry for {@code url} from all enabled caches, if it exists. * <p/> * If you have the disk cache enabled, you should not call this method from * main/UI thread. */ public void remove(String url) { if (null != mMemoryCache) { mMemoryCache.remove(url); } if (null != mDiskCache) { checkNotOnMainThread(); try { mDiskCache.remove(transformUrlForDiskCacheKey(url)); scheduleDiskCacheFlush(); } catch (IOException e) { e.printStackTrace(); } } } public void removeFromMemory(String url) { if (null != mMemoryCache) { mMemoryCache.remove(url); Log.d("cache memory size", mMemoryCache.size() + ""); } } /** * This method iterates through the memory cache (if enabled) and removes * any entries which are not currently being displayed. A good place to call * this would be from {@link android.app.Application#onLowMemory() * Application.onLowMemory()}. */ public void trimMemory() { if (null != mMemoryCache) { mMemoryCache.trimMemory(); } } synchronized void setDiskCache(DiskLruCache diskCache) { mDiskCache = diskCache; if (null != diskCache) { mDiskCacheEditLocks = new HashMap<String, ReentrantLock>(); mDiskCacheFlusherExecutor = new ScheduledThreadPoolExecutor(1); mDiskCacheFlusherRunnable = new DiskCacheFlushRunnable(diskCache); } } void setMemoryCache(BitmapMemoryLruCache memoryCache, RecyclePolicy recyclePolicy) { mMemoryCache = memoryCache; mRecyclePolicy = recyclePolicy; } private ReentrantLock getLockForDiskCacheEdit(String url) { synchronized (mDiskCacheEditLocks) { ReentrantLock lock = mDiskCacheEditLocks.get(url); if (null == lock) { lock = new ReentrantLock(); mDiskCacheEditLocks.put(url, lock); } return lock; } } private void scheduleDiskCacheFlush() { // If we already have a flush scheduled, cancel it if (null != mDiskCacheFuture) { mDiskCacheFuture.cancel(false); } // Schedule a flush mDiskCacheFuture = mDiskCacheFlusherExecutor.schedule( mDiskCacheFlusherRunnable, DISK_CACHE_FLUSH_DELAY_SECS, TimeUnit.SECONDS); } /** * Builder class for {link {@link BitmapLruCache}. An example call: * * <pre> * BitmapLruCache.Builder builder = new BitmapLruCache.Builder(); * builder.setMemoryCacheEnabled(true).setMemoryCacheMaxSizeUsingHeapSize(this); * builder.setDiskCacheEnabled(true).setDiskCacheLocation(...); * * BitmapLruCache cache = builder.build(); * </pre> * * @author Chris Banes */ public final static class Builder { static final int MEGABYTE = 1024 * 1024; static final float DEFAULT_MEMORY_CACHE_HEAP_RATIO = 1f / 8f; static final float MAX_MEMORY_CACHE_HEAP_RATIO = 0.75f; static final int DEFAULT_DISK_CACHE_MAX_SIZE_MB = 10; static final int DEFAULT_MEM_CACHE_MAX_SIZE_MB = 3; static final RecyclePolicy DEFAULT_RECYCLE_POLICY = RecyclePolicy.ALWAYS; // Only used for Javadoc static final float DEFAULT_MEMORY_CACHE_HEAP_PERCENTAGE = DEFAULT_MEMORY_CACHE_HEAP_RATIO * 100; static final float MAX_MEMORY_CACHE_HEAP_PERCENTAGE = MAX_MEMORY_CACHE_HEAP_RATIO * 100; private static long getHeapSize() { return Runtime.getRuntime().maxMemory(); } private Context mContext; private boolean mDiskCacheEnabled; private File mDiskCacheLocation; private long mDiskCacheMaxSize; private boolean mMemoryCacheEnabled; private int mMemoryCacheMaxSize; private RecyclePolicy mRecyclePolicy; /** * @deprecated You should now use {@link Builder(Context)}. This is so * that we can reliably set up correctly. */ public Builder() { this(null); } public Builder(Context context) { mContext = context; // Disk Cache is disabled by default, but it's default size is set mDiskCacheMaxSize = DEFAULT_DISK_CACHE_MAX_SIZE_MB * MEGABYTE; // Memory Cache is enabled by default, with a small maximum size mMemoryCacheEnabled = true; mMemoryCacheMaxSize = DEFAULT_MEM_CACHE_MAX_SIZE_MB * MEGABYTE; mRecyclePolicy = DEFAULT_RECYCLE_POLICY; } /** * @return A new {@link BitmapLruCache} created with the arguments * supplied to this builder. */ public BitmapLruCache build() { final BitmapLruCache cache = new BitmapLruCache(mContext); if (isValidOptionsForMemoryCache()) { if (Constants.DEBUG) { Log.d("BitmapLruCache.Builder", "Creating Memory Cache"); } cache.setMemoryCache(new BitmapMemoryLruCache( mMemoryCacheMaxSize), mRecyclePolicy); } if (isValidOptionsForDiskCache()) { new AsyncTask<Void, Void, DiskLruCache>() { @Override protected DiskLruCache doInBackground(Void... params) { try { return DiskLruCache.open(mDiskCacheLocation, 0, 1, mDiskCacheMaxSize); } catch (IOException e) { e.printStackTrace(); return null; } } @Override protected void onPostExecute(DiskLruCache result) { cache.setDiskCache(result); } }.execute(); } return cache; } /** * Set whether the Disk Cache should be enabled. Defaults to * {@code false}. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setDiskCacheEnabled(boolean enabled) { mDiskCacheEnabled = enabled; return this; } /** * Set the Disk Cache location. This location should be read-writeable. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setDiskCacheLocation(File location) { mDiskCacheLocation = location; return this; } /** * Set the maximum number of bytes the Disk Cache should use to store * values. Defaults to {@value #DEFAULT_DISK_CACHE_MAX_SIZE_MB}MB. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setDiskCacheMaxSize(long maxSize) { mDiskCacheMaxSize = maxSize; return this; } /** * Set whether the Memory Cache should be enabled. Defaults to * {@code true}. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheEnabled(boolean enabled) { mMemoryCacheEnabled = enabled; return this; } /** * Set the maximum number of bytes the Memory Cache should use to store * values. Defaults to {@value #DEFAULT_MEM_CACHE_MAX_SIZE_MB}MB. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheMaxSize(int size) { mMemoryCacheMaxSize = size; return this; } /** * Sets the Memory Cache maximum size to be the default value of * {@value #DEFAULT_MEMORY_CACHE_HEAP_PERCENTAGE}% of heap size. * * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheMaxSizeUsingHeapSize() { return setMemoryCacheMaxSizeUsingHeapSize(DEFAULT_MEMORY_CACHE_HEAP_RATIO); } /** * Sets the Memory Cache maximum size to be the given percentage of heap * size. This is capped at {@value #MAX_MEMORY_CACHE_HEAP_PERCENTAGE}% * of the app heap size. * * @param percentageOfHeap * - percentage of heap size. Valid values are 0.0 <= x <= * {@value #MAX_MEMORY_CACHE_HEAP_RATIO}. * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setMemoryCacheMaxSizeUsingHeapSize(float percentageOfHeap) { int size = Math.round(getHeapSize() * Math.min(percentageOfHeap, MAX_MEMORY_CACHE_HEAP_RATIO)); return setMemoryCacheMaxSize(size); } /** * Sets the recycle policy. This controls if * {@link android.graphics.Bitmap#recycle()} is called. * * @param recyclePolicy * - New recycle policy, can not be null. * @return This Builder object to allow for chaining of calls to set * methods. */ public Builder setRecyclePolicy(RecyclePolicy recyclePolicy) { if (null == recyclePolicy) { throw new IllegalArgumentException( "The recycle policy can not be null"); } mRecyclePolicy = recyclePolicy; return this; } private boolean isValidOptionsForDiskCache() { if (mDiskCacheEnabled) { if (null == mDiskCacheLocation) { Log.i(Constants.LOG_TAG, "Disk Cache has been enabled, but no location given. Please call setDiskCacheLocation(...)"); return false; } else if (!mDiskCacheLocation.canWrite()) { throw new IllegalArgumentException( "Disk Cache Location is not write-able"); } return true; } return false; } private boolean isValidOptionsForMemoryCache() { return mMemoryCacheEnabled && mMemoryCacheMaxSize > 0; } } static final class DiskCacheFlushRunnable implements Runnable { private final DiskLruCache mDiskCache; public DiskCacheFlushRunnable(DiskLruCache cache) { mDiskCache = cache; } public void run() { // Make sure we're running with a background priority Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); if (Constants.DEBUG) { Log.d(Constants.LOG_TAG, "Flushing Disk Cache"); } try { mDiskCache.flush(); } catch (IOException e) { e.printStackTrace(); } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/src/uk/co/senab/bitmapcache/BitmapLruCache.java
Java
art
25,027
/** Automatically generated file. DO NOT MODIFY */ package uk.co.senab.bitmapcache; public final class BuildConfig { public final static boolean DEBUG = true; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/libraryForCaching/gen/uk/co/senab/bitmapcache/BuildConfig.java
Java
art
165
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.content.ContentResolver; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import com.facebook.android.BuildConfig; import com.facebook.internal.Utility; import com.facebook.model.GraphObject; import com.facebook.internal.Validate; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * Allows some customization of sdk behavior. */ public final class Settings { private static final HashSet<LoggingBehavior> loggingBehaviors = new HashSet<LoggingBehavior>(Arrays.asList(LoggingBehavior.DEVELOPER_ERRORS)); private static volatile Executor executor; private static volatile boolean shouldAutoPublishInstall; private static final int DEFAULT_CORE_POOL_SIZE = 5; private static final int DEFAULT_MAXIMUM_POOL_SIZE = 128; private static final int DEFAULT_KEEP_ALIVE = 1; private static final Object LOCK = new Object(); private static final Uri ATTRIBUTION_ID_CONTENT_URI = Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider"); private static final String ATTRIBUTION_ID_COLUMN_NAME = "aid"; private static final String ATTRIBUTION_PREFERENCES = "com.facebook.sdk.attributionTracking"; private static final String PUBLISH_ACTIVITY_PATH = "%s/activities"; private static final String MOBILE_INSTALL_EVENT = "MOBILE_APP_INSTALL"; private static final String ANALYTICS_EVENT = "event"; private static final String ATTRIBUTION_KEY = "attribution"; private static final BlockingQueue<Runnable> DEFAULT_WORK_QUEUE = new LinkedBlockingQueue<Runnable>(10); private static final ThreadFactory DEFAULT_THREAD_FACTORY = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(0); public Thread newThread(Runnable runnable) { return new Thread(runnable, "FacebookSdk #" + counter.incrementAndGet()); } }; /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Returns the types of extended logging that are currently enabled. * * @return a set containing enabled logging behaviors */ public static final Set<LoggingBehavior> getLoggingBehaviors() { synchronized (loggingBehaviors) { return Collections.unmodifiableSet(new HashSet<LoggingBehavior>(loggingBehaviors)); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Enables a particular extended logging in the sdk. * * @param behavior * The LoggingBehavior to enable */ public static final void addLoggingBehavior(LoggingBehavior behavior) { synchronized (loggingBehaviors) { loggingBehaviors.add(behavior); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Disables a particular extended logging behavior in the sdk. * * @param behavior * The LoggingBehavior to disable */ public static final void removeLoggingBehavior(LoggingBehavior behavior) { synchronized (loggingBehaviors) { loggingBehaviors.remove(behavior); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Disables all extended logging behaviors. */ public static final void clearLoggingBehaviors() { synchronized (loggingBehaviors) { loggingBehaviors.clear(); } } /** * Certain logging behaviors are available for debugging beyond those that should be * enabled in production. * * Checks if a particular extended logging behavior is enabled. * * @param behavior * The LoggingBehavior to check * @return whether behavior is enabled */ public static final boolean isLoggingBehaviorEnabled(LoggingBehavior behavior) { synchronized (loggingBehaviors) { return BuildConfig.DEBUG && loggingBehaviors.contains(behavior); } } /** * Returns the Executor used by the SDK for non-AsyncTask background work. * * By default this uses AsyncTask Executor via reflection if the API level is high enough. * Otherwise this creates a new Executor with defaults similar to those used in AsyncTask. * * @return an Executor used by the SDK. This will never be null. */ public static Executor getExecutor() { synchronized (LOCK) { if (Settings.executor == null) { Executor executor = getAsyncTaskExecutor(); if (executor == null) { executor = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY); } Settings.executor = executor; } } return Settings.executor; } /** * Sets the Executor used by the SDK for non-AsyncTask background work. * * @param executor * the Executor to use; must not be null. */ public static void setExecutor(Executor executor) { Validate.notNull(executor, "executor"); synchronized (LOCK) { Settings.executor = executor; } } private static Executor getAsyncTaskExecutor() { Field executorField = null; try { executorField = AsyncTask.class.getField("THREAD_POOL_EXECUTOR"); } catch (NoSuchFieldException e) { return null; } if (executorField == null) { return null; } Object executorObject = null; try { executorObject = executorField.get(null); } catch (IllegalAccessException e) { return null; } if (executorObject == null) { return null; } if (!(executorObject instanceof Executor)) { return null; } return (Executor) executorObject; } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. */ public static void publishInstallAsync(final Context context, final String applicationId) { publishInstallAsync(context, applicationId, null); } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @param callback a callback to invoke with a Response object, carrying the server response, or an error. */ public static void publishInstallAsync(final Context context, final String applicationId, final Request.Callback callback) { // grab the application context ahead of time, since we will return to the caller immediately. final Context applicationContext = context.getApplicationContext(); Settings.getExecutor().execute(new Runnable() { @Override public void run() { final Response response = Settings.publishInstallAndWaitForResponse(applicationContext, applicationId); if (callback != null) { // invoke the callback on the main thread. Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { callback.onCompleted(response); } }); } } }); } /** * Sets whether opening a Session should automatically publish install attribution to the Facebook graph. * * @param shouldAutoPublishInstall true to automatically publish, false to not */ public static void setShouldAutoPublishInstall(boolean shouldAutoPublishInstall) { Settings.shouldAutoPublishInstall = shouldAutoPublishInstall; } /** * Gets whether opening a Session should automatically publish install attribution to the Facebook graph. * * @return true to automatically publish, false to not */ public static boolean getShouldAutoPublishInstall() { return shouldAutoPublishInstall; } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @return returns false on error. Applications should retry until true is returned. Safe to call again after * true is returned. */ public static boolean publishInstallAndWait(final Context context, final String applicationId) { Response response = publishInstallAndWaitForResponse(context, applicationId); return response != null && response.getError() == null; } /** * Manually publish install attribution to the Facebook graph. Internally handles caching repeat calls to prevent * multiple installs being published to the graph. * @param context the current Context * @param applicationId the fb application being published. * @return returns a Response object, carrying the server response, or an error. */ public static Response publishInstallAndWaitForResponse(final Context context, final String applicationId) { try { if (context == null || applicationId == null) { throw new IllegalArgumentException("Both context and applicationId must be non-null"); } String attributionId = Settings.getAttributionId(context.getContentResolver()); SharedPreferences preferences = context.getSharedPreferences(ATTRIBUTION_PREFERENCES, Context.MODE_PRIVATE); String pingKey = applicationId+"ping"; String jsonKey = applicationId+"json"; long lastPing = preferences.getLong(pingKey, 0); String lastResponseJSON = preferences.getString(jsonKey, null); GraphObject publishParams = GraphObject.Factory.create(); publishParams.setProperty(ANALYTICS_EVENT, MOBILE_INSTALL_EVENT); publishParams.setProperty(ATTRIBUTION_KEY, attributionId); String publishUrl = String.format(PUBLISH_ACTIVITY_PATH, applicationId); Request publishRequest = Request.newPostRequest(null, publishUrl, publishParams, null); if (lastPing != 0) { GraphObject graphObject = null; try { if (lastResponseJSON != null) { graphObject = GraphObject.Factory.create(new JSONObject(lastResponseJSON)); } } catch (JSONException je) { // return the default graph object if there is any problem reading the data. } if (graphObject == null) { return Response.createResponsesFromString("true", null, new RequestBatch(publishRequest), true).get(0); } else { return new Response(null, null, graphObject, true); } } else if (attributionId == null) { throw new FacebookException("No attribution id returned from the Facebook application"); } else { if (!Utility.queryAppAttributionSupportAndWait(applicationId)) { throw new FacebookException("Install attribution has been disabled on the server."); } Response publishResponse = publishRequest.executeAndWait(); // denote success since no error threw from the post. SharedPreferences.Editor editor = preferences.edit(); lastPing = System.currentTimeMillis(); editor.putLong(pingKey, lastPing); // if we got an object response back, cache the string of the JSON. if (publishResponse.getGraphObject() != null && publishResponse.getGraphObject().getInnerJSONObject() != null) { editor.putString(jsonKey, publishResponse.getGraphObject().getInnerJSONObject().toString()); } editor.commit(); return publishResponse; } } catch (Exception e) { // if there was an error, fall through to the failure case. Utility.logd("Facebook-publish", e); return new Response(null, null, new FacebookRequestError(null, e)); } } /** * Acquire the current attribution id from the facebook app. * @return returns null if the facebook app is not present on the phone. */ public static String getAttributionId(ContentResolver contentResolver) { String [] projection = {ATTRIBUTION_ID_COLUMN_NAME}; Cursor c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null); if (c == null || !c.moveToFirst()) { return null; } String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME)); c.close(); return attributionId; } /** * Gets the current version of the Facebook SDK for Android as a string. * * @return the current version of the SDK */ public static String getSdkVersion() { return FacebookSdkVersion.BUILD; } /** * Gets the current Facebook migration bundle string; this string can be passed to Graph API * endpoints to specify a set of platform migrations that are explicitly turned on or off for * that call, in order to ensure compatibility between a given version of the SDK and the * Graph API. * @return the migration bundle supported by this version of the SDK */ public static String getMigrationBundle() { return FacebookSdkVersion.MIGRATION_BUNDLE; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/Settings.java
Java
art
15,556
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import com.facebook.model.GraphObject; import com.facebook.model.GraphObjectList; import com.facebook.internal.Logger; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import org.json.JSONException; import org.json.JSONObject; import java.util.*; /** * Implements an subclass of Session that knows about test users for a particular * application. This should never be used from a real application, but may be useful * for writing unit tests, etc. * <p/> * Facebook allows developers to create test accounts for testing their applications' * Facebook integration (see https://developers.facebook.com/docs/test_users/). This class * simplifies use of these accounts for writing unit tests. It is not designed for use in * production application code. * <p/> * The main use case for this class is using {@link #createSessionWithPrivateUser(android.app.Activity, java.util.List)} * or {@link #createSessionWithSharedUser(android.app.Activity, java.util.List)} * to create a session for a test user. Two modes are supported. In "shared" mode, an attempt * is made to find an existing test user that has the required permissions. If no such user is available, * a new one is created with the required permissions. In "private" mode, designed for * scenarios which require a new user in a known clean state, a new test user will always be * created, and it will be automatically deleted when the TestSession is closed. The session * obeys the same lifecycle as a regular Session, meaning it must be opened after creation before * it can be used to make calls to the Facebook API. * <p/> * Prior to creating a TestSession, two static methods must be called to initialize the * application ID and application Secret to be used for managing test users. These methods are * {@link #setTestApplicationId(String)} and {@link #setTestApplicationSecret(String)}. * <p/> * Note that the shared test user functionality depends on a naming convention for the test users. * It is important that any testing of functionality which will mutate the permissions for a * test user NOT use a shared test user, or this scheme will break down. If a shared test user * seems to be in an invalid state, it can be deleted manually via the Web interface at * https://developers.facebook.com/apps/APP_ID/permissions?role=test+users. */ public class TestSession extends Session { private static final long serialVersionUID = 1L; private enum Mode { PRIVATE, SHARED } private static final String LOG_TAG = Logger.LOG_TAG_BASE + "TestSession"; private static Map<String, TestAccount> appTestAccounts; private static String testApplicationSecret; private static String testApplicationId; private final String sessionUniqueUserTag; private final List<String> requestedPermissions; private final Mode mode; private String testAccountId; private boolean wasAskedToExtendAccessToken; TestSession(Activity activity, List<String> permissions, TokenCachingStrategy tokenCachingStrategy, String sessionUniqueUserTag, Mode mode) { super(activity, TestSession.testApplicationId, tokenCachingStrategy); Validate.notNull(permissions, "permissions"); // Validate these as if they were arguments even though they are statics. Validate.notNullOrEmpty(testApplicationId, "testApplicationId"); Validate.notNullOrEmpty(testApplicationSecret, "testApplicationSecret"); this.sessionUniqueUserTag = sessionUniqueUserTag; this.mode = mode; this.requestedPermissions = permissions; } /** * Constructs a TestSession which creates a test user on open, and destroys the user on * close; This method should not be used in application code -- but is useful for creating unit tests * that use the Facebook SDK. * * @param activity the Activity to use for opening the session * @param permissions list of strings containing permissions to request; nil will result in * a common set of permissions (email, publish_actions) being requested * @return a new TestSession that is in the CREATED state, ready to be opened */ public static TestSession createSessionWithPrivateUser(Activity activity, List<String> permissions) { return createTestSession(activity, permissions, Mode.PRIVATE, null); } /** * Constructs a TestSession which uses a shared test user with the right permissions, * creating one if necessary on open (but not deleting it on close, so it can be re-used in later * tests). * <p/> * This method should not be used in application code -- but is useful for creating unit tests * that use the Facebook SDK. * * @param activity the Activity to use for opening the session * @param permissions list of strings containing permissions to request; nil will result in * a common set of permissions (email, publish_actions) being requested * @return a new TestSession that is in the CREATED state, ready to be opened */ public static TestSession createSessionWithSharedUser(Activity activity, List<String> permissions) { return createSessionWithSharedUser(activity, permissions, null); } /** * Constructs a TestSession which uses a shared test user with the right permissions, * creating one if necessary on open (but not deleting it on close, so it can be re-used in later * tests). * <p/> * This method should not be used in application code -- but is useful for creating unit tests * that use the Facebook SDK. * * @param activity the Activity to use for opening the session * @param permissions list of strings containing permissions to request; nil will result in * a common set of permissions (email, publish_actions) being requested * @param sessionUniqueUserTag a string which will be used to make this user unique among other * users with the same permissions. Useful for tests which require two or more users to interact * with each other, and which therefore must have sessions associated with different users. * @return a new TestSession that is in the CREATED state, ready to be opened */ public static TestSession createSessionWithSharedUser(Activity activity, List<String> permissions, String sessionUniqueUserTag) { return createTestSession(activity, permissions, Mode.SHARED, sessionUniqueUserTag); } /** * Gets the Facebook Application ID for the application under test. * * @return the application ID */ public static synchronized String getTestApplicationId() { return testApplicationId; } /** * Sets the Facebook Application ID for the application under test. This must be specified * prior to creating a TestSession. * * @param applicationId the application ID */ public static synchronized void setTestApplicationId(String applicationId) { if (testApplicationId != null && !testApplicationId.equals(applicationId)) { throw new FacebookException("Can't have more than one test application ID"); } testApplicationId = applicationId; } /** * Gets the Facebook Application Secret for the application under test. * * @return the application secret */ public static synchronized String getTestApplicationSecret() { return testApplicationSecret; } /** * Sets the Facebook Application Secret for the application under test. This must be specified * prior to creating a TestSession. * * @param applicationSecret the application secret */ public static synchronized void setTestApplicationSecret(String applicationSecret) { if (testApplicationSecret != null && !testApplicationSecret.equals(applicationSecret)) { throw new FacebookException("Can't have more than one test application secret"); } testApplicationSecret = applicationSecret; } /** * Gets the ID of the test user that this TestSession is authenticated as. * * @return the Facebook user ID of the test user */ public final String getTestUserId() { return testAccountId; } private static synchronized TestSession createTestSession(Activity activity, List<String> permissions, Mode mode, String sessionUniqueUserTag) { if (Utility.isNullOrEmpty(testApplicationId) || Utility.isNullOrEmpty(testApplicationSecret)) { throw new FacebookException("Must provide app ID and secret"); } if (Utility.isNullOrEmpty(permissions)) { permissions = Arrays.asList("email", "publish_actions"); } return new TestSession(activity, permissions, new TestTokenCachingStrategy(), sessionUniqueUserTag, mode); } private static synchronized void retrieveTestAccountsForAppIfNeeded() { if (appTestAccounts != null) { return; } appTestAccounts = new HashMap<String, TestAccount>(); // The data we need is split across two different FQL tables. We construct two queries, submit them // together (the second one refers to the first one), then cross-reference the results. // Get the test accounts for this app. String testAccountQuery = String.format("SELECT id,access_token FROM test_account WHERE app_id = %s", testApplicationId); // Get the user names for those accounts. String userQuery = "SELECT uid,name FROM user WHERE uid IN (SELECT id FROM #test_accounts)"; Bundle parameters = new Bundle(); // Build a JSON string that contains our queries and pass it as the 'q' parameter of the query. JSONObject multiquery; try { multiquery = new JSONObject(); multiquery.put("test_accounts", testAccountQuery); multiquery.put("users", userQuery); } catch (JSONException exception) { throw new FacebookException(exception); } parameters.putString("q", multiquery.toString()); // We need to authenticate as this app. parameters.putString("access_token", getAppAccessToken()); Request request = new Request(null, "fql", parameters, null); Response response = request.executeAndWait(); if (response.getError() != null) { throw response.getError().getException(); } FqlResponse fqlResponse = response.getGraphObjectAs(FqlResponse.class); GraphObjectList<FqlResult> fqlResults = fqlResponse.getData(); if (fqlResults == null || fqlResults.size() != 2) { throw new FacebookException("Unexpected number of results from FQL query"); } // We get back two sets of results. The first is from the test_accounts query, the second from the users query. Collection<TestAccount> testAccounts = fqlResults.get(0).getFqlResultSet().castToListOf(TestAccount.class); Collection<UserAccount> userAccounts = fqlResults.get(1).getFqlResultSet().castToListOf(UserAccount.class); // Use both sets of results to populate our static array of accounts. populateTestAccounts(testAccounts, userAccounts); return; } private static synchronized void populateTestAccounts(Collection<TestAccount> testAccounts, Collection<UserAccount> userAccounts) { // We get different sets of data from each of these queries. We want to combine them into a single data // structure. We have added a Name property to the TestAccount interface, even though we don't really get // a name back from the service from that query. We stick the Name from the corresponding UserAccount in it. for (TestAccount testAccount : testAccounts) { storeTestAccount(testAccount); } for (UserAccount userAccount : userAccounts) { TestAccount testAccount = appTestAccounts.get(userAccount.getUid()); if (testAccount != null) { testAccount.setName(userAccount.getName()); } } } private static synchronized void storeTestAccount(TestAccount testAccount) { appTestAccounts.put(testAccount.getId(), testAccount); } private static synchronized TestAccount findTestAccountMatchingIdentifier(String identifier) { retrieveTestAccountsForAppIfNeeded(); for (TestAccount testAccount : appTestAccounts.values()) { if (testAccount.getName().contains(identifier)) { return testAccount; } } return null; } @Override public final String toString() { String superString = super.toString(); return new StringBuilder().append("{TestSession").append(" testUserId:").append(testAccountId) .append(" ").append(superString).append("}").toString(); } @Override void authorize(AuthorizationRequest request) { if (mode == Mode.PRIVATE) { createTestAccountAndFinishAuth(); } else { findOrCreateSharedTestAccount(); } } @Override void postStateChange(final SessionState oldState, final SessionState newState, final Exception error) { // Make sure this doesn't get overwritten. String id = testAccountId; super.postStateChange(oldState, newState, error); if (newState.isClosed() && id != null && mode == Mode.PRIVATE) { deleteTestAccount(id, getAppAccessToken()); } } boolean getWasAskedToExtendAccessToken() { return wasAskedToExtendAccessToken; } void forceExtendAccessToken(boolean forceExtendAccessToken) { AccessToken currentToken = getTokenInfo(); setTokenInfo( new AccessToken(currentToken.getToken(), new Date(), currentToken.getPermissions(), AccessTokenSource.TEST_USER, new Date(0))); setLastAttemptedTokenExtendDate(new Date(0)); } @Override boolean shouldExtendAccessToken() { boolean result = super.shouldExtendAccessToken(); wasAskedToExtendAccessToken = false; return result; } @Override void extendAccessToken() { wasAskedToExtendAccessToken = true; super.extendAccessToken(); } void fakeTokenRefreshAttempt() { setCurrentTokenRefreshRequest(new TokenRefreshRequest()); } static final String getAppAccessToken() { return testApplicationId + "|" + testApplicationSecret; } private void findOrCreateSharedTestAccount() { TestAccount testAccount = findTestAccountMatchingIdentifier(getSharedTestAccountIdentifier()); if (testAccount != null) { finishAuthWithTestAccount(testAccount); } else { createTestAccountAndFinishAuth(); } } private void finishAuthWithTestAccount(TestAccount testAccount) { testAccountId = testAccount.getId(); AccessToken accessToken = AccessToken.createFromString(testAccount.getAccessToken(), requestedPermissions, AccessTokenSource.TEST_USER); finishAuthOrReauth(accessToken, null); } private TestAccount createTestAccountAndFinishAuth() { Bundle parameters = new Bundle(); parameters.putString("installed", "true"); parameters.putString("permissions", getPermissionsString()); parameters.putString("access_token", getAppAccessToken()); // If we're in shared mode, we want to rename this user to encode its permissions, so we can find it later // in another shared session. If we're in private mode, don't bother renaming it since we're just going to // delete it at the end of the session. if (mode == Mode.SHARED) { parameters.putString("name", String.format("Shared %s Testuser", getSharedTestAccountIdentifier())); } String graphPath = String.format("%s/accounts/test-users", testApplicationId); Request createUserRequest = new Request(null, graphPath, parameters, HttpMethod.POST); Response response = createUserRequest.executeAndWait(); FacebookRequestError error = response.getError(); TestAccount testAccount = response.getGraphObjectAs(TestAccount.class); if (error != null) { finishAuthOrReauth(null, error.getException()); return null; } else { assert testAccount != null; // If we are in shared mode, store this new account in the dictionary so we can re-use it later. if (mode == Mode.SHARED) { // Remember the new name we gave it, since we didn't get it back in the results of the create request. testAccount.setName(parameters.getString("name")); storeTestAccount(testAccount); } finishAuthWithTestAccount(testAccount); return testAccount; } } private void deleteTestAccount(String testAccountId, String appAccessToken) { Bundle parameters = new Bundle(); parameters.putString("access_token", appAccessToken); Request request = new Request(null, testAccountId, parameters, HttpMethod.DELETE); Response response = request.executeAndWait(); FacebookRequestError error = response.getError(); GraphObject graphObject = response.getGraphObject(); if (error != null) { Log.w(LOG_TAG, String.format("Could not delete test account %s: %s", testAccountId, error.getException().toString())); } else if (graphObject.getProperty(Response.NON_JSON_RESPONSE_PROPERTY) == (Boolean) false) { Log.w(LOG_TAG, String.format("Could not delete test account %s: unknown reason", testAccountId)); } } private String getPermissionsString() { return TextUtils.join(",", requestedPermissions); } private String getSharedTestAccountIdentifier() { // We use long even though hashes are ints to avoid sign issues. long permissionsHash = getPermissionsString().hashCode() & 0xffffffffL; long sessionTagHash = (sessionUniqueUserTag != null) ? sessionUniqueUserTag.hashCode() & 0xffffffffL : 0; long combinedHash = permissionsHash ^ sessionTagHash; return validNameStringFromInteger(combinedHash); } private String validNameStringFromInteger(long i) { String s = Long.toString(i); StringBuilder result = new StringBuilder("Perm"); // We know each character is a digit. Convert it into a letter 'a'-'j'. Avoid repeated characters // that might make Facebook reject the name by converting every other repeated character into one // 10 higher ('k'-'t'). char lastChar = 0; for (char c : s.toCharArray()) { if (c == lastChar) { c += 10; } result.append((char) (c + 'a' - '0')); lastChar = c; } return result.toString(); } private interface TestAccount extends GraphObject { String getId(); String getAccessToken(); // Note: We don't actually get Name from our FQL query. We fill it in by correlating with UserAccounts. String getName(); void setName(String name); } private interface UserAccount extends GraphObject { String getUid(); String getName(); void setName(String name); } private interface FqlResult extends GraphObject { GraphObjectList<GraphObject> getFqlResultSet(); } private interface FqlResponse extends GraphObject { GraphObjectList<FqlResult> getData(); } private static final class TestTokenCachingStrategy extends TokenCachingStrategy { private Bundle bundle; @Override public Bundle load() { return bundle; } @Override public void save(Bundle value) { bundle = value; } @Override public void clear() { bundle = null; } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/TestSession.java
Java
art
21,148
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.content.Context; import android.os.Bundle; import com.facebook.internal.Logger; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import com.facebook.model.GraphObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.math.BigDecimal; import java.util.Currency; import java.util.Set; /** * The InsightsLogger class allows the developer to log various types of events back to Facebook. In order to log * events, the app must create an instance of this class via a {@link #newLogger newLogger} method, and then call * the various "log" methods off of that. Note that a Client Token for the app is required in calls to newLogger so * apps that have not authenticated their users can still get meaningful user-demographics from the logged events * on Facebook. */ public class InsightsLogger { // Constants // Event names, these match what the server expects. private static final String EVENT_NAME_LOG_CONVERSION_PIXEL = "fb_log_offsite_pixel"; private static final String EVENT_NAME_LOG_MOBILE_PURCHASE = "fb_mobile_purchase"; // Event parameter names, these match what the server expects. private static final String EVENT_PARAMETER_CURRENCY = "fb_currency"; private static final String EVENT_PARAMETER_PIXEL_ID = "fb_offsite_pixel_id"; private static final String EVENT_PARAMETER_PIXEL_VALUE = "fb_offsite_pixel_value"; // Static member variables private static Session appAuthSession = null; // Instance member variables private final Context context; private final String clientToken; private final String applicationId; private final Session specifiedSession; /** * Constructor is private, newLogger() methods should be used to build an instance. */ private InsightsLogger(Context context, String clientToken, String applicationId, Session session) { Validate.notNull(context, "context"); // Always ensure the client token is present, even if not needed for this particular logging (because at // some point it will be required). Be harsh by throwing an exception because this is all too easy to miss // and things will work with authenticated sessions, but start failing with users that don't have // authenticated sessions. Validate.notNullOrEmpty(clientToken, "clientToken"); if (applicationId == null) { applicationId = Utility.getMetadataApplicationId(context); } this.context = context; this.clientToken = clientToken; this.applicationId = applicationId; this.specifiedSession = session; } /** * Build an InsightsLogger instance to log events through. The Facebook app that these events are targeted at * comes from this application's metadata. * * @param context Used to access the applicationId and the attributionId for non-authenticated users. * @param clientToken The Facebook app's "client token", which, for a given appid can be found in the Security * section of the Advanced tab of the Facebook App settings found * at <https://developers.facebook.com/apps/[your-app-id]>. * * @return InsightsLogger instance to invoke log* methods on. */ public static InsightsLogger newLogger(Context context, String clientToken) { return new InsightsLogger(context, clientToken, null, null); } /** * Build an InsightsLogger instance to log events through. Allow explicit specification of an Facebook app * to target. * * @param context Used to access the attributionId for non-authenticated users. * @param clientToken The Facebook app's "client token", which, for a given appid can be found in the Security * section of the Advanced tab of the Facebook App settings found * at <https://developers.facebook.com/apps/[your-app-id]> * @param applicationId Explicitly specified Facebook applicationId to log events against. If null, the * applicationId embedded in the application metadata accessible from 'context' will * be used. * * @return InsightsLogger instance to invoke log* methods on. */ public static InsightsLogger newLogger(Context context, String clientToken, String applicationId) { return new InsightsLogger(context, clientToken, applicationId, null); } /** * Build an InsightsLogger instance to log events through. * * @param context Used to access the attributionId for non-authenticated users. * @param clientToken The Facebook app's "client token", which, for a given appid can be found in the Security * section of the Advanced tab of the Facebook App settings found * at <https://developers.facebook.com/apps/[your-app-id]> * @param applicationId Explicitly specified Facebook applicationId to log events against. If null, the * applicationId embedded in the application metadata accessible from 'context' will * be used. * @param session Explicitly specified Session to log events against. If null, the activeSession * will be used if it's open, otherwise the logging will happen via the "clientToken" * and specified appId. * * @return InsightsLogger instance to invoke log* methods on. */ public static InsightsLogger newLogger(Context context, String clientToken, String applicationId, Session session) { return new InsightsLogger(context, clientToken, applicationId, session); } /** * Logs a purchase event with Facebook, in the specified amount and with the specified currency. * * @param purchaseAmount Amount of purchase, in the currency specified by the 'currency' parameter. This value * will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346). * @param currency Currency used to specify the amount. */ public void logPurchase(BigDecimal purchaseAmount, Currency currency) { logPurchase(purchaseAmount, currency, null); } /** * Logs a purchase event with Facebook, in the specified amount and with the specified currency. Additional * detail about the purchase can be passed in through the parameters bundle. * * @param purchaseAmount Amount of purchase, in the currency specified by the 'currency' parameter. This value * will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346). * @param currency Currency used to specify the amount. * @param parameters Arbitrary additional information for describing this event. Should have no more than * 10 entries, and keys should be mostly consistent from one purchase event to the next. */ public void logPurchase(BigDecimal purchaseAmount, Currency currency, Bundle parameters) { if (purchaseAmount == null) { notifyDeveloperError("purchaseAmount cannot be null"); return; } else if (currency == null) { notifyDeveloperError("currency cannot be null"); return; } if (parameters == null) { parameters = new Bundle(); } parameters.putString(EVENT_PARAMETER_CURRENCY, currency.getCurrencyCode()); logEventNow(EVENT_NAME_LOG_MOBILE_PURCHASE, purchaseAmount.doubleValue(), parameters); } /** * Log, or "Fire" a Conversion Pixel. Conversion Pixels are used for Ads Conversion Tracking. See * https://www.facebook.com/help/435189689870514 to learn more. * * @param pixelId Numeric ID for the conversion pixel to be logged. See * https://www.facebook.com/help/435189689870514 to learn how to create a conversion pixel. * @param valueOfPixel Value of what the logging of this pixel is worth to the calling app. The currency that this * is expressed in doesn't matter, so long as it is consistent across all logging for this * pixel. This value will be rounded to the thousandths place (e.g., 12.34567 becomes 12.346). */ public void logConversionPixel(String pixelId, double valueOfPixel) { if (pixelId == null) { notifyDeveloperError("pixelID cannot be null"); return; } Bundle parameters = new Bundle(); parameters.putString(EVENT_PARAMETER_PIXEL_ID, pixelId); parameters.putDouble(EVENT_PARAMETER_PIXEL_VALUE, valueOfPixel); logEventNow(EVENT_NAME_LOG_CONVERSION_PIXEL, valueOfPixel, parameters); } /** * This is the workhorse function of the InsightsLogger class and does the packaging and POST. As InsightsLogger * is expanded to support more custom app events, this logic will become more complicated and allow for batching * and flushing of multiple events, of persisting to disk so as to survive network outages, implicitly logging * (with the dev's permission) SDK actions, etc. */ private void logEventNow( final String eventName, final double valueToSum, final Bundle parameters) { // Run everything synchronously on a worker thread. Settings.getExecutor().execute(new Runnable() { @Override public void run() { final String eventJSON = buildJSONForEvent(eventName, valueToSum, parameters); if (eventJSON == null) { // Failure in building JSON, already reported, so just return. return; } GraphObject publishParams = GraphObject.Factory.create(); publishParams.setProperty("event", "CUSTOM_APP_EVENTS"); publishParams.setProperty("custom_events", eventJSON); if (Utility.queryAppAttributionSupportAndWait(applicationId)) { String attributionId = Settings.getAttributionId(context.getContentResolver()); if (attributionId != null) { publishParams.setProperty("attribution", attributionId); } } String publishUrl = String.format("%s/activities", applicationId); try { Request postRequest = Request.newPostRequest(sessionToLogTo(), publishUrl, publishParams, null); Response response = postRequest.executeAndWait(); // A -1 error code happens if there is no connectivity. No need to notify the // developer in that case. final int NO_CONNECTIVITY_ERROR_CODE = -1; if (response.getError() != null && response.getError().getErrorCode() != NO_CONNECTIVITY_ERROR_CODE) { notifyDeveloperError( String.format( "Error publishing Insights event '%s'\n Response: %s\n Error: %s", eventJSON, response.toString(), response.getError().toString())); } } catch (Exception e) { Utility.logd("Insights-exception: ", e); } } }); } private static String buildJSONForEvent(String eventName, double valueToSum, Bundle parameters) { String result; try { // Build custom event payload JSONObject eventObject = new JSONObject(); eventObject.put("_eventName", eventName); if (valueToSum != 1.0) { eventObject.put("_valueToSum", valueToSum); } if (parameters != null) { Set<String> keys = parameters.keySet(); for (String key : keys) { Object value = parameters.get(key); if (!(value instanceof String) && !(value instanceof Number)) { notifyDeveloperError( String.format("Parameter '%s' must be a string or a numeric type.", key)); } eventObject.put(key, value); } } JSONArray eventArray = new JSONArray(); eventArray.put(eventObject); result = eventArray.toString(); } catch (JSONException exception) { notifyDeveloperError(exception.toString()); result = null; } return result; } /** * Using the specifiedSession member variable (which may be nil), find the real session to log to * (with an access token). Precedence: 1) specified session, 2) activeSession, 3) app authenticated * session via Client Token. */ private Session sessionToLogTo() { synchronized (this) { Session session = specifiedSession; // Require an open session. if (session == null || !session.isOpened()) { session = Session.getActiveSession(); } if (session == null || !session.isOpened() || session.getAccessToken() == null) { if (appAuthSession == null) { // Build and stash a client-token based session. // Form the clientToken based access token from appID and client token. String tokenString = String.format("%s|%s", applicationId, clientToken); AccessToken token = AccessToken.createFromString(tokenString, null, AccessTokenSource.CLIENT_TOKEN); appAuthSession = new Session(null, applicationId, new NonCachingTokenCachingStrategy(), false); appAuthSession.open(token, null); } session = appAuthSession; } return session; } } /** * Invoke this method, rather than throwing an Exception, for situations where user/server input might reasonably * cause this to occur, and thus don't want an exception thrown at production time, but do want logging * notification. */ private static void notifyDeveloperError(String message) { Logger.log(LoggingBehavior.DEVELOPER_ERRORS, "Insights", message); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/InsightsLogger.java
Java
art
15,477
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * Specifies different categories of logging messages that can be generated. * * @see Settings#addLoggingBehavior(LoggingBehavior) */ public enum LoggingBehavior { /** * Indicates that HTTP requests and a summary of responses should be logged. */ REQUESTS, /** * Indicates that access tokens should be logged as part of the request logging; normally they are not. */ INCLUDE_ACCESS_TOKENS, /** * Indicates that the entire raw HTTP response for each request should be logged. */ INCLUDE_RAW_RESPONSES, /** * Indicates that cache operations should be logged. */ CACHE, /** * Indicates that likely developer errors should be logged. (This is set by default in LoggingBehavior.) */ DEVELOPER_ERRORS }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/LoggingBehavior.java
Java
art
1,420
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import com.facebook.android.R; import com.facebook.internal.Utility; import org.json.JSONException; import org.json.JSONObject; import java.net.HttpURLConnection; /** * This class represents an error that occurred during a Facebook request. * <p/> * In general, one would call {@link #getCategory()} to determine the type * of error that occurred, and act accordingly. The app can also call * {@link #getUserActionMessageId()} in order to get the resource id for a * string that can be displayed to the user. For more information on error * handling, see <a href="https://developers.facebook.com/docs/reference/api/errors/"> * https://developers.facebook.com/docs/reference/api/errors/</a> */ public final class FacebookRequestError { /** Represents an invalid or unknown error code from the server. */ public static final int INVALID_ERROR_CODE = -1; /** * Indicates that there was no valid HTTP status code returned, indicating * that either the error occurred locally, before the request was sent, or * that something went wrong with the HTTP connection. Check the exception * from {@link #getException()}; */ public static final int INVALID_HTTP_STATUS_CODE = -1; private static final int INVALID_MESSAGE_ID = 0; private static final String CODE_KEY = "code"; private static final String BODY_KEY = "body"; private static final String ERROR_KEY = "error"; private static final String ERROR_TYPE_FIELD_KEY = "type"; private static final String ERROR_CODE_FIELD_KEY = "code"; private static final String ERROR_MESSAGE_FIELD_KEY = "message"; private static final String ERROR_CODE_KEY = "error_code"; private static final String ERROR_SUB_CODE_KEY = "error_subcode"; private static final String ERROR_MSG_KEY = "error_msg"; private static final String ERROR_REASON_KEY = "error_reason"; private static class Range { private final int start, end; private Range(int start, int end) { this.start = start; this.end = end; } boolean contains(int value) { return start <= value && value <= end; } } private static final int EC_UNKNOWN_ERROR = 1; private static final int EC_SERVICE_UNAVAILABLE = 2; private static final int EC_APP_TOO_MANY_CALLS = 4; private static final int EC_USER_TOO_MANY_CALLS = 17; private static final int EC_PERMISSION_DENIED = 10; private static final int EC_INVALID_SESSION = 102; private static final int EC_INVALID_TOKEN = 190; private static final Range EC_RANGE_PERMISSION = new Range(200, 299); private static final int EC_APP_NOT_INSTALLED = 458; private static final int EC_USER_CHECKPOINTED = 459; private static final int EC_PASSWORD_CHANGED = 460; private static final int EC_EXPIRED = 463; private static final int EC_UNCONFIRMED_USER = 464; private static final Range HTTP_RANGE_SUCCESS = new Range(200, 299); private static final Range HTTP_RANGE_CLIENT_ERROR = new Range(400, 499); private static final Range HTTP_RANGE_SERVER_ERROR = new Range(500, 599); private final int userActionMessageId; private final boolean shouldNotifyUser; private final Category category; private final int requestStatusCode; private final int errorCode; private final int subErrorCode; private final String errorType; private final String errorMessage; private final JSONObject requestResult; private final JSONObject requestResultBody; private final Object batchRequestResult; private final HttpURLConnection connection; private final FacebookException exception; private FacebookRequestError(int requestStatusCode, int errorCode, int subErrorCode, String errorType, String errorMessage, JSONObject requestResultBody, JSONObject requestResult, Object batchRequestResult, HttpURLConnection connection, FacebookException exception) { this.requestStatusCode = requestStatusCode; this.errorCode = errorCode; this.subErrorCode = subErrorCode; this.errorType = errorType; this.errorMessage = errorMessage; this.requestResultBody = requestResultBody; this.requestResult = requestResult; this.batchRequestResult = batchRequestResult; this.connection = connection; boolean isLocalException = false; if (exception != null) { this.exception = exception; isLocalException = true; } else { this.exception = new FacebookServiceException(this, errorMessage); } // Initializes the error categories based on the documented error codes as outlined here // https://developers.facebook.com/docs/reference/api/errors/ Category errorCategory = null; int messageId = INVALID_MESSAGE_ID; boolean shouldNotify = false; if (isLocalException) { errorCategory = Category.CLIENT; messageId = INVALID_MESSAGE_ID; } else { if (errorCode == EC_UNKNOWN_ERROR || errorCode == EC_SERVICE_UNAVAILABLE) { errorCategory = Category.SERVER; } else if (errorCode == EC_APP_TOO_MANY_CALLS || errorCode == EC_USER_TOO_MANY_CALLS) { errorCategory = Category.THROTTLING; } else if (errorCode == EC_PERMISSION_DENIED || EC_RANGE_PERMISSION.contains(errorCode)) { errorCategory = Category.PERMISSION; messageId = R.string.com_facebook_requesterror_permissions; } else if (errorCode == EC_INVALID_SESSION || errorCode == EC_INVALID_TOKEN) { if (subErrorCode == EC_USER_CHECKPOINTED || subErrorCode == EC_UNCONFIRMED_USER) { errorCategory = Category.AUTHENTICATION_RETRY; messageId = R.string.com_facebook_requesterror_web_login; shouldNotify = true; } else { errorCategory = Category.AUTHENTICATION_REOPEN_SESSION; if ((subErrorCode == EC_APP_NOT_INSTALLED) || (subErrorCode == EC_EXPIRED)) { messageId = R.string.com_facebook_requesterror_relogin; } else if (subErrorCode == EC_PASSWORD_CHANGED) { messageId = R.string.com_facebook_requesterror_password_changed; } else { messageId = R.string.com_facebook_requesterror_reconnect; shouldNotify = true; } } } if (errorCategory == null) { if (HTTP_RANGE_CLIENT_ERROR.contains(requestStatusCode)) { errorCategory = Category.BAD_REQUEST; } else if (HTTP_RANGE_SERVER_ERROR.contains(requestStatusCode)) { errorCategory = Category.SERVER; } else { errorCategory = Category.OTHER; } } } this.category = errorCategory; this.userActionMessageId = messageId; this.shouldNotifyUser = shouldNotify; } private FacebookRequestError(int requestStatusCode, int errorCode, int subErrorCode, String errorType, String errorMessage, JSONObject requestResultBody, JSONObject requestResult, Object batchRequestResult, HttpURLConnection connection) { this(requestStatusCode, errorCode, subErrorCode, errorType, errorMessage, requestResultBody, requestResult, batchRequestResult, connection, null); } FacebookRequestError(HttpURLConnection connection, Exception exception) { this(INVALID_HTTP_STATUS_CODE, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null, null, null, null, null, connection, (exception instanceof FacebookException) ? (FacebookException) exception : new FacebookException(exception)); } public FacebookRequestError(int errorCode, String errorType, String errorMessage) { this(INVALID_HTTP_STATUS_CODE, errorCode, INVALID_ERROR_CODE, errorType, errorMessage, null, null, null, null, null); } /** * Returns the resource id for a user-friendly message for the application to * present to the user. * * @return a user-friendly message to present to the user */ public int getUserActionMessageId() { return userActionMessageId; } /** * Returns whether direct user action is required to successfully continue with the Facebook * operation. If user action is required, apps can also call {@link #getUserActionMessageId()} * in order to get a resource id for a message to show the user. * * @return whether direct user action is required */ public boolean shouldNotifyUser() { return shouldNotifyUser; } /** * Returns the category in which the error belongs. Applications can use the category * to determine how best to handle the errors (e.g. exponential backoff for retries if * being throttled). * * @return the category in which the error belong */ public Category getCategory() { return category; } /** * Returns the HTTP status code for this particular request. * * @return the HTTP status code for the request */ public int getRequestStatusCode() { return requestStatusCode; } /** * Returns the error code returned from Facebook. * * @return the error code returned from Facebook */ public int getErrorCode() { return errorCode; } /** * Returns the sub-error code returned from Facebook. * * @return the sub-error code returned from Facebook */ public int getSubErrorCode() { return subErrorCode; } /** * Returns the type of error as a raw string. This is generally less useful * than using the {@link #getCategory()} method, but can provide further details * on the error. * * @return the type of error as a raw string */ public String getErrorType() { return errorType; } /** * Returns the error message returned from Facebook. * * @return the error message returned from Facebook */ public String getErrorMessage() { if (errorMessage != null) { return errorMessage; } else { return exception.getLocalizedMessage(); } } /** * Returns the body portion of the response corresponding to the request from Facebook. * * @return the body of the response for the request */ public JSONObject getRequestResultBody() { return requestResultBody; } /** * Returns the full JSON response for the corresponding request. In a non-batch request, * this would be the raw response in the form of a JSON object. In a batch request, this * result will contain the body of the response as well as the HTTP headers that pertain * to the specific request (in the form of a "headers" JSONArray). * * @return the full JSON response for the request */ public JSONObject getRequestResult() { return requestResult; } /** * Returns the full JSON response for the batch request. If the request was not a batch * request, then the result from this method is the same as {@link #getRequestResult()}. * In case of a batch request, the result will be a JSONArray where the elements * correspond to the requests in the batch. Callers should check the return type against * either JSONObject or JSONArray and cast accordingly. * * @return the full JSON response for the batch */ public Object getBatchRequestResult() { return batchRequestResult; } /** * Returns the HTTP connection that was used to make the request. * * @return the HTTP connection used to make the request */ public HttpURLConnection getConnection() { return connection; } /** * Returns the exception associated with this request, if any. * * @return the exception associated with this request */ public FacebookException getException() { return exception; } @Override public String toString() { return new StringBuilder("{HttpStatus: ") .append(requestStatusCode) .append(", errorCode: ") .append(errorCode) .append(", errorType: ") .append(errorType) .append(", errorMessage: ") .append(errorMessage) .append("}") .toString(); } static FacebookRequestError checkResponseAndCreateError(JSONObject singleResult, Object batchResult, HttpURLConnection connection) { try { if (singleResult.has(CODE_KEY)) { int responseCode = singleResult.getInt(CODE_KEY); Object body = Utility.getStringPropertyAsJSON(singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY); if (body != null && body instanceof JSONObject) { JSONObject jsonBody = (JSONObject) body; // Does this response represent an error from the service? We might get either an "error" // with several sub-properties, or else one or more top-level fields containing error info. String errorType = null; String errorMessage = null; int errorCode = INVALID_ERROR_CODE; int errorSubCode = INVALID_ERROR_CODE; boolean hasError = false; if (jsonBody.has(ERROR_KEY)) { // We assume the error object is correctly formatted. JSONObject error = (JSONObject) Utility.getStringPropertyAsJSON(jsonBody, ERROR_KEY, null); errorType = error.optString(ERROR_TYPE_FIELD_KEY, null); errorMessage = error.optString(ERROR_MESSAGE_FIELD_KEY, null); errorCode = error.optInt(ERROR_CODE_FIELD_KEY, INVALID_ERROR_CODE); errorSubCode = error.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } else if (jsonBody.has(ERROR_CODE_KEY) || jsonBody.has(ERROR_MSG_KEY) || jsonBody.has(ERROR_REASON_KEY)) { errorType = jsonBody.optString(ERROR_REASON_KEY, null); errorMessage = jsonBody.optString(ERROR_MSG_KEY, null); errorCode = jsonBody.optInt(ERROR_CODE_KEY, INVALID_ERROR_CODE); errorSubCode = jsonBody.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE); hasError = true; } if (hasError) { return new FacebookRequestError(responseCode, errorCode, errorSubCode, errorType, errorMessage, jsonBody, singleResult, batchResult, connection); } } // If we didn't get error details, but we did get a failure response code, report it. if (!HTTP_RANGE_SUCCESS.contains(responseCode)) { return new FacebookRequestError(responseCode, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null, null, singleResult.has(BODY_KEY) ? (JSONObject) Utility.getStringPropertyAsJSON( singleResult, BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY) : null, singleResult, batchResult, connection); } } } catch (JSONException e) { // defer the throwing of a JSONException to the graph object proxy } return null; } /** * An enum that represents the Facebook SDK classification for the error that occurred. */ public enum Category { /** * Indicates that the error is authentication related, and that the app should retry * the request after some user action. */ AUTHENTICATION_RETRY, /** * Indicates that the error is authentication related, and that the app should close * the session and reopen it. */ AUTHENTICATION_REOPEN_SESSION, /** Indicates that the error is permission related. */ PERMISSION, /** * Indicates that the error implies the server had an unexpected failure or may be * temporarily unavailable. */ SERVER, /** Indicates that the error results from the server throttling the client. */ THROTTLING, /** * Indicates that the error is Facebook-related but cannot be categorized at this time, * and is likely newer than the current version of the SDK. */ OTHER, /** * Indicates that the error is an application error resulting in a bad or malformed * request to the server. */ BAD_REQUEST, /** * Indicates that this is a client-side error. Examples of this can include, but are * not limited to, JSON parsing errors or {@link java.io.IOException}s. */ CLIENT }; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/FacebookRequestError.java
Java
art
18,268
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; /** * This class helps to create, automatically open (if applicable), save, and * restore the Active Session in a way that is similar to Android UI lifecycles. * <p> * When using this class, clients MUST call all the public methods from the * respective methods in either an Activity or Fragment. Failure to call all the * methods can result in improperly initialized or uninitialized Sessions. */ public class UiLifecycleHelper { private final static String ACTIVITY_NULL_MESSAGE = "activity cannot be null"; private final Activity activity; private final Session.StatusCallback callback; private final BroadcastReceiver receiver; private final LocalBroadcastManager broadcastManager; /** * Creates a new UiLifecycleHelper. * * @param activity the Activity associated with the helper. If calling from a Fragment, * use {@link android.support.v4.app.Fragment#getActivity()} * @param callback the callback for Session status changes, can be null */ public UiLifecycleHelper(Activity activity, Session.StatusCallback callback) { if (activity == null) { throw new IllegalArgumentException(ACTIVITY_NULL_MESSAGE); } this.activity = activity; this.callback = callback; this.receiver = new ActiveSessionBroadcastReceiver(); this.broadcastManager = LocalBroadcastManager.getInstance(activity); } /** * To be called from an Activity or Fragment's onCreate method. * * @param savedInstanceState the previously saved state */ public void onCreate(Bundle savedInstanceState) { Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(activity, null, callback, savedInstanceState); } if (session == null) { session = new Session(activity); } Session.setActiveSession(session); } } /** * To be called from an Activity or Fragment's onResume method. */ public void onResume() { Session session = Session.getActiveSession(); if (session != null) { if (callback != null) { session.addCallback(callback); } if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())) { session.openForRead(null); } } // add the broadcast receiver IntentFilter filter = new IntentFilter(); filter.addAction(Session.ACTION_ACTIVE_SESSION_SET); filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET); // Add a broadcast receiver to listen to when the active Session // is set or unset, and add/remove our callback as appropriate broadcastManager.registerReceiver(receiver, filter); } /** * To be called from an Activity or Fragment's onActivityResult method. * * @param requestCode the request code * @param resultCode the result code * @param data the result data */ public void onActivityResult(int requestCode, int resultCode, Intent data) { Session session = Session.getActiveSession(); if (session != null) { session.onActivityResult(activity, requestCode, resultCode, data); } } /** * To be called from an Activity or Fragment's onSaveInstanceState method. * * @param outState the bundle to save state in */ public void onSaveInstanceState(Bundle outState) { Session.saveSession(Session.getActiveSession(), outState); } /** * To be called from an Activity or Fragment's onPause method. */ public void onPause() { // remove the broadcast receiver broadcastManager.unregisterReceiver(receiver); if (callback != null) { Session session = Session.getActiveSession(); if (session != null) { session.removeCallback(callback); } } } /** * To be called from an Activity or Fragment's onDestroy method. */ public void onDestroy() { } /** * The BroadcastReceiver implementation that either adds or removes the callback * from the active Session object as it's SET or UNSET. */ private class ActiveSessionBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Session.ACTION_ACTIVE_SESSION_SET.equals(intent.getAction())) { Session session = Session.getActiveSession(); if (session != null && callback != null) { session.addCallback(callback); } } else if (Session.ACTION_ACTIVE_SESSION_UNSET.equals(intent.getAction())) { Session session = Session.getActiveSession(); if (session != null && callback != null) { session.removeCallback(callback); } } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/UiLifecycleHelper.java
Java
art
5,996
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * Indicates where a Facebook access token was obtained from. */ public enum AccessTokenSource { /** * Indicates an access token has not been obtained, or is otherwise invalid. */ NONE(false), /** * Indicates an access token was obtained by the user logging in through the * Facebook app for Android using the web login dialog. */ FACEBOOK_APPLICATION_WEB(true), /** * Indicates an access token was obtained by the user logging in through the * Facebook app for Android using the native login dialog. */ FACEBOOK_APPLICATION_NATIVE(true), /** * Indicates an access token was obtained by asking the Facebook app for the * current token based on permissions the user has already granted to the app. * No dialog was shown to the user in this case. */ FACEBOOK_APPLICATION_SERVICE(true), /** * Indicates an access token was obtained by the user logging in through the * Web-based dialog. */ WEB_VIEW(false), /** * Indicates an access token is for a test user rather than an actual * Facebook user. */ TEST_USER(true), /** * Indicates an access token constructed with a Client Token. */ CLIENT_TOKEN(true); private final boolean canExtendToken; AccessTokenSource(boolean canExtendToken) { this.canExtendToken = canExtendToken; } boolean canExtendToken() { return canExtendToken; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/AccessTokenSource.java
Java
art
2,103
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * Enumeration of HTTP methods supported by Request */ public enum HttpMethod { /** * Use HTTP method "GET" for the request */ GET, /** * Use HTTP method "POST" for the request */ POST, /** * Use HTTP method "DELETE" for the request */ DELETE, }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/HttpMethod.java
Java
art
932
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * An Exception indicating that a Session failed to open or obtain new permissions. */ public class FacebookAuthorizationException extends FacebookException { static final long serialVersionUID = 1; /** * Constructs a FacebookAuthorizationException with no additional * information. */ public FacebookAuthorizationException() { super(); } /** * Constructs a FacebookAuthorizationException with a message. * * @param message * A String to be returned from getMessage. */ public FacebookAuthorizationException(String message) { super(message); } /** * Constructs a FacebookAuthorizationException with a message and inner * error. * * @param message * A String to be returned from getMessage. * @param throwable * A Throwable to be returned from getCause. */ public FacebookAuthorizationException(String message, Throwable throwable) { super(message, throwable); } /** * Constructs a FacebookAuthorizationException with an inner error. * * @param throwable * A Throwable to be returned from getCause. */ public FacebookAuthorizationException(Throwable throwable) { super(throwable); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/FacebookAuthorizationException.java
Java
art
1,954
/** * Copyright 2012 Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; final class FacebookSdkVersion { public static final String BUILD = "3.0.1"; public static final String MIGRATION_BUNDLE = "fbsdk:20121026"; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/FacebookSdkVersion.java
Java
art
767
/** * Copyright 2010-present Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.android; import android.Manifest; import android.app.Activity; import android.content.*; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.net.Uri; import android.os.*; import com.facebook.*; import com.facebook.Session.StatusCallback; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * THIS CLASS SHOULD BE CONSIDERED DEPRECATED. * <p/> * All public members of this class are intentionally deprecated. * New code should instead use * {@link Session} to manage session state, * {@link Request} to make API requests, and * {@link com.facebook.widget.WebDialog} to make dialog requests. * <p/> * Adding @Deprecated to this class causes warnings in other deprecated classes * that reference this one. That is the only reason this entire class is not * deprecated. * * @devDocDeprecated */ public class Facebook { // Strings used in the authorization flow @Deprecated public static final String REDIRECT_URI = "fbconnect://success"; @Deprecated public static final String CANCEL_URI = "fbconnect://cancel"; @Deprecated public static final String TOKEN = "access_token"; @Deprecated public static final String EXPIRES = "expires_in"; @Deprecated public static final String SINGLE_SIGN_ON_DISABLED = "service_disabled"; @Deprecated public static final Uri ATTRIBUTION_ID_CONTENT_URI = Uri.parse("content://com.facebook.katana.provider.AttributionIdProvider"); @Deprecated public static final String ATTRIBUTION_ID_COLUMN_NAME = "aid"; @Deprecated public static final int FORCE_DIALOG_AUTH = -1; private static final String LOGIN = "oauth"; // Used as default activityCode by authorize(). See authorize() below. private static final int DEFAULT_AUTH_ACTIVITY_CODE = 32665; // Facebook server endpoints: may be modified in a subclass for testing @Deprecated protected static String DIALOG_BASE_URL = "https://m.facebook.com/dialog/"; @Deprecated protected static String GRAPH_BASE_URL = "https://graph.facebook.com/"; @Deprecated protected static String RESTSERVER_URL = "https://api.facebook.com/restserver.php"; private final Object lock = new Object(); private String accessToken = null; private long accessExpiresMillisecondsAfterEpoch = 0; private long lastAccessUpdateMillisecondsAfterEpoch = 0; private String mAppId; private Activity pendingAuthorizationActivity; private String[] pendingAuthorizationPermissions; private Session pendingOpeningSession; private volatile Session session; // must synchronize this.sync to write private boolean sessionInvalidated; // must synchronize this.sync to access private SetterTokenCachingStrategy tokenCache; private volatile Session userSetSession; // If the last time we extended the access token was more than 24 hours ago // we try to refresh the access token again. final private long REFRESH_TOKEN_BARRIER = 24L * 60L * 60L * 1000L; /** * Constructor for Facebook object. * * @param appId * Your Facebook application ID. Found at * www.facebook.com/developers/apps.php. */ @Deprecated public Facebook(String appId) { if (appId == null) { throw new IllegalArgumentException("You must specify your application ID when instantiating " + "a Facebook object. See README for details."); } mAppId = appId; } /** * Default authorize method. Grants only basic permissions. * <p/> * See authorize() below for @params. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. */ @Deprecated public void authorize(Activity activity, final DialogListener listener) { authorize(activity, new String[]{}, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK, listener); } /** * Authorize method that grants custom permissions. * <p/> * See authorize() below for @params. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. */ @Deprecated public void authorize(Activity activity, String[] permissions, final DialogListener listener) { authorize(activity, permissions, DEFAULT_AUTH_ACTIVITY_CODE, SessionLoginBehavior.SSO_WITH_FALLBACK, listener); } /** * Full authorize method. * <p/> * Starts either an Activity or a dialog which prompts the user to log in to * Facebook and grant the requested permissions to the given application. * <p/> * This method will, when possible, use Facebook's single sign-on for * Android to obtain an access token. This involves proxying a call through * the Facebook for Android stand-alone application, which will handle the * authentication flow, and return an OAuth access token for making API * calls. * <p/> * Because this process will not be available for all users, if single * sign-on is not possible, this method will automatically fall back to the * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled * by Facebook in an embedded WebView, not by the client application. As * such, the dialog makes a network request and renders HTML content rather * than a native UI. The access token is retrieved from a redirect to a * special URL that the WebView handles. * <p/> * Note that User credentials could be handled natively using the OAuth 2.0 * Username and Password Flow, but this is not supported by this SDK. * <p/> * See http://developers.facebook.com/docs/authentication/ and * http://wiki.oauth.net/OAuth-2 for more details. * <p/> * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * <p/> * Also note that requests may be made to the API without calling authorize * first, in which case only public information is returned. * <p/> * IMPORTANT: Note that single sign-on authentication will not function * correctly if you do not include a call to the authorizeCallback() method * in your onActivityResult() function! Please see below for more * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH * as the activityCode parameter in your call to authorize(). * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param activity * The Android activity in which we want to display the * authorization dialog. * @param permissions * A list of permissions required for this application: e.g. * "read_stream", "publish_stream", "offline_access", etc. see * http://developers.facebook.com/docs/authentication/permissions * This parameter should not be null -- if you do not require any * permissions, then pass in an empty String array. * @param activityCode * Single sign-on requires an activity result to be called back * to the client application -- if you are waiting on other * activities to return data, pass a custom activity code here to * avoid collisions. If you would like to force the use of legacy * dialog-based authorization, pass FORCE_DIALOG_AUTH for this * parameter. Otherwise just omit this parameter and Facebook * will use a suitable default. See * http://developer.android.com/reference/android/ * app/Activity.html for more information. * @param listener * Callback interface for notifying the calling application when * the authentication dialog has completed, failed, or been * canceled. */ @Deprecated public void authorize(Activity activity, String[] permissions, int activityCode, final DialogListener listener) { SessionLoginBehavior behavior = (activityCode >= 0) ? SessionLoginBehavior.SSO_WITH_FALLBACK : SessionLoginBehavior.SUPPRESS_SSO; authorize(activity, permissions, activityCode, behavior, listener); } /** * Full authorize method. * * Starts either an Activity or a dialog which prompts the user to log in to * Facebook and grant the requested permissions to the given application. * * This method will, when possible, use Facebook's single sign-on for * Android to obtain an access token. This involves proxying a call through * the Facebook for Android stand-alone application, which will handle the * authentication flow, and return an OAuth access token for making API * calls. * * Because this process will not be available for all users, if single * sign-on is not possible, this method will automatically fall back to the * OAuth 2.0 User-Agent flow. In this flow, the user credentials are handled * by Facebook in an embedded WebView, not by the client application. As * such, the dialog makes a network request and renders HTML content rather * than a native UI. The access token is retrieved from a redirect to a * special URL that the WebView handles. * * Note that User credentials could be handled natively using the OAuth 2.0 * Username and Password Flow, but this is not supported by this SDK. * * See http://developers.facebook.com/docs/authentication/ and * http://wiki.oauth.net/OAuth-2 for more details. * * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * * Also note that requests may be made to the API without calling authorize * first, in which case only public information is returned. * * IMPORTANT: Note that single sign-on authentication will not function * correctly if you do not include a call to the authorizeCallback() method * in your onActivityResult() function! Please see below for more * information. single sign-on may be disabled by passing FORCE_DIALOG_AUTH * as the activityCode parameter in your call to authorize(). * * @param activity * The Android activity in which we want to display the * authorization dialog. * @param permissions * A list of permissions required for this application: e.g. * "read_stream", "publish_stream", "offline_access", etc. see * http://developers.facebook.com/docs/authentication/permissions * This parameter should not be null -- if you do not require any * permissions, then pass in an empty String array. * @param activityCode * Single sign-on requires an activity result to be called back * to the client application -- if you are waiting on other * activities to return data, pass a custom activity code here to * avoid collisions. If you would like to force the use of legacy * dialog-based authorization, pass FORCE_DIALOG_AUTH for this * parameter. Otherwise just omit this parameter and Facebook * will use a suitable default. See * http://developer.android.com/reference/android/ * app/Activity.html for more information. * @param behavior * The {@link SessionLoginBehavior SessionLoginBehavior} that * specifies what behaviors should be attempted during * authorization. * @param listener * Callback interface for notifying the calling application when * the authentication dialog has completed, failed, or been * canceled. */ private void authorize(Activity activity, String[] permissions, int activityCode, SessionLoginBehavior behavior, final DialogListener listener) { checkUserSession("authorize"); pendingOpeningSession = new Session.Builder(activity). setApplicationId(mAppId). setTokenCachingStrategy(getTokenCache()). build(); pendingAuthorizationActivity = activity; pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0]; StatusCallback callback = new StatusCallback() { @Override public void call(Session callbackSession, SessionState state, Exception exception) { // Invoke user-callback. onSessionCallback(callbackSession, state, exception, listener); } }; Session.OpenRequest openRequest = new Session.OpenRequest(activity). setCallback(callback). setLoginBehavior(behavior). setRequestCode(activityCode). setPermissions(Arrays.asList(permissions)); openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0); } private void openSession(Session session, Session.OpenRequest openRequest, boolean isPublish) { openRequest.setIsLegacy(true); if (isPublish) { session.openForPublish(openRequest); } else { session.openForRead(openRequest); } } @SuppressWarnings("deprecation") private void onSessionCallback(Session callbackSession, SessionState state, Exception exception, DialogListener listener) { Bundle extras = callbackSession.getAuthorizationBundle(); if (state == SessionState.OPENED) { Session sessionToClose = null; synchronized (Facebook.this.lock) { if (callbackSession != Facebook.this.session) { sessionToClose = Facebook.this.session; Facebook.this.session = callbackSession; Facebook.this.sessionInvalidated = false; } } if (sessionToClose != null) { sessionToClose.close(); } listener.onComplete(extras); } else if (exception != null) { if (exception instanceof FacebookOperationCanceledException) { listener.onCancel(); } else if ((exception instanceof FacebookAuthorizationException) && (extras != null) && extras.containsKey(Session.WEB_VIEW_ERROR_CODE_KEY) && extras.containsKey(Session.WEB_VIEW_FAILING_URL_KEY)) { DialogError error = new DialogError(exception.getMessage(), extras.getInt(Session.WEB_VIEW_ERROR_CODE_KEY), extras.getString(Session.WEB_VIEW_FAILING_URL_KEY)); listener.onError(error); } else { FacebookError error = new FacebookError(exception.getMessage()); listener.onFacebookError(error); } } } /** * Helper to validate a service intent by resolving and checking the * provider's package signature. * * @param context * @param intent * @return true if the service intent resolution happens successfully and * the signatures match. */ private boolean validateServiceIntent(Context context, Intent intent) { ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0); if (resolveInfo == null) { return false; } return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName); } /** * Query the signature for the application that would be invoked by the * given intent and verify that it matches the FB application's signature. * * @param context * @param packageName * @return true if the app's signature matches the expected signature. */ private boolean validateAppSignatureForPackage(Context context, String packageName) { PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); } catch (NameNotFoundException e) { return false; } for (Signature signature : packageInfo.signatures) { if (signature.toCharsString().equals(FB_APP_SIGNATURE)) { return true; } } return false; } /** * IMPORTANT: If you are using the deprecated authorize() method, * this method must be invoked at the top of the calling * activity's onActivityResult() function or Facebook authentication will * not function properly! * <p/> * If your calling activity does not currently implement onActivityResult(), * you must implement it and include a call to this method if you intend to * use the authorize() method in this SDK. * <p/> * For more information, see * http://developer.android.com/reference/android/app/ * Activity.html#onActivityResult(int, int, android.content.Intent) * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. */ @Deprecated public void authorizeCallback(int requestCode, int resultCode, Intent data) { checkUserSession("authorizeCallback"); Session pending = this.pendingOpeningSession; if (pending != null) { if (pending.onActivityResult(this.pendingAuthorizationActivity, requestCode, resultCode, data)) { this.pendingOpeningSession = null; this.pendingAuthorizationActivity = null; this.pendingAuthorizationPermissions = null; } } } /** * Refresh OAuth access token method. Binds to Facebook for Android * stand-alone application application to refresh the access token. This * method tries to connect to the Facebook App which will handle the * authentication flow, and return a new OAuth access token. This method * will automatically replace the old token with a new one. Note that this * method is asynchronous and the callback will be invoked in the original * calling thread (not in a background thread). * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param context * The Android Context that will be used to bind to the Facebook * RefreshToken Service * @param serviceListener * Callback interface for notifying the calling application when * the refresh request has completed or failed (can be null). In * case of a success a new token can be found inside the result * Bundle under Facebook.ACCESS_TOKEN key. * @return true if the binding to the RefreshToken Service was created */ @Deprecated public boolean extendAccessToken(Context context, ServiceListener serviceListener) { checkUserSession("extendAccessToken"); Intent intent = new Intent(); intent.setClassName("com.facebook.katana", "com.facebook.katana.platform.TokenRefreshService"); // Verify that the application whose package name is // com.facebook.katana // has the expected FB app signature. if (!validateServiceIntent(context, intent)) { return false; } return context.bindService(intent, new TokenRefreshServiceConnection(context, serviceListener), Context.BIND_AUTO_CREATE); } /** * Calls extendAccessToken if shouldExtendAccessToken returns true. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @return the same value as extendAccessToken if the the token requires * refreshing, true otherwise */ @Deprecated public boolean extendAccessTokenIfNeeded(Context context, ServiceListener serviceListener) { checkUserSession("extendAccessTokenIfNeeded"); if (shouldExtendAccessToken()) { return extendAccessToken(context, serviceListener); } return true; } /** * Check if the access token requires refreshing. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @return true if the last time a new token was obtained was over 24 hours * ago. */ @Deprecated public boolean shouldExtendAccessToken() { checkUserSession("shouldExtendAccessToken"); return isSessionValid() && (System.currentTimeMillis() - lastAccessUpdateMillisecondsAfterEpoch >= REFRESH_TOKEN_BARRIER); } /** * Handles connection to the token refresh service (this service is a part * of Facebook App). */ private class TokenRefreshServiceConnection implements ServiceConnection { final Messenger messageReceiver = new Messenger( new TokenRefreshConnectionHandler(Facebook.this, this)); final ServiceListener serviceListener; final Context applicationsContext; Messenger messageSender = null; public TokenRefreshServiceConnection(Context applicationsContext, ServiceListener serviceListener) { this.applicationsContext = applicationsContext; this.serviceListener = serviceListener; } @Override public void onServiceConnected(ComponentName className, IBinder service) { messageSender = new Messenger(service); refreshToken(); } @Override public void onServiceDisconnected(ComponentName arg) { serviceListener.onError(new Error("Service disconnected")); // We returned an error so there's no point in // keeping the binding open. applicationsContext.unbindService(TokenRefreshServiceConnection.this); } private void refreshToken() { Bundle requestData = new Bundle(); requestData.putString(TOKEN, accessToken); Message request = Message.obtain(); request.setData(requestData); request.replyTo = messageReceiver; try { messageSender.send(request); } catch (RemoteException e) { serviceListener.onError(new Error("Service connection error")); } } } // Creating a static Handler class to reduce the possibility of a memory leak. // Handler objects for the same thread all share a common Looper object, which they post messages // to and read from. As messages contain target Handler, as long as there are messages with target // handler in the message queue, the handler cannot be garbage collected. If handler is not static, // the instance of the containing class also cannot be garbage collected even if it is destroyed. private static class TokenRefreshConnectionHandler extends Handler { WeakReference<Facebook> facebookWeakReference; WeakReference<TokenRefreshServiceConnection> connectionWeakReference; TokenRefreshConnectionHandler(Facebook facebook, TokenRefreshServiceConnection connection) { super(); facebookWeakReference = new WeakReference<Facebook>(facebook); connectionWeakReference = new WeakReference<TokenRefreshServiceConnection>(connection); } @Override @SuppressWarnings("deprecation") public void handleMessage(Message msg) { Facebook facebook = facebookWeakReference.get(); TokenRefreshServiceConnection connection = connectionWeakReference.get(); if (facebook == null || connection == null) { return; } String token = msg.getData().getString(TOKEN); // Legacy functions in Facebook class (and ServiceListener implementors) expect expires_in in // milliseconds from epoch long expiresAtMsecFromEpoch = msg.getData().getLong(EXPIRES) * 1000L; if (token != null) { facebook.setAccessToken(token); facebook.setAccessExpires(expiresAtMsecFromEpoch); Session refreshSession = facebook.session; if (refreshSession != null) { // Session.internalRefreshToken expects the original bundle with expires_in in seconds from // epoch. LegacyHelper.extendTokenCompleted(refreshSession, msg.getData()); } if (connection.serviceListener != null) { // To avoid confusion we should return the expiration time in // the same format as the getAccessExpires() function - that // is in milliseconds. Bundle resultBundle = (Bundle) msg.getData().clone(); resultBundle.putLong(EXPIRES, expiresAtMsecFromEpoch); connection.serviceListener.onComplete(resultBundle); } } else if (connection.serviceListener != null) { // extract errors only if // client wants them String error = msg.getData().getString("error"); if (msg.getData().containsKey("error_code")) { int errorCode = msg.getData().getInt("error_code"); connection.serviceListener.onFacebookError(new FacebookError(error, null, errorCode)); } else { connection.serviceListener.onError(new Error(error != null ? error : "Unknown service error")); } } if (connection != null) { // The refreshToken function should be called rarely, // so there is no point in keeping the binding open. connection.applicationsContext.unbindService(connection); } } } /** * Invalidate the current user session by removing the access token in * memory, clearing the browser cookie, and calling auth.expireSession * through the API. * <p/> * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param context * The Android context in which the logout should be called: it * should be the same context in which the login occurred in * order to clear any stored cookies * @throws IOException * @throws MalformedURLException * @return JSON string representation of the auth.expireSession response * ("true" if successful) */ @Deprecated public String logout(Context context) throws MalformedURLException, IOException { return logoutImpl(context); } String logoutImpl(Context context) throws MalformedURLException, IOException { checkUserSession("logout"); Bundle b = new Bundle(); b.putString("method", "auth.expireSession"); String response = request(b); long currentTimeMillis = System.currentTimeMillis(); Session sessionToClose = null; synchronized (this.lock) { sessionToClose = session; session = null; accessToken = null; accessExpiresMillisecondsAfterEpoch = 0; lastAccessUpdateMillisecondsAfterEpoch = currentTimeMillis; sessionInvalidated = false; } if (sessionToClose != null) { sessionToClose.closeAndClearTokenInformation(); } return response; } /** * Make a request to Facebook's old (pre-graph) API with the given * parameters. One of the parameter keys must be "method" and its value * should be a valid REST server API method. * <p/> * See http://developers.facebook.com/docs/reference/rest/ * <p/> * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * <p/> * Example: <code> * Bundle parameters = new Bundle(); * parameters.putString("method", "auth.expireSession"); * String response = request(parameters); * </code> * <p/> * This method is deprecated. See {@link Facebook} and {@link Request} for more info. * * @param parameters * Key-value pairs of parameters to the request. Refer to the * documentation: one of the parameters must be "method". * @throws IOException * if a network error occurs * @throws MalformedURLException * if accessing an invalid endpoint * @throws IllegalArgumentException * if one of the parameters is not "method" * @return JSON string representation of the response */ @Deprecated public String request(Bundle parameters) throws MalformedURLException, IOException { if (!parameters.containsKey("method")) { throw new IllegalArgumentException("API method must be specified. " + "(parameters must contain key \"method\" and value). See" + " http://developers.facebook.com/docs/reference/rest/"); } return requestImpl(null, parameters, "GET"); } /** * Make a request to the Facebook Graph API without any parameters. * <p/> * See http://developers.facebook.com/docs/api * <p/> * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * <p/> * This method is deprecated. See {@link Facebook} and {@link Request} for more info. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @throws IOException * @throws MalformedURLException * @return JSON string representation of the response */ @Deprecated public String request(String graphPath) throws MalformedURLException, IOException { return requestImpl(graphPath, new Bundle(), "GET"); } /** * Make a request to the Facebook Graph API with the given string parameters * using an HTTP GET (default method). * <p/> * See http://developers.facebook.com/docs/api * <p/> * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * <p/> * This method is deprecated. See {@link Facebook} and {@link Request} for more info. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters "q" : "facebook" would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @throws IOException * @throws MalformedURLException * @return JSON string representation of the response */ @Deprecated public String request(String graphPath, Bundle parameters) throws MalformedURLException, IOException { return requestImpl(graphPath, parameters, "GET"); } /** * Synchronously make a request to the Facebook Graph API with the given * HTTP method and string parameters. Note that binary data parameters (e.g. * pictures) are not yet supported by this helper function. * <p/> * See http://developers.facebook.com/docs/api * <p/> * Note that this method blocks waiting for a network response, so do not * call it in a UI thread. * <p/> * This method is deprecated. See {@link Facebook} and {@link Request} for more info. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param params * Key-value string parameters, e.g. the path "search" with * parameters {"q" : "facebook"} would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param httpMethod * http verb, e.g. "GET", "POST", "DELETE" * @throws IOException * @throws MalformedURLException * @return JSON string representation of the response */ @Deprecated public String request(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException, MalformedURLException, IOException { return requestImpl(graphPath, params, httpMethod); } // Internal call to avoid deprecated warnings. @SuppressWarnings("deprecation") String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException, MalformedURLException, IOException { params.putString("format", "json"); if (isSessionValid()) { params.putString(TOKEN, getAccessToken()); } String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL; return Util.openUrl(url, httpMethod, params); } /** * Generate a UI dialog for the request action in the given Android context. * <p/> * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * * This method is deprecated. See {@link com.facebook.widget.WebDialog}. * * @param context * The Android context in which we will generate this dialog. * @param action * String representation of the desired method: e.g. "login", * "stream.publish", ... * @param listener * Callback interface to notify the application when the dialog * has completed. */ @Deprecated public void dialog(Context context, String action, DialogListener listener) { dialog(context, action, new Bundle(), listener); } /** * Generate a UI dialog for the request action in the given Android context * with the provided parameters. * <p/> * Note that this method is asynchronous and the callback will be invoked in * the original calling thread (not in a background thread). * * This method is deprecated. See {@link com.facebook.widget.WebDialog}. * * @param context * The Android context in which we will generate this dialog. * @param action * String representation of the desired method: e.g. "feed" ... * @param parameters * String key-value pairs to be passed as URL parameters. * @param listener * Callback interface to notify the application when the dialog * has completed. */ @Deprecated public void dialog(Context context, String action, Bundle parameters, final DialogListener listener) { parameters.putString("display", "touch"); parameters.putString("redirect_uri", REDIRECT_URI); if (action.equals(LOGIN)) { parameters.putString("type", "user_agent"); parameters.putString("client_id", mAppId); } else { parameters.putString("app_id", mAppId); // We do not want to add an access token when displaying the auth dialog. if (isSessionValid()) { parameters.putString(TOKEN, getAccessToken()); } } if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) { Util.showAlert(context, "Error", "Application requires permission to access the Internet"); } else { new FbDialog(context, action, parameters, listener).show(); } } /** * Returns whether the current access token is valid * * @return boolean - whether this object has an non-expired session token */ @Deprecated public boolean isSessionValid() { return (getAccessToken() != null) && ((getAccessExpires() == 0) || (System.currentTimeMillis() < getAccessExpires())); } /** * Allows the user to set a Session for the Facebook class to use. * If a Session is set here, then one should not use the authorize, logout, * or extendAccessToken methods which alter the Session object since that may * result in undefined behavior. Using those methods after setting the * session here will result in exceptions being thrown. * * @param session the Session object to use, cannot be null */ @Deprecated public void setSession(Session session) { if (session == null) { throw new IllegalArgumentException("session cannot be null"); } synchronized (this.lock) { this.userSetSession = session; } } private void checkUserSession(String methodName) { if (userSetSession != null) { throw new UnsupportedOperationException( String.format("Cannot call %s after setSession has been called.", methodName)); } } /** * Get the underlying Session object to use with 3.0 api. * * @return Session - underlying session */ @Deprecated public final Session getSession() { while (true) { String cachedToken = null; Session oldSession = null; synchronized (this.lock) { if (userSetSession != null) { return userSetSession; } if ((session != null) || !sessionInvalidated) { return session; } cachedToken = accessToken; oldSession = session; } if (cachedToken == null) { return null; } // At this point we do not have a valid session, but mAccessToken is // non-null. // So we can try building a session based on that. List<String> permissions; if (oldSession != null) { permissions = oldSession.getPermissions(); } else if (pendingAuthorizationPermissions != null) { permissions = Arrays.asList(pendingAuthorizationPermissions); } else { permissions = Collections.<String>emptyList(); } Session newSession = new Session.Builder(pendingAuthorizationActivity). setApplicationId(mAppId). setTokenCachingStrategy(getTokenCache()). build(); if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) { return null; } Session.OpenRequest openRequest = new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions); openSession(newSession, openRequest, !permissions.isEmpty()); Session invalidatedSession = null; Session returnSession = null; synchronized (this.lock) { if (sessionInvalidated || (session == null)) { invalidatedSession = session; returnSession = session = newSession; sessionInvalidated = false; } } if (invalidatedSession != null) { invalidatedSession.close(); } if (returnSession != null) { return returnSession; } // Else token state changed between the synchronized blocks, so // retry.. } } /** * Retrieve the OAuth 2.0 access token for API access: treat with care. * Returns null if no session exists. * * @return String - access token */ @Deprecated public String getAccessToken() { Session s = getSession(); if (s != null) { return s.getAccessToken(); } else { return null; } } /** * Retrieve the current session's expiration time (in milliseconds since * Unix epoch), or 0 if the session doesn't expire or doesn't exist. * * @return long - session expiration time */ @Deprecated public long getAccessExpires() { Session s = getSession(); if (s != null) { return s.getExpirationDate().getTime(); } else { return accessExpiresMillisecondsAfterEpoch; } } /** * Retrieve the last time the token was updated (in milliseconds since * the Unix epoch), or 0 if the token has not been set. * * @return long - timestamp of the last token update. */ @Deprecated public long getLastAccessUpdate() { return lastAccessUpdateMillisecondsAfterEpoch; } /** * Restore the token, expiration time, and last update time from cached values. * These should be values obtained from getAccessToken(), getAccessExpires, and * getLastAccessUpdate() respectively. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param accessToken - access token * @param accessExpires - access token expiration time * @param lastAccessUpdate - timestamp of the last token update */ @Deprecated public void setTokenFromCache(String accessToken, long accessExpires, long lastAccessUpdate) { checkUserSession("setTokenFromCache"); synchronized (this.lock) { this.accessToken = accessToken; accessExpiresMillisecondsAfterEpoch = accessExpires; lastAccessUpdateMillisecondsAfterEpoch = lastAccessUpdate; } } /** * Set the OAuth 2.0 access token for API access. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param token * - access token */ @Deprecated public void setAccessToken(String token) { checkUserSession("setAccessToken"); synchronized (this.lock) { accessToken = token; lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis(); sessionInvalidated = true; } } /** * Set the current session's expiration time (in milliseconds since Unix * epoch), or 0 if the session doesn't expire. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param timestampInMsec * - timestamp in milliseconds */ @Deprecated public void setAccessExpires(long timestampInMsec) { checkUserSession("setAccessExpires"); synchronized (this.lock) { accessExpiresMillisecondsAfterEpoch = timestampInMsec; lastAccessUpdateMillisecondsAfterEpoch = System.currentTimeMillis(); sessionInvalidated = true; } } /** * Set the current session's duration (in seconds since Unix epoch), or "0" * if session doesn't expire. * <p/> * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param expiresInSecsFromNow * - duration in seconds (or 0 if the session doesn't expire) */ @Deprecated public void setAccessExpiresIn(String expiresInSecsFromNow) { checkUserSession("setAccessExpiresIn"); if (expiresInSecsFromNow != null) { long expires = expiresInSecsFromNow.equals("0") ? 0 : System.currentTimeMillis() + Long.parseLong(expiresInSecsFromNow) * 1000L; setAccessExpires(expires); } } /** * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @return the String representing application ID */ @Deprecated public String getAppId() { return mAppId; } /** * This method is deprecated. See {@link Facebook} and {@link Session} for more info. * * @param appId the String representing the application ID */ @Deprecated public void setAppId(String appId) { checkUserSession("setAppId"); synchronized (this.lock) { mAppId = appId; sessionInvalidated = true; } } private TokenCachingStrategy getTokenCache() { // Intentionally not volatile/synchronized--it is okay if we race to // create more than one of these. if (tokenCache == null) { tokenCache = new SetterTokenCachingStrategy(); } return tokenCache; } private static String[] stringArray(List<String> list) { String[] array = new String[list.size()]; if (list != null) { for (int i = 0; i < array.length; i++) { array[i] = list.get(i); } } return array; } private static List<String> stringList(String[] array) { if (array != null) { return Arrays.asList(array); } else { return Collections.emptyList(); } } private class SetterTokenCachingStrategy extends TokenCachingStrategy { @Override public Bundle load() { Bundle bundle = new Bundle(); if (accessToken != null) { TokenCachingStrategy.putToken(bundle, accessToken); TokenCachingStrategy.putExpirationMilliseconds(bundle, accessExpiresMillisecondsAfterEpoch); TokenCachingStrategy.putPermissions(bundle, stringList(pendingAuthorizationPermissions)); TokenCachingStrategy.putSource(bundle, AccessTokenSource.WEB_VIEW); TokenCachingStrategy.putLastRefreshMilliseconds(bundle, lastAccessUpdateMillisecondsAfterEpoch); } return bundle; } @Override public void save(Bundle bundle) { accessToken = TokenCachingStrategy.getToken(bundle); accessExpiresMillisecondsAfterEpoch = TokenCachingStrategy.getExpirationMilliseconds(bundle); pendingAuthorizationPermissions = stringArray(TokenCachingStrategy.getPermissions(bundle)); lastAccessUpdateMillisecondsAfterEpoch = TokenCachingStrategy.getLastRefreshMilliseconds(bundle); } @Override public void clear() { accessToken = null; } } /** * Get Attribution ID for app install conversion tracking. * <p/> * This method is deprecated. See {@link Facebook} and {@link Settings} for more info. * * @param contentResolver * @return Attribution ID that will be used for conversion tracking. It will be null only if * the user has not installed or logged in to the Facebook app. */ @Deprecated public static String getAttributionId(ContentResolver contentResolver) { return Settings.getAttributionId(contentResolver); } /** * Get the auto install publish setting. If true, an install event will be published during authorize(), unless * it has occurred previously or the app does not have install attribution enabled on the application's developer * config page. * <p/> * This method is deprecated. See {@link Facebook} and {@link Settings} for more info. * * @return a Boolean indicating whether installation of the app should be auto-published. */ @Deprecated public boolean getShouldAutoPublishInstall() { return Settings.getShouldAutoPublishInstall(); } /** * Sets whether auto publishing of installs will occur. * <p/> * This method is deprecated. See {@link Facebook} and {@link Settings} for more info. * * @param value a Boolean indicating whether installation of the app should be auto-published. */ @Deprecated public void setShouldAutoPublishInstall(boolean value) { Settings.setShouldAutoPublishInstall(value); } /** * Manually publish install attribution to the Facebook graph. Internally handles tracking repeat calls to prevent * multiple installs being published to the graph. * <p/> * This method is deprecated. See {@link Facebook} and {@link Settings} for more info. * * @param context the current Android context * @return Always false. Earlier versions of the API returned true if it was no longer necessary to call. * Apps should ignore this value, but for compatibility we will return false to ensure repeat calls (and the * underlying code will prevent duplicate network traffic). */ @Deprecated public boolean publishInstall(final Context context) { Settings.publishInstallAsync(context, mAppId); return false; } /** * Callback interface for dialog requests. * <p/> * THIS CLASS SHOULD BE CONSIDERED DEPRECATED. * <p/> * All public members of this class are intentionally deprecated. * New code should instead use * {@link com.facebook.widget.WebDialog} * <p/> * Adding @Deprecated to this class causes warnings in other deprecated classes * that reference this one. That is the only reason this entire class is not * deprecated. * * @devDocDeprecated */ public static interface DialogListener { /** * Called when a dialog completes. * * Executed by the thread that initiated the dialog. * * @param values * Key-value string pairs extracted from the response. */ public void onComplete(Bundle values); /** * Called when a Facebook responds to a dialog with an error. * * Executed by the thread that initiated the dialog. * */ public void onFacebookError(FacebookError e); /** * Called when a dialog has an error. * * Executed by the thread that initiated the dialog. * */ public void onError(DialogError e); /** * Called when a dialog is canceled by the user. * * Executed by the thread that initiated the dialog. * */ public void onCancel(); } /** * Callback interface for service requests. * <p/> * THIS CLASS SHOULD BE CONSIDERED DEPRECATED. * <p/> * All public members of this class are intentionally deprecated. * New code should instead use * {@link Session} to manage session state. * <p/> * Adding @Deprecated to this class causes warnings in other deprecated classes * that reference this one. That is the only reason this entire class is not * deprecated. * * @devDocDeprecated */ public static interface ServiceListener { /** * Called when a service request completes. * * @param values * Key-value string pairs extracted from the response. */ public void onComplete(Bundle values); /** * Called when a Facebook server responds to the request with an error. */ public void onFacebookError(FacebookError e); /** * Called when a Facebook Service responds to the request with an error. */ public void onError(Error e); } @Deprecated public static final String FB_APP_SIGNATURE = "30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310" + "b3009060355040613025553310b30090603550408130243413112301006035504" + "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204" + "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504" + "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333" + "13231353231365a180f32303530303932353231353231365a307a310b30090603" + "55040613025553310b30090603550408130243413112301006035504071309506" + "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c" + "653111300f060355040b130846616365626f6f6b311d301b06035504031314466" + "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01" + "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa" + "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7" + "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc" + "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603" + "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050" + "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c" + "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6" + "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2" + "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd" + "928a2"; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/android/Facebook.java
Java
art
54,948
/** * Copyright 2010-present Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.android; import android.app.AlertDialog.Builder; import android.content.Context; import android.os.Bundle; import com.facebook.internal.Utility; import org.json.JSONException; import org.json.JSONObject; import java.io.*; import java.net.*; /** * Utility class supporting the Facebook Object. * <p/> * THIS CLASS SHOULD BE CONSIDERED DEPRECATED. * <p/> * All public members of this class are intentionally deprecated. * New code should instead use * {@link com.facebook.Request} * <p/> * Adding @Deprecated to this class causes warnings in other deprecated classes * that reference this one. That is the only reason this entire class is not * deprecated. * * @devDocDeprecated */ public final class Util { private final static String UTF8 = "UTF-8"; /** * Generate the multi-part post body providing the parameters and boundary * string * * @param parameters the parameters need to be posted * @param boundary the random string as boundary * @return a string of the post body */ @Deprecated public static String encodePostBody(Bundle parameters, String boundary) { if (parameters == null) return ""; StringBuilder sb = new StringBuilder(); for (String key : parameters.keySet()) { Object parameter = parameters.get(key); if (!(parameter instanceof String)) { continue; } sb.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n" + (String)parameter); sb.append("\r\n" + "--" + boundary + "\r\n"); } return sb.toString(); } @Deprecated public static String encodeUrl(Bundle parameters) { if (parameters == null) { return ""; } StringBuilder sb = new StringBuilder(); boolean first = true; for (String key : parameters.keySet()) { Object parameter = parameters.get(key); if (!(parameter instanceof String)) { continue; } if (first) first = false; else sb.append("&"); sb.append(URLEncoder.encode(key) + "=" + URLEncoder.encode(parameters.getString(key))); } return sb.toString(); } @Deprecated public static Bundle decodeUrl(String s) { Bundle params = new Bundle(); if (s != null) { String array[] = s.split("&"); for (String parameter : array) { String v[] = parameter.split("="); try { if (v.length == 2) { params.putString(URLDecoder.decode(v[0], UTF8), URLDecoder.decode(v[1], UTF8)); } else if (v.length == 1) { params.putString(URLDecoder.decode(v[0], UTF8), ""); } } catch (UnsupportedEncodingException e) { // shouldn't happen } } } return params; } /** * Parse a URL query and fragment parameters into a key-value bundle. * * @param url the URL to parse * @return a dictionary bundle of keys and values */ @Deprecated public static Bundle parseUrl(String url) { // hack to prevent MalformedURLException url = url.replace("fbconnect", "http"); try { URL u = new URL(url); Bundle b = decodeUrl(u.getQuery()); b.putAll(decodeUrl(u.getRef())); return b; } catch (MalformedURLException e) { return new Bundle(); } } /** * Connect to an HTTP URL and return the response as a string. * * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url - the resource to open: must be a welformed URL * @param method - the HTTP method to use ("GET", "POST", etc.) * @param params - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException - if the URL format is invalid * @throws IOException - if a network problem occurs */ @Deprecated public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Utility.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties(). getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { Object parameter = params.get(key); if (parameter instanceof byte[]) { dataparams.putByteArray(key, (byte[])parameter); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty( "Content-Type", "multipart/form-data;boundary="+strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary +endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key: dataparams.keySet()){ os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; } @Deprecated private static String read(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); } in.close(); return sb.toString(); } /** * Parse a server response into a JSON Object. This is a basic * implementation using org.json.JSONObject representation. More * sophisticated applications may wish to do their own parsing. * * The parsed JSON is checked for a variety of error fields and * a FacebookException is thrown if an error condition is set, * populated with the error message and error type or code if * available. * * @param response - string representation of the response * @return the response as a JSON Object * @throws JSONException - if the response is not valid JSON * @throws FacebookError - if an error condition is set */ @Deprecated public static JSONObject parseJson(String response) throws JSONException, FacebookError { // Edge case: when sending a POST request to /[post_id]/likes // the return value is 'true' or 'false'. Unfortunately // these values cause the JSONObject constructor to throw // an exception. if (response.equals("false")) { throw new FacebookError("request failed"); } if (response.equals("true")) { response = "{value : true}"; } JSONObject json = new JSONObject(response); // errors set by the server are not consistent // they depend on the method and endpoint if (json.has("error")) { JSONObject error = json.getJSONObject("error"); throw new FacebookError( error.getString("message"), error.getString("type"), 0); } if (json.has("error_code") && json.has("error_msg")) { throw new FacebookError(json.getString("error_msg"), "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_code")) { throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code"))); } if (json.has("error_msg")) { throw new FacebookError(json.getString("error_msg")); } if (json.has("error_reason")) { throw new FacebookError(json.getString("error_reason")); } return json; } /** * Display a simple alert dialog with the given text and title. * * @param context * Android context in which the dialog should be displayed * @param title * Alert dialog title * @param text * Alert dialog message */ @Deprecated public static void showAlert(Context context, String title, String text) { Builder alertBuilder = new Builder(context); alertBuilder.setTitle(title); alertBuilder.setMessage(text); alertBuilder.create().show(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/android/Util.java
Java
art
11,060
/** * Copyright 2010-present Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.android; /** * Encapsulation of Dialog Error. * <p/> * THIS CLASS SHOULD BE CONSIDERED DEPRECATED. * <p/> * All public members of this class are intentionally deprecated. * New code should instead use * {@link com.facebook.FacebookException} * <p/> * Adding @Deprecated to this class causes warnings in other deprecated classes * that reference this one. That is the only reason this entire class is not * deprecated. * * @devDocDeprecated */ public class DialogError extends Throwable { private static final long serialVersionUID = 1L; /** * The ErrorCode received by the WebView: see * http://developer.android.com/reference/android/webkit/WebViewClient.html */ private int mErrorCode; /** The URL that the dialog was trying to load */ private String mFailingUrl; @Deprecated public DialogError(String message, int errorCode, String failingUrl) { super(message); mErrorCode = errorCode; mFailingUrl = failingUrl; } @Deprecated public int getErrorCode() { return mErrorCode; } @Deprecated public String getFailingUrl() { return mFailingUrl; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/android/DialogError.java
Java
art
1,802
/** * Copyright 2010-present Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.android; /** * Encapsulation of a Facebook Error: a Facebook request that could not be * fulfilled. * <p/> * THIS CLASS SHOULD BE CONSIDERED DEPRECATED. * <p/> * All public members of this class are intentionally deprecated. * New code should instead use * {@link com.facebook.FacebookException} * <p/> * Adding @Deprecated to this class causes warnings in other deprecated classes * that reference this one. That is the only reason this entire class is not * deprecated. * * @devDocDeprecated */ public class FacebookError extends RuntimeException { private static final long serialVersionUID = 1L; private int mErrorCode = 0; private String mErrorType; @Deprecated public FacebookError(String message) { super(message); } @Deprecated public FacebookError(String message, String type, int code) { super(message); mErrorType = type; mErrorCode = code; } @Deprecated public int getErrorCode() { return mErrorCode; } @Deprecated public String getErrorType() { return mErrorType; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/android/FacebookError.java
Java
art
1,735
/** * Copyright 2010-present Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.android; import android.content.Context; import android.os.Bundle; import com.facebook.*; import com.facebook.android.Facebook.DialogListener; import com.facebook.widget.WebDialog; /** * This class is deprecated. See {@link com.facebook.widget.WebDialog}. */ @Deprecated public class FbDialog extends WebDialog { private DialogListener mListener; public FbDialog(Context context, String url, DialogListener listener) { this(context, url, listener, DEFAULT_THEME); } public FbDialog(Context context, String url, DialogListener listener, int theme) { super(context, url, theme); setDialogListener(listener); } public FbDialog(Context context, String action, Bundle parameters, DialogListener listener) { super(context, action, parameters, DEFAULT_THEME, null); setDialogListener(listener); } public FbDialog(Context context, String action, Bundle parameters, DialogListener listener, int theme) { super(context, action, parameters, theme, null); setDialogListener(listener); } private void setDialogListener(DialogListener listener) { this.mListener = listener; setOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { callDialogListener(values, error); } }); } private void callDialogListener(Bundle values, FacebookException error) { if (mListener == null) { return; } if (values != null) { mListener.onComplete(values); } else { if (error instanceof FacebookDialogException) { FacebookDialogException facebookDialogException = (FacebookDialogException) error; DialogError dialogError = new DialogError(facebookDialogException.getMessage(), facebookDialogException.getErrorCode(), facebookDialogException.getFailingUrl()); mListener.onError(dialogError); } else if (error instanceof FacebookOperationCanceledException) { mListener.onCancel(); } else { FacebookError facebookError = new FacebookError(error.getMessage()); mListener.onFacebookError(facebookError); } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/android/FbDialog.java
Java
art
2,999
/** * Copyright 2010-present Facebook * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.android; import android.content.Context; import android.os.Bundle; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; /** * A sample implementation of asynchronous API requests. This class provides * the ability to execute API methods and have the call return immediately, * without blocking the calling thread. This is necessary when accessing the * API in the UI thread, for instance. The request response is returned to * the caller via a callback interface, which the developer must implement. * * This sample implementation simply spawns a new thread for each request, * and makes the API call immediately. This may work in many applications, * but more sophisticated users may re-implement this behavior using a thread * pool, a network thread, a request queue, or other mechanism. Advanced * functionality could be built, such as rate-limiting of requests, as per * a specific application's needs. * * @deprecated * * @see RequestListener * The callback interface. * * @author Jim Brusstar (jimbru@fb.com), * Yariv Sadan (yariv@fb.com), * Luke Shepard (lshepard@fb.com) */ @Deprecated public class AsyncFacebookRunner { Facebook fb; public AsyncFacebookRunner(Facebook fb) { this.fb = fb; } /** * Invalidate the current user session by removing the access token in * memory, clearing the browser cookies, and calling auth.expireSession * through the API. The application will be notified when logout is * complete via the callback interface. * <p/> * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * <p/> * This method is deprecated. See {@link Facebook} and {@link com.facebook.Session} for more info. * * @param context * The Android context in which the logout should be called: it * should be the same context in which the login occurred in * order to clear any stored cookies * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ @Deprecated public void logout(final Context context, final RequestListener listener, final Object state) { new Thread() { @Override public void run() { try { String response = fb.logoutImpl(context); if (response.length() == 0 || response.equals("false")){ listener.onFacebookError(new FacebookError( "auth.expireSession failed"), state); return; } listener.onComplete(response, state); } catch (FileNotFoundException e) { listener.onFileNotFoundException(e, state); } catch (MalformedURLException e) { listener.onMalformedURLException(e, state); } catch (IOException e) { listener.onIOException(e, state); } } }.start(); } @Deprecated public void logout(final Context context, final RequestListener listener) { logout(context, listener, /* state */ null); } /** * Make a request to Facebook's old (pre-graph) API with the given * parameters. One of the parameter keys must be "method" and its value * should be a valid REST server API method. * <p/> * See http://developers.facebook.com/docs/reference/rest/ * <p/> * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * <p/> * Example: * <code> * Bundle parameters = new Bundle(); * parameters.putString("method", "auth.expireSession", new Listener()); * String response = request(parameters); * </code> * <p/> * This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info. * * @param parameters * Key-value pairs of parameters to the request. Refer to the * documentation: one of the parameters must be "method". * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ @Deprecated public void request(Bundle parameters, RequestListener listener, final Object state) { request(null, parameters, "GET", listener, state); } @Deprecated public void request(Bundle parameters, RequestListener listener) { request(null, parameters, "GET", listener, /* state */ null); } /** * Make a request to the Facebook Graph API without any parameters. * <p/> * See http://developers.facebook.com/docs/api * <p/> * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * <p/> * This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ @Deprecated public void request(String graphPath, RequestListener listener, final Object state) { request(graphPath, new Bundle(), "GET", listener, state); } @Deprecated public void request(String graphPath, RequestListener listener) { request(graphPath, new Bundle(), "GET", listener, /* state */ null); } /** * Make a request to the Facebook Graph API with the given string parameters * using an HTTP GET (default method). * <p/> * See http://developers.facebook.com/docs/api * <p/> * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * <p/> * This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters "q" : "facebook" would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ @Deprecated public void request(String graphPath, Bundle parameters, RequestListener listener, final Object state) { request(graphPath, parameters, "GET", listener, state); } @Deprecated public void request(String graphPath, Bundle parameters, RequestListener listener) { request(graphPath, parameters, "GET", listener, /* state */ null); } /** * Make a request to the Facebook Graph API with the given HTTP method and * string parameters. Note that binary data parameters (e.g. pictures) are * not yet supported by this helper function. * <p/> * See http://developers.facebook.com/docs/api * <p/> * Note that this method is asynchronous and the callback will be invoked * in a background thread; operations that affect the UI will need to be * posted to the UI thread or an appropriate handler. * <p/> * This method is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info. * * @param graphPath * Path to resource in the Facebook graph, e.g., to fetch data * about the currently logged authenticated user, provide "me", * which will fetch http://graph.facebook.com/me * @param parameters * key-value string parameters, e.g. the path "search" with * parameters {"q" : "facebook"} would produce a query for the * following graph resource: * https://graph.facebook.com/search?q=facebook * @param httpMethod * http verb, e.g. "POST", "DELETE" * @param listener * Callback interface to notify the application when the request * has completed. * @param state * An arbitrary object used to identify the request when it * returns to the callback. This has no effect on the request * itself. */ @Deprecated public void request(final String graphPath, final Bundle parameters, final String httpMethod, final RequestListener listener, final Object state) { new Thread() { @Override public void run() { try { String resp = fb.requestImpl(graphPath, parameters, httpMethod); listener.onComplete(resp, state); } catch (FileNotFoundException e) { listener.onFileNotFoundException(e, state); } catch (MalformedURLException e) { listener.onMalformedURLException(e, state); } catch (IOException e) { listener.onIOException(e, state); } } }.start(); } /** * Callback interface for API requests. * <p/> * Each method includes a 'state' parameter that identifies the calling * request. It will be set to the value passed when originally calling the * request method, or null if none was passed. * <p/> * This interface is deprecated. See {@link Facebook} and {@link com.facebook.Request} for more info. */ @Deprecated public static interface RequestListener { /** * Called when a request completes with the given response. * * Executed by a background thread: do not update the UI in this method. */ public void onComplete(String response, Object state); /** * Called when a request has a network or request error. * * Executed by a background thread: do not update the UI in this method. */ public void onIOException(IOException e, Object state); /** * Called when a request fails because the requested resource is * invalid or does not exist. * * Executed by a background thread: do not update the UI in this method. */ public void onFileNotFoundException(FileNotFoundException e, Object state); /** * Called if an invalid graph path is provided (which may result in a * malformed URL). * * Executed by a background thread: do not update the UI in this method. */ public void onMalformedURLException(MalformedURLException e, Object state); /** * Called when the server-side Facebook method fails. * * Executed by a background thread: do not update the UI in this method. */ public void onFacebookError(FacebookError e, Object state); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/android/AsyncFacebookRunner.java
Java
art
13,836
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.os.Handler; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; /** * RequestBatch contains a list of Request objects that can be sent to Facebook in a single round-trip. */ public class RequestBatch extends AbstractList<Request> { private static AtomicInteger idGenerator = new AtomicInteger(); private Handler callbackHandler; private List<Request> requests = new ArrayList<Request>(); private int timeoutInMilliseconds = 0; private final String id = Integer.valueOf(idGenerator.incrementAndGet()).toString(); private List<Callback> callbacks = new ArrayList<Callback>(); private String batchApplicationId; /** * Constructor. Creates an empty batch. */ public RequestBatch() { this.requests = new ArrayList<Request>(); } /** * Constructor. * @param requests the requests to add to the batch */ public RequestBatch(Collection<Request> requests) { this.requests = new ArrayList<Request>(requests); } /** * Constructor. * @param requests the requests to add to the batch */ public RequestBatch(Request... requests) { this.requests = Arrays.asList(requests); } /** * Constructor. * @param requests the requests to add to the batch */ public RequestBatch(RequestBatch requests) { this.requests = new ArrayList<Request>(requests); this.callbackHandler = requests.callbackHandler; this.timeoutInMilliseconds = requests.timeoutInMilliseconds; this.callbacks = new ArrayList<Callback>(requests.callbacks); } /** * Gets the timeout to wait for responses from the server before a timeout error occurs. * @return the timeout, in milliseconds; 0 (the default) means do not timeout */ public int getTimeout() { return timeoutInMilliseconds; } /** * Sets the timeout to wait for responses from the server before a timeout error occurs. * @param timeoutInMilliseconds the timeout, in milliseconds; 0 means do not timeout */ public void setTimeout(int timeoutInMilliseconds) { if (timeoutInMilliseconds < 0) { throw new IllegalArgumentException("Argument timeoutInMilliseconds must be >= 0."); } this.timeoutInMilliseconds = timeoutInMilliseconds; } /** * Adds a batch-level callback which will be called when the entire batch has finished executing. * * @param callback the callback */ public void addCallback(Callback callback) { if (!callbacks.contains(callback)) { callbacks.add(callback); } } /** * Removes a batch-level callback. * * @param callback the callback */ public void removeCallback(Callback callback) { callbacks.remove(callback); } @Override public final boolean add(Request request) { return requests.add(request); } @Override public final void add(int location, Request request) { requests.add(location, request); } @Override public final void clear() { requests.clear(); } @Override public final Request get(int i) { return requests.get(i); } @Override public final Request remove(int location) { return requests.remove(location); } @Override public final Request set(int location, Request request) { return requests.set(location, request); } @Override public final int size() { return requests.size(); } final String getId() { return id; } final Handler getCallbackHandler() { return callbackHandler; } final void setCallbackHandler(Handler callbackHandler) { this.callbackHandler = callbackHandler; } final List<Request> getRequests() { return requests; } final List<Callback> getCallbacks() { return callbacks; } final String getBatchApplicationId() { return batchApplicationId; } final void setBatchApplicationId(String batchApplicationId) { this.batchApplicationId = batchApplicationId; } /** * Executes this batch on the current thread and returns the responses. * <p/> * This should only be used if you have transitioned off the UI thread. * * @return a list of Response objects representing the results of the requests; responses are returned in the same * order as the requests were specified. * * @throws FacebookException * If there was an error in the protocol used to communicate with the service * @throws IllegalArgumentException if the passed in RequestBatch is empty * @throws NullPointerException if the passed in RequestBatch or any of its contents are null */ public final List<Response> executeAndWait() { return executeAndWaitImpl(); } /** * Executes this batch asynchronously. This function will return immediately, and the batch will * be processed on a separate thread. In order to process results of a request, or determine * whether a request succeeded or failed, a callback must be specified (see * {@link Request#setCallback(com.facebook.Request.Callback)}) * <p/> * This should only be called from the UI thread. * * @return a RequestAsyncTask that is executing the request * * @throws IllegalArgumentException if this batch is empty * @throws NullPointerException if any of the contents of this batch are null */ public final RequestAsyncTask executeAsync() { return executeAsyncImpl(); } /** * Specifies the interface that consumers of the RequestBatch class can implement in order to be notified when the * entire batch completes execution. It will be called after all per-Request callbacks are called. */ public interface Callback { /** * The method that will be called when a batch completes. * * @param batch the RequestBatch containing the Requests which were executed */ void onBatchCompleted(RequestBatch batch); } List<Response> executeAndWaitImpl() { return Request.executeBatchAndWait(this); } RequestAsyncTask executeAsyncImpl() { return Request.executeBatchAsync(this); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/RequestBatch.java
Java
art
7,045
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.app.Activity; import android.content.*; import android.content.pm.ResolveInfo; import android.os.*; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.facebook.internal.SessionAuthorizationType; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import java.io.*; import java.lang.ref.WeakReference; import java.util.*; /** * <p> * Session is used to authenticate a user and manage the user's session with * Facebook. * </p> * <p> * Sessions must be opened before they can be used to make a Request. When a * Session is created, it attempts to initialize itself from a TokenCachingStrategy. * Closing the session can optionally clear this cache. The Session lifecycle * uses {@link SessionState SessionState} to indicate its state. * </p> * <p> * Instances of Session provide state change notification via a callback * interface, {@link Session.StatusCallback StatusCallback}. * </p> */ public class Session implements Serializable { private static final long serialVersionUID = 1L; /** * The logging tag used by Session. */ public static final String TAG = Session.class.getCanonicalName(); /** * The default activity code used for authorization. * * @see #openForRead(OpenRequest) * open */ public static final int DEFAULT_AUTHORIZE_ACTIVITY_CODE = 0xface; /** * If Session authorization fails and provides a web view error code, the * web view error code is stored in the Bundle returned from * {@link #getAuthorizationBundle getAuthorizationBundle} under this key. */ public static final String WEB_VIEW_ERROR_CODE_KEY = "com.facebook.sdk.WebViewErrorCode"; /** * If Session authorization fails and provides a failing url, the failing * url is stored in the Bundle returned from {@link #getAuthorizationBundle * getAuthorizationBundle} under this key. */ public static final String WEB_VIEW_FAILING_URL_KEY = "com.facebook.sdk.FailingUrl"; /** * The action used to indicate that the active session has been set. This should * be used as an action in an IntentFilter and BroadcastReceiver registered with * the {@link android.support.v4.content.LocalBroadcastManager}. */ public static final String ACTION_ACTIVE_SESSION_SET = "com.facebook.sdk.ACTIVE_SESSION_SET"; /** * The action used to indicate that the active session has been set to null. This should * be used as an action in an IntentFilter and BroadcastReceiver registered with * the {@link android.support.v4.content.LocalBroadcastManager}. */ public static final String ACTION_ACTIVE_SESSION_UNSET = "com.facebook.sdk.ACTIVE_SESSION_UNSET"; /** * The action used to indicate that the active session has been opened. This should * be used as an action in an IntentFilter and BroadcastReceiver registered with * the {@link android.support.v4.content.LocalBroadcastManager}. */ public static final String ACTION_ACTIVE_SESSION_OPENED = "com.facebook.sdk.ACTIVE_SESSION_OPENED"; /** * The action used to indicate that the active session has been closed. This should * be used as an action in an IntentFilter and BroadcastReceiver registered with * the {@link android.support.v4.content.LocalBroadcastManager}. */ public static final String ACTION_ACTIVE_SESSION_CLOSED = "com.facebook.sdk.ACTIVE_SESSION_CLOSED"; /** * Session takes application id as a constructor parameter. If this is null, * Session will attempt to load the application id from * application/meta-data using this String as the key. */ public static final String APPLICATION_ID_PROPERTY = "com.facebook.sdk.ApplicationId"; private static final Object STATIC_LOCK = new Object(); private static Session activeSession; private static volatile Context staticContext; // Token extension constants private static final int TOKEN_EXTEND_THRESHOLD_SECONDS = 24 * 60 * 60; // 1 // day private static final int TOKEN_EXTEND_RETRY_SECONDS = 60 * 60; // 1 hour private static final String SESSION_BUNDLE_SAVE_KEY = "com.facebook.sdk.Session.saveSessionKey"; private static final String AUTH_BUNDLE_SAVE_KEY = "com.facebook.sdk.Session.authBundleKey"; private static final String PUBLISH_PERMISSION_PREFIX = "publish"; private static final String MANAGE_PERMISSION_PREFIX = "manage"; @SuppressWarnings("serial") private static final Set<String> OTHER_PUBLISH_PERMISSIONS = new HashSet<String>() {{ add("ads_management"); add("create_event"); add("rsvp_event"); }}; private String applicationId; private SessionState state; private AccessToken tokenInfo; private Date lastAttemptedTokenExtendDate = new Date(0); private AuthorizationRequest pendingRequest; private AuthorizationClient authorizationClient; // The following are not serialized with the Session object private volatile Bundle authorizationBundle; private final List<StatusCallback> callbacks; private Handler handler; private AutoPublishAsyncTask autoPublishAsyncTask; // This is the object that synchronizes access to state and tokenInfo private final Object lock = new Object(); private TokenCachingStrategy tokenCachingStrategy; private volatile TokenRefreshRequest currentTokenRefreshRequest; /** * Serialization proxy for the Session class. This is version 1 of * serialization. Future serializations may differ in format. This * class should not be modified. If serializations formats change, * create a new class SerializationProxyVx. */ private static class SerializationProxyV1 implements Serializable { private static final long serialVersionUID = 7663436173185080063L; private final String applicationId; private final SessionState state; private final AccessToken tokenInfo; private final Date lastAttemptedTokenExtendDate; private final boolean shouldAutoPublish; private final AuthorizationRequest pendingRequest; SerializationProxyV1(String applicationId, SessionState state, AccessToken tokenInfo, Date lastAttemptedTokenExtendDate, boolean shouldAutoPublish, AuthorizationRequest pendingRequest) { this.applicationId = applicationId; this.state = state; this.tokenInfo = tokenInfo; this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate; this.shouldAutoPublish = shouldAutoPublish; this.pendingRequest = pendingRequest; } private Object readResolve() { return new Session(applicationId, state, tokenInfo, lastAttemptedTokenExtendDate, shouldAutoPublish, pendingRequest); } } /** * Used by version 1 of the serialization proxy, do not modify. */ private Session(String applicationId, SessionState state, AccessToken tokenInfo, Date lastAttemptedTokenExtendDate, boolean shouldAutoPublish, AuthorizationRequest pendingRequest) { this.applicationId = applicationId; this.state = state; this.tokenInfo = tokenInfo; this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate; this.pendingRequest = pendingRequest; handler = new Handler(Looper.getMainLooper()); currentTokenRefreshRequest = null; tokenCachingStrategy = null; callbacks = new ArrayList<StatusCallback>(); } /** * Initializes a new Session with the specified context. * * @param currentContext The Activity or Service creating this Session. */ public Session(Context currentContext) { this(currentContext, null, null, true); } Session(Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy) { this(context, applicationId, tokenCachingStrategy, true); } Session(Context context, String applicationId, TokenCachingStrategy tokenCachingStrategy, boolean loadTokenFromCache) { // if the application ID passed in is null, try to get it from the // meta-data in the manifest. if ((context != null) && (applicationId == null)) { applicationId = Utility.getMetadataApplicationId(context); } Validate.notNull(applicationId, "applicationId"); initializeStaticContext(context); if (tokenCachingStrategy == null) { tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(staticContext); } this.applicationId = applicationId; this.tokenCachingStrategy = tokenCachingStrategy; this.state = SessionState.CREATED; this.pendingRequest = null; this.callbacks = new ArrayList<StatusCallback>(); this.handler = new Handler(Looper.getMainLooper()); Bundle tokenState = loadTokenFromCache ? tokenCachingStrategy.load() : null; if (TokenCachingStrategy.hasTokenInformation(tokenState)) { Date cachedExpirationDate = TokenCachingStrategy .getDate(tokenState, TokenCachingStrategy.EXPIRATION_DATE_KEY); Date now = new Date(); if ((cachedExpirationDate == null) || cachedExpirationDate.before(now)) { // If expired or we require new permissions, clear out the // current token cache. tokenCachingStrategy.clear(); this.tokenInfo = AccessToken.createEmptyToken(Collections.<String>emptyList()); } else { // Otherwise we have a valid token, so use it. this.tokenInfo = AccessToken.createFromCache(tokenState); this.state = SessionState.CREATED_TOKEN_LOADED; } } else { this.tokenInfo = AccessToken.createEmptyToken(Collections.<String>emptyList()); } } /** * Returns a Bundle containing data that was returned from Facebook during * authorization. * * @return a Bundle containing data that was returned from Facebook during * authorization. */ public final Bundle getAuthorizationBundle() { synchronized (this.lock) { return this.authorizationBundle; } } /** * Returns a boolean indicating whether the session is opened. * * @return a boolean indicating whether the session is opened. */ public final boolean isOpened() { synchronized (this.lock) { return this.state.isOpened(); } } public final boolean isClosed() { synchronized (this.lock) { return this.state.isClosed(); } } /** * Returns the current state of the Session. * See {@link SessionState} for details. * * @return the current state of the Session. */ public final SessionState getState() { synchronized (this.lock) { return this.state; } } /** * Returns the application id associated with this Session. * * @return the application id associated with this Session. */ public final String getApplicationId() { return this.applicationId; } /** * Returns the access token String. * * @return the access token String, or null if there is no access token */ public final String getAccessToken() { synchronized (this.lock) { return (this.tokenInfo == null) ? null : this.tokenInfo.getToken(); } } /** * <p> * Returns the Date at which the current token will expire. * </p> * <p> * Note that Session automatically attempts to extend the lifetime of Tokens * as needed when Facebook requests are made. * </p> * * @return the Date at which the current token will expire, or null if there is no access token */ public final Date getExpirationDate() { synchronized (this.lock) { return (this.tokenInfo == null) ? null : this.tokenInfo.getExpires(); } } /** * <p> * Returns the list of permissions associated with the session. * </p> * <p> * If there is a valid token, this represents the permissions granted by * that token. This can change during calls to * {@link #requestNewReadPermissions} * or {@link #requestNewPublishPermissions}. * </p> * * @return the list of permissions associated with the session, or null if there is no access token */ public final List<String> getPermissions() { synchronized (this.lock) { return (this.tokenInfo == null) ? null : this.tokenInfo.getPermissions(); } } /** * <p> * Logs a user in to Facebook. * </p> * <p> * A session may not be used with {@link Request Request} and other classes * in the SDK until it is open. If, prior to calling open, the session is in * the {@link SessionState#CREATED_TOKEN_LOADED CREATED_TOKEN_LOADED} * state, and the requested permissions are a subset of the previously authorized * permissions, then the Session becomes usable immediately with no user interaction. * </p> * <p> * The permissions associated with the openRequest passed to this method must * be read permissions only (or null/empty). It is not allowed to pass publish * permissions to this method and will result in an exception being thrown. * </p> * <p> * Any open method must be called at most once, and cannot be called after the * Session is closed. Calling the method at an invalid time will result in * UnsuportedOperationException. * </p> * * @param openRequest the open request, can be null only if the Session is in the * {@link SessionState#CREATED_TOKEN_LOADED CREATED_TOKEN_LOADED} state * @throws FacebookException if any publish or manage permissions are requested */ public final void openForRead(OpenRequest openRequest) { open(openRequest, SessionAuthorizationType.READ); } /** * <p> * Logs a user in to Facebook. * </p> * <p> * A session may not be used with {@link Request Request} and other classes * in the SDK until it is open. If, prior to calling open, the session is in * the {@link SessionState#CREATED_TOKEN_LOADED CREATED_TOKEN_LOADED} * state, and the requested permissions are a subset of the previously authorized * permissions, then the Session becomes usable immediately with no user interaction. * </p> * <p> * The permissions associated with the openRequest passed to this method must * be publish or manage permissions only and must be non-empty. Any read permissions * will result in a warning, and may fail during server-side authorization. * </p> * <p> * Any open method must be called at most once, and cannot be called after the * Session is closed. Calling the method at an invalid time will result in * UnsuportedOperationException. * </p> * * @param openRequest the open request, can be null only if the Session is in the * {@link SessionState#CREATED_TOKEN_LOADED CREATED_TOKEN_LOADED} state * @throws FacebookException if the passed in request is null or has no permissions set. */ public final void openForPublish(OpenRequest openRequest) { open(openRequest, SessionAuthorizationType.PUBLISH); } /** * Opens a session based on an existing Facebook access token. This method should be used * only in instances where an application has previously obtained an access token and wishes * to import it into the Session/TokenCachingStrategy-based session-management system. An * example would be an application which previously did not use the Facebook SDK for Android * and implemented its own session-management scheme, but wishes to implement an upgrade path * for existing users so they do not need to log in again when upgrading to a version of * the app that uses the SDK. * <p/> * No validation is done that the token, token source, or permissions are actually valid. * It is the caller's responsibility to ensure that these accurately reflect the state of * the token that has been passed in, or calls to the Facebook API may fail. * * @param accessToken the access token obtained from Facebook * @param callback a callback that will be called when the session status changes; may be null */ public final void open(AccessToken accessToken, StatusCallback callback) { synchronized (this.lock) { if (pendingRequest != null) { throw new UnsupportedOperationException( "Session: an attempt was made to open a session that has a pending request."); } if (state != SessionState.CREATED && state != SessionState.CREATED_TOKEN_LOADED) { throw new UnsupportedOperationException( "Session: an attempt was made to open an already opened session."); } if (callback != null) { addCallback(callback); } this.tokenInfo = accessToken; if (this.tokenCachingStrategy != null) { this.tokenCachingStrategy.save(accessToken.toCacheBundle()); } final SessionState oldState = state; state = SessionState.OPENED; this.postStateChange(oldState, state, null); } autoPublishAsync(); } /** * <p> * Issues a request to add new read permissions to the Session. * </p> * <p> * If successful, this will update the set of permissions on this session to * match the newPermissions. If this fails, the Session remains unchanged. * </p> * <p> * The permissions associated with the newPermissionsRequest passed to this method must * be read permissions only (or null/empty). It is not allowed to pass publish * permissions to this method and will result in an exception being thrown. * </p> * * @param newPermissionsRequest the new permissions request */ public final void requestNewReadPermissions(NewPermissionsRequest newPermissionsRequest) { requestNewPermissions(newPermissionsRequest, SessionAuthorizationType.READ); } /** * <p> * Issues a request to add new publish or manage permissions to the Session. * </p> * <p> * If successful, this will update the set of permissions on this session to * match the newPermissions. If this fails, the Session remains unchanged. * </p> * <p> * The permissions associated with the newPermissionsRequest passed to this method must * be publish or manage permissions only and must be non-empty. Any read permissions * will result in a warning, and may fail during server-side authorization. * </p> * * @param newPermissionsRequest the new permissions request */ public final void requestNewPublishPermissions(NewPermissionsRequest newPermissionsRequest) { requestNewPermissions(newPermissionsRequest, SessionAuthorizationType.PUBLISH); } /** * Provides an implementation for {@link Activity#onActivityResult * onActivityResult} that updates the Session based on information returned * during the authorization flow. The Activity that calls open or * requestNewPermissions should forward the resulting onActivityResult call here to * update the Session state based on the contents of the resultCode and * data. * * @param currentActivity The Activity that is forwarding the onActivityResult call. * @param requestCode The requestCode parameter from the forwarded call. When this * onActivityResult occurs as part of Facebook authorization * flow, this value is the activityCode passed to open or * authorize. * @param resultCode An int containing the resultCode parameter from the forwarded * call. * @param data The Intent passed as the data parameter from the forwarded * call. * @return A boolean indicating whether the requestCode matched a pending * authorization request for this Session. */ public final boolean onActivityResult(Activity currentActivity, int requestCode, int resultCode, Intent data) { Validate.notNull(currentActivity, "currentActivity"); initializeStaticContext(currentActivity); synchronized (lock) { if (pendingRequest == null || (requestCode != pendingRequest.getRequestCode())) { return false; } } AccessToken newToken = null; Exception exception = null; if (data != null) { AuthorizationClient.Result result = (AuthorizationClient.Result) data.getSerializableExtra( LoginActivity.RESULT_KEY); if (result != null) { // This came from LoginActivity. handleAuthorizationResult(resultCode, result); return true; } else if (authorizationClient != null) { // Delegate to the auth client. authorizationClient.onActivityResult(requestCode, resultCode, data); return true; } } else if (resultCode == Activity.RESULT_CANCELED) { exception = new FacebookOperationCanceledException("User canceled operation."); } finishAuthOrReauth(newToken, exception); return true; } /** * Closes the local in-memory Session object, but does not clear the * persisted token cache. */ @SuppressWarnings("incomplete-switch") public final void close() { synchronized (this.lock) { final SessionState oldState = this.state; switch (this.state) { case CREATED: case OPENING: this.state = SessionState.CLOSED_LOGIN_FAILED; postStateChange(oldState, this.state, new FacebookException( "Log in attempt aborted.")); break; case CREATED_TOKEN_LOADED: case OPENED: case OPENED_TOKEN_UPDATED: this.state = SessionState.CLOSED; postStateChange(oldState, this.state, null); break; } } } /** * Closes the local in-memory Session object and clears any persisted token * cache related to the Session. */ public final void closeAndClearTokenInformation() { if (this.tokenCachingStrategy != null) { this.tokenCachingStrategy.clear(); } Utility.clearFacebookCookies(staticContext); close(); } /** * Adds a callback that will be called when the state of this Session changes. * * @param callback the callback */ public final void addCallback(StatusCallback callback) { synchronized (callbacks) { if (callback != null && !callbacks.contains(callback)) { callbacks.add(callback); } } } /** * Removes a StatusCallback from this Session. * * @param callback the callback */ public final void removeCallback(StatusCallback callback) { synchronized (callbacks) { callbacks.remove(callback); } } @Override public String toString() { return new StringBuilder().append("{Session").append(" state:").append(this.state).append(", token:") .append((this.tokenInfo == null) ? "null" : this.tokenInfo).append(", appId:") .append((this.applicationId == null) ? "null" : this.applicationId).append("}").toString(); } void extendTokenCompleted(Bundle bundle) { synchronized (this.lock) { final SessionState oldState = this.state; switch (this.state) { case OPENED: this.state = SessionState.OPENED_TOKEN_UPDATED; postStateChange(oldState, this.state, null); break; case OPENED_TOKEN_UPDATED: break; default: // Silently ignore attempts to refresh token if we are not open Log.d(TAG, "refreshToken ignored in state " + this.state); return; } this.tokenInfo = AccessToken.createFromRefresh(this.tokenInfo, bundle); if (this.tokenCachingStrategy != null) { this.tokenCachingStrategy.save(this.tokenInfo.toCacheBundle()); } } } private Object writeReplace() { return new SerializationProxyV1(applicationId, state, tokenInfo, lastAttemptedTokenExtendDate, false, pendingRequest); } // have a readObject that throws to prevent spoofing private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Cannot readObject, serialization proxy required"); } /** * Save the Session object into the supplied Bundle. * * @param session the Session to save * @param bundle the Bundle to save the Session to */ public static final void saveSession(Session session, Bundle bundle) { if (bundle != null && session != null && !bundle.containsKey(SESSION_BUNDLE_SAVE_KEY)) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { new ObjectOutputStream(outputStream).writeObject(session); } catch (IOException e) { throw new FacebookException("Unable to save session.", e); } bundle.putByteArray(SESSION_BUNDLE_SAVE_KEY, outputStream.toByteArray()); bundle.putBundle(AUTH_BUNDLE_SAVE_KEY, session.authorizationBundle); } } /** * Restores the saved session from a Bundle, if any. Returns the restored Session or * null if it could not be restored. * * @param context the Activity or Service creating the Session, must not be null * @param cachingStrategy the TokenCachingStrategy to use to load and store the token. If this is * null, a default token cachingStrategy that stores data in * SharedPreferences will be used * @param callback the callback to notify for Session state changes, can be null * @param bundle the bundle to restore the Session from * @return the restored Session, or null */ public static final Session restoreSession( Context context, TokenCachingStrategy cachingStrategy, StatusCallback callback, Bundle bundle) { if (bundle == null) { return null; } byte[] data = bundle.getByteArray(SESSION_BUNDLE_SAVE_KEY); if (data != null) { ByteArrayInputStream is = new ByteArrayInputStream(data); try { Session session = (Session) (new ObjectInputStream(is)).readObject(); initializeStaticContext(context); if (cachingStrategy != null) { session.tokenCachingStrategy = cachingStrategy; } else { session.tokenCachingStrategy = new SharedPreferencesTokenCachingStrategy(context); } if (callback != null) { session.addCallback(callback); } session.authorizationBundle = bundle.getBundle(AUTH_BUNDLE_SAVE_KEY); return session; } catch (ClassNotFoundException e) { Log.w(TAG, "Unable to restore session", e); } catch (IOException e) { Log.w(TAG, "Unable to restore session.", e); } } return null; } /** * Returns the current active Session, or null if there is none. * * @return the current active Session, or null if there is none. */ public static final Session getActiveSession() { synchronized (Session.STATIC_LOCK) { return Session.activeSession; } } /** * <p> * Sets the current active Session. * </p> * <p> * The active Session is used implicitly by predefined Request factory * methods as well as optionally by UI controls in the sdk. * </p> * <p> * It is legal to set this to null, or to a Session that is not yet open. * </p> * * @param session A Session to use as the active Session, or null to indicate * that there is no active Session. */ public static final void setActiveSession(Session session) { synchronized (Session.STATIC_LOCK) { if (session != Session.activeSession) { Session oldSession = Session.activeSession; if (oldSession != null) { oldSession.close(); } Session.activeSession = session; if (oldSession != null) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_UNSET); } if (session != null) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_SET); if (session.isOpened()) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED); } } } } } /** * Create a new Session, and if a token cache is available, open the * Session and make it active without any user interaction. * * @param context The Context creating this session * @return The new session or null if one could not be created */ public static Session openActiveSessionFromCache(Context context) { return openActiveSession(context, false, null); } /** * If allowLoginUI is true, this will create a new Session, make it active, and * open it. If the default token cache is not available, then this will request * basic permissions. If the default token cache is available and cached tokens * are loaded, this will use the cached token and associated permissions. * <p/> * If allowedLoginUI is false, this will only create the active session and open * it if it requires no user interaction (i.e. the token cache is available and * there are cached tokens). * * @param activity The Activity that is opening the new Session. * @param allowLoginUI if false, only sets the active session and opens it if it * does not require user interaction * @param callback The {@link StatusCallback SessionStatusCallback} to * notify regarding Session state changes. May be null. * @return The new Session or null if one could not be created */ public static Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback) { return openActiveSession(activity, allowLoginUI, new OpenRequest(activity).setCallback(callback)); } /** * If allowLoginUI is true, this will create a new Session, make it active, and * open it. If the default token cache is not available, then this will request * basic permissions. If the default token cache is available and cached tokens * are loaded, this will use the cached token and associated permissions. * <p/> * If allowedLoginUI is false, this will only create the active session and open * it if it requires no user interaction (i.e. the token cache is available and * there are cached tokens). * * @param context The Activity or Service creating this Session * @param fragment The Fragment that is opening the new Session. * @param allowLoginUI if false, only sets the active session and opens it if it * does not require user interaction * @param callback The {@link StatusCallback SessionStatusCallback} to * notify regarding Session state changes. * @return The new Session or null if one could not be created */ public static Session openActiveSession(Context context, Fragment fragment, boolean allowLoginUI, StatusCallback callback) { return openActiveSession(context, allowLoginUI, new OpenRequest(fragment).setCallback(callback)); } /** * Opens a session based on an existing Facebook access token, and also makes this session * the currently active session. This method should be used * only in instances where an application has previously obtained an access token and wishes * to import it into the Session/TokenCachingStrategy-based session-management system. A primary * example would be an application which previously did not use the Facebook SDK for Android * and implemented its own session-management scheme, but wishes to implement an upgrade path * for existing users so they do not need to log in again when upgrading to a version of * the app that uses the SDK. In general, this method will be called only once, when the app * detects that it has been upgraded -- after that, the usual Session lifecycle methods * should be used to manage the session and its associated token. * <p/> * No validation is done that the token, token source, or permissions are actually valid. * It is the caller's responsibility to ensure that these accurately reflect the state of * the token that has been passed in, or calls to the Facebook API may fail. * * @param context the Context to use for creation the session * @param accessToken the access token obtained from Facebook * @param callback a callback that will be called when the session status changes; may be null * @return The new Session or null if one could not be created */ public static Session openActiveSessionWithAccessToken(Context context, AccessToken accessToken, StatusCallback callback) { Session session = new Session(context, null, null, false); setActiveSession(session); session.open(accessToken, callback); return session; } private static Session openActiveSession(Context context, boolean allowLoginUI, OpenRequest openRequest) { Session session = new Builder(context).build(); if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) { setActiveSession(session); session.openForRead(openRequest); return session; } return null; } static Context getStaticContext() { return staticContext; } static void initializeStaticContext(Context currentContext) { if ((currentContext != null) && (staticContext == null)) { Context applicationContext = currentContext.getApplicationContext(); staticContext = (applicationContext != null) ? applicationContext : currentContext; } } void authorize(AuthorizationRequest request) { boolean started = false; request.setApplicationId(applicationId); autoPublishAsync(); started = tryLoginActivity(request); if (!started && request.isLegacy) { started = tryLegacyAuth(request); } if (!started) { synchronized (this.lock) { final SessionState oldState = this.state; switch (this.state) { case CLOSED: case CLOSED_LOGIN_FAILED: return; default: this.state = SessionState.CLOSED_LOGIN_FAILED; postStateChange(oldState, this.state, new FacebookException("Log in attempt failed.")); } } } } private void open(OpenRequest openRequest, SessionAuthorizationType authType) { validatePermissions(openRequest, authType); validateLoginBehavior(openRequest); SessionState newState; synchronized (this.lock) { if (pendingRequest != null) { postStateChange(state, state, new UnsupportedOperationException( "Session: an attempt was made to open a session that has a pending request.")); return; } final SessionState oldState = this.state; switch (this.state) { case CREATED: this.state = newState = SessionState.OPENING; if (openRequest == null) { throw new IllegalArgumentException("openRequest cannot be null when opening a new Session"); } pendingRequest = openRequest; break; case CREATED_TOKEN_LOADED: if (openRequest != null && !Utility.isNullOrEmpty(openRequest.getPermissions())) { if (!Utility.isSubset(openRequest.getPermissions(), getPermissions())) { pendingRequest = openRequest; } } if (pendingRequest == null) { this.state = newState = SessionState.OPENED; } else { this.state = newState = SessionState.OPENING; } break; default: throw new UnsupportedOperationException( "Session: an attempt was made to open an already opened session."); } if (openRequest != null) { addCallback(openRequest.getCallback()); } this.postStateChange(oldState, newState, null); } if (newState == SessionState.OPENING) { authorize(openRequest); } } private void requestNewPermissions(NewPermissionsRequest newPermissionsRequest, SessionAuthorizationType authType) { validatePermissions(newPermissionsRequest, authType); validateLoginBehavior(newPermissionsRequest); if (newPermissionsRequest != null) { synchronized (this.lock) { if (pendingRequest != null) { throw new UnsupportedOperationException( "Session: an attempt was made to request new permissions for a session that has a pending request."); } switch (this.state) { case OPENED: case OPENED_TOKEN_UPDATED: pendingRequest = newPermissionsRequest; break; default: throw new UnsupportedOperationException( "Session: an attempt was made to request new permissions for a session that is not currently open."); } } newPermissionsRequest.setValidateSameFbidAsToken(getAccessToken()); authorize(newPermissionsRequest); } } private void validateLoginBehavior(AuthorizationRequest request) { if (request != null && !request.isLegacy) { Intent intent = new Intent(); intent.setClass(getStaticContext(), LoginActivity.class); if (!resolveIntent(intent)) { throw new FacebookException(String.format( "Cannot use SessionLoginBehavior %s when %s is not declared as an activity in AndroidManifest.xml", request.getLoginBehavior(), LoginActivity.class.getName())); } } } private void validatePermissions(AuthorizationRequest request, SessionAuthorizationType authType) { if (request == null || Utility.isNullOrEmpty(request.getPermissions())) { if (SessionAuthorizationType.PUBLISH.equals(authType)) { throw new FacebookException("Cannot request publish or manage authorization with no permissions."); } return; // nothing to check } for (String permission : request.getPermissions()) { if (isPublishPermission(permission)) { if (SessionAuthorizationType.READ.equals(authType)) { throw new FacebookException( String.format( "Cannot pass a publish or manage permission (%s) to a request for read authorization", permission)); } } else { if (SessionAuthorizationType.PUBLISH.equals(authType)) { Log.w(TAG, String.format( "Should not pass a read permission (%s) to a request for publish or manage authorization", permission)); } } } } static boolean isPublishPermission(String permission) { return permission != null && (permission.startsWith(PUBLISH_PERMISSION_PREFIX) || permission.startsWith(MANAGE_PERMISSION_PREFIX) || OTHER_PUBLISH_PERMISSIONS.contains(permission)); } private void handleAuthorizationResult(int resultCode, AuthorizationClient.Result result) { AccessToken newToken = null; Exception exception = null; if (resultCode == Activity.RESULT_OK) { if (result.code == AuthorizationClient.Result.Code.SUCCESS) { newToken = result.token; } else { exception = new FacebookAuthorizationException(result.errorMessage); } } else if (resultCode == Activity.RESULT_CANCELED) { exception = new FacebookOperationCanceledException(result.errorMessage); } authorizationClient = null; finishAuthOrReauth(newToken, exception); } private boolean tryLoginActivity(AuthorizationRequest request) { Intent intent = getLoginActivityIntent(request); if (!resolveIntent(intent)) { return false; } try { request.getStartActivityDelegate().startActivityForResult(intent, request.getRequestCode()); } catch (ActivityNotFoundException e) { return false; } return true; } private boolean resolveIntent(Intent intent) { ResolveInfo resolveInfo = getStaticContext().getPackageManager().resolveActivity(intent, 0); if (resolveInfo == null) { return false; } return true; } private Intent getLoginActivityIntent(AuthorizationRequest request) { Intent intent = new Intent(); intent.setClass(getStaticContext(), LoginActivity.class); intent.setAction(request.getLoginBehavior().toString()); // Let LoginActivity populate extras appropriately AuthorizationClient.AuthorizationRequest authClientRequest = request.getAuthorizationClientRequest(); Bundle extras = LoginActivity.populateIntentExtras(authClientRequest); intent.putExtras(extras); return intent; } private boolean tryLegacyAuth(final AuthorizationRequest request) { authorizationClient = new AuthorizationClient(); authorizationClient.setOnCompletedListener(new AuthorizationClient.OnCompletedListener() { @Override public void onCompleted(AuthorizationClient.Result result) { int activityResult; if (result.code == AuthorizationClient.Result.Code.CANCEL) { activityResult = Activity.RESULT_CANCELED; } else { activityResult = Activity.RESULT_OK; } handleAuthorizationResult(activityResult, result); } }); authorizationClient.setContext(getStaticContext()); authorizationClient.startOrContinueAuth(request.getAuthorizationClientRequest()); return true; } @SuppressWarnings("incomplete-switch") void finishAuthOrReauth(AccessToken newToken, Exception exception) { // If the token we came up with is expired/invalid, then auth failed. if ((newToken != null) && newToken.isInvalid()) { newToken = null; exception = new FacebookException("Invalid access token."); } synchronized (this.lock) { switch (this.state) { case OPENING: // This means we are authorizing for the first time in this Session. finishAuthorization(newToken, exception); break; case OPENED: case OPENED_TOKEN_UPDATED: // This means we are reauthorizing. finishReauthorization(newToken, exception); break; } } } private void finishAuthorization(AccessToken newToken, Exception exception) { final SessionState oldState = state; if (newToken != null) { tokenInfo = newToken; saveTokenToCache(newToken); state = SessionState.OPENED; } else if (exception != null) { state = SessionState.CLOSED_LOGIN_FAILED; } pendingRequest = null; postStateChange(oldState, state, exception); } private void finishReauthorization(final AccessToken newToken, Exception exception) { final SessionState oldState = state; if (newToken != null) { tokenInfo = newToken; saveTokenToCache(newToken); state = SessionState.OPENED_TOKEN_UPDATED; } pendingRequest = null; postStateChange(oldState, state, exception); } private void saveTokenToCache(AccessToken newToken) { if (newToken != null && tokenCachingStrategy != null) { tokenCachingStrategy.save(newToken.toCacheBundle()); } } void postStateChange(final SessionState oldState, final SessionState newState, final Exception exception) { // When we request new permissions, we stay in SessionState.OPENED_TOKEN_UPDATED, // but we still want notifications of the state change since permissions are // different now. if ((oldState == newState) && (oldState != SessionState.OPENED_TOKEN_UPDATED) && (exception == null)) { return; } if (newState.isClosed()) { this.tokenInfo = AccessToken.createEmptyToken(Collections.<String>emptyList()); } synchronized (callbacks) { // Need to schedule the callbacks inside the same queue to preserve ordering. // Otherwise these callbacks could have been added to the queue before the SessionTracker // gets the ACTIVE_SESSION_SET action. Runnable runCallbacks = new Runnable() { public void run() { for (final StatusCallback callback : callbacks) { Runnable closure = new Runnable() { public void run() { // This can be called inside a synchronized block. callback.call(Session.this, newState, exception); } }; runWithHandlerOrExecutor(handler, closure); } } }; runWithHandlerOrExecutor(handler, runCallbacks); } if (this == Session.activeSession) { if (oldState.isOpened() != newState.isOpened()) { if (newState.isOpened()) { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_OPENED); } else { postActiveSessionAction(Session.ACTION_ACTIVE_SESSION_CLOSED); } } } } static void postActiveSessionAction(String action) { final Intent intent = new Intent(action); LocalBroadcastManager.getInstance(getStaticContext()).sendBroadcast(intent); } private static void runWithHandlerOrExecutor(Handler handler, Runnable runnable) { if (handler != null) { handler.post(runnable); } else { Settings.getExecutor().execute(runnable); } } void extendAccessTokenIfNeeded() { if (shouldExtendAccessToken()) { extendAccessToken(); } } void extendAccessToken() { TokenRefreshRequest newTokenRefreshRequest = null; synchronized (this.lock) { if (currentTokenRefreshRequest == null) { newTokenRefreshRequest = new TokenRefreshRequest(); currentTokenRefreshRequest = newTokenRefreshRequest; } } if (newTokenRefreshRequest != null) { newTokenRefreshRequest.bind(); } } boolean shouldExtendAccessToken() { if (currentTokenRefreshRequest != null) { return false; } boolean result = false; Date now = new Date(); if (state.isOpened() && tokenInfo.getSource().canExtendToken() && now.getTime() - lastAttemptedTokenExtendDate.getTime() > TOKEN_EXTEND_RETRY_SECONDS * 1000 && now.getTime() - tokenInfo.getLastRefresh().getTime() > TOKEN_EXTEND_THRESHOLD_SECONDS * 1000) { result = true; } return result; } AccessToken getTokenInfo() { return tokenInfo; } void setTokenInfo(AccessToken tokenInfo) { this.tokenInfo = tokenInfo; } Date getLastAttemptedTokenExtendDate() { return lastAttemptedTokenExtendDate; } void setLastAttemptedTokenExtendDate(Date lastAttemptedTokenExtendDate) { this.lastAttemptedTokenExtendDate = lastAttemptedTokenExtendDate; } void setCurrentTokenRefreshRequest(TokenRefreshRequest request) { this.currentTokenRefreshRequest = request; } class TokenRefreshRequest implements ServiceConnection { final Messenger messageReceiver = new Messenger( new TokenRefreshRequestHandler(Session.this, this)); Messenger messageSender = null; public void bind() { Intent intent = NativeProtocol.createTokenRefreshIntent(getStaticContext()); if (intent != null && staticContext.bindService(intent, new TokenRefreshRequest(), Context.BIND_AUTO_CREATE)) { setLastAttemptedTokenExtendDate(new Date()); } else { cleanup(); } } @Override public void onServiceConnected(ComponentName className, IBinder service) { messageSender = new Messenger(service); refreshToken(); } @Override public void onServiceDisconnected(ComponentName arg) { cleanup(); // We returned an error so there's no point in // keeping the binding open. staticContext.unbindService(TokenRefreshRequest.this); } private void cleanup() { if (currentTokenRefreshRequest == this) { currentTokenRefreshRequest = null; } } private void refreshToken() { Bundle requestData = new Bundle(); requestData.putString(AccessToken.ACCESS_TOKEN_KEY, getTokenInfo().getToken()); Message request = Message.obtain(); request.setData(requestData); request.replyTo = messageReceiver; try { messageSender.send(request); } catch (RemoteException e) { cleanup(); } } } // Creating a static Handler class to reduce the possibility of a memory leak. // Handler objects for the same thread all share a common Looper object, which they post messages // to and read from. As messages contain target Handler, as long as there are messages with target // handler in the message queue, the handler cannot be garbage collected. If handler is not static, // the instance of the containing class also cannot be garbage collected even if it is destroyed. static class TokenRefreshRequestHandler extends Handler { private WeakReference<Session> sessionWeakReference; private WeakReference<TokenRefreshRequest> refreshRequestWeakReference; TokenRefreshRequestHandler(Session session, TokenRefreshRequest refreshRequest) { super(Looper.getMainLooper()); sessionWeakReference = new WeakReference<Session>(session); refreshRequestWeakReference = new WeakReference<TokenRefreshRequest>(refreshRequest); } @Override public void handleMessage(Message msg) { String token = msg.getData().getString(AccessToken.ACCESS_TOKEN_KEY); Session session = sessionWeakReference.get(); if (session != null && token != null) { session.extendTokenCompleted(msg.getData()); } TokenRefreshRequest request = refreshRequestWeakReference.get(); if (request != null) { // The refreshToken function should be called rarely, // so there is no point in keeping the binding open. staticContext.unbindService(request); request.cleanup(); } } } /** * Provides asynchronous notification of Session state changes. * * @see Session#open open */ public interface StatusCallback { public void call(Session session, SessionState state, Exception exception); } @Override public int hashCode() { return 0; } @Override public boolean equals(Object otherObj) { if (!(otherObj instanceof Session)) { return false; } Session other = (Session) otherObj; return areEqual(other.applicationId, applicationId) && areEqual(other.authorizationBundle, authorizationBundle) && areEqual(other.state, state) && areEqual(other.getExpirationDate(), getExpirationDate()); } private static boolean areEqual(Object a, Object b) { if (a == null) { return b == null; } else { return a.equals(b); } } /** * Builder class used to create a Session. */ public static final class Builder { private final Context context; private String applicationId; private TokenCachingStrategy tokenCachingStrategy; /** * Constructs a new Builder associated with the context. * * @param context the Activity or Service starting the Session */ public Builder(Context context) { this.context = context; } /** * Sets the application id for the Session. * * @param applicationId the application id * @return the Builder instance */ public Builder setApplicationId(final String applicationId) { this.applicationId = applicationId; return this; } /** * Sets the TokenCachingStrategy for the Session. * * @param tokenCachingStrategy the token cache to use * @return the Builder instance */ public Builder setTokenCachingStrategy(final TokenCachingStrategy tokenCachingStrategy) { this.tokenCachingStrategy = tokenCachingStrategy; return this; } /** * Build the Session. * * @return a new Session */ public Session build() { return new Session(context, applicationId, tokenCachingStrategy); } } interface StartActivityDelegate { public void startActivityForResult(Intent intent, int requestCode); public Activity getActivityContext(); } private void autoPublishAsync() { AutoPublishAsyncTask asyncTask = null; synchronized (this) { if (autoPublishAsyncTask == null && Settings.getShouldAutoPublishInstall()) { // copy the application id to guarantee thread safety against our container. String applicationId = Session.this.applicationId; // skip publish if we don't have an application id. if (applicationId != null) { asyncTask = autoPublishAsyncTask = new AutoPublishAsyncTask(applicationId, staticContext); } } } if (asyncTask != null) { asyncTask.execute(); } } /** * Async implementation to allow auto publishing to not block the ui thread. */ private class AutoPublishAsyncTask extends AsyncTask<Void, Void, Void> { private final String mApplicationId; private final Context mApplicationContext; public AutoPublishAsyncTask(String applicationId, Context context) { mApplicationId = applicationId; mApplicationContext = context.getApplicationContext(); } @Override protected Void doInBackground(Void... voids) { try { Settings.publishInstallAndWait(mApplicationContext, mApplicationId); } catch (Exception e) { Utility.logd("Facebook-publish", e); } return null; } @Override protected void onPostExecute(Void result) { // always clear out the publisher to allow other invocations. synchronized (Session.this) { autoPublishAsyncTask = null; } } } /** * Base class for authorization requests {@link OpenRequest} and {@link NewPermissionsRequest}. */ public static class AuthorizationRequest implements Serializable { private static final long serialVersionUID = 1L; private final StartActivityDelegate startActivityDelegate; private SessionLoginBehavior loginBehavior = SessionLoginBehavior.SSO_WITH_FALLBACK; private int requestCode = DEFAULT_AUTHORIZE_ACTIVITY_CODE; private StatusCallback statusCallback; private boolean isLegacy = false; private List<String> permissions = Collections.emptyList(); private SessionDefaultAudience defaultAudience = SessionDefaultAudience.FRIENDS; private String applicationId; private String validateSameFbidAsToken; AuthorizationRequest(final Activity activity) { startActivityDelegate = new StartActivityDelegate() { @Override public void startActivityForResult(Intent intent, int requestCode) { activity.startActivityForResult(intent, requestCode); } @Override public Activity getActivityContext() { return activity; } }; } AuthorizationRequest(final Fragment fragment) { startActivityDelegate = new StartActivityDelegate() { @Override public void startActivityForResult(Intent intent, int requestCode) { fragment.startActivityForResult(intent, requestCode); } @Override public Activity getActivityContext() { return fragment.getActivity(); } }; } /** * Constructor to be used for V1 serialization only, DO NOT CHANGE. */ private AuthorizationRequest(SessionLoginBehavior loginBehavior, int requestCode, List<String> permissions, String defaultAudience, boolean isLegacy, String applicationId, String validateSameFbidAsToken) { startActivityDelegate = new StartActivityDelegate() { @Override public void startActivityForResult(Intent intent, int requestCode) { throw new UnsupportedOperationException( "Cannot create an AuthorizationRequest without a valid Activity or Fragment"); } @Override public Activity getActivityContext() { throw new UnsupportedOperationException( "Cannot create an AuthorizationRequest without a valid Activity or Fragment"); } }; this.loginBehavior = loginBehavior; this.requestCode = requestCode; this.permissions = permissions; this.defaultAudience = SessionDefaultAudience.valueOf(defaultAudience); this.isLegacy = isLegacy; this.applicationId = applicationId; this.validateSameFbidAsToken = validateSameFbidAsToken; } /** * Used for backwards compatibility with Facebook.java only, DO NOT USE. * * @param isLegacy */ public void setIsLegacy(boolean isLegacy) { this.isLegacy = isLegacy; } boolean isLegacy() { return isLegacy; } AuthorizationRequest setCallback(StatusCallback statusCallback) { this.statusCallback = statusCallback; return this; } StatusCallback getCallback() { return statusCallback; } AuthorizationRequest setLoginBehavior(SessionLoginBehavior loginBehavior) { if (loginBehavior != null) { this.loginBehavior = loginBehavior; } return this; } SessionLoginBehavior getLoginBehavior() { return loginBehavior; } AuthorizationRequest setRequestCode(int requestCode) { if (requestCode >= 0) { this.requestCode = requestCode; } return this; } int getRequestCode() { return requestCode; } AuthorizationRequest setPermissions(List<String> permissions) { if (permissions != null) { this.permissions = permissions; } return this; } List<String> getPermissions() { return permissions; } AuthorizationRequest setDefaultAudience(SessionDefaultAudience defaultAudience) { if (defaultAudience != null) { this.defaultAudience = defaultAudience; } return this; } SessionDefaultAudience getDefaultAudience() { return defaultAudience; } StartActivityDelegate getStartActivityDelegate() { return startActivityDelegate; } String getApplicationId() { return applicationId; } void setApplicationId(String applicationId) { this.applicationId = applicationId; } String getValidateSameFbidAsToken() { return validateSameFbidAsToken; } void setValidateSameFbidAsToken(String validateSameFbidAsToken) { this.validateSameFbidAsToken = validateSameFbidAsToken; } AuthorizationClient.AuthorizationRequest getAuthorizationClientRequest() { AuthorizationClient.StartActivityDelegate delegate = new AuthorizationClient.StartActivityDelegate() { @Override public void startActivityForResult(Intent intent, int requestCode) { startActivityDelegate.startActivityForResult(intent, requestCode); } @Override public Activity getActivityContext() { return startActivityDelegate.getActivityContext(); } }; return new AuthorizationClient.AuthorizationRequest(loginBehavior, requestCode, isLegacy, permissions, defaultAudience, applicationId, validateSameFbidAsToken, delegate); } // package private so subclasses can use it Object writeReplace() { return new AuthRequestSerializationProxyV1( loginBehavior, requestCode, permissions, defaultAudience.name(), isLegacy, applicationId, validateSameFbidAsToken); } // have a readObject that throws to prevent spoofing // package private so subclasses can use it void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Cannot readObject, serialization proxy required"); } private static class AuthRequestSerializationProxyV1 implements Serializable { private static final long serialVersionUID = -8748347685113614927L; private final SessionLoginBehavior loginBehavior; private final int requestCode; private boolean isLegacy; private final List<String> permissions; private final String defaultAudience; private final String applicationId; private final String validateSameFbidAsToken; private AuthRequestSerializationProxyV1(SessionLoginBehavior loginBehavior, int requestCode, List<String> permissions, String defaultAudience, boolean isLegacy, String applicationId, String validateSameFbidAsToken) { this.loginBehavior = loginBehavior; this.requestCode = requestCode; this.permissions = permissions; this.defaultAudience = defaultAudience; this.isLegacy = isLegacy; this.applicationId = applicationId; this.validateSameFbidAsToken = validateSameFbidAsToken; } private Object readResolve() { return new AuthorizationRequest(loginBehavior, requestCode, permissions, defaultAudience, isLegacy, applicationId, validateSameFbidAsToken); } } } /** * A request used to open a Session. */ public static final class OpenRequest extends AuthorizationRequest { private static final long serialVersionUID = 1L; /** * Constructs an OpenRequest. * * @param activity the Activity to use to open the Session */ public OpenRequest(Activity activity) { super(activity); } /** * Constructs an OpenRequest. * * @param fragment the Fragment to use to open the Session */ public OpenRequest(Fragment fragment) { super(fragment); } /** * Sets the StatusCallback for the OpenRequest. * * @param statusCallback The {@link StatusCallback SessionStatusCallback} to * notify regarding Session state changes. * @return the OpenRequest object to allow for chaining */ public final OpenRequest setCallback(StatusCallback statusCallback) { super.setCallback(statusCallback); return this; } /** * Sets the login behavior for the OpenRequest. * * @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that * specifies what behaviors should be attempted during * authorization. * @return the OpenRequest object to allow for chaining */ public final OpenRequest setLoginBehavior(SessionLoginBehavior loginBehavior) { super.setLoginBehavior(loginBehavior); return this; } /** * Sets the request code for the OpenRequest. * * @param requestCode An integer that identifies this request. This integer will be used * as the request code in {@link Activity#onActivityResult * onActivityResult}. This integer should be >= 0. If a value < 0 is * passed in, then a default value will be used. * @return the OpenRequest object to allow for chaining */ public final OpenRequest setRequestCode(int requestCode) { super.setRequestCode(requestCode); return this; } /** * Sets the permissions for the OpenRequest. * * @param permissions A List&lt;String&gt; representing the permissions to request * during the authentication flow. A null or empty List * represents basic permissions. * @return the OpenRequest object to allow for chaining */ public final OpenRequest setPermissions(List<String> permissions) { super.setPermissions(permissions); return this; } /** * Sets the defaultAudience for the OpenRequest. * <p/> * This is only used during Native login using a sufficiently recent facebook app. * * @param defaultAudience A SessionDefaultAudience representing the default audience setting to request. * @return the OpenRequest object to allow for chaining */ public final OpenRequest setDefaultAudience(SessionDefaultAudience defaultAudience) { super.setDefaultAudience(defaultAudience); return this; } } /** * A request to be used to request new permissions for a Session. */ public static final class NewPermissionsRequest extends AuthorizationRequest { private static final long serialVersionUID = 1L; /** * Constructs a NewPermissionsRequest. * * @param activity the Activity used to issue the request * @param permissions additional permissions to request */ public NewPermissionsRequest(Activity activity, List<String> permissions) { super(activity); setPermissions(permissions); } /** * Constructs a NewPermissionsRequest. * * @param fragment the Fragment used to issue the request * @param permissions additional permissions to request */ public NewPermissionsRequest(Fragment fragment, List<String> permissions) { super(fragment); setPermissions(permissions); } /** * Sets the StatusCallback for the NewPermissionsRequest. * * @param statusCallback The {@link StatusCallback SessionStatusCallback} to * notify regarding Session state changes. * @return the NewPermissionsRequest object to allow for chaining */ public final NewPermissionsRequest setCallback(StatusCallback statusCallback) { super.setCallback(statusCallback); return this; } /** * Sets the login behavior for the NewPermissionsRequest. * * @param loginBehavior The {@link SessionLoginBehavior SessionLoginBehavior} that * specifies what behaviors should be attempted during * authorization. * @return the NewPermissionsRequest object to allow for chaining */ public final NewPermissionsRequest setLoginBehavior(SessionLoginBehavior loginBehavior) { super.setLoginBehavior(loginBehavior); return this; } /** * Sets the request code for the NewPermissionsRequest. * * @param requestCode An integer that identifies this request. This integer will be used * as the request code in {@link Activity#onActivityResult * onActivityResult}. This integer should be >= 0. If a value < 0 is * passed in, then a default value will be used. * @return the NewPermissionsRequest object to allow for chaining */ public final NewPermissionsRequest setRequestCode(int requestCode) { super.setRequestCode(requestCode); return this; } /** * Sets the defaultAudience for the OpenRequest. * * @param defaultAudience A SessionDefaultAudience representing the default audience setting to request. * @return the NewPermissionsRequest object to allow for chaining */ public final NewPermissionsRequest setDefaultAudience(SessionDefaultAudience defaultAudience) { super.setDefaultAudience(defaultAudience); return this; } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/Session.java
Java
art
74,442
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * An Exception indicating that an operation was canceled before it completed. */ public class FacebookOperationCanceledException extends FacebookException { static final long serialVersionUID = 1; /** * Constructs a FacebookOperationCanceledException with no additional information. */ public FacebookOperationCanceledException() { super(); } /** * Constructs a FacebookOperationCanceledException with a message. * * @param message A String to be returned from getMessage. */ public FacebookOperationCanceledException(String message) { super(message); } /** * Constructs a FacebookOperationCanceledException with a message and inner error. * * @param message A String to be returned from getMessage. * @param throwable A Throwable to be returned from getCause. */ public FacebookOperationCanceledException(String message, Throwable throwable) { super(message, throwable); } /** * Constructs a FacebookOperationCanceledException with an inner error. * * @param throwable A Throwable to be returned from getCause. */ public FacebookOperationCanceledException(Throwable throwable) { super(throwable); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/FacebookOperationCanceledException.java
Java
art
1,898
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * <p> * Identifies the state of a Session. * </p> * <p> * Session objects implement a state machine that controls their lifecycle. This * enum represents the states of the state machine. * </p> */ public enum SessionState { /** * Indicates that the Session has not yet been opened and has no cached * token. Opening a Session in this state will involve user interaction. */ CREATED(Category.CREATED_CATEGORY), /** * <p> * Indicates that the Session has not yet been opened and has a cached * token. Opening a Session in this state will not involve user interaction. * </p> * <p> * If you are using Session from an Android Service, you must provide a * TokenCachingStrategy implementation that contains a valid token to the Session * constructor. The resulting Session will be created in this state, and you * can then safely call open, passing null for the Activity. * </p> */ CREATED_TOKEN_LOADED(Category.CREATED_CATEGORY), /** * Indicates that the Session is in the process of opening. */ OPENING(Category.CREATED_CATEGORY), /** * Indicates that the Session is opened. In this state, the Session may be * used with a {@link Request}. */ OPENED(Category.OPENED_CATEGORY), /** * <p> * Indicates that the Session is opened and that the token has changed. In * this state, the Session may be used with {@link Request}. * </p> * <p> * Every time the token is updated, {@link Session.StatusCallback * StatusCallback} is called with this value. * </p> */ OPENED_TOKEN_UPDATED(Category.OPENED_CATEGORY), /** * Indicates that the Session is closed, and that it was not closed * normally. Typically this means that the open call failed, and the * Exception parameter to {@link Session.StatusCallback StatusCallback} will * be non-null. */ CLOSED_LOGIN_FAILED(Category.CLOSED_CATEGORY), /** * Indicates that the Session was closed normally. */ CLOSED(Category.CLOSED_CATEGORY); private final Category category; SessionState(Category category) { this.category = category; } /** * Returns a boolean indicating whether the state represents a successfully * opened state in which the Session can be used with a {@link Request}. * * @return a boolean indicating whether the state represents a successfully * opened state in which the Session can be used with a * {@link Request}. */ public boolean isOpened() { return this.category == Category.OPENED_CATEGORY; } /** * Returns a boolean indicating whether the state represents a closed * Session that can no longer be used with a {@link Request}. * * @return a boolean indicating whether the state represents a closed * Session that can no longer be used with a {@link Request}. */ public boolean isClosed() { return this.category == Category.CLOSED_CATEGORY; } private enum Category { CREATED_CATEGORY, OPENED_CATEGORY, CLOSED_CATEGORY } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/SessionState.java
Java
art
3,816
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Bundle; import android.text.TextUtils; import android.webkit.CookieSyncManager; import com.facebook.android.R; import com.facebook.internal.ServerProtocol; import com.facebook.internal.Utility; import com.facebook.model.GraphMultiResult; import com.facebook.model.GraphObject; import com.facebook.model.GraphObjectList; import com.facebook.model.GraphUser; import com.facebook.widget.WebDialog; import java.io.Serializable; import java.util.ArrayList; import java.util.List; class AuthorizationClient implements Serializable { private static final long serialVersionUID = 1L; private static final String TAG = "Facebook-AuthorizationClient"; private static final String WEB_VIEW_AUTH_HANDLER_STORE = "com.facebook.AuthorizationClient.WebViewAuthHandler.TOKEN_STORE_KEY"; private static final String WEB_VIEW_AUTH_HANDLER_TOKEN_KEY = "TOKEN"; List<AuthHandler> handlersToTry; AuthHandler currentHandler; transient Context context; transient StartActivityDelegate startActivityDelegate; transient OnCompletedListener onCompletedListener; transient BackgroundProcessingListener backgroundProcessingListener; transient boolean checkedInternetPermission; AuthorizationRequest pendingRequest; interface OnCompletedListener { void onCompleted(Result result); } interface BackgroundProcessingListener { void onBackgroundProcessingStarted(); void onBackgroundProcessingStopped(); } interface StartActivityDelegate { public void startActivityForResult(Intent intent, int requestCode); public Activity getActivityContext(); } void setContext(final Context context) { this.context = context; // We rely on individual requests to tell us how to start an activity. startActivityDelegate = null; } void setContext(final Activity activity) { this.context = activity; // If we are used in the context of an activity, we will always use that activity to // call startActivityForResult. startActivityDelegate = new StartActivityDelegate() { @Override public void startActivityForResult(Intent intent, int requestCode) { activity.startActivityForResult(intent, requestCode); } @Override public Activity getActivityContext() { return activity; } }; } void startOrContinueAuth(AuthorizationRequest request) { if (getInProgress()) { continueAuth(); } else { authorize(request); } } void authorize(AuthorizationRequest request) { if (request == null) { return; } if (pendingRequest != null) { throw new FacebookException("Attempted to authorize while a request is pending."); } if (request.needsNewTokenValidation() && !checkInternetPermission()) { // We're going to need INTERNET permission later and don't have it, so fail early. return; } pendingRequest = request; handlersToTry = getHandlerTypes(request); tryNextHandler(); } void continueAuth() { if (pendingRequest == null || currentHandler == null) { throw new FacebookException("Attempted to continue authorization without a pending request."); } if (currentHandler.needsRestart()) { currentHandler.cancel(); tryCurrentHandler(); } } boolean getInProgress() { return pendingRequest != null && currentHandler != null; } void cancelCurrentHandler() { if (currentHandler != null) { currentHandler.cancel(); } } boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == pendingRequest.getRequestCode()) { return currentHandler.onActivityResult(requestCode, resultCode, data); } return false; } private List<AuthHandler> getHandlerTypes(AuthorizationRequest request) { ArrayList<AuthHandler> handlers = new ArrayList<AuthHandler>(); final SessionLoginBehavior behavior = request.getLoginBehavior(); if (behavior.allowsKatanaAuth()) { if (!request.isLegacy()) { handlers.add(new GetTokenAuthHandler()); handlers.add(new KatanaLoginDialogAuthHandler()); } handlers.add(new KatanaProxyAuthHandler()); } if (behavior.allowsWebViewAuth()) { handlers.add(new WebViewAuthHandler()); } return handlers; } boolean checkInternetPermission() { if (checkedInternetPermission) { return true; } int permissionCheck = checkPermission(Manifest.permission.INTERNET); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { String errorType = context.getString(R.string.com_facebook_internet_permission_error_title); String errorDescription = context.getString(R.string.com_facebook_internet_permission_error_message); complete(Result.createErrorResult(errorType, errorDescription)); return false; } checkedInternetPermission = true; return true; } void tryNextHandler() { while (handlersToTry != null && !handlersToTry.isEmpty()) { currentHandler = handlersToTry.remove(0); boolean started = tryCurrentHandler(); if (started) { return; } } if (pendingRequest != null) { // We went through all handlers without successfully attempting an auth. completeWithFailure(); } } private void completeWithFailure() { complete(Result.createErrorResult("Login attempt failed.", null)); } boolean tryCurrentHandler() { if (currentHandler.needsInternetPermission() && !checkInternetPermission()) { return false; } return currentHandler.tryAuthorize(pendingRequest); } void completeAndValidate(Result outcome) { // Do we need to validate a successful result (as in the case of a reauth)? if (outcome.token != null && pendingRequest.needsNewTokenValidation()) { validateSameFbidAndFinish(outcome); } else { // We're done, just notify the listener. complete(outcome); } } void complete(Result outcome) { handlersToTry = null; currentHandler = null; pendingRequest = null; notifyOnCompleteListener(outcome); } OnCompletedListener getOnCompletedListener() { return onCompletedListener; } void setOnCompletedListener(OnCompletedListener onCompletedListener) { this.onCompletedListener = onCompletedListener; } BackgroundProcessingListener getBackgroundProcessingListener() { return backgroundProcessingListener; } void setBackgroundProcessingListener(BackgroundProcessingListener backgroundProcessingListener) { this.backgroundProcessingListener = backgroundProcessingListener; } StartActivityDelegate getStartActivityDelegate() { if (startActivityDelegate != null) { return startActivityDelegate; } else if (pendingRequest != null) { // Wrap the request's delegate in our own. return new StartActivityDelegate() { @Override public void startActivityForResult(Intent intent, int requestCode) { pendingRequest.getStartActivityDelegate().startActivityForResult(intent, requestCode); } @Override public Activity getActivityContext() { return pendingRequest.getStartActivityDelegate().getActivityContext(); } }; } return null; } int checkPermission(String permission) { return context.checkCallingOrSelfPermission(permission); } void validateSameFbidAndFinish(Result pendingResult) { if (pendingResult.token == null) { throw new FacebookException("Can't validate without a token"); } RequestBatch batch = createReauthValidationBatch(pendingResult); notifyBackgroundProcessingStart(); batch.executeAsync(); } RequestBatch createReauthValidationBatch(final Result pendingResult) { // We need to ensure that the token we got represents the same fbid as the old one. We issue // a "me" request using the current token, a "me" request using the new token, and a "me/permissions" // request using the current token to get the permissions of the user. final ArrayList<String> fbids = new ArrayList<String>(); final ArrayList<String> tokenPermissions = new ArrayList<String>(); final String newToken = pendingResult.token.getToken(); Request.Callback meCallback = new Request.Callback() { @Override public void onCompleted(Response response) { try { GraphUser user = response.getGraphObjectAs(GraphUser.class); if (user != null) { fbids.add(user.getId()); } } catch (Exception ex) { } } }; String validateSameFbidAsToken = pendingRequest.getPreviousAccessToken(); Request requestCurrentTokenMe = createGetProfileIdRequest(validateSameFbidAsToken); requestCurrentTokenMe.setCallback(meCallback); Request requestNewTokenMe = createGetProfileIdRequest(newToken); requestNewTokenMe.setCallback(meCallback); Request requestCurrentTokenPermissions = createGetPermissionsRequest(validateSameFbidAsToken); requestCurrentTokenPermissions.setCallback(new Request.Callback() { @Override public void onCompleted(Response response) { try { GraphMultiResult result = response.getGraphObjectAs(GraphMultiResult.class); if (result != null) { GraphObjectList<GraphObject> data = result.getData(); if (data != null && data.size() == 1) { GraphObject permissions = data.get(0); // The keys are the permission names. tokenPermissions.addAll(permissions.asMap().keySet()); } } } catch (Exception ex) { } } }); RequestBatch batch = new RequestBatch(requestCurrentTokenMe, requestNewTokenMe, requestCurrentTokenPermissions); batch.setBatchApplicationId(pendingRequest.getApplicationId()); batch.addCallback(new RequestBatch.Callback() { @Override public void onBatchCompleted(RequestBatch batch) { try { Result result = null; if (fbids.size() == 2 && fbids.get(0) != null && fbids.get(1) != null && fbids.get(0).equals(fbids.get(1))) { // Modify the token to have the right permission set. AccessToken tokenWithPermissions = AccessToken .createFromTokenWithRefreshedPermissions(pendingResult.token, tokenPermissions); result = Result.createTokenResult(tokenWithPermissions); } else { result = Result .createErrorResult("User logged in as different Facebook user.", null); } complete(result); } catch (Exception ex) { complete(Result.createErrorResult("Caught exception", ex.getMessage())); } finally { notifyBackgroundProcessingStop(); } } }); return batch; } Request createGetPermissionsRequest(String accessToken) { Bundle parameters = new Bundle(); parameters.putString("fields", "id"); parameters.putString("access_token", accessToken); return new Request(null, "me/permissions", parameters, HttpMethod.GET, null); } Request createGetProfileIdRequest(String accessToken) { Bundle parameters = new Bundle(); parameters.putString("fields", "id"); parameters.putString("access_token", accessToken); return new Request(null, "me", parameters, HttpMethod.GET, null); } private void notifyOnCompleteListener(Result outcome) { if (onCompletedListener != null) { onCompletedListener.onCompleted(outcome); } } private void notifyBackgroundProcessingStart() { if (backgroundProcessingListener != null) { backgroundProcessingListener.onBackgroundProcessingStarted(); } } private void notifyBackgroundProcessingStop() { if (backgroundProcessingListener != null) { backgroundProcessingListener.onBackgroundProcessingStopped(); } } abstract class AuthHandler implements Serializable { private static final long serialVersionUID = 1L; abstract boolean tryAuthorize(AuthorizationRequest request); boolean onActivityResult(int requestCode, int resultCode, Intent data) { return false; } boolean needsRestart() { return false; } boolean needsInternetPermission() { return false; } void cancel() { } } class WebViewAuthHandler extends AuthHandler { private static final long serialVersionUID = 1L; private transient WebDialog loginDialog; @Override boolean needsRestart() { // Because we are presenting WebView UI within the current context, we need to explicitly // restart the process if the context goes away and is recreated. return true; } @Override boolean needsInternetPermission() { return true; } @Override void cancel() { if (loginDialog != null) { loginDialog.dismiss(); loginDialog = null; } } @Override boolean tryAuthorize(final AuthorizationRequest request) { String applicationId = request.getApplicationId(); Bundle parameters = new Bundle(); if (!Utility.isNullOrEmpty(request.getPermissions())) { parameters.putString(ServerProtocol.DIALOG_PARAM_SCOPE, TextUtils.join(",", request.getPermissions())); } String previousToken = request.getPreviousAccessToken(); if (!Utility.isNullOrEmpty(previousToken) && (previousToken.equals(loadCookieToken()))) { parameters.putString(ServerProtocol.DIALOG_PARAM_ACCESS_TOKEN, previousToken); } else { // The call to clear cookies will create the first instance of CookieSyncManager if necessary Utility.clearFacebookCookies(context); } WebDialog.OnCompleteListener listener = new WebDialog.OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { onWebDialogComplete(request, values, error); } }; WebDialog.Builder builder = new AuthDialogBuilder(getStartActivityDelegate().getActivityContext(), applicationId, parameters) .setOnCompleteListener(listener); loginDialog = builder.build(); loginDialog.show(); return true; } void onWebDialogComplete(AuthorizationRequest request, Bundle values, FacebookException error) { Result outcome; if (values != null) { AccessToken token = AccessToken .createFromWebBundle(request.getPermissions(), values, AccessTokenSource.WEB_VIEW); outcome = Result.createTokenResult(token); // Ensure any cookies set by the dialog are saved // This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager // has never been created. CookieSyncManager syncManager = CookieSyncManager.createInstance(context); syncManager.sync(); saveCookieToken(token.getToken()); } else { if (error instanceof FacebookOperationCanceledException) { outcome = Result.createCancelResult("User canceled log in."); } else { outcome = Result.createErrorResult(error.getMessage(), null); } } completeAndValidate(outcome); } private void saveCookieToken(String token) { Context context = getStartActivityDelegate().getActivityContext(); SharedPreferences sharedPreferences = context.getSharedPreferences( WEB_VIEW_AUTH_HANDLER_STORE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, token); if (!editor.commit()) { Utility.logd(TAG, "Could not update saved web view auth handler token."); } } private String loadCookieToken() { Context context = getStartActivityDelegate().getActivityContext(); SharedPreferences sharedPreferences = context.getSharedPreferences( WEB_VIEW_AUTH_HANDLER_STORE, Context.MODE_PRIVATE); return sharedPreferences.getString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, ""); } } class GetTokenAuthHandler extends AuthHandler { private static final long serialVersionUID = 1L; private transient GetTokenClient getTokenClient; @Override void cancel() { if (getTokenClient != null) { getTokenClient.cancel(); getTokenClient = null; } } boolean tryAuthorize(final AuthorizationRequest request) { getTokenClient = new GetTokenClient(context, request.getApplicationId()); if (!getTokenClient.start()) { return false; } notifyBackgroundProcessingStart(); GetTokenClient.CompletedListener callback = new GetTokenClient.CompletedListener() { @Override public void completed(Bundle result) { getTokenCompleted(request, result); } }; getTokenClient.setCompletedListener(callback); return true; } void getTokenCompleted(AuthorizationRequest request, Bundle result) { getTokenClient = null; notifyBackgroundProcessingStop(); if (result != null) { ArrayList<String> currentPermissions = result.getStringArrayList(NativeProtocol.EXTRA_PERMISSIONS); List<String> permissions = request.getPermissions(); if ((currentPermissions != null) && ((permissions == null) || currentPermissions.containsAll(permissions))) { // We got all the permissions we needed, so we can complete the auth now. AccessToken token = AccessToken .createFromNativeLogin(result, AccessTokenSource.FACEBOOK_APPLICATION_SERVICE); Result outcome = Result.createTokenResult(token); completeAndValidate(outcome); return; } // We didn't get all the permissions we wanted, so update the request with just the permissions // we still need. ArrayList<String> newPermissions = new ArrayList<String>(); for (String permission : permissions) { if (!currentPermissions.contains(permission)) { newPermissions.add(permission); } } request.setPermissions(newPermissions); } tryNextHandler(); } } abstract class KatanaAuthHandler extends AuthHandler { private static final long serialVersionUID = 1L; protected boolean tryIntent(Intent intent, int requestCode) { if (intent == null) { return false; } try { getStartActivityDelegate().startActivityForResult(intent, requestCode); } catch (ActivityNotFoundException e) { return false; } return true; } } class KatanaLoginDialogAuthHandler extends KatanaAuthHandler { private static final long serialVersionUID = 1L; @Override boolean tryAuthorize(AuthorizationRequest request) { Intent intent = NativeProtocol.createLoginDialog20121101Intent(context, request.getApplicationId(), new ArrayList<String>(request.getPermissions()), request.getDefaultAudience().getNativeProtocolAudience()); return tryIntent(intent, request.getRequestCode()); } @Override boolean onActivityResult(int requestCode, int resultCode, Intent data) { Result outcome; if (data == null) { // This happens if the user presses 'Back'. outcome = Result.createCancelResult("Operation canceled"); } else if (NativeProtocol.isServiceDisabledResult20121101(data)) { outcome = null; } else if (resultCode == Activity.RESULT_CANCELED) { outcome = Result.createCancelResult( data.getStringExtra(NativeProtocol.STATUS_ERROR_DESCRIPTION)); } else if (resultCode != Activity.RESULT_OK) { outcome = Result.createErrorResult("Unexpected resultCode from authorization.", null); } else { outcome = handleResultOk(data); } if (outcome != null) { completeAndValidate(outcome); } else { tryNextHandler(); } return true; } private Result handleResultOk(Intent data) { Bundle extras = data.getExtras(); String errorType = extras.getString(NativeProtocol.STATUS_ERROR_TYPE); if (errorType == null) { return Result.createTokenResult( AccessToken.createFromNativeLogin(extras, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE)); } else if (NativeProtocol.ERROR_SERVICE_DISABLED.equals(errorType)) { return null; } else if (NativeProtocol.ERROR_USER_CANCELED.equals(errorType)) { return Result.createCancelResult(null); } else { return Result.createErrorResult(errorType, extras.getString("error_description")); } } } class KatanaProxyAuthHandler extends KatanaAuthHandler { private static final long serialVersionUID = 1L; @Override boolean tryAuthorize(AuthorizationRequest request) { Intent intent = NativeProtocol.createProxyAuthIntent(context, request.getApplicationId(), request.getPermissions()); return tryIntent(intent, request.getRequestCode()); } @Override boolean onActivityResult(int requestCode, int resultCode, Intent data) { // Handle stuff Result outcome; if (data == null) { // This happens if the user presses 'Back'. outcome = Result.createCancelResult("Operation canceled"); } else if (resultCode == Activity.RESULT_CANCELED) { outcome = Result.createCancelResult(data.getStringExtra("error")); } else if (resultCode != Activity.RESULT_OK) { outcome = Result.createErrorResult("Unexpected resultCode from authorization.", null); } else { outcome = handleResultOk(data); } if (outcome != null) { completeAndValidate(outcome); } else { tryNextHandler(); } return true; } private Result handleResultOk(Intent data) { Bundle extras = data.getExtras(); String error = extras.getString("error"); if (error == null) { error = extras.getString("error_type"); } if (error == null) { AccessToken token = AccessToken.createFromWebBundle(pendingRequest.getPermissions(), extras, AccessTokenSource.FACEBOOK_APPLICATION_WEB); return Result.createTokenResult(token); } else if (ServerProtocol.errorsProxyAuthDisabled.contains(error)) { return null; } else if (ServerProtocol.errorsUserCanceled.contains(error)) { return Result.createCancelResult(null); } else { return Result.createErrorResult(error, extras.getString("error_description")); } } } static class AuthDialogBuilder extends WebDialog.Builder { private static final String OAUTH_DIALOG = "oauth"; static final String REDIRECT_URI = "fbconnect://success"; public AuthDialogBuilder(Context context, String applicationId, Bundle parameters) { super(context, applicationId, OAUTH_DIALOG, parameters); } @Override public WebDialog build() { Bundle parameters = getParameters(); parameters.putString(ServerProtocol.DIALOG_PARAM_REDIRECT_URI, REDIRECT_URI); parameters.putString(ServerProtocol.DIALOG_PARAM_CLIENT_ID, getApplicationId()); return new WebDialog(getContext(), OAUTH_DIALOG, parameters, getTheme(), getListener()); } } static class AuthorizationRequest implements Serializable { private static final long serialVersionUID = 1L; private transient final StartActivityDelegate startActivityDelegate; private SessionLoginBehavior loginBehavior; private int requestCode; private boolean isLegacy = false; private List<String> permissions; private SessionDefaultAudience defaultAudience; private String applicationId; private String previousAccessToken; AuthorizationRequest(SessionLoginBehavior loginBehavior, int requestCode, boolean isLegacy, List<String> permissions, SessionDefaultAudience defaultAudience, String applicationId, String validateSameFbidAsToken, StartActivityDelegate startActivityDelegate) { this.loginBehavior = loginBehavior; this.requestCode = requestCode; this.isLegacy = isLegacy; this.permissions = permissions; this.defaultAudience = defaultAudience; this.applicationId = applicationId; this.previousAccessToken = validateSameFbidAsToken; this.startActivityDelegate = startActivityDelegate; } StartActivityDelegate getStartActivityDelegate() { return startActivityDelegate; } List<String> getPermissions() { return permissions; } void setPermissions(List<String> permissions) { this.permissions = permissions; } SessionLoginBehavior getLoginBehavior() { return loginBehavior; } int getRequestCode() { return requestCode; } SessionDefaultAudience getDefaultAudience() { return defaultAudience; } String getApplicationId() { return applicationId; } boolean isLegacy() { return isLegacy; } void setIsLegacy(boolean isLegacy) { this.isLegacy = isLegacy; } String getPreviousAccessToken() { return previousAccessToken; } boolean needsNewTokenValidation() { return previousAccessToken != null && !isLegacy; } } static class Result implements Serializable { private static final long serialVersionUID = 1L; enum Code { SUCCESS, CANCEL, ERROR } final Code code; final AccessToken token; final String errorMessage; private Result(Code code, AccessToken token, String errorMessage) { this.token = token; this.errorMessage = errorMessage; this.code = code; } static Result createTokenResult(AccessToken token) { return new Result(Code.SUCCESS, token, null); } static Result createCancelResult(String message) { return new Result(Code.CANCEL, null, message); } static Result createErrorResult(String errorType, String errorDescription) { String message = errorType; if (errorDescription != null) { message += ": " + errorDescription; } return new Result(Code.ERROR, null, message); } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/AuthorizationClient.java
Java
art
30,856
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.facebook.android.R; /** * This Activity is a necessary part of the overall Facebook login process * but is not meant to be used directly. Add this activity to your * AndroidManifest.xml to ensure proper handling of Facebook login. * <pre> * {@code * <activity android:name="com.facebook.LoginActivity" * android:theme="@android:style/Theme.Translucent.NoTitleBar" * android:label="@string/app_name" /> * } * </pre> * Do not start this activity directly. */ public class LoginActivity extends Activity { static final String RESULT_KEY = "com.facebook.LoginActivity:Result"; private static final String NULL_CALLING_PKG_ERROR_MSG = "Cannot call LoginActivity with a null calling package. " + "This can occur if the launchMode of the caller is singleInstance."; private static final String SAVED_CALLING_PKG_KEY = "callingPackage"; private static final String SAVED_AUTH_CLIENT = "authorizationClient"; private static final String EXTRA_REQUEST = "request"; private String callingPackage; private AuthorizationClient authorizationClient; private AuthorizationClient.AuthorizationRequest request; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.com_facebook_login_activity_layout); if (savedInstanceState != null) { callingPackage = savedInstanceState.getString(SAVED_CALLING_PKG_KEY); authorizationClient = (AuthorizationClient) savedInstanceState.getSerializable(SAVED_AUTH_CLIENT); } else { callingPackage = getCallingPackage(); authorizationClient = new AuthorizationClient(); request = (AuthorizationClient.AuthorizationRequest) getIntent().getSerializableExtra(EXTRA_REQUEST); } authorizationClient.setContext(this); authorizationClient.setOnCompletedListener(new AuthorizationClient.OnCompletedListener() { @Override public void onCompleted(AuthorizationClient.Result outcome) { onAuthClientCompleted(outcome); } }); authorizationClient.setBackgroundProcessingListener(new AuthorizationClient.BackgroundProcessingListener() { @Override public void onBackgroundProcessingStarted() { findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.VISIBLE); } @Override public void onBackgroundProcessingStopped() { findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.GONE); } }); } private void onAuthClientCompleted(AuthorizationClient.Result outcome) { request = null; int resultCode = (outcome.code == AuthorizationClient.Result.Code.CANCEL) ? RESULT_CANCELED : RESULT_OK; Bundle bundle = new Bundle(); bundle.putSerializable(RESULT_KEY, outcome); Intent resultIntent = new Intent(); resultIntent.putExtras(bundle); setResult(resultCode, resultIntent); finish(); } @Override public void onResume() { super.onResume(); // If the calling package is null, this generally means that the callee was started // with a launchMode of singleInstance. Unfortunately, Android does not allow a result // to be set when the callee is a singleInstance, so we throw an exception here. if (callingPackage == null) { throw new FacebookException(NULL_CALLING_PKG_ERROR_MSG); } authorizationClient.startOrContinueAuth(request); } @Override public void onPause() { super.onPause(); authorizationClient.cancelCurrentHandler(); findViewById(R.id.com_facebook_login_activity_progress_bar).setVisibility(View.GONE); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(SAVED_CALLING_PKG_KEY, callingPackage); outState.putSerializable(SAVED_AUTH_CLIENT, authorizationClient); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { authorizationClient.onActivityResult(requestCode, resultCode, data); } static Bundle populateIntentExtras(AuthorizationClient.AuthorizationRequest request) { Bundle extras = new Bundle(); extras.putSerializable(EXTRA_REQUEST, request); return extras; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/LoginActivity.java
Java
art
5,348
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.content.Context; import com.facebook.internal.*; import com.facebook.model.GraphObject; import com.facebook.model.GraphObjectList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Encapsulates the response, successful or otherwise, of a call to the Facebook platform. */ public class Response { private final HttpURLConnection connection; private final GraphObject graphObject; private final GraphObjectList<GraphObject> graphObjectList; private final boolean isFromCache; private final FacebookRequestError error; private final Request request; /** * Property name of non-JSON results in the GraphObject. Certain calls to Facebook result in a non-JSON response * (e.g., the string literal "true" or "false"). To present a consistent way of accessing results, these are * represented as a GraphObject with a single string property with this name. */ public static final String NON_JSON_RESPONSE_PROPERTY = "FACEBOOK_NON_JSON_RESULT"; private static final int INVALID_SESSION_FACEBOOK_ERROR_CODE = 190; private static final String CODE_KEY = "code"; private static final String BODY_KEY = "body"; private static final String RESPONSE_LOG_TAG = "Response"; private static final String RESPONSE_CACHE_TAG = "ResponseCache"; private static FileLruCache responseCache; Response(Request request, HttpURLConnection connection, GraphObject graphObject, boolean isFromCache) { this.request = request; this.connection = connection; this.graphObject = graphObject; this.graphObjectList = null; this.isFromCache = isFromCache; this.error = null; } Response(Request request, HttpURLConnection connection, GraphObjectList<GraphObject> graphObjects, boolean isFromCache) { this.request = request; this.connection = connection; this.graphObject = null; this.graphObjectList = graphObjects; this.isFromCache = isFromCache; this.error = null; } Response(Request request, HttpURLConnection connection, FacebookRequestError error) { this.request = request; this.connection = connection; this.graphObject = null; this.graphObjectList = null; this.isFromCache = false; this.error = error; } /** * Returns information about any errors that may have occurred during the request. * * @return the error from the server, or null if there was no server error */ public final FacebookRequestError getError() { return error; } /** * The single graph object returned for this request, if any. * * @return the graph object returned, or null if none was returned (or if the result was a list) */ public final GraphObject getGraphObject() { return graphObject; } /** * The single graph object returned for this request, if any, cast into a particular type of GraphObject. * * @param graphObjectClass the GraphObject-derived interface to cast the graph object into * @return the graph object returned, or null if none was returned (or if the result was a list) * @throws FacebookException If the passed in Class is not a valid GraphObject interface */ public final <T extends GraphObject> T getGraphObjectAs(Class<T> graphObjectClass) { if (graphObject == null) { return null; } if (graphObjectClass == null) { throw new NullPointerException("Must pass in a valid interface that extends GraphObject"); } return graphObject.cast(graphObjectClass); } /** * The list of graph objects returned for this request, if any. * * @return the list of graph objects returned, or null if none was returned (or if the result was not a list) */ public final GraphObjectList<GraphObject> getGraphObjectList() { return graphObjectList; } /** * The list of graph objects returned for this request, if any, cast into a particular type of GraphObject. * * @param graphObjectClass the GraphObject-derived interface to cast the graph objects into * @return the list of graph objects returned, or null if none was returned (or if the result was not a list) * @throws FacebookException If the passed in Class is not a valid GraphObject interface */ public final <T extends GraphObject> GraphObjectList<T> getGraphObjectListAs(Class<T> graphObjectClass) { if (graphObjectList == null) { return null; } return graphObjectList.castToListOf(graphObjectClass); } /** * Returns the HttpURLConnection that this response was generated from. If the response was retrieved * from the cache, this will be null. * * @return the connection, or null */ public final HttpURLConnection getConnection() { return connection; } /** * Returns the request that this response is for. * * @return the request that this response is for */ public Request getRequest() { return request; } /** * Indicates whether paging is being done forward or backward. */ public enum PagingDirection { /** * Indicates that paging is being performed in the forward direction. */ NEXT, /** * Indicates that paging is being performed in the backward direction. */ PREVIOUS } /** * If a Response contains results that contain paging information, returns a new * Request that will retrieve the next page of results, in whichever direction * is desired. If no paging information is available, returns null. * * @param direction enum indicating whether to page forward or backward * @return a Request that will retrieve the next page of results in the desired * direction, or null if no paging information is available */ public Request getRequestForPagedResults(PagingDirection direction) { String link = null; if (graphObject != null) { PagedResults pagedResults = graphObject.cast(PagedResults.class); PagingInfo pagingInfo = pagedResults.getPaging(); if (pagingInfo != null) { if (direction == PagingDirection.NEXT) { link = pagingInfo.getNext(); } else { link = pagingInfo.getPrevious(); } } } if (Utility.isNullOrEmpty(link)) { return null; } if (link != null && link.equals(request.getUrlForSingleRequest())) { // We got the same "next" link as we just tried to retrieve. This could happen if cached // data is invalid. All we can do in this case is pretend we have finished. return null; } Request pagingRequest; try { pagingRequest = new Request(request.getSession(), new URL(link)); } catch (MalformedURLException e) { return null; } return pagingRequest; } /** * Provides a debugging string for this response. */ @Override public String toString() { String responseCode; try { responseCode = String.format("%d", (connection != null) ? connection.getResponseCode() : 200); } catch (IOException e) { responseCode = "unknown"; } return new StringBuilder().append("{Response: ").append(" responseCode: ").append(responseCode) .append(", graphObject: ").append(graphObject).append(", error: ").append(error) .append(", isFromCache:").append(isFromCache).append("}") .toString(); } /** * Indicates whether the response was retrieved from a local cache or from the server. * * @return true if the response was cached locally, false if it was retrieved from the server */ public final boolean getIsFromCache() { return isFromCache; } static FileLruCache getResponseCache() { if (responseCache == null) { Context applicationContext = Session.getStaticContext(); if (applicationContext != null) { responseCache = new FileLruCache(applicationContext, RESPONSE_CACHE_TAG, new FileLruCache.Limits()); } } return responseCache; } @SuppressWarnings("resource") static List<Response> fromHttpConnection(HttpURLConnection connection, RequestBatch requests) { InputStream stream = null; FileLruCache cache = null; String cacheKey = null; if (requests instanceof CacheableRequestBatch) { CacheableRequestBatch cacheableRequestBatch = (CacheableRequestBatch) requests; cache = getResponseCache(); cacheKey = cacheableRequestBatch.getCacheKeyOverride(); if (Utility.isNullOrEmpty(cacheKey)) { if (requests.size() == 1) { // Default for single requests is to use the URL. cacheKey = requests.get(0).getUrlForSingleRequest(); } else { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_CACHE_TAG, "Not using cache for cacheable request because no key was specified"); } } // Try loading from cache. If that fails, load from the network. if (!cacheableRequestBatch.getForceRoundTrip() && cache != null && !Utility.isNullOrEmpty(cacheKey)) { try { stream = cache.get(cacheKey); if (stream != null) { return createResponsesFromStream(stream, null, requests, true); } } catch (FacebookException exception) { // retry via roundtrip below } catch (JSONException exception) { } catch (IOException exception) { } finally { Utility.closeQuietly(stream); } } } // Load from the network, and cache the result if not an error. try { if (connection.getResponseCode() >= 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); if ((cache != null) && (cacheKey != null) && (stream != null)) { InputStream interceptStream = cache.interceptAndPut(cacheKey, stream); if (interceptStream != null) { stream = interceptStream; } } } return createResponsesFromStream(stream, connection, requests, false); } catch (FacebookException facebookException) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException); return constructErrorResponses(requests, connection, facebookException); } catch (JSONException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } catch (IOException exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); return constructErrorResponses(requests, connection, new FacebookException(exception)); } finally { Utility.closeQuietly(stream); } } static List<Response> createResponsesFromStream(InputStream stream, HttpURLConnection connection, RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException { String responseString = Utility.readStreamToString(stream); Logger.log(LoggingBehavior.INCLUDE_RAW_RESPONSES, RESPONSE_LOG_TAG, "Response (raw)\n Size: %d\n Response:\n%s\n", responseString.length(), responseString); return createResponsesFromString(responseString, connection, requests, isFromCache); } static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection, RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException { JSONTokener tokener = new JSONTokener(responseString); Object resultObject = tokener.nextValue(); List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache); Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n", requests.getId(), responseString.length(), responses); return responses; } private static List<Response> createResponsesFromObject(HttpURLConnection connection, List<Request> requests, Object object, boolean isFromCache) throws FacebookException, JSONException { assert (connection != null) || isFromCache; int numRequests = requests.size(); List<Response> responses = new ArrayList<Response>(numRequests); Object originalResult = object; if (numRequests == 1) { Request request = requests.get(0); try { // Single request case -- the entire response is the result, wrap it as "body" so we can handle it // the same as we do in the batched case. We get the response code from the actual HTTP response, // as opposed to the batched case where it is returned as a "code" element. JSONObject jsonObject = new JSONObject(); jsonObject.put(BODY_KEY, object); int responseCode = (connection != null) ? connection.getResponseCode() : 200; jsonObject.put(CODE_KEY, responseCode); JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonObject); // Pretend we got an array of 1 back. object = jsonArray; } catch (JSONException e) { responses.add(new Response(request, connection, new FacebookRequestError(connection, e))); } catch (IOException e) { responses.add(new Response(request, connection, new FacebookRequestError(connection, e))); } } if (!(object instanceof JSONArray) || ((JSONArray) object).length() != numRequests) { FacebookException exception = new FacebookException("Unexpected number of results"); throw exception; } JSONArray jsonArray = (JSONArray) object; for (int i = 0; i < jsonArray.length(); ++i) { Request request = requests.get(i); try { Object obj = jsonArray.get(i); responses.add(createResponseFromObject(request, connection, obj, isFromCache, originalResult)); } catch (JSONException e) { responses.add(new Response(request, connection, new FacebookRequestError(connection, e))); } catch (FacebookException e) { responses.add(new Response(request, connection, new FacebookRequestError(connection, e))); } } return responses; } private static Response createResponseFromObject(Request request, HttpURLConnection connection, Object object, boolean isFromCache, Object originalResult) throws JSONException { if (object instanceof JSONObject) { JSONObject jsonObject = (JSONObject) object; FacebookRequestError error = FacebookRequestError.checkResponseAndCreateError(jsonObject, originalResult, connection); if (error != null) { if (error.getErrorCode() == INVALID_SESSION_FACEBOOK_ERROR_CODE) { Session session = request.getSession(); if (session != null) { session.closeAndClearTokenInformation(); } } return new Response(request, connection, error); } Object body = Utility.getStringPropertyAsJSON(jsonObject, BODY_KEY, NON_JSON_RESPONSE_PROPERTY); if (body instanceof JSONObject) { GraphObject graphObject = GraphObject.Factory.create((JSONObject) body); return new Response(request, connection, graphObject, isFromCache); } else if (body instanceof JSONArray) { GraphObjectList<GraphObject> graphObjectList = GraphObject.Factory.createList( (JSONArray) body, GraphObject.class); return new Response(request, connection, graphObjectList, isFromCache); } // We didn't get a body we understand how to handle, so pretend we got nothing. object = JSONObject.NULL; } if (object == JSONObject.NULL) { return new Response(request, connection, (GraphObject)null, isFromCache); } else { throw new FacebookException("Got unexpected object type in response, class: " + object.getClass().getSimpleName()); } } static List<Response> constructErrorResponses(List<Request> requests, HttpURLConnection connection, FacebookException error) { int count = requests.size(); List<Response> responses = new ArrayList<Response>(count); for (int i = 0; i < count; ++i) { Response response = new Response(requests.get(i), connection, new FacebookRequestError(connection, error)); responses.add(response); } return responses; } interface PagingInfo extends GraphObject { String getNext(); String getPrevious(); } interface PagedResults extends GraphObject { GraphObjectList<GraphObject> getData(); PagingInfo getPaging(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/Response.java
Java
art
19,061
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.os.Bundle; import android.text.TextUtils; import com.facebook.internal.Utility; import java.util.ArrayList; import java.util.List; final class NativeProtocol { static final String KATANA_PACKAGE = "com.facebook.katana"; static final String KATANA_PROXY_AUTH_ACTIVITY = "com.facebook.katana.ProxyAuth"; static final String KATANA_TOKEN_REFRESH_ACTIVITY = "com.facebook.katana.platform.TokenRefreshService"; static final String KATANA_SIGNATURE = "30820268308201d102044a9c4610300d06092a864886f70d0101040500307a310" + "b3009060355040613025553310b30090603550408130243413112301006035504" + "07130950616c6f20416c746f31183016060355040a130f46616365626f6f6b204" + "d6f62696c653111300f060355040b130846616365626f6f6b311d301b06035504" + "03131446616365626f6f6b20436f72706f726174696f6e3020170d30393038333" + "13231353231365a180f32303530303932353231353231365a307a310b30090603" + "55040613025553310b30090603550408130243413112301006035504071309506" + "16c6f20416c746f31183016060355040a130f46616365626f6f6b204d6f62696c" + "653111300f060355040b130846616365626f6f6b311d301b06035504031314466" + "16365626f6f6b20436f72706f726174696f6e30819f300d06092a864886f70d01" + "0101050003818d0030818902818100c207d51df8eb8c97d93ba0c8c1002c928fa" + "b00dc1b42fca5e66e99cc3023ed2d214d822bc59e8e35ddcf5f44c7ae8ade50d7" + "e0c434f500e6c131f4a2834f987fc46406115de2018ebbb0d5a3c261bd97581cc" + "fef76afc7135a6d59e8855ecd7eacc8f8737e794c60a761c536b72b11fac8e603" + "f5da1a2d54aa103b8a13c0dbc10203010001300d06092a864886f70d010104050" + "0038181005ee9be8bcbb250648d3b741290a82a1c9dc2e76a0af2f2228f1d9f9c" + "4007529c446a70175c5a900d5141812866db46be6559e2141616483998211f4a6" + "73149fb2232a10d247663b26a9031e15f84bc1c74d141ff98a02d76f85b2c8ab2" + "571b6469b232d8e768a7f7ca04f7abe4a775615916c07940656b58717457b42bd" + "928a2"; private static final String BASIC_INFO = "basic_info"; public static final String KATANA_PROXY_AUTH_PERMISSIONS_KEY = "scope"; public static final String KATANA_PROXY_AUTH_APP_ID_KEY = "client_id"; static final boolean validateSignature(Context context, String packageName) { PackageInfo packageInfo = null; try { packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); } catch (PackageManager.NameNotFoundException e) { return false; } for (Signature signature : packageInfo.signatures) { if (signature.toCharsString().equals(KATANA_SIGNATURE)) { return true; } } return false; } static Intent validateKatanaActivityIntent(Context context, Intent intent) { if (intent == null) { return null; } ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(intent, 0); if (resolveInfo == null) { return null; } if (!validateSignature(context, resolveInfo.activityInfo.packageName)) { return null; } return intent; } static Intent validateKatanaServiceIntent(Context context, Intent intent) { if (intent == null) { return null; } ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0); if (resolveInfo == null) { return null; } if (!validateSignature(context, resolveInfo.serviceInfo.packageName)) { return null; } return intent; } static Intent createProxyAuthIntent(Context context, String applicationId, List<String> permissions) { Intent intent = new Intent() .setClassName(KATANA_PACKAGE, KATANA_PROXY_AUTH_ACTIVITY) .putExtra(KATANA_PROXY_AUTH_APP_ID_KEY, applicationId); if (!Utility.isNullOrEmpty(permissions)) { intent.putExtra(KATANA_PROXY_AUTH_PERMISSIONS_KEY, TextUtils.join(",", permissions)); } return validateKatanaActivityIntent(context, intent); } static Intent createTokenRefreshIntent(Context context) { Intent intent = new Intent(); intent.setClassName(KATANA_PACKAGE, KATANA_TOKEN_REFRESH_ACTIVITY); return validateKatanaServiceIntent(context, intent); } // --------------------------------------------------------------------------------------------- // Native Protocol updated 2012-11 static final String INTENT_ACTION_PLATFORM_ACTIVITY = "com.facebook.platform.PLATFORM_ACTIVITY"; static final String INTENT_ACTION_PLATFORM_SERVICE = "com.facebook.platform.PLATFORM_SERVICE"; static final int PROTOCOL_VERSION_20121101 = 20121101; static final String EXTRA_PROTOCOL_VERSION = "com.facebook.platform.protocol.PROTOCOL_VERSION"; static final String EXTRA_PROTOCOL_ACTION = "com.facebook.platform.protocol.PROTOCOL_ACTION"; // Messages supported by PlatformService: static final int MESSAGE_GET_ACCESS_TOKEN_REQUEST = 0x10000; static final int MESSAGE_GET_ACCESS_TOKEN_REPLY = 0x10001; // MESSAGE_ERROR_REPLY data keys: // See STATUS_* // MESSAGE_GET_ACCESS_TOKEN_REQUEST data keys: // EXTRA_APPLICATION_ID // MESSAGE_GET_ACCESS_TOKEN_REPLY data keys: // EXTRA_ACCESS_TOKEN // EXTRA_EXPIRES_SECONDS_SINCE_EPOCH // EXTRA_PERMISSIONS // Values of EXTRA_PROTOCOL_ACTION supported by PlatformActivity: static final String ACTION_LOGIN_DIALOG = "com.facebook.platform.action.request.LOGIN_DIALOG"; // Values of EXTRA_PROTOCOL_ACTION values returned by PlatformActivity: static final String ACTION_LOGIN_DIALOG_REPLY = "com.facebook.platform.action.reply.LOGIN_DIALOG"; // Extras supported for ACTION_LOGIN_DIALOG: static final String EXTRA_PERMISSIONS = "com.facebook.platform.extra.PERMISSIONS"; static final String EXTRA_WRITE_PRIVACY = "com.facebook.platform.extra.WRITE_PRIVACY"; static final String EXTRA_APPLICATION_ID = "com.facebook.platform.extra.APPLICATION_ID"; // Extras returned by setResult() for ACTION_LOGIN_DIALOG static final String EXTRA_ACCESS_TOKEN = "com.facebook.platform.extra.ACCESS_TOKEN"; static final String EXTRA_EXPIRES_SECONDS_SINCE_EPOCH = "com.facebook.platform.extra.EXPIRES_SECONDS_SINCE_EPOCH"; // EXTRA_PERMISSIONS // Keys for status data in MESSAGE_ERROR_REPLY from PlatformService and for error // extras returned by PlatformActivity's setResult() in case of errors: static final String STATUS_ERROR_TYPE = "com.facebook.platform.status.ERROR_TYPE"; static final String STATUS_ERROR_DESCRIPTION = "com.facebook.platform.status.ERROR_DESCRIPTION"; static final String STATUS_ERROR_CODE = "com.facebook.platform.status.ERROR_CODE"; static final String STATUS_ERROR_SUBCODE = "com.facebook.platform.status.ERROR_SUBCODE"; static final String STATUS_ERROR_JSON = "com.facebook.platform.status.ERROR_JSON"; // Expected values for ERROR_KEY_TYPE. Clients should tolerate other values: static final String ERROR_UNKNOWN_ERROR = "UnknownError"; static final String ERROR_PROTOCOL_ERROR = "ProtocolError"; static final String ERROR_USER_CANCELED = "UserCanceled"; static final String ERROR_APPLICATION_ERROR = "ApplicationError"; static final String ERROR_NETWORK_ERROR = "NetworkError"; static final String ERROR_PERMISSION_DENIED = "PermissionDenied"; static final String ERROR_SERVICE_DISABLED = "ServiceDisabled"; static final String AUDIENCE_ME = "SELF"; static final String AUDIENCE_FRIENDS = "ALL_FRIENDS"; static final String AUDIENCE_EVERYONE = "EVERYONE"; static Intent createLoginDialog20121101Intent(Context context, String applicationId, ArrayList<String> permissions, String audience) { Intent intent = new Intent() .setAction(INTENT_ACTION_PLATFORM_ACTIVITY) .addCategory(Intent.CATEGORY_DEFAULT) .putExtra(EXTRA_PROTOCOL_VERSION, PROTOCOL_VERSION_20121101) .putExtra(EXTRA_PROTOCOL_ACTION, ACTION_LOGIN_DIALOG) .putExtra(EXTRA_APPLICATION_ID, applicationId) .putStringArrayListExtra(EXTRA_PERMISSIONS, ensureDefaultPermissions(permissions)) .putExtra(EXTRA_WRITE_PRIVACY, ensureDefaultAudience(audience)); return validateKatanaActivityIntent(context, intent); } private static String ensureDefaultAudience(String audience) { if (Utility.isNullOrEmpty(audience)) { return AUDIENCE_ME; } else { return audience; } } private static ArrayList<String> ensureDefaultPermissions(ArrayList<String> permissions) { ArrayList<String> updated; // Return if we are doing publish, or if basic_info is already included if (Utility.isNullOrEmpty(permissions)) { updated = new ArrayList<String>(); } else { for (String permission : permissions) { if (Session.isPublishPermission(permission) || BASIC_INFO.equals(permission)) { return permissions; } } updated = new ArrayList<String>(permissions); } updated.add(BASIC_INFO); return updated; } static boolean isServiceDisabledResult20121101(Intent data) { int protocolVersion = data.getIntExtra(EXTRA_PROTOCOL_VERSION, 0); String errorType = data.getStringExtra(STATUS_ERROR_TYPE); return ((PROTOCOL_VERSION_20121101 == protocolVersion) && ERROR_SERVICE_DISABLED.equals(errorType)); } static AccessTokenSource getAccessTokenSourceFromNative(Bundle extras) { long expected = PROTOCOL_VERSION_20121101; long actual = extras.getInt(EXTRA_PROTOCOL_VERSION, 0); if (expected == actual) { return AccessTokenSource.FACEBOOK_APPLICATION_NATIVE; } else { return AccessTokenSource.FACEBOOK_APPLICATION_WEB; } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/NativeProtocol.java
Java
art
11,290
/** * Copyright 2010-present Facebook. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook; /** * Represents an error condition specific to the Facebook SDK for Android. */ public class FacebookException extends RuntimeException { static final long serialVersionUID = 1; /** * Constructs a new FacebookException. */ public FacebookException() { super(); } /** * Constructs a new FacebookException. * * @param message * the detail message of this exception */ public FacebookException(String message) { super(message); } /** * Constructs a new FacebookException. * * @param message * the detail message of this exception * @param throwable * the cause of this exception */ public FacebookException(String message, Throwable throwable) { super(message, throwable); } /** * Constructs a new FacebookException. * * @param throwable * the cause of this exception */ public FacebookException(Throwable throwable) { super(throwable); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/FacebookSDK/src/com/facebook/FacebookException.java
Java
art
1,696