code
stringlengths
1
2.08M
language
stringclasses
1 value
var searchData= [ ['operator_2b',['operator+',['../class_basic_1_1_position.html#a6004db73e0d762f72a911a17eaf8ef20',1,'Basic::Position']]] ];
JavaScript
var searchData= [ ['scheduler',['Scheduler',['../class_scheduler_1_1_scheduler.html',1,'Scheduler']]], ['schedulerparameters',['SchedulerParameters',['../class_parameters_1_1_scheduler_parameters.html',1,'Parameters']]], ['schedulingalgorithm',['SchedulingAlgorithm',['../class_scheduler_1_1_scheduling_algorithm.html',1,'Scheduler']]], ['simulation',['Simulation',['../class_simulation_1_1_simulation.html',1,'Simulation']]], ['simulationenvironment',['SimulationEnvironment',['../class_simulation_environment_1_1_simulation_environment.html',1,'SimulationEnvironment']]], ['simulationparameters',['SimulationParameters',['../class_parameters_1_1_simulation_parameters.html',1,'Parameters']]], ['slot',['Slot',['../class_physical_layer_1_1_slot.html',1,'PhysicalLayer']]], ['smallscalefading',['SmallScaleFading',['../class_radio_channel_1_1_small_scale_fading.html',1,'RadioChannel']]], ['statistics',['Statistics',['../class_basic_1_1_statistics.html',1,'Basic']]], ['subcarrier',['Subcarrier',['../class_physical_layer_1_1_subcarrier.html',1,'PhysicalLayer']]], ['subframe',['Subframe',['../class_physical_layer_1_1_subframe.html',1,'PhysicalLayer']]], ['systemparameters',['SystemParameters',['../class_parameters_1_1_system_parameters.html',1,'Parameters']]] ];
JavaScript
var searchData= [ ['antenna_2ecpp',['Antenna.cpp',['../_antenna_8cpp.html',1,'']]], ['antenna_2eh',['Antenna.h',['../_antenna_8h.html',1,'']]], ['antennaparameters_2ecpp',['AntennaParameters.cpp',['../_antenna_parameters_8cpp.html',1,'']]], ['antennaparameters_2eh',['AntennaParameters.h',['../_antenna_parameters_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['mobility',['Mobility',['../namespace_mobility.html',1,'']]] ];
JavaScript
var searchData= [ ['y',['y',['../class_basic_1_1_position.html#af82aa750d8f6f3c2c8b90b5b299b4d40',1,'Basic::Position::y()'],['../class_basic_1_1_position.html#a97569d5ba867724e82ce39cc2e5358e7',1,'Basic::Position::y(double y_arg)']]] ];
JavaScript
var searchData= [ ['timemanager',['TimeManager',['../class_time_manager_1_1_time_manager.html',1,'TimeManager']]], ['transmission',['Transmission',['../class_transmission_1_1_transmission.html',1,'Transmission']]], ['transmitter',['Transmitter',['../class_physical_node_1_1_transmitter.html',1,'PhysicalNode']]] ];
JavaScript
var searchData= [ ['link',['Link',['../namespace_link.html',1,'']]], ['linkadaptation',['LinkAdaptation',['../namespace_link_adaptation.html',1,'']]] ];
JavaScript
var searchData= [ ['frequencyplanning',['FrequencyPlanning',['../namespace_frequency_planning.html',1,'']]] ];
JavaScript
var searchData= [ ['abs',['abs',['../class_basic_1_1_position.html#aa9b5b0e9b35feb76399d3c2cfc609d74',1,'Basic::Position']]], ['adduser',['addUser',['../class_physical_node_1_1_e_node_b.html#a5fe75248ae4857f119b4705606a926d6',1,'PhysicalNode::ENodeB']]], ['adduserid',['addUserId',['../class_results_1_1_results.html#aea8decccc7858d71d4c9aa0eff71a971',1,'Results::Results']]], ['adjustcqi',['adjustCQI',['../class_physical_node_1_1_user.html#ad75cd70683a88e6d0bf5f4fdb5a7c7c2',1,'PhysicalNode::User']]], ['allocatefrequencies',['allocateFrequencies',['../class_frequency_planning_1_1_frequency_planning.html#afa1a455615e84098437df80f6e0baf7d',1,'FrequencyPlanning::FrequencyPlanning']]], ['antenna',['Antenna',['../class_physical_node_1_1_antenna.html',1,'PhysicalNode']]], ['antenna',['Antenna',['../class_physical_node_1_1_antenna.html#a15173c682b42f974b6dc0daa2de195dd',1,'PhysicalNode::Antenna']]], ['antenna_2ecpp',['Antenna.cpp',['../_antenna_8cpp.html',1,'']]], ['antenna_2eh',['Antenna.h',['../_antenna_8h.html',1,'']]], ['antenna_5f',['antenna_',['../class_physical_node_1_1_device.html#a2cf2bed708094a94fe625e77eae411c7',1,'PhysicalNode::Device']]], ['antennaparameters',['AntennaParameters',['../class_parameters_1_1_antenna_parameters.html',1,'Parameters']]], ['antennaparameters_2ecpp',['AntennaParameters.cpp',['../_antenna_parameters_8cpp.html',1,'']]], ['antennaparameters_2eh',['AntennaParameters.h',['../_antenna_parameters_8h.html',1,'']]], ['arg',['arg',['../class_basic_1_1_position.html#a06b31cd86861f9f3a15d8d6d3c844385',1,'Basic::Position']]] ];
JavaScript
var searchData= [ ['radiochannel',['RadioChannel',['../namespace_radio_channel.html',1,'']]] ];
JavaScript
var searchData= [ ['bestcqialgorithm',['BestCQIAlgorithm',['../class_scheduler_1_1_best_c_q_i_algorithm.html',1,'Scheduler']]] ];
JavaScript
var searchData= [ ['enodeb_2ecpp',['ENodeB.cpp',['../_e_node_b_8cpp.html',1,'']]], ['enodeb_2eh',['ENodeB.h',['../_e_node_b_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['timemanager_2ecpp',['TimeManager.cpp',['../_time_manager_8cpp.html',1,'']]], ['timemanager_2eh',['TimeManager.h',['../_time_manager_8h.html',1,'']]], ['transmission_2ecpp',['Transmission.cpp',['../_transmission_8cpp.html',1,'']]], ['transmission_2eh',['Transmission.h',['../_transmission_8h.html',1,'']]], ['transmitter_2ecpp',['Transmitter.cpp',['../_transmitter_8cpp.html',1,'']]], ['transmitter_2eh',['Transmitter.h',['../_transmitter_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['genericantenna_2ecpp',['GenericAntenna.cpp',['../_generic_antenna_8cpp.html',1,'']]], ['genericantenna_2eh',['GenericAntenna.h',['../_generic_antenna_8h.html',1,'']]], ['grid_2ecpp',['Grid.cpp',['../_grid_8cpp.html',1,'']]], ['grid_2eh',['Grid.h',['../_grid_8h.html',1,'']]], ['gridparameters_2ecpp',['GridParameters.cpp',['../_grid_parameters_8cpp.html',1,'']]], ['gridparameters_2eh',['GridParameters.h',['../_grid_parameters_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['effectivebits_5f',['effectiveBits_',['../class_physical_layer_1_1_resource_element.html#ab896af9f43b9397c201643fa92121ca2',1,'PhysicalLayer::ResourceElement::effectiveBits_()'],['../class_physical_node_1_1_physical_node.html#a6e345a627bd97ee2b4597a5ddf227578',1,'PhysicalNode::PhysicalNode::effectiveBits_()']]], ['enodeb',['ENodeB',['../class_physical_node_1_1_e_node_b.html',1,'PhysicalNode']]], ['enodeb',['ENodeB',['../class_physical_node_1_1_e_node_b.html#ad15f75f973745caae604b4fac2724ef3',1,'PhysicalNode::ENodeB::ENodeB()'],['../class_physical_node_1_1_e_node_b.html#a789ffae9f22054261bec28738b9db8c1',1,'PhysicalNode::ENodeB::ENodeB(Basic::Position p, int id)']]], ['enodeb_2ecpp',['ENodeB.cpp',['../_e_node_b_8cpp.html',1,'']]], ['enodeb_2eh',['ENodeB.h',['../_e_node_b_8h.html',1,'']]], ['enodebid_5f',['eNodeBId_',['../class_physical_node_1_1_user.html#a5b5b3de0e7f6d9aa22c3cd5dfb665005',1,'PhysicalNode::User']]] ];
JavaScript
var searchData= [ ['antenna_5f',['antenna_',['../class_physical_node_1_1_device.html#a2cf2bed708094a94fe625e77eae411c7',1,'PhysicalNode::Device']]] ];
JavaScript
var searchData= [ ['mathfunctions',['MathFunctions',['../class_basic_1_1_math_functions.html',1,'Basic']]], ['mobility',['Mobility',['../class_mobility_1_1_mobility.html',1,'Mobility']]], ['mobilityparameters',['MobilityParameters',['../class_parameters_1_1_mobility_parameters.html',1,'Parameters']]] ];
JavaScript
var searchData= [ ['basic',['Basic',['../namespace_basic.html',1,'']]] ];
JavaScript
var searchData= [ ['scheduler',['Scheduler',['../namespace_scheduler.html',1,'']]], ['simulation',['Simulation',['../namespace_simulation.html',1,'']]], ['simulationenvironment',['SimulationEnvironment',['../namespace_simulation_environment.html',1,'']]] ];
JavaScript
var searchData= [ ['scheduler_2ecpp',['Scheduler.cpp',['../_scheduler_8cpp.html',1,'']]], ['scheduler_2eh',['Scheduler.h',['../_scheduler_8h.html',1,'']]], ['schedulerparameters_2ecpp',['SchedulerParameters.cpp',['../_scheduler_parameters_8cpp.html',1,'']]], ['schedulerparameters_2eh',['SchedulerParameters.h',['../_scheduler_parameters_8h.html',1,'']]], ['schedulingalgorithm_2ecpp',['SchedulingAlgorithm.cpp',['../_scheduling_algorithm_8cpp.html',1,'']]], ['schedulingalgorithm_2eh',['SchedulingAlgorithm.h',['../_scheduling_algorithm_8h.html',1,'']]], ['simulation_2ecpp',['Simulation.cpp',['../_simulation_8cpp.html',1,'']]], ['simulation_2eh',['Simulation.h',['../_simulation_8h.html',1,'']]], ['simulationenvironment_2ecpp',['SimulationEnvironment.cpp',['../_simulation_environment_8cpp.html',1,'']]], ['simulationenvironment_2eh',['SimulationEnvironment.h',['../_simulation_environment_8h.html',1,'']]], ['simulationparameters_2ecpp',['SimulationParameters.cpp',['../_simulation_parameters_8cpp.html',1,'']]], ['simulationparameters_2eh',['SimulationParameters.h',['../_simulation_parameters_8h.html',1,'']]], ['slot_2ecpp',['Slot.cpp',['../_slot_8cpp.html',1,'']]], ['slot_2eh',['Slot.h',['../_slot_8h.html',1,'']]], ['smallscalefading_2ecpp',['SmallScaleFading.cpp',['../_small_scale_fading_8cpp.html',1,'']]], ['smallscalefading_2eh',['SmallScaleFading.h',['../_small_scale_fading_8h.html',1,'']]], ['statistics_2ecpp',['Statistics.cpp',['../_statistics_8cpp.html',1,'']]], ['statistics_2eh',['Statistics.h',['../_statistics_8h.html',1,'']]], ['subcarrier_2ecpp',['Subcarrier.cpp',['../_subcarrier_8cpp.html',1,'']]], ['subcarrier_2eh',['Subcarrier.h',['../_subcarrier_8h.html',1,'']]], ['subframe_2ecpp',['Subframe.cpp',['../_subframe_8cpp.html',1,'']]], ['subframe_2eh',['Subframe.h',['../_subframe_8h.html',1,'']]], ['systemparameters_2ecpp',['SystemParameters.cpp',['../_system_parameters_8cpp.html',1,'']]], ['systemparameters_2eh',['SystemParameters.h',['../_system_parameters_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['y',['y',['../class_basic_1_1_position.html#af82aa750d8f6f3c2c8b90b5b299b4d40',1,'Basic::Position::y()'],['../class_basic_1_1_position.html#a97569d5ba867724e82ce39cc2e5358e7',1,'Basic::Position::y(double y_arg)']]] ];
JavaScript
var searchData= [ ['fading_2ecpp',['Fading.cpp',['../_fading_8cpp.html',1,'']]], ['fading_2eh',['Fading.h',['../_fading_8h.html',1,'']]], ['file_2ecpp',['File.cpp',['../_file_8cpp.html',1,'']]], ['file_2eh',['File.h',['../_file_8h.html',1,'']]], ['frame_2ecpp',['Frame.cpp',['../_frame_8cpp.html',1,'']]], ['frame_2eh',['Frame.h',['../_frame_8h.html',1,'']]], ['frequencyplanning_2ecpp',['FrequencyPlanning.cpp',['../_frequency_planning_8cpp.html',1,'']]], ['frequencyplanning_2eh',['FrequencyPlanning.h',['../_frequency_planning_8h.html',1,'']]], ['frequencyselectivechannel_2ecpp',['FrequencySelectiveChannel.cpp',['../_frequency_selective_channel_8cpp.html',1,'']]], ['frequencyselectivechannel_2eh',['FrequencySelectiveChannel.h',['../_frequency_selective_channel_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['parameters_2ecpp',['Parameters.cpp',['../_parameters_8cpp.html',1,'']]], ['parameters_2eh',['Parameters.h',['../_parameters_8h.html',1,'']]], ['physicallayer_2ecpp',['PhysicalLayer.cpp',['../_physical_layer_8cpp.html',1,'']]], ['physicallayer_2eh',['PhysicalLayer.h',['../_physical_layer_8h.html',1,'']]], ['physicallayerparameters_2ecpp',['PhysicalLayerParameters.cpp',['../_physical_layer_parameters_8cpp.html',1,'']]], ['physicallayerparameters_2eh',['PhysicalLayerParameters.h',['../_physical_layer_parameters_8h.html',1,'']]], ['physicalnode_2ecpp',['PhysicalNode.cpp',['../_physical_node_8cpp.html',1,'']]], ['physicalnode_2eh',['PhysicalNode.h',['../_physical_node_8h.html',1,'']]], ['physicalresourceblock_2ecpp',['PhysicalResourceBlock.cpp',['../_physical_resource_block_8cpp.html',1,'']]], ['physicalresourceblock_2eh',['PhysicalResourceBlock.h',['../_physical_resource_block_8h.html',1,'']]], ['position_2ecpp',['Position.cpp',['../_position_8cpp.html',1,'']]], ['position_2eh',['Position.h',['../_position_8h.html',1,'']]], ['proportionalfairalgorithm_2ecpp',['ProportionalFairAlgorithm.cpp',['../_proportional_fair_algorithm_8cpp.html',1,'']]], ['proportionalfairalgorithm_2eh',['ProportionalFairAlgorithm.h',['../_proportional_fair_algorithm_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['largescalefading_2ecpp',['LargeScaleFading.cpp',['../_large_scale_fading_8cpp.html',1,'']]], ['largescalefading_2eh',['LargeScaleFading.h',['../_large_scale_fading_8h.html',1,'']]], ['link_2ecpp',['Link.cpp',['../_link_8cpp.html',1,'']]], ['link_2eh',['Link.h',['../_link_8h.html',1,'']]], ['linkadaptation_2ecpp',['LinkAdaptation.cpp',['../_link_adaptation_8cpp.html',1,'']]], ['linkadaptation_2eh',['LinkAdaptation.h',['../_link_adaptation_8h.html',1,'']]], ['linkadaptationparameters_2ecpp',['LinkAdaptationParameters.cpp',['../_link_adaptation_parameters_8cpp.html',1,'']]], ['linkadaptationparameters_2eh',['LinkAdaptationParameters.h',['../_link_adaptation_parameters_8h.html',1,'']]] ];
JavaScript
var searchData= [ ['largescalefading',['LargeScaleFading',['../class_radio_channel_1_1_large_scale_fading.html',1,'RadioChannel']]], ['largescalefading',['LargeScaleFading',['../class_radio_channel_1_1_large_scale_fading.html#ac7ca540f10d15ab3d3241d40180fd397',1,'RadioChannel::LargeScaleFading']]], ['largescalefading_2ecpp',['LargeScaleFading.cpp',['../_large_scale_fading_8cpp.html',1,'']]], ['largescalefading_2eh',['LargeScaleFading.h',['../_large_scale_fading_8h.html',1,'']]], ['link',['Link',['../class_link_1_1_link.html',1,'Link']]], ['link',['Link',['../namespace_link.html',1,'']]], ['link_2ecpp',['Link.cpp',['../_link_8cpp.html',1,'']]], ['link_2eh',['Link.h',['../_link_8h.html',1,'']]], ['link_5f',['link_',['../class_simulation_1_1_simulation.html#a3f215be3b98611171f77b8521a14e104',1,'Simulation::Simulation']]], ['linkadaptation',['LinkAdaptation',['../namespace_link_adaptation.html',1,'']]], ['linkadaptation',['LinkAdaptation',['../class_link_adaptation_1_1_link_adaptation.html',1,'LinkAdaptation']]], ['linkadaptation_2ecpp',['LinkAdaptation.cpp',['../_link_adaptation_8cpp.html',1,'']]], ['linkadaptation_2eh',['LinkAdaptation.h',['../_link_adaptation_8h.html',1,'']]], ['linkadaptation_5f',['linkAdaptation_',['../class_scheduler_1_1_scheduling_algorithm.html#aa0a3c32bce2ae7fc5025b6320dc30d00',1,'Scheduler::SchedulingAlgorithm::linkAdaptation_()'],['../class_simulation_1_1_simulation.html#a6aba5f5b0b14d6eaad13369fa2ff5533',1,'Simulation::Simulation::linkAdaptation_()']]], ['linkadaptationparameters',['LinkAdaptationParameters',['../class_parameters_1_1_link_adaptation_parameters.html',1,'Parameters']]], ['linkadaptationparameters_2ecpp',['LinkAdaptationParameters.cpp',['../_link_adaptation_parameters_8cpp.html',1,'']]], ['linkadaptationparameters_2eh',['LinkAdaptationParameters.h',['../_link_adaptation_parameters_8h.html',1,'']]], ['linkedusers_5f',['linkedUsers_',['../class_physical_node_1_1_e_node_b.html#a1e09f6288a4ffe76b809e31dbd7c8fa9',1,'PhysicalNode::ENodeB']]] ];
JavaScript
var searchData= [ ['operator_2b',['operator+',['../class_basic_1_1_position.html#a6004db73e0d762f72a911a17eaf8ef20',1,'Basic::Position']]], ['operator_3c_3c',['operator<<',['../class_basic_1_1_position.html#a14d89ec2c15e82ce10902fcd138637f4',1,'Basic::Position']]], ['orientation_5f',['orientation_',['../class_physical_node_1_1_device.html#ae6dfc34ae592db3db237bfe9fc9d89ed',1,'PhysicalNode::Device']]] ];
JavaScript
var searchData= [ ['effectivebits_5f',['effectiveBits_',['../class_physical_layer_1_1_resource_element.html#ab896af9f43b9397c201643fa92121ca2',1,'PhysicalLayer::ResourceElement::effectiveBits_()'],['../class_physical_node_1_1_physical_node.html#a6e345a627bd97ee2b4597a5ddf227578',1,'PhysicalNode::PhysicalNode::effectiveBits_()']]], ['enodebid_5f',['eNodeBId_',['../class_physical_node_1_1_user.html#a5b5b3de0e7f6d9aa22c3cd5dfb665005',1,'PhysicalNode::User']]] ];
JavaScript
var searchData= [ ['hasresolutionstepchanged',['hasResolutionStepChanged',['../class_time_manager_1_1_time_manager.html#aac0d7fa5bbb2d937cc357122f1e906ea',1,'TimeManager::TimeManager']]] ];
JavaScript
var searchData= [ ['user',['User',['../class_physical_node_1_1_user.html',1,'PhysicalNode']]], ['userparameters',['UserParameters',['../class_parameters_1_1_user_parameters.html',1,'Parameters']]] ];
JavaScript
var searchData= [ ['genericantenna',['GenericAntenna',['../class_physical_node_1_1_generic_antenna.html',1,'PhysicalNode']]], ['grid',['Grid',['../class_grid_1_1_grid.html',1,'Grid']]], ['gridparameters',['GridParameters',['../class_parameters_1_1_grid_parameters.html',1,'Parameters']]] ];
JavaScript
var searchData= [ ['x',['x',['../class_basic_1_1_position.html#acf7520d40b7a067e36dff0663903d122',1,'Basic::Position::x()'],['../class_basic_1_1_position.html#a31a9dbb2158bec0e7b3c51d6c00effc8',1,'Basic::Position::x(double x_arg)']]], ['xy',['xy',['../class_basic_1_1_position.html#afe01f5a63a7cd0d4af4180b30d57588a',1,'Basic::Position']]] ];
JavaScript
var searchData= [ ['timemanager',['TimeManager',['../namespace_time_manager.html',1,'']]], ['transmission',['Transmission',['../namespace_transmission.html',1,'']]] ];
JavaScript
// ==UserScript== // @name 4chan Cancer Vision // @namespace darkflames430 // @copyright 2012 darkflames430 <darkflames430@gmail.com> // @copyright 2011 Bento <mr_blank@bigfoot.com> // @description This blocks reasonable content. // @include http*://*.4chan.org/* // @version 0.4 // @license GNU GPL v2(MUST READ) <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html> // @updateURL https://4chan-chemo.googlecode.com/trunk/stable/4chan-chemo.user.js // ==/UserScript== var spamindex = "https://4chan-chemo.googlecode.com/svn/trunk/spam_index.txt"; GM_xmlhttpRequest({ method: "GET", url: spamindex, onload: function(resp) { parse(resp.responseText); } }); function parse(spam) { spam = spam.split(",") console.log(spam); var posts = document.getElementsByTagName("blockquote"), post, pInner; for(var i = posts.length - 1; i >=0; --i) { post = posts[i]; pInner = post.innerHTML; for(var a = spam.length - 1; a >= 0; --a) if(pInner.toLowerCase().indexOf(spam[a]) == 0) { post.title = post.textContent; post.innerHTML = '<span class="spoiler">' + post.innerHTML + "</span></br>{Cancer detected: " + spam[a] + ", post was deleted, roll over to read the blocked content}"; break; } } }
JavaScript
// ==UserScript== // @name 4chan Chemo // @namespace darkflames430 // @copyright 2012 darkflames430 <darkflames430@gmail.com> // @copyright 2011 Bento <mr_blank@bigfoot.com> // @description This blocks cancerous content. // @include http*://*.4chan.org/* // @version 0.4 // @license GNU GPL v2(MUST READ) <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html> // @updateURL https://4chan-chemo.googlecode.com/trunk/stable/4chan-chemo.user.js // ==/UserScript== var spamindex = "https://4chan-chemo.googlecode.com/svn/trunk/spam_index.txt"; GM_xmlhttpRequest({ method: "GET", url: spamindex, onload: function(resp) { parse(resp.responseText); } }); function parse(spam) { spam = spam.split(",") console.log(spam); var posts = document.getElementsByTagName("blockquote"), post, pInner; for(var i = posts.length - 1; i >=0; --i) { post = posts[i]; pInner = post.innerHTML; for(var a = spam.length - 1; a >= 0; --a) if(pInner.toLowerCase().indexOf(spam[a]) >= 0) { post.title = post.textContent; post.innerHTML = '<span class="spoiler">' + post.innerHTML + "</span></br>{Cancer detected: " + spam[a] + ", post was deleted, roll over to read the blocked content}"; break; } } }
JavaScript
function create_menu(basepath) { var base = (basepath == 'null') ? '' : basepath; document.write( '<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' + '<td class="td" valign="top">' + '<ul>' + '<li><a href="'+base+'index.html">User Guide Home</a></li>' + '<li><a href="'+base+'toc.html">Table of Contents Page</a></li>' + '</ul>' + '<h3>Basic Info</h3>' + '<ul>' + '<li><a href="'+base+'general/requirements.html">Server Requirements</a></li>' + '<li><a href="'+base+'license.html">License Agreement</a></li>' + '<li><a href="'+base+'changelog.html">Change Log</a></li>' + '<li><a href="'+base+'general/credits.html">Credits</a></li>' + '</ul>' + '<h3>Installation</h3>' + '<ul>' + '<li><a href="'+base+'installation/downloads.html">Downloading CodeIgniter</a></li>' + '<li><a href="'+base+'installation/index.html">Installation Instructions</a></li>' + '<li><a href="'+base+'installation/upgrading.html">Upgrading from a Previous Version</a></li>' + '<li><a href="'+base+'installation/troubleshooting.html">Troubleshooting</a></li>' + '</ul>' + '<h3>Introduction</h3>' + '<ul>' + '<li><a href="'+base+'overview/getting_started.html">Getting Started</a></li>' + '<li><a href="'+base+'overview/at_a_glance.html">CodeIgniter at a Glance</a></li>' + '<li><a href="'+base+'overview/cheatsheets.html">CodeIgniter Cheatsheets</a></li>' + '<li><a href="'+base+'overview/features.html">Supported Features</a></li>' + '<li><a href="'+base+'overview/appflow.html">Application Flow Chart</a></li>' + '<li><a href="'+base+'overview/mvc.html">Model-View-Controller</a></li>' + '<li><a href="'+base+'overview/goals.html">Architectural Goals</a></li>' + '</ul>' + '<h3>Tutorial</h3>' + '<ul>' + '<li><a href="'+base+'tutorial/index.html">Introduction</a></li>' + '<li><a href="'+base+'tutorial/static_pages.html">Static pages</a></li>' + '<li><a href="'+base+'tutorial/news_section.html">News section</a></li>' + '<li><a href="'+base+'tutorial/create_news_items.html">Create news items</a></li>' + '<li><a href="'+base+'tutorial/conclusion.html">Conclusion</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>General Topics</h3>' + '<ul>' + '<li><a href="'+base+'general/urls.html">CodeIgniter URLs</a></li>' + '<li><a href="'+base+'general/controllers.html">Controllers</a></li>' + '<li><a href="'+base+'general/reserved_names.html">Reserved Names</a></li>' + '<li><a href="'+base+'general/views.html">Views</a></li>' + '<li><a href="'+base+'general/models.html">Models</a></li>' + '<li><a href="'+base+'general/helpers.html">Helpers</a></li>' + '<li><a href="'+base+'general/libraries.html">Using CodeIgniter Libraries</a></li>' + '<li><a href="'+base+'general/creating_libraries.html">Creating Your Own Libraries</a></li>' + '<li><a href="'+base+'general/drivers.html">Using CodeIgniter Drivers</a></li>' + '<li><a href="'+base+'general/creating_drivers.html">Creating Your Own Drivers</a></li>' + '<li><a href="'+base+'general/core_classes.html">Creating Core Classes</a></li>' + '<li><a href="'+base+'general/hooks.html">Hooks - Extending the Core</a></li>' + '<li><a href="'+base+'general/autoloader.html">Auto-loading Resources</a></li>' + '<li><a href="'+base+'general/common_functions.html">Common Functions</a></li>' + '<li><a href="'+base+'general/routing.html">URI Routing</a></li>' + '<li><a href="'+base+'general/errors.html">Error Handling</a></li>' + '<li><a href="'+base+'general/caching.html">Caching</a></li>' + '<li><a href="'+base+'general/profiling.html">Profiling Your Application</a></li>' + '<li><a href="'+base+'general/cli.html">Running via the CLI</a></li>' + '<li><a href="'+base+'general/managing_apps.html">Managing Applications</a></li>' + '<li><a href="'+base+'general/environments.html">Handling Multiple Environments</a></li>' + '<li><a href="'+base+'general/alternative_php.html">Alternative PHP Syntax</a></li>' + '<li><a href="'+base+'general/security.html">Security</a></li>' + '<li><a href="'+base+'general/styleguide.html">PHP Style Guide</a></li>' + '<li><a href="'+base+'doc_style/index.html">Writing Documentation</a></li>' + '</ul>' + '<h3>Additional Resources</h3>' + '<ul>' + '<li><a href="http://codeigniter.com/forums/">Community Forums</a></li>' + '<li><a href="http://codeigniter.com/wiki/">Community Wiki</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>Class Reference</h3>' + '<ul>' + '<li><a href="'+base+'libraries/benchmark.html">Benchmarking Class</a></li>' + '<li><a href="'+base+'libraries/calendar.html">Calendar Class</a></li>' + '<li><a href="'+base+'libraries/cart.html">Cart Class</a></li>' + '<li><a href="'+base+'libraries/config.html">Config Class</a></li>' + '<li><a href="'+base+'libraries/email.html">Email Class</a></li>' + '<li><a href="'+base+'libraries/encryption.html">Encryption Class</a></li>' + '<li><a href="'+base+'libraries/file_uploading.html">File Uploading Class</a></li>' + '<li><a href="'+base+'libraries/form_validation.html">Form Validation Class</a></li>' + '<li><a href="'+base+'libraries/ftp.html">FTP Class</a></li>' + '<li><a href="'+base+'libraries/table.html">HTML Table Class</a></li>' + '<li><a href="'+base+'libraries/image_lib.html">Image Manipulation Class</a></li>' + '<li><a href="'+base+'libraries/input.html">Input Class</a></li>' + '<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' + '<li><a href="'+base+'libraries/loader.html">Loader Class</a></li>' + '<li><a href="'+base+'libraries/language.html">Language Class</a></li>' + '<li><a href="'+base+'libraries/migration.html">Migration Class</a></li>' + '<li><a href="'+base+'libraries/output.html">Output Class</a></li>' + '<li><a href="'+base+'libraries/pagination.html">Pagination Class</a></li>' + '<li><a href="'+base+'libraries/security.html">Security Class</a></li>' + '<li><a href="'+base+'libraries/sessions.html">Session Class</a></li>' + '<li><a href="'+base+'libraries/trackback.html">Trackback Class</a></li>' + '<li><a href="'+base+'libraries/parser.html">Template Parser Class</a></li>' + '<li><a href="'+base+'libraries/typography.html">Typography Class</a></li>' + '<li><a href="'+base+'libraries/unit_testing.html">Unit Testing Class</a></li>' + '<li><a href="'+base+'libraries/uri.html">URI Class</a></li>' + '<li><a href="'+base+'libraries/user_agent.html">User Agent Class</a></li>' + '<li><a href="'+base+'libraries/xmlrpc.html">XML-RPC Class</a></li>' + '<li><a href="'+base+'libraries/zip.html">Zip Encoding Class</a></li>' + '</ul>' + '</td><td class="td_sep" valign="top">' + '<h3>Driver Reference</h3>' + '<ul>' + '<li><a href="'+base+'libraries/caching.html">Caching Class</a></li>' + '<li><a href="'+base+'database/index.html">Database Class</a></li>' + '<li><a href="'+base+'libraries/javascript.html">Javascript Class</a></li>' + '</ul>' + '<h3>Helper Reference</h3>' + '<ul>' + '<li><a href="'+base+'helpers/array_helper.html">Array Helper</a></li>' + '<li><a href="'+base+'helpers/captcha_helper.html">CAPTCHA Helper</a></li>' + '<li><a href="'+base+'helpers/cookie_helper.html">Cookie Helper</a></li>' + '<li><a href="'+base+'helpers/date_helper.html">Date Helper</a></li>' + '<li><a href="'+base+'helpers/directory_helper.html">Directory Helper</a></li>' + '<li><a href="'+base+'helpers/download_helper.html">Download Helper</a></li>' + '<li><a href="'+base+'helpers/email_helper.html">Email Helper</a></li>' + '<li><a href="'+base+'helpers/file_helper.html">File Helper</a></li>' + '<li><a href="'+base+'helpers/form_helper.html">Form Helper</a></li>' + '<li><a href="'+base+'helpers/html_helper.html">HTML Helper</a></li>' + '<li><a href="'+base+'helpers/inflector_helper.html">Inflector Helper</a></li>' + '<li><a href="'+base+'helpers/language_helper.html">Language Helper</a></li>' + '<li><a href="'+base+'helpers/number_helper.html">Number Helper</a></li>' + '<li><a href="'+base+'helpers/path_helper.html">Path Helper</a></li>' + '<li><a href="'+base+'helpers/security_helper.html">Security Helper</a></li>' + '<li><a href="'+base+'helpers/smiley_helper.html">Smiley Helper</a></li>' + '<li><a href="'+base+'helpers/string_helper.html">String Helper</a></li>' + '<li><a href="'+base+'helpers/text_helper.html">Text Helper</a></li>' + '<li><a href="'+base+'helpers/typography_helper.html">Typography Helper</a></li>' + '<li><a href="'+base+'helpers/url_helper.html">URL Helper</a></li>' + '<li><a href="'+base+'helpers/xml_helper.html">XML Helper</a></li>' + '</ul>' + '</td></tr></table>'); }
JavaScript
/* moo.fx, simple effects library built with prototype.js (http://prototype.conio.net). by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE. for more info (http://moofx.mad4milk.net). 10/24/2005 v(1.0.2) */ //base var fx = new Object(); fx.Base = function(){}; fx.Base.prototype = { setOptions: function(options) { this.options = { duration: 500, onComplete: '' } Object.extend(this.options, options || {}); }, go: function() { this.duration = this.options.duration; this.startTime = (new Date).getTime(); this.timer = setInterval (this.step.bind(this), 13); }, step: function() { var time = (new Date).getTime(); var Tpos = (time - this.startTime) / (this.duration); if (time >= this.duration+this.startTime) { this.now = this.to; clearInterval (this.timer); this.timer = null; if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10); } else { this.now = ((-Math.cos(Tpos*Math.PI)/2) + 0.5) * (this.to-this.from) + this.from; //this time-position, sinoidal transition thing is from script.aculo.us } this.increase(); }, custom: function(from, to) { if (this.timer != null) return; this.from = from; this.to = to; this.go(); }, hide: function() { this.now = 0; this.increase(); }, clearTimer: function() { clearInterval(this.timer); this.timer = null; } } //stretchers fx.Layout = Class.create(); fx.Layout.prototype = Object.extend(new fx.Base(), { initialize: function(el, options) { this.el = $(el); this.el.style.overflow = "hidden"; this.el.iniWidth = this.el.offsetWidth; this.el.iniHeight = this.el.offsetHeight; this.setOptions(options); } }); fx.Height = Class.create(); Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), { increase: function() { this.el.style.height = this.now + "px"; }, toggle: function() { if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0); else this.custom(0, this.el.scrollHeight); } });
JavaScript
window.onload = function() { myHeight = new fx.Height('nav', {duration: 400}); myHeight.hide(); }
JavaScript
function get_curOnline() { $.ajax({ url: base + 'index.php/play_durak/get_file', data: "", dataType: 'json', success: function(data) { if(data.length == 0) { $('#onlineList')[0].innerHTML = '<th>No Online Found</th>' ; } else { $('#onlineList')[0].innerHTML = '<th>Online</th>' + '<th id="stat">Status</th>' ; for(var x=0; x < data.length; x++) { $('#onlineList')[0].innerHTML += '<tr>' + '<td>' + data[x]['fname'] + ' '+ data[x]['lname'] + '</td>' + '<td>' + '<a href=#>Play</a>'+ '</td>' + '</tr>' ; } } } }); } $(document).ready(function() { $.ajaxSetup({ cache: false }); setInterval(function() { get_curOnline(); }, 1000); });
JavaScript
function addEvent( obj, evType, fn, useCapture ) { if ( obj.addEventListener ) { obj.addEventListener(evType, fn, useCapture); return true; } else if ( obj.attachEvent ) { var r = obj.attachEvent("on" + evType, fn); return r; } return false; } function removeEvent( obj, evType, fn, useCapture ) { if ( obj.removeEventListener ) { obj.removeEventListener(evType, fn, useCapture); return true; } else if ( obj.detachEvent ) { var r = obj.detachEvent("on" + evType, fn); return r; } return false; } function $( id ) { return document.getElementById(id); } function $new( tag ) { return document.createElement(tag); } var Tetris = { version : '0.5', div : null, divNext : null, divScreen : null, iframe : null, running : false, initSuccess : false, gameOver : false, bricksWidth : 11, bricksHeight : 21, level : 0, levelLabel : null, // levels : [0, 500, 1200, 2100, 3300, 4800, 6800, 9500, 13000, 18000, 25000], lives : 1, livesLabel : null, points : 0, pointsLabel : null, lines : 0, linesLabel : null, current : null, next : null, ghost : null, // Will never start with S, Z, O history : [0, 1, 2], nextForce : [], // Config Values rotateClockwise : 1, randomBrickColors : 0, stackPieces : 0, useGhost : 0, // bricksMap : [], bricks : [ [ // ## // ## { w : 2, h : 2, m : [[1, 1], [1, 1]], n : 'cuadrado', i : 0 } ], [ // ## // ## { w : 3, h : 2, m : [[0, 1, 1], [1, 1, 0]], n : 'escalera right', i : 1 }, // # // ## // # { w : 2, h : 3, m : [[1, 0], [1, 1], [0, 1]], n : 'escalera rayo right', i : 1 } ], [ // ## // ## { w : 3, h : 2, m : [[1, 1, 0], [0, 1, 1]], n : 'escalera left', i : 2 }, // # // ## // # { w : 2, h : 3, m : [[0, 1], [1, 1], [1, 0]], n : 'escalera rayo left', i : 2 } ], [ // # // ### { w : 3, h : 2, m : [[0, 1, 0], [1, 1, 1]], n : 'monumento up', i : 3 }, // # // ## // # { w : 2, h : 3, m : [[1, 0], [1, 1], [1, 0]], n : 'monumento right', i : 3 }, // ### // # { w : 3, h : 2, m : [[1, 1, 1], [0, 1, 0]], n : 'monumento down', i : 3 }, // # // ## // # { w : 2, h : 3, m : [[0, 1], [1, 1], [0, 1]], n : 'monumento left', i : 3 } ], [ // # // # // # // # { w : 1, h : 4, m : [[1], [1], [1], [1]], n : 'palito', i : 4 }, // #### { w : 4, h : 1, m : [[1, 1, 1, 1]], n : 'palito acostado', i : 4 } ], [ // ## // # // # { w : 2, h : 3, m : [[1, 1], [0, 1], [0, 1]], n : 'ele left', i : 5 }, // # // ### { w : 3, h : 2, m : [[0, 0, 1], [1, 1, 1]], n : 'ele up', i : 5 }, // # // # // ## { w : 2, h : 3, m : [[1, 0], [1, 0], [1, 1]], n : 'ele right', i : 5 }, // ### // # { w : 3, h : 2, m : [[1, 1, 1], [1, 0, 0]], n : 'ele down', i : 5 } ], [ // ## // # // # { w : 2, h : 3, m : [[1, 1], [1, 0], [1, 0]], n : 'contra-ele right', i : 6 }, // ### // # { w : 3, h : 2, m : [[1, 1, 1], [0, 0, 1]], n : 'contra-ele down', i : 6 }, // # // # // ## { w : 2, h : 3, m : [[0, 1], [0, 1], [1, 1]], n : 'contra-ele left', i : 6 }, // # // ### { w : 3, h : 2, m : [[1, 0, 0], [1, 1, 1]], n : 'contra-ele up', i : 6 } ] ], options : { divId : 'tetris', divNextId : 'next', divScreenId : 'screen', divScreenTitleId : 'title', divScreenMessageId : 'message', divScreenScoreId : 'score', divScreenConfigId : 'configure', labelLevel : 'level', labelLives : 'lives', labelPoints : 'points', labelLines : 'lines', brickImage : 'img/brick', brickImageExt : 'gif' }, constructor : function() { document.title = '4Bricks v' + Tetris.version; Tetris.div = $(Tetris.options.divId); Tetris.divNext = $(Tetris.options.divNextId); Tetris.divScreen = $(Tetris.options.divScreenId); Tetris.divScreen.heading = $(Tetris.options.divScreenTitleId); Tetris.divScreen.message = $(Tetris.options.divScreenMessageId); Tetris.divScreen.scoring = $(Tetris.options.divScreenScoreId); Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf = $(Tetris.options.divScreenConfigId); Tetris.divScreen.conf.style.display = 'none'; Tetris.levelLabel = $(Tetris.options.labelLevel); Tetris.livesLabel = $(Tetris.options.labelLives); Tetris.pointsLabel = $(Tetris.options.labelPoints); Tetris.linesLabel = $(Tetris.options.labelLines); addEvent( $('start'), 'click', Tetris.start, true ); addEvent( $('stop'), 'click', Tetris.stop, true ); addEvent( $('restart'), 'click', Tetris.restart, true ); addEvent( $('config'), 'click', Tetris.viewConfig, true ); addEvent( $('scores'), 'click', Tetris.viewScores, true ); addEvent( $('about'), 'click', Tetris.about, true ); // Config Checkboxs addEvent( $('gr'), 'click', Tetris.changeBackground, true ); addEvent( $('rt'), 'click', Tetris.changeRotateDirection, true ); addEvent( $('cl'), 'click', Tetris.changeRandomBrickColors, true ); addEvent( $('st'), 'click', Tetris.changeStackPieces, true ); addEvent( $('gs'), 'click', Tetris.changeGhost, true ); $('gr').checked = 'checked'; $('rt').checked = 'checked'; $('cl').checked = ''; $('st').checked = ''; $('gs').checked = ''; addEvent(document, 'keypress', Tetris.keyPress, true); addEvent(document, 'keyup', Tetris.keyUp, true); Tetris.init(); }, init : function() { // // Tetris.bricksMap = [] // // for ( var i = 0, h = ( Tetris.div.clientHeight / 16 ); i < h; i++ ) // { // if ( typeof Tetris.bricksMap[i] == 'undefined' ) // Tetris.bricksMap[i] = [] // // for ( var e = 0, w = ( Tetris.div.clientWidth / 16 ); e < w; e++ ) // Tetris.bricksMap[i][e] = 0; // } // }, changeBackground : function() { if ( Tetris.div.style.backgroundImage == 'none' ) Tetris.div.style.backgroundImage = ''; else Tetris.div.style.backgroundImage = 'none'; }, changeRotateDirection : function() { Tetris.rotateClockwise = ( Tetris.rotateClockwise == 1 ) ? 0 : 1; }, changeRandomBrickColors : function() { Tetris.randomBrickColors = ( Tetris.randomBrickColors == 1 ) ? 0 : 1; }, changeStackPieces : function() { Tetris.stackPieces = ( Tetris.stackPieces == 1 ) ? 0 : 1; }, changeGhost : function() { Tetris.useGhost = ( Tetris.useGhost == 1 ) ? 0 : 1; }, randomBrick : function() { // // var rand = parseInt( Math.random() * 7 ); // // while ( typeof Tetris.bricks[rand][0] == 'undefined' ) // rand = parseInt( Math.random() * 7 ); // var rand = 0; var found = true; while ( found ) { rand = parseInt( Math.random() * 7 ); found = false; for ( var p in Tetris.history ) if ( Tetris.history[p] == rand ) found = true; if ( !( found ) ) break; } // console.log(rand + ( found ? ' found' : ' not found' ) + ' in ' + Tetris.history); Tetris.history.pop(); Tetris.history.unshift(rand); return Tetris.bricks[rand][0]; }, createBrickImages : function( next ) { var brickImages = [] // var rand = parseInt( Math.random() * Tetris.options.brickImageCount ); if ( next ) Tetris.divNext.innerHTML = ''; for ( var i = 0; i < 4; i++ ) { var img = $new('img'); // img.id = 'brick[' + i + ']'; // img.src = Tetris.options.brickImage + rand + '.' + Tetris.options.brickImageExt; img.style.display = 'none'; img.style.position = 'absolute'; if ( next ) Tetris.divNext.appendChild(img); else Tetris.div.appendChild(img); brickImages.push(img); } return brickImages; }, createBrick : function( next, brickNum ) { if ( next ) { Tetris.next = { images : Tetris.createBrickImages(true), def : Tetris.randomBrick() } Tetris.posBrick(Tetris.next, 1, 1, true); } else { if ( brickNum != null && parseInt(brickNum) >= 0 ) var inDef = Tetris.bricks[brickNum][0]; else var inDef = Tetris.randomBrick(); Tetris.current = { images : Tetris.createBrickImages(), def : inDef, x : 0, y : 0, r : 0 } Tetris.posBrick(Tetris.current, ( 5 - parseInt(Tetris.current.def.w / 2) ), 0); if ( Tetris.useGhost == 1 ) { Tetris.ghost = { images : Tetris.createBrickImages(), def : inDef, ghost : true, x : Tetris.current.x, y : 0, r : 0 } Tetris.posBrick(Tetris.ghost, Tetris.current.x, Tetris.current.y); Tetris.dropBrick(Tetris.ghost, true); } } }, posBrick : function( brick, x, y, next ) { if ( brick ) { var currentImage = 0; var realX = ( x * 16 ); var realY = ( y * 16 ); var rand = brick.def.i; brick.x = x; brick.y = y; if ( Tetris.randomBrickColors == 1 ) rand = parseInt( Math.random() * 7 ); for ( var i = 0, h = brick.def.h; i < h; i++ ) { for ( var e = 0, w = brick.def.w; e < w; e++ ) { var bool = brick.def.m[i][e]; // alert('n:' + brick.def.n + '; i:' + i + '; e:' + e + '; m: ' + brick.def.m[i][e]); if ( bool == 1 ) { var posX = realX + ( e * 16 ); var posY = realY + ( i * 16 ); // if ( !( next ) ) // Tetris.bricksMap[y + i][x + e] = 1; var ghost = ( Tetris.useGhost == 1 && brick.ghost ) ? 'ghost' : ''; // if ( Tetris.randomBrickColors == 1 ) brick.images[currentImage].src = Tetris.options.brickImage + rand + ghost + '.' + Tetris.options.brickImageExt; // else // brick.images[currentImage].src = Tetris.options.brickImage + brick.def.i + '.' // + Tetris.options.brickImageExt; brick.images[currentImage].style.display = 'block'; brick.images[currentImage].style.position = 'absolute'; brick.images[currentImage].style.left = posX + 'px'; brick.images[currentImage].posX = parseInt(x + e); if ( y != -1 ) { brick.images[currentImage].style.top = posY + 'px'; brick.images[currentImage].posY = parseInt(y + i); } if ( next ) brick.images[currentImage].id = 'brickNext[' + currentImage + ']'; else brick.images[currentImage].id = 'brick[' + parseInt(y + i) + '][' + parseInt(x + e) + ']'; currentImage++; } } } } }, dropBrick : function( brick, ghost ) { if ( brick ) { while ( ( brick.y * 16 ) <= Tetris.div.clientHeight - ( brick.def.h * 16 ) ) { if ( Tetris.crash(brick) ) break; if ( !( ghost ) ) Tetris.points += 2; Tetris.moveDown(brick, ghost); } return brick.y; } return 0; }, crash : function( brick ) { // if ( typeof Tetris.bricksMap[brick.y + brick.def.h] == 'undefined' ) // return true; if ( parseInt(brick.y + brick.def.h) * 16 >= Tetris.div.clientHeight ) return true; var toCheck = [] for ( var e = 0, w = brick.def.w; e < w; e++ ) { var lastVertical = null; for ( var i = 0, h = brick.def.h; i < h; i++ ) { for ( var r = 0; r < 4; r++ ) { if ( brick.images[r].posY == brick.y + i && brick.images[r].posX == brick.x + e ) lastVertical = brick.images[r]; } } if ( lastVertical != null ) toCheck.push(lastVertical); } for ( var w = 0, l = toCheck.length; w < l; w++ ) { var brickDown = $('brick[' + parseInt(toCheck[w].posY + 1) + '][' + toCheck[w].posX + ']'); // if ( Tetris.bricksMap[toCheck[w].posY + 1][toCheck[w].posX] == 1 || ( typeof brickDown != 'undefined' && brickDown != null && brickDown.tagName.toLowerCase() == 'img' ) ) if ( typeof brickDown != 'undefined' && brickDown != null && brickDown.tagName.toLowerCase() == 'img' ) { // alert('bricks[' + parseInt(toCheck[w].posY + 1) + '][' + toCheck[w].posX + ']'); // alert('x:' + toCheck[w].posX + '; y:' + toCheck[w].posY); if ( brickDown.src.indexOf('ghost') == -1 ) return true; } } return false; }, crashLeft : function( brick ) { if ( brick.x <= 0 ) return true; var toCheck = [] for ( var i = 0, h = brick.def.h; i < h; i++ ) { var firstHoriz = null; var found = false; for ( var e = 0, w = brick.def.w; e < w; e++ ) { if ( found ) break; for ( var r = 0; r < 4; r++ ) { if ( brick.images[r].posY == brick.y + i && brick.images[r].posX == brick.x + e ) { firstHoriz = brick.images[r]; found = true; break; } } } toCheck.push(firstHoriz); } for ( var w = 0, l = toCheck.length; w < l; w++ ) { var brickLeft = $('brick[' + toCheck[w].posY + '][' + parseInt(toCheck[w].posX - 1) + ']'); // if ( Tetris.bricksMap[toCheck[w].posY][toCheck[w].posX - 1] == 1 || ( typeof brickLeft != 'undefined' && brickLeft != null && brickLeft.tagName.toLowerCase() == 'img' ) ) if ( typeof brickLeft != 'undefined' && brickLeft != null && brickLeft.tagName.toLowerCase() == 'img' ) return true; } return false; }, crashRight : function( brick ) { if ( ( brick.x + brick.def.w ) * 16 >= Tetris.div.clientWidth ) return true; var toCheck = [] for ( var i = 0, h = brick.def.h; i < h; i++ ) { var lastHoriz = null; for ( var e = 0, w = brick.def.w; e < w; e++ ) { for ( var r = 0; r < 4; r++ ) { if ( brick.images[r].posY == brick.y + i && brick.images[r].posX == brick.x + e ) lastHoriz = brick.images[r]; } } toCheck.push(lastHoriz); } for ( var w = 0, l = toCheck.length; w < l; w++ ) { var brickRight = $('brick[' + toCheck[w].posY + '][' + parseInt(toCheck[w].posX + 1) + ']'); // if ( Tetris.bricksMap[toCheck[w].posY][toCheck[w].posX + 1] == 1 || ( typeof brickRight != 'undefined' && brickRight != null && brickRight.tagName.toLowerCase() == 'img' ) ) if ( typeof brickRight != 'undefined' && brickRight != null && brickRight.tagName.toLowerCase() == 'img' ) return true; } return false; }, crashRotate : function( brick ) { var i = brick.def.i; var nextBrick; if ( Tetris.bricks[i].length > 1 ) { if ( Tetris.rotateClockwise == 1 ) { if ( typeof Tetris.bricks[i][brick.r + 1] == 'undefined' ) nextBrick = Tetris.bricks[i][0]; else nextBrick = Tetris.bricks[i][brick.r + 1]; } else { if ( typeof Tetris.bricks[i][brick.r - 1] == 'undefined' ) nextBrick = Tetris.bricks[i][Tetris.bricks[i].length - 1]; else nextBrick = Tetris.bricks[i][brick.r - 1]; } if ( ( brick.x + nextBrick.w ) * 16 > Tetris.div.clientWidth ) { // Wall Kick !!! // Tetris.posBrick(brick, brick.x - 1, brick.y, false); if ( !( Tetris.crashLeft(Tetris.current) ) ) Tetris.moveHoriz(Tetris.current, -1); return true; } if ( ( brick.y + nextBrick.h ) * 16 > Tetris.div.clientHeight ) return true; } return false; }, moveDown : function( brick, ghost ) { brick.y++; for ( var i = 0; i < 4; i++ ) { // alert('x:' + brick.images[i].posX + '; y:' + brick.images[i].posY); // Tetris.bricksMap[brick.images[i].posY][brick.images[i].posX] = 0; // Tetris.bricksMap[brick.images[i].posY + 1][brick.images[i].posX] = 1; brick.images[i].posY++; brick.images[i].style.top = ( brick.images[i].posY * 16 ) + 'px'; brick.images[i].id = 'brick[' + brick.images[i].posY + '][' + brick.images[i].posX + ']'; // Tetris.bricksMap[brick.images[i].posY][brick.images[i].posX] = 1; // alert(brick.images[i].id + ' = ' + Tetris.bricksMap[brick.images[i].posY][brick.images[i].posX]); } // Tetris.points++; // Tetris.writeScore(); if ( Tetris.useGhost == 1 && Tetris.ghost && !( ghost ) ) if ( brick.y + brick.def.h > Tetris.ghost.y + 1 ) Tetris.removeGhost(); }, moveHoriz : function( brick, m ) { if ( typeof m == 'undefined' || m == null ) m = 1; var diff = 1 * m; brick.x += diff; for ( var i = 0; i < 4; i++ ) { // Tetris.bricksMap[brick.images[i].posY][brick.images[i].posX] = 0; // Tetris.bricksMap[brick.images[i].posY][brick.images[i].posX + diff] = 1; brick.images[i].posX += diff; brick.images[i].style.left = ( brick.images[i].posX * 16 ) + 'px'; brick.images[i].id = 'brick[' + brick.images[i].posY + '][' + brick.images[i].posX + ']'; // Tetris.bricksMap[brick.images[i].posY][brick.images[i].posX] = 1; } if ( Tetris.useGhost == 1 && Tetris.ghost ) { Tetris.posBrick(Tetris.ghost, brick.x, brick.y + brick.def.h); Tetris.dropBrick(Tetris.ghost, true); } }, rotate : function( brick ) { var i = brick.def.i; var x = brick.x, y = brick.y; if ( Tetris.bricks[i].length > 1 ) { if ( Tetris.rotateClockwise == 1 ) { if ( typeof Tetris.bricks[i][brick.r + 1] == 'undefined' ) brick.r = 0; else brick.r++; } else { if ( typeof Tetris.bricks[i][brick.r - 1] == 'undefined' ) brick.r = Tetris.bricks[i].length - 1; else brick.r--; } brick.def = Tetris.bricks[i][brick.r]; if ( Tetris.useGhost == 1 && Tetris.ghost ) Tetris.ghost.def = brick.def; Tetris.posBrick(brick, x, y); if ( Tetris.useGhost == 1 && Tetris.ghost ) { Tetris.posBrick(Tetris.ghost, x, y + brick.def.h); Tetris.dropBrick(Tetris.ghost, true); } } }, keyPress : function( event ) { var keyCode = ( event.which ) ? event.which : event.keyCode; var key = String.fromCharCode(keyCode).toLowerCase(); if ( Tetris.running ) { if ( key == 'p' ) Tetris.stop(); else if ( keyCode == event.DOM_VK_SPACE ) Tetris.dropBrick(Tetris.current); else if ( keyCode == event.DOM_VK_LEFT || key == 'a' ) { if ( !( Tetris.crashLeft(Tetris.current) ) ) Tetris.moveHoriz(Tetris.current, -1); } else if ( keyCode == event.DOM_VK_UP || key == 'w' ) { if ( !( Tetris.crashRotate(Tetris.current) ) ) { // Tetris.points--; // Tetris.writeScore(); Tetris.rotate(Tetris.current); } } else if ( keyCode == event.DOM_VK_RIGHT || key == 'd' ) { if ( !( Tetris.crashRight(Tetris.current) ) ) Tetris.moveHoriz(Tetris.current, 1); } else if ( keyCode == event.DOM_VK_DOWN || key == 's' ) { if ( !( Tetris.crash(Tetris.current) ) ) { Tetris.points++; Tetris.writeScore(); Tetris.moveDown(Tetris.current); } } } else if ( key == 'p' ) { if ( Tetris.initSuccess ) Tetris.start(); } }, keyUp : function() { if ( Tetris.running ) { // Nothing } }, removeGhost : function() { if ( Tetris.ghost ) { if ( Tetris.ghost.images.length > 0 ) { for ( var i = 0, l = Tetris.ghost.images.length; i < l; i++ ) { if ( typeof Tetris.ghost.images[i] != 'undefined' ) Tetris.div.removeChild(Tetris.ghost.images[i]); } } Tetris.ghost = null; } }, removeLines : function( brick ) { var lines = 0; var linesPoints = 0; var linesPoints2 = 0; for ( var j = brick.y, l = brick.y + brick.def.h; j < l; j++ ) { var brickCount = 0; for ( var e = 0; e < Tetris.bricksWidth; e++ ) { var brickCurrent = $('brick[' + j + '][' + e + ']'); if ( typeof brickCurrent != 'undefined' && brickCurrent != null && brickCurrent.tagName.toLowerCase() == 'img' ) brickCount++; } if ( brickCount == Tetris.bricksWidth ) { var line = j; for ( var e = 0; e < Tetris.bricksWidth; e++ ) Tetris.div.removeChild( $('brick[' + line + '][' + e + ']') ); for ( var i = ( line - 1 ), w = 0; i > w; i-- ) { for ( var e = 0; e < Tetris.bricksWidth; e++ ) { var brickCurrent = $('brick[' + i + '][' + e + ']'); if ( typeof brickCurrent != 'undefined' && brickCurrent != null && brickCurrent.tagName.toLowerCase() == 'img' ) { brickCurrent.posY++; brickCurrent.style.top = ( brickCurrent.posY * 16 ) + 'px'; brickCurrent.id = 'brick[' + brickCurrent.posY + '][' + brickCurrent.posX + ']'; } } } lines++; linesPoints2 += Tetris.bricksHeight - ( brick.y + brick.def.h ); } } switch ( lines ) { case 0: linesPoints = 0; break; case 1: linesPoints = 40; break; case 2: linesPoints = 100; break; case 3: linesPoints = 300; break; case 4: linesPoints = 1200; break; } // Tetris.points += ( 100 * lines * lines ); Tetris.points += linesPoints * ( Tetris.level + 1 + linesPoints2 ); Tetris.lines += lines; Tetris.writeScore(); }, writeScore : function() { if ( Tetris.initSuccess ) { // // if ( typeof Tetris.levels[Tetris.level + 1] != 'undefined' ) // { // if ( Tetris.points > Tetris.levels[Tetris.level + 1] ) // { // Tetris.level++; // Tetris.points += 5 * Tetris.level; // } // } // var l = parseInt(Tetris.lines / 10); if ( ( l > Tetris.level ) && ( l <= 10 ) ) { Tetris.level = l; Tetris.points += 5 * l; } Tetris.levelLabel.innerHTML = 'level ' + Tetris.level; Tetris.livesLabel.innerHTML = 'lives: ' + Tetris.lives; Tetris.pointsLabel.innerHTML = 'points: ' + Tetris.points; Tetris.linesLabel.innerHTML = 'lines: ' + Tetris.lines; } else { Tetris.levelLabel.innerHTML = '&nbsp;'; Tetris.livesLabel.innerHTML = '&nbsp;'; Tetris.pointsLabel.innerHTML = '&nbsp;'; Tetris.linesLabel.innerHTML = '&nbsp;'; } }, start : function() { if ( Tetris.gameOver ) return; if ( Tetris.iframe ) { document.body.removeChild(Tetris.iframe); Tetris.iframe = null; } if ( !( Tetris.running ) ) { if ( !( Tetris.initSuccess ) ) { Tetris.init(); Tetris.createBrick(); Tetris.createBrick(true); } Tetris.div.className = ''; Tetris.divScreen.style.display = 'none'; Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf.style.display = 'none'; Tetris.initSuccess = true; Tetris.running = true; Tetris.writeScore(); Tetris.redraw(); } }, stop : function() { if ( Tetris.gameOver ) return; if ( Tetris.iframe ) { document.body.removeChild(Tetris.iframe); Tetris.iframe = null; } Tetris.running = false; Tetris.div.className = 'pause'; Tetris.divScreen.style.display = ''; Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf.style.display = 'none'; Tetris.divScreen.heading.innerHTML = 'Pause'; Tetris.divScreen.message.innerHTML = 'press start to continue'; }, restart : function( ) { if ( Tetris.iframe ) { document.body.removeChild(Tetris.iframe); Tetris.iframe = null; } Tetris.div.innerHTML = ''; Tetris.div.className = ''; Tetris.divNext.innerHTML = ''; Tetris.divScreen.style.display = ''; Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf.style.display = 'none'; Tetris.divScreen.heading.innerHTML = 'Welcome to 4Bricks'; Tetris.divScreen.message.innerHTML = '&nbsp;'; Tetris.initSuccess = false; Tetris.running = false; Tetris.current = null; Tetris.next = null; Tetris.ghost = null; Tetris.history = [0, 1, 2]; Tetris.level = 0; Tetris.lives = 1; Tetris.points = 0; Tetris.lines = 0; Tetris.writeScore(); Tetris.gameOver = false; // Tetris.start(); }, viewConfig : function() { if ( Tetris.iframe ) { document.body.removeChild(Tetris.iframe); Tetris.iframe = null; } Tetris.stop(); Tetris.divScreen.style.display = ''; Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf.style.display = ''; Tetris.divScreen.heading.innerHTML = 'Configure'; Tetris.divScreen.message.innerHTML = '&nbsp;'; }, viewScores : function() { if ( Tetris.iframe ) { document.body.removeChild(Tetris.iframe); Tetris.iframe = null; } Tetris.stop(); Tetris.iframe = $new('iframe'); Tetris.iframe.src = 'score.php'; document.body.appendChild(Tetris.iframe); }, about : function() { if ( Tetris.iframe ) { document.body.removeChild(Tetris.iframe); Tetris.iframe = null; } Tetris.stop(); Tetris.divScreen.style.display = ''; Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf.style.display = 'none'; Tetris.divScreen.heading.innerHTML = 'About'; Tetris.divScreen.message.innerHTML = 'by <a href="mailto:joksnet@gmail.com">joksnet@gmail.com</a>'; }, redraw : function() { if ( Tetris.running ) { if ( Tetris.crash(Tetris.current) ) { if ( Tetris.useGhost == 1 && Tetris.ghost ) Tetris.removeGhost(); Tetris.removeLines(Tetris.current); if ( Tetris.current.y == 0 ) { Tetris.lives--; Tetris.writeScore(); // Tetris.stop(); if ( Tetris.lives == 0 ) { Tetris.stop(); Tetris.gameOver = true; Tetris.divScreen.style.display = ''; Tetris.divScreen.scoring.style.display = ''; Tetris.divScreen.conf.style.display = 'none'; Tetris.divScreen.heading.innerHTML = 'Game Over'; Tetris.divScreen.message.innerHTML = 'press restart or submit your score'; var elementPoints = null; var elementName = null; var elementSubmit = null; // for ( var i in Tetris.divScreen.scoring.childNodes ) for ( var i = 0, l = Tetris.divScreen.scoring.childNodes.length; i < l; i++ ) { var element = Tetris.divScreen.scoring.childNodes[i]; if ( typeof element != 'undefined' && element != null && element.nodeType == 1 ) { if ( element.tagName.toLowerCase() == 'h3' ) elementPoints = element; else if ( element.tagName.toLowerCase() == 'input' ) { if ( elementName ) elementSubmit = element; else elementName = element; } } } // IE Fix if ( Tetris.divScreen.conf.style.display == '' ) Tetris.divScreen.conf.style.display = 'none'; if ( elementPoints && elementName && elementSubmit ) { elementPoints.innerHTML = Tetris.points; elementName.value = ''; elementSubmit.onclick = function() { Tetris.iframe = $new('iframe'); Tetris.iframe.src = 'score.php?n=' + elementName.value + '&p=' + Tetris.points; document.body.appendChild(Tetris.iframe); } } } else { Tetris.div.innerHTML = ''; Tetris.div.className = ''; Tetris.divNext.innerHTML = ''; Tetris.divScreen.style.display = ''; Tetris.divScreen.scoring.style.display = 'none'; Tetris.divScreen.conf.style.display = 'none'; Tetris.divScreen.heading.innerHTML = 'Pause'; Tetris.divScreen.message.innerHTML = 'you loose one life, press start to continue'; Tetris.initSuccess = false; Tetris.running = false; } return; } if ( Tetris.stackPieces == 1 ) { if ( Tetris.current.images.length > 0 ) { for ( var i = 0, l = Tetris.current.images.length; i < l; i++ ) { if ( typeof Tetris.current.images[i] != 'undefined' ) Tetris.current.images[i].src = Tetris.current.images[i].src.replace(/.gif/, 'stack.gif'); } } } if ( typeof Tetris.next != 'undefined' && Tetris.next != null ) Tetris.createBrick(false, Tetris.next.def.i); else Tetris.createBrick(); if ( Tetris.nextForce.length > 0 ) Tetris.createBrick(false, Tetris.nextForce.unshift()); else Tetris.createBrick(true); } else Tetris.moveDown(Tetris.current); if ( Tetris.running ) setTimeout(Tetris.redraw, ( ( 10 - Tetris.level ) * 50 ) + 50); } } } addEvent(window, 'load', Tetris.constructor, true);
JavaScript
// Copyright (c) 2008 Yahoo! Inc. All rights reserved. // Licensed under the Yahoo! Search BOSS Terms of Use // (http://info.yahoo.com/legal/us/yahoo/search/bosstos/bosstos-2317.html) // An XHR DataSource var myServer = "suggest"; var mySchema = ["Results", "v"]; var myDataSource = new YAHOO.widget.DS_XHR(myServer, mySchema); // ...or configure the response type to be JSON (default) myDataSource.responseType = YAHOO.widget.DS_XHR.TYPE_JSON; myDataSource.scriptQueryParam = "q"; var myAutoComp = new YAHOO.widget.AutoComplete("myInput", "myContainer", myDataSource); // Container will expand and collapse vertically myAutoComp.animVert = true; // Require user to type at least 3 characters before triggering a query myAutoComp.minQueryLength = 3; // Disable type ahead myAutoComp.typeAhead = false; myAutoComp.autoHighlight = false; // Submit button var oButton = new YAHOO.widget.Button( "searchbutton", { type: "submit", label: "Search" });
JavaScript
// Copyright 2012 Google Inc. /** * @name Store Locator for Google Maps API V3 * @version 0.1 * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * @license * * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Namespace for Store Locator. * @constructor */ var storeLocator = function() {}; window['storeLocator'] = storeLocator; /** * Convert from degrees to radians. * @private * @param {number} degrees the number in degrees. * @return {number} the number in radians. */ storeLocator.toRad_ = function(degrees) { return degrees * Math.PI / 180; };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Allows developers to specify a static set of stores to be used in the * storelocator. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A DataFeed with a static set of stores. Provides sorting of stores by * proximity and feature filtering (store must have <em>all</em> features from * the filter). * @example <pre> * var dataFeed = new storeLocator.StaticDataFeed(); * jQuery.getJSON('stores.json', function(json) { * var stores = parseStores(json); * dataFeed.setStores(stores); * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements {storeLocator.DataFeed} * @constructor * @implements storeLocator_StaticDataFeed */ storeLocator.StaticDataFeed = function() { /** * The static list of stores. * @private * @type {Array.<storeLocator.Store>} */ this.stores_ = []; }; storeLocator['StaticDataFeed'] = storeLocator.StaticDataFeed; /** * This will contain a callback to be called if getStores was called before * setStores (i.e. if the map is waiting for data from the data source). * @private * @type {Function} */ storeLocator.StaticDataFeed.prototype.firstCallback_; /** * Set the stores for this data feed. * @param {!Array.<!storeLocator.Store>} stores the stores for this data feed. */ storeLocator.StaticDataFeed.prototype.setStores = function(stores) { this.stores_ = stores; if (this.firstCallback_) { this.firstCallback_(); } else { delete this.firstCallback_; } }; /** * @inheritDoc */ storeLocator.StaticDataFeed.prototype.getStores = function(bounds, features, callback) { // Prevent race condition - if getStores is called before stores are loaded. if (!this.stores_.length) { var that = this; this.firstCallback_ = function() { that.getStores(bounds, features, callback); }; return; } // Filter stores for features. var stores = []; for (var i = 0, store; store = this.stores_[i]; i++) { if (store.hasAllFeatures(features)) { stores.push(store); } } this.sortByDistance_(bounds.getCenter(), stores); callback(stores); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.StaticDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Feature model class for Store Locator library. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Representation of a feature of a store. (e.g. 24 hours, BYO, etc). * @example <pre> * var feature = new storeLocator.Feature('24hour', 'Open 24 Hours'); * </pre> * @param {string} id unique identifier for this feature. * @param {string} name display name of this feature. * @constructor * @implements storeLocator_Feature */ storeLocator.Feature = function(id, name) { this.id_ = id; this.name_ = name; }; storeLocator['Feature'] = storeLocator.Feature; /** * Gets this Feature's ID. * @return {string} this feature's ID. */ storeLocator.Feature.prototype.getId = function() { return this.id_; }; /** * Gets this Feature's display name. * @return {string} this feature's display name. */ storeLocator.Feature.prototype.getDisplayName = function() { return this.name_; }; storeLocator.Feature.prototype.toString = function() { return this.getDisplayName(); };
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * An info panel, which complements the map view of the Store Locator. * Provides a list of stores, location search, feature filter, and directions. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * An info panel, to complement the map view. * Provides a list of stores, location search, feature filter, and directions. * @example <pre> * var container = document.getElementById('panel'); * var panel = new storeLocator.Panel(container, { * view: view, * locationSearchLabel: 'Location:' * }); * google.maps.event.addListener(panel, 'geocode', function(result) { * geocodeMarker.setPosition(result.geometry.location); * }); * </pre> * @extends {google.maps.MVCObject} * @param {!Node} el the element to contain this panel. * @param {storeLocator.PanelOptions} opt_options * @constructor * @implements storeLocator_Panel */ storeLocator.Panel = function(el, opt_options) { this.el_ = $(el); this.el_.addClass('storelocator-panel'); this.settings_ = $.extend({ 'locationSearch': true, 'locationSearchLabel': 'Where are you?', 'featureFilter': true, 'directions': true, 'view': null }, opt_options); this.directionsRenderer_ = new google.maps.DirectionsRenderer({ draggable: true }); this.directionsService_ = new google.maps.DirectionsService; this.init_(); }; storeLocator['Panel'] = storeLocator.Panel; storeLocator.Panel.prototype = new google.maps.MVCObject; /** * Initialise the info panel * @private */ storeLocator.Panel.prototype.init_ = function() { var that = this; this.itemCache_ = {}; if (this.settings_['view']) { this.set('view', this.settings_['view']); } this.filter_ = $('<form class="storelocator-filter"/>'); this.el_.append(this.filter_); if (this.settings_['locationSearch']) { this.locationSearch_ = $('<div class="location-search"><h4>' + this.settings_['locationSearchLabel'] + '</h4><input></div>'); this.filter_.append(this.locationSearch_); if (typeof google.maps.places != 'undefined') { this.initAutocomplete_(); } else { this.filter_.submit(function() { var search = $('input', that.locationSearch_).val(); that.searchPosition(/** @type {string} */(search)); }); } this.filter_.submit(function() { return false; }); google.maps.event.addListener(this, 'geocode', function(place) { if (!place.geometry) { that.searchPosition(place.name); return; } this.directionsFrom_ = place.geometry.location; if (that.directionsVisible_) { that.renderDirections_(); } var sl = that.get('view'); sl.highlight(null); var map = sl.getMap(); if (place.geometry.viewport) { map.fitBounds(place.geometry.viewport); } else { map.setCenter(place.geometry.location); map.setZoom(13); } sl.refreshView(); that.listenForStoresUpdate_(); }); } if (this.settings_['featureFilter']) { // TODO(cbro): update this on view_changed this.featureFilter_ = $('<div class="feature-filter"/>'); var allFeatures = this.get('view').getFeatures().asList(); for (var i = 0, ii = allFeatures.length; i < ii; i++) { var feature = allFeatures[i]; var checkbox = $('<input type="checkbox"/>'); checkbox.data('feature', feature); $('<label/>').append(checkbox).append(feature.getDisplayName()) .appendTo(this.featureFilter_); } this.filter_.append(this.featureFilter_); this.featureFilter_.find('input').change(function() { var feature = $(this).data('feature'); that.toggleFeatureFilter_(/** @type {storeLocator.Feature} */(feature)); that.get('view').refreshView(); }); } this.storeList_ = $('<ul class="store-list"/>'); this.el_.append(this.storeList_); if (this.settings_['directions']) { this.directionsPanel_ = $('<div class="directions-panel"><form>' + '<input class="directions-to"/>' + '<input type="submit" value="Find directions"/>' + '<a href="#" class="close-directions">Close</a>' + '</form><div class="rendered-directions"></div></div>'); this.directionsPanel_.find('.directions-to').attr('readonly', 'readonly'); this.directionsPanel_.hide(); this.directionsVisible_ = false; this.directionsPanel_.find('form').submit(function() { that.renderDirections_(); return false; }); this.directionsPanel_.find('.close-directions').click(function() { that.hideDirections(); }); this.el_.append(this.directionsPanel_); } }; /** * Toggles a particular feature on/off in the feature filter. * @param {storeLocator.Feature} feature The feature to toggle. * @private */ storeLocator.Panel.prototype.toggleFeatureFilter_ = function(feature) { var featureFilter = this.get('featureFilter'); featureFilter.toggle(feature); this.set('featureFilter', featureFilter); }; /** * Global Geocoder instance, for convenience. * @type {google.maps.Geocoder} * @private */ storeLocator.geocoder_ = new google.maps.Geocoder; /** * Triggers an update for the store list in the Panel. Will wait for stores * to load asynchronously from the data source. * @private */ storeLocator.Panel.prototype.listenForStoresUpdate_ = function() { var that = this; var view = /** @type storeLocator.View */(this.get('view')); if (this.storesChangedListener_) { google.maps.event.removeListener(this.storesChangedListener_); } this.storesChangedListener_ = google.maps.event.addListenerOnce(view, 'stores_changed', function() { that.set('stores', view.get('stores')); }); }; /** * Search and pan to the specified address. * @param {string} searchText the address to pan to. */ storeLocator.Panel.prototype.searchPosition = function(searchText) { var that = this; var request = { address: searchText, bounds: this.get('view').getMap().getBounds() }; storeLocator.geocoder_.geocode(request, function(result, status) { if (status != google.maps.GeocoderStatus.OK) { //TODO(cbro): proper error handling return; } google.maps.event.trigger(that, 'geocode', result[0]); }); }; /** * Sets the associated View. * @param {storeLocator.View} view the view to set. */ storeLocator.Panel.prototype.setView = function(view) { this.set('view', view); }; /** * view_changed handler. * Sets up additional bindings between the info panel and the map view. */ storeLocator.Panel.prototype.view_changed = function() { var sl = /** @type {google.maps.MVCObject} */ (this.get('view')); this.bindTo('selectedStore', sl); var that = this; if (this.geolocationListener_) { google.maps.event.removeListener(this.geolocationListener_); } if (this.zoomListener_) { google.maps.event.removeListener(this.zoomListener_); } if (this.idleListener_) { google.maps.event.removeListener(this.idleListener_); } var center = sl.getMap().getCenter(); var updateList = function() { sl.clearMarkers(); that.listenForStoresUpdate_(); }; //TODO(cbro): somehow get the geolocated position and populate the 'from' box. this.geolocationListener_ = google.maps.event.addListener(sl, 'load', updateList); this.zoomListener_ = google.maps.event.addListener(sl.getMap(), 'zoom_changed', updateList); this.idleListener_ = google.maps.event.addListener(sl.getMap(), 'idle', function() { return that.idle_(sl.getMap()); }); updateList(); this.bindTo('featureFilter', sl); if (this.autoComplete_) { this.autoComplete_.bindTo('bounds', sl.getMap()); } }; /** * Adds autocomplete to the input box. * @private */ storeLocator.Panel.prototype.initAutocomplete_ = function() { var that = this; var input = $('input', this.locationSearch_)[0]; this.autoComplete_ = new google.maps.places.Autocomplete(input); if (this.get('view')) { this.autoComplete_.bindTo('bounds', this.get('view').getMap()); } google.maps.event.addListener(this.autoComplete_, 'place_changed', function() { google.maps.event.trigger(that, 'geocode', this.getPlace()); }); }; /** * Called on the view's map idle event. Refreshes the store list if the * user has navigated far away enough. * @param {google.maps.Map} map the current view's map. * @private */ storeLocator.Panel.prototype.idle_ = function(map) { if (!this.center_) { this.center_ = map.getCenter(); } else if (!map.getBounds().contains(this.center_)) { this.center_ = map.getCenter(); this.listenForStoresUpdate_(); } }; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_HTML_ = '<li class="no-stores">There are no' + ' stores in this area.</li>'; /** * @const * @type {string} * @private */ storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">There are' + ' no stores in this area. However, stores closest to you are' + ' listed below.</li>'; /** * Handler for stores_changed. Updates the list of stores. * @this storeLocator.Panel */ storeLocator.Panel.prototype.stores_changed = function() { if (!this.get('stores')) { return; } var view = this.get('view'); var bounds = view && view.getMap().getBounds(); var that = this; var stores = this.get('stores'); var selectedStore = this.get('selectedStore'); this.storeList_.empty(); if (!stores.length) { this.storeList_.append(storeLocator.Panel.NO_STORES_HTML_); } else if (bounds && !bounds.contains(stores[0].getLocation())) { this.storeList_.append(storeLocator.Panel.NO_STORES_IN_VIEW_HTML_); } var clickHandler = function() { view.highlight(this['store'], true); }; // TODO(cbro): change 10 to a setting/option for (var i = 0, ii = Math.min(10, stores.length); i < ii; i++) { var storeLi = stores[i].getInfoPanelItem(); storeLi['store'] = stores[i]; if (selectedStore && stores[i].getId() == selectedStore.getId()) { $(storeLi).addClass('highlighted'); } if (!storeLi.clickHandler_) { storeLi.clickHandler_ = google.maps.event.addDomListener( storeLi, 'click', clickHandler); } that.storeList_.append(storeLi); } }; /** * Handler for selectedStore_changed. Highlights the selected store in the * store list. * @this storeLocator.Panel */ storeLocator.Panel.prototype.selectedStore_changed = function() { $('.highlighted', this.storeList_).removeClass('highlighted'); var that = this; var store = this.get('selectedStore'); if (!store) { return; } this.directionsTo_ = store; this.storeList_.find('#store-' + store.getId()).addClass('highlighted'); if (this.settings_['directions']) { this.directionsPanel_.find('.directions-to') .val(store.getDetails().title); } var node = that.get('view').getInfoWindow().getContent(); var directionsLink = $('<a/>') .text('Directions') .attr('href', '#') .addClass('action') .addClass('directions'); // TODO(cbro): Make these two permanent fixtures in InfoWindow. // Move out of Panel. var zoomLink = $('<a/>') .text('Zoom here') .attr('href', '#') .addClass('action') .addClass('zoomhere'); var streetViewLink = $('<a/>') .text('Street view') .attr('href', '#') .addClass('action') .addClass('streetview'); directionsLink.click(function() { that.showDirections(); return false; }); zoomLink.click(function() { that.get('view').getMap().setOptions({ center: store.getLocation(), zoom: 16 }); }); streetViewLink.click(function() { var streetView = that.get('view').getMap().getStreetView(); streetView.setPosition(store.getLocation()); streetView.setVisible(true); }); $(node).append(directionsLink).append(zoomLink).append(streetViewLink); }; /** * Hides the directions panel. */ storeLocator.Panel.prototype.hideDirections = function() { this.directionsVisible_ = false; this.directionsPanel_.fadeOut(); this.featureFilter_.fadeIn(); this.storeList_.fadeIn(); this.directionsRenderer_.setMap(null); }; /** * Shows directions to the selected store. */ storeLocator.Panel.prototype.showDirections = function() { var store = this.get('selectedStore'); this.featureFilter_.fadeOut(); this.storeList_.fadeOut(); this.directionsPanel_.find('.directions-to').val(store.getDetails().title); this.directionsPanel_.fadeIn(); this.renderDirections_(); this.directionsVisible_ = true; }; /** * Renders directions from the location in the input box, to the store that is * pre-filled in the 'to' box. * @private */ storeLocator.Panel.prototype.renderDirections_ = function() { var that = this; if (!this.directionsFrom_ || !this.directionsTo_) { return; } var rendered = this.directionsPanel_.find('.rendered-directions').empty(); this.directionsService_.route({ origin: this.directionsFrom_, destination: this.directionsTo_.getLocation(), travelMode: google.maps['DirectionsTravelMode'].DRIVING //TODO(cbro): region biasing, waypoints, travelmode }, function(result, status) { if (status != google.maps.DirectionsStatus.OK) { // TODO(cbro): better error handling return; } var renderer = that.directionsRenderer_; renderer.setPanel(rendered[0]); renderer.setMap(that.get('view').getMap()); renderer.setDirections(result); }); }; /** * featureFilter_changed event handler. */ storeLocator.Panel.prototype.featureFilter_changed = function() { this.listenForStoresUpdate_(); }; /** * Fired when searchPosition has been called. This happens when the user has * searched for a location from the location search box and/or autocomplete. * @name storeLocator.Panel#event:geocode * @param {google.maps.PlaceResult|google.maps.GeocoderResult} result * @event */ /** * Fired when the <code>Panel</code>'s <code>view</code> property changes. * @name storeLocator.Panel#event:view_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.Panel#event:featureFilter_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>stores</code> property changes. * @name storeLocator.Panel#event:stores_changed * @event */ /** * Fired when the <code>Panel</code>'s <code>selectedStore</code> property * changes. * @name storeLocator.Panel#event:selectedStore_changed * @event */ /** * @example see storeLocator.Panel * @interface */ storeLocator.PanelOptions = function() {}; /** * Whether to show the location search box. Default is true. * @type boolean */ storeLocator.prototype.locationSearch; /** * The label to show above the location search box. Default is "Where are you * now?". * @type string */ storeLocator.PanelOptions.prototype.locationSearchLabel; /** * Whether to show the feature filter picker. Default is true. * @type boolean */ storeLocator.PanelOptions.prototype.featureFilter; /** * Whether to provide directions. Deafult is true. * @type boolean */ storeLocator.PanelOptions.prototype.directions; /** * The store locator model to bind to. * @type storeLocator.View */ storeLocator.PanelOptions.prototype.view;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * This library makes it easy to create a fully-featured Store Locator for * your business's website. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Data feed that returns stores based on a given bounds and a set of features. * @example <pre> * // always returns the same stores * function SimpleStaticFeed(stores) { * this.stores = stores; * } * SimpleStaticFeed.prototype.getStores = function(bounds, features, callback) { * callback(this.stores); * }; * new storeLocator.View(map, new SimpleStaticFeed()); * </pre> * @interface */ storeLocator.DataFeed = function() {}; storeLocator['DataFeed'] = storeLocator.DataFeed; /** * Fetch stores, based on bounds to search within, and features to filter on. * @param {google.maps.LatLngBounds} bounds the bounds to search within. * @param {storeLocator.FeatureSet} features the features to filter on. * @param {function(Array.<!storeLocator.Store>)} callback the callback * function. */ storeLocator.DataFeed.prototype.getStores = function(bounds, features, callback) {}; /** * The main store locator object. * @example <pre> * new storeLocator.View(map, dataFeed); * </pre> * <pre> * var features = new storeLocator.FeatureSet(feature1, feature2, feature3); * new storeLocator.View(map, dataFeed, { * markerIcon: 'icon.png', * features: features, * geolocation: false * }); * </pre> * <pre> * // refresh stores every 10 seconds, regardless of interaction on the map. * var view = new storeLocator.View(map, dataFeed, { * updateOnPan: false * }); * setTimeout(function() { * view.refreshView(); * }, 10000); * </pre> * <pre> * // custom MarkerOptions, by overriding the createMarker method. * view.createMarker = function(store) { * return new google.maps.Marker({ * position: store.getLocation(), * icon: store.getDetails().icon, * title: store.getDetails().title * }); * }; * </pre> * @extends {google.maps.MVCObject} * @param {google.maps.Map} map the map to operate upon. * @param {storeLocator.DataFeed} data the data feed to fetch stores from. * @param {storeLocator.ViewOptions} opt_options * @constructor * @implements storeLocator_View */ storeLocator.View = function(map, data, opt_options) { this.map_ = map; this.data_ = data; this.settings_ = $.extend({ 'updateOnPan': true, 'geolocation': true, 'features': new storeLocator.FeatureSet }, opt_options); this.init_(); google.maps.event.trigger(this, 'load'); this.set('featureFilter', new storeLocator.FeatureSet); }; storeLocator['View'] = storeLocator.View; storeLocator.View.prototype = new google.maps.MVCObject; /** * Attempt to perform geolocation and pan to the given location * @private */ storeLocator.View.prototype.geolocate_ = function() { var that = this; if (window.navigator && navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(pos) { var loc = new google.maps.LatLng( pos.coords.latitude, pos.coords.longitude); that.getMap().setCenter(loc); that.getMap().setZoom(11); google.maps.event.trigger(that, 'load'); }, undefined, /** @type GeolocationPositionOptions */({ maximumAge: 60 * 1000, timeout: 10 * 1000 })); } }; /** * Initialise the View object * @private */ storeLocator.View.prototype.init_ = function() { if (this.settings_['geolocation']) { this.geolocate_(); } this.markerCache_ = {}; this.infoWindow_ = new google.maps.InfoWindow; var that = this; var map = this.getMap(); this.set('updateOnPan', this.settings_['updateOnPan']); google.maps.event.addListener(this.infoWindow_, 'closeclick', function() { that.highlight(null); }); google.maps.event.addListener(map, 'click', function() { that.highlight(null); that.infoWindow_.close(); }); }; /** * Adds/remove hooks as appropriate. */ storeLocator.View.prototype.updateOnPan_changed = function() { if (this.updateOnPanListener_) { google.maps.event.removeListener(this.updateOnPanListener_); } if (this.get('updateOnPan') && this.getMap()) { var that = this; var map = this.getMap(); this.updateOnPanListener_ = google.maps.event.addListener(map, 'idle', function() { that.refreshView(); }); } }; /** * Add a store to the map. * @param {storeLocator.Store} store the store to add. */ storeLocator.View.prototype.addStoreToMap = function(store) { var marker = this.getMarker(store); store.setMarker(marker); var that = this; marker.clickListener_ = google.maps.event.addListener(marker, 'click', function() { that.highlight(store, false); }); if (marker.getMap() != this.getMap()) { marker.setMap(this.getMap()); } }; /** * Create a marker for a store. * @param {storeLocator.Store} store the store to produce a marker for. * @this storeLocator.View * @return {google.maps.Marker} a new marker. * @export */ storeLocator.View.prototype.createMarker = function(store) { var markerOptions = { position: store.getLocation() }; var opt_icon = this.settings_['markerIcon']; if (opt_icon) { markerOptions.icon = opt_icon; } return new google.maps.Marker(markerOptions); }; /** * Get a marker for a store. By default, this caches the value from * createMarker(store) * @param {storeLocator.Store} store the store to get the marker from. * @return {google.maps.Marker} the marker. */ storeLocator.View.prototype.getMarker = function(store) { var cache = this.markerCache_; var key = store.getId(); if (!cache[key]) { cache[key] = this['createMarker'](store); } return cache[key]; }; /** * Get a InfoWindow for a particular store. * @param {storeLocator.Store} store the store. * @return {google.maps.InfoWindow} the store's InfoWindow. */ storeLocator.View.prototype.getInfoWindow = function(store) { if (!store) { return this.infoWindow_; } var div = $(store.getInfoWindowContent()); this.infoWindow_.setContent(div[0]); return this.infoWindow_; }; /** * Gets all possible features for this View. * @return {storeLocator.FeatureSet} All possible features. */ storeLocator.View.prototype.getFeatures = function() { return this.settings_['features']; }; /** * Gets a feature by its id. Convenience method. * @param {string} id the feature's id. * @return {storeLocator.Feature|undefined} The feature, if the id is valid. * undefined if not. */ storeLocator.View.prototype.getFeatureById = function(id) { if (!this.featureById_) { this.featureById_ = {}; for (var i = 0, feature; feature = this.settings_['features'][i]; i++) { this.featureById_[feature.getId()] = feature; } } return this.featureById_[id]; }; /** * featureFilter_changed event handler. */ storeLocator.View.prototype.featureFilter_changed = function() { google.maps.event.trigger(this, 'featureFilter_changed', this.get('featureFilter')); if (this.get('stores')) { this.clearMarkers(); } }; /** * Clears the visible markers on the map. */ storeLocator.View.prototype.clearMarkers = function() { for (var marker in this.markerCache_) { this.markerCache_[marker].setMap(null); var listener = this.markerCache_[marker].clickListener_; if (listener) { google.maps.event.removeListener(listener); } } }; /** * Refresh the map's view. This will fetch new data based on the map's bounds. */ storeLocator.View.prototype.refreshView = function() { var that = this; this.data_.getStores(this.getMap().getBounds(), /** @type {storeLocator.FeatureSet} */ (this.get('featureFilter')), function(stores) { var oldStores = that.get('stores'); if (oldStores) { for (var i = 0, ii = oldStores.length; i < ii; i++) { google.maps.event.removeListener( oldStores[i].getMarker().clickListener_); } } that.set('stores', stores); }); }; /** * stores_changed event handler. * This will display all new stores on the map. * @this storeLocator.View */ storeLocator.View.prototype.stores_changed = function() { var stores = this.get('stores'); for (var i = 0, store; store = stores[i]; i++) { this.addStoreToMap(store); } }; /** * Gets the view's Map. * @return {google.maps.Map} the view's Map. */ storeLocator.View.prototype.getMap = function() { return this.map_; }; /** * Select a particular store. * @param {storeLocator.Store} store the store to highlight. * @param {boolean=} opt_pan if panning to the store on the map is desired. */ storeLocator.View.prototype.highlight = function(store, opt_pan) { var infoWindow = this.getInfoWindow(store); if (store) { var infoWindow = this.getInfoWindow(store); if (store.getMarker()) { infoWindow.open(this.getMap(), store.getMarker()); } else { infoWindow.setPosition(store.getLocation()); infoWindow.open(this.getMap()); } if (opt_pan) { this.getMap().panTo(store.getLocation()); } if (this.getMap().getStreetView().getVisible()) { this.getMap().getStreetView().setPosition(store.getLocation()); } } else { infoWindow.close(); } this.set('selectedStore', store); }; /** * Re-triggers the selectedStore_changed event with the store as a parameter. * @this storeLocator.View */ storeLocator.View.prototype.selectedStore_changed = function() { google.maps.event.trigger(this, 'selectedStore_changed', this.get('selectedStore')); }; /** * Fired when the <code>View</code> is loaded. This happens once immediately, * then once more if geolocation is successful. * @name storeLocator.View#event:load * @event */ /** * Fired when the <code>View</code>'s <code>featureFilter</code> property * changes. * @name storeLocator.View#event:featureFilter_changed * @event */ /** * Fired when the <code>View</code>'s <code>updateOnPan</code> property changes. * @name storeLocator.View#event:updateOnPan_changed * @event */ /** * Fired when the <code>View</code>'s <code>stores</code> property changes. * @name storeLocator.View#event:stores_changed * @event */ /** * Fired when the <code>View</code>'s <code>selectedStore</code> property * changes. This happens after <code>highlight()</code> is called. * @name storeLocator.View#event:selectedStore_changed * @param {storeLocator.Store} store * @event */ /** * @example see storeLocator.View * @interface */ storeLocator.ViewOptions = function() {}; /** * Whether the map should update stores in the visible area when the visible * area changes. <code>refreshView()</code> will need to be called * programatically. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.updateOnPan; /** * Whether the store locator should attempt to determine the user's location * for the initial view. Defaults to true. * @type boolean */ storeLocator.ViewOptions.prototype.geolocation; /** * All available store features. Defaults to empty FeatureSet. * @type storeLocator.FeatureSet */ storeLocator.ViewOptions.prototype.features; /** * The icon to use for markers representing stores. * @type string|google.maps.MarkerImage */ storeLocator.ViewOptions.prototype.markerIcon;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Store model class for Store Locator library. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Represents a store. * @example <pre> * var latLng = new google.maps.LatLng(40.7585, -73.9861); * var store = new storeLocator.Store('times_square', latLng, null); * </pre> * <pre> * var features = new storeLocator.FeatureSet( * view.getFeatureById('24hour'), * view.getFeatureById('express'), * view.getFeatureById('wheelchair_access')); * * var store = new storeLocator.Store('times_square', latLng, features, { * title: 'Times Square', * address: '1 Times Square&lt;br>Manhattan, NY 10036' * }); * </pre> * <pre> * store.distanceTo(map.getCenter()); * * // override default info window * store.getInfoWindowContent = function() { * var details = this.getDetails(); * return '&lt;h1>' + details.title + '&lt;h1>' + details.address; * }; * </pre> * @param {string} id globally unique id of the store - should be suitable to * use as a HTML id. * @param {!google.maps.LatLng} location location of the store. * @param {storeLocator.FeatureSet} features the features of this store. * @param {Object.<string, *>=} props any additional properties. * <p> Recommended fields are: * 'title', 'address', 'phone', 'misc', 'web'. </p> * @constructor * @implements storeLocator_Store */ storeLocator.Store = function(id, location, features, props) { this.id_ = id; this.location_ = location; this.features_ = features || storeLocator.FeatureSet.NONE; this.props_ = props || {}; }; storeLocator['Store'] = storeLocator.Store; /** * Sets this store's Marker. * @param {google.maps.Marker} marker the marker to set on this store. */ storeLocator.Store.prototype.setMarker = function(marker) { this.marker_ = marker; google.maps.event.trigger(this, 'marker_changed', marker); }; /** * Gets this store's Marker * @return {google.maps.Marker} the store's marker. */ storeLocator.Store.prototype.getMarker = function() { return this.marker_; }; /** * Gets this store's ID. * @return {string} this store's ID. */ storeLocator.Store.prototype.getId = function() { return this.id_; }; /** * Gets this store's location. * @return {google.maps.LatLng} this store's location. */ storeLocator.Store.prototype.getLocation = function() { return this.location_; }; /** * Gets this store's features. * @return {storeLocator.FeatureSet} this store's features. */ storeLocator.Store.prototype.getFeatures = function() { return this.features_; }; /** * Checks whether this store has a particular feature. * @param {!storeLocator.Feature} feature the feature to check for. * @return {boolean} true if the store has the feature, false otherwise. */ storeLocator.Store.prototype.hasFeature = function(feature) { return this.features_.contains(feature); }; /** * Checks whether this store has all the given features. * @param {storeLocator.FeatureSet} features the features to check for. * @return {boolean} true if the store has all features, false otherwise. */ storeLocator.Store.prototype.hasAllFeatures = function(features) { if (!features) { return true; } var featureList = features.asList(); for (var i = 0, ii = featureList.length; i < ii; i++) { if (!this.hasFeature(featureList[i])) { return false; } } return true; }; /** * Gets additional details about this store. * @return {Object} additional properties of this store. */ storeLocator.Store.prototype.getDetails = function() { return this.props_; }; /** * Generates HTML for additional details about this store. * @private * @param {Array.<string>} fields the optional fields of this store to output. * @return {string} html version of additional fields of this store. */ storeLocator.Store.prototype.generateFieldsHTML_ = function(fields) { var html = []; for (var i = 0, ii = fields.length; i < ii; i++) { var prop = fields[i]; if (this.props_[prop]) { html.push('<div class="'); html.push(prop); html.push('">'); html.push(this.props_[prop]); html.push('</div>'); } } return html.join(''); }; /** * Generates a HTML list of this store's features. * @private * @return {string} html list of this store's features. */ storeLocator.Store.prototype.generateFeaturesHTML_ = function() { var html = []; html.push('<ul class="features">'); var featureList = this.features_.asList(); for (var i = 0, feature; feature = featureList[i]; i++) { html.push('<li>'); html.push(feature.getDisplayName()); html.push('</li>'); } html.push('</ul>'); return html.join(''); }; /** * Gets the HTML content for this Store, suitable for use in an InfoWindow. * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoWindowContent = function() { if (!this.content_) { // TODO(cbro): make this a setting? var fields = ['title', 'address', 'phone', 'misc', 'web']; var html = ['<div class="store">']; html.push(this.generateFieldsHTML_(fields)); html.push(this.generateFeaturesHTML_()); html.push('</div>'); this.content_ = html.join(''); } return this.content_; }; /** * Gets the HTML content for this Store, suitable for use in suitable for use * in the sidebar info panel. * @this storeLocator.Store * @return {string} a HTML version of this store. */ storeLocator.Store.prototype.getInfoPanelContent = function() { return this.getInfoWindowContent(); }; /** * Keep a cache of InfoPanel items (DOM Node), keyed by the store ID. * @private * @type {Object} */ storeLocator.Store.infoPanelCache_ = {}; /** * Gets a HTML element suitable for use in the InfoPanel. * @return {Node} a HTML element. */ storeLocator.Store.prototype.getInfoPanelItem = function() { var cache = storeLocator.Store.infoPanelCache_; var store = this; var key = store.getId(); if (!cache[key]) { var content = store.getInfoPanelContent(); cache[key] = $('<li class="store" id="store-' + store.getId() + '">' + content + '</li>')[0]; } return cache[key]; }; /** * Gets the distance between this Store and a certain location. * @param {google.maps.LatLng} point the point to calculate distance to/from. * @return {number} the distance from this store to a given point. * @license * Latitude/longitude spherical geodesy formulae & scripts * (c) Chris Veness 2002-2010 * www.movable-type.co.uk/scripts/latlong.html */ storeLocator.Store.prototype.distanceTo = function(point) { var R = 6371; // mean radius of earth var location = this.getLocation(); var lat1 = storeLocator.toRad_(location.lat()); var lon1 = storeLocator.toRad_(location.lng()); var lat2 = storeLocator.toRad_(point.lat()); var lon2 = storeLocator.toRad_(point.lng()); var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; }; /** * Fired when the <code>Store</code>'s <code>marker</code> property changes. * @name storeLocator.Store#event:marker_changed * @param {google.maps.Marker} marker * @event */
JavaScript
// Copyright 2013 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * Provides access to store data through Google Maps Engine. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A DataFeed where stores are provided by Google Maps Engine. * <p> * Note: the table that contains the stores needs to be publicly accessible. * @example <pre> * var dataFeed = new storeLocator.GMEDataFeed({ * tableId: '12421761926155747447-06672618218968397709', * apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', * propertiesModifier: function(props) { * return { * id: transformId(props.store_id), * title: props.store_title * }; * } * }); * new storeLocator.View(map, dataFeed); * </pre> * @implements storeLocator.DataFeed * @param {!storeLocator.GMEDataFeedOptions} opts the table ID, API key and * a transformation function for feature/store properties. * @constructor * @implements storeLocator_GMEDataFeed */ storeLocator.GMEDataFeed = function(opts) { this.tableId_ = opts['tableId']; this.apiKey_ = opts['apiKey']; if (opts['propertiesModifier']) { this.propertiesModifier_ = opts['propertiesModifier']; } }; storeLocator['GMEDataFeed'] = storeLocator.GMEDataFeed; storeLocator.GMEDataFeed.prototype.getStores = function(bounds, features, callback) { // TODO: use features. var that = this; var center = bounds.getCenter(); var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' + ' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)'; var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + this.tableId_ + '/features?callback=?'; $.getJSON(url, { 'key': this.apiKey_, 'where': where, 'version': 'published', 'maxResults': 300 }, function(resp) { var stores = that.parse_(resp); that.sortByDistance_(center, stores); callback(stores); }); }; /** * @private * @param {!google.maps.LatLng} point * @return {string} */ storeLocator.GMEDataFeed.prototype.latLngToWkt_ = function(point) { return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')'; }; /** * @private * @param {!google.maps.LatLngBounds} bounds * @return {string} */ storeLocator.GMEDataFeed.prototype.boundsToWkt_ = function(bounds) { var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); return [ "ST_GEOMFROMTEXT('POLYGON ((", sw.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', sw.lat(), "))')" ].join(''); }; /** * @private * @param {*} data GeoJSON feature set. * @return {!Array.<!storeLocator.Store>} */ storeLocator.GMEDataFeed.prototype.parse_ = function(data) { if (data['error']) { window.alert(data['error']['message']); return []; } var features = data['features']; if (!features) { return []; } var stores = []; for (var i = 0, row; row = features[i]; i++) { var coordinates = row['geometry']['coordinates']; var position = new google.maps.LatLng(coordinates[1], coordinates[0]); var props = this.propertiesModifier_(row['properties']); var store = new storeLocator.Store(props['id'], position, null, props); stores.push(store); } return stores; }; /** * Default properties modifier. Just returns the same properties passed into * it. Useful if the columns in the GME table are already appropriate. * @private * @param {Object} props * @return {Object} an Object to be passed into the "props" argument in the * Store constructor. */ storeLocator.GMEDataFeed.prototype.propertiesModifier_ = function(props) { return props; }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ storeLocator.GMEDataFeed.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); }; /** * @example see storeLocator.GMEDataFeed * @interface */ storeLocator.GMEDataFeedOptions = function() {}; /** * The table's asset ID. * @type string */ storeLocator.GMEDataFeedOptions.prototype.tableId; /** * The API key to use for all requests. * @type string */ storeLocator.GMEDataFeedOptions.prototype.apiKey; /** * A transformation function. The first argument is the feature's properties. * Return an object useful for the <code>"props"</code> argument in the * storeLocator.Store constructor. The default properties modifier * function passes the feature straight through. * <p> * Note: storeLocator.GMEDataFeed expects an <code>"id"</code> property. * @type ?(function(Object): Object) */ storeLocator.GMEDataFeedOptions.prototype.propertiesModifier;
JavaScript
// Copyright 2012 Google Inc. /** * @author Chris Broadfoot (Google) * @fileoverview * FeatureSet class for Store Locator library. A mutable, ordered set of * storeLocator.Features. */ /** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A mutable, ordered set of <code>storeLocator.Feature</code>s. * @example <pre> * var feature1 = new storeLocator.Feature('1', 'Feature One'); * var feature2 = new storeLocator.Feature('2', 'Feature Two'); * var feature3 = new storeLocator.Feature('3', 'Feature Three'); * * var featureSet = new storeLocator.FeatureSet(feature1, feature2, feature3); * </pre> * @param {...storeLocator.Feature} var_args the initial features to add to * the set. * @constructor * @implements storeLocator_FeatureSet */ storeLocator.FeatureSet = function(var_args) { /** * Stores references to the actual Feature. * @private * @type {!Array.<storeLocator.Feature>} */ this.array_ = []; /** * Maps from a Feature's id to its array index. * @private * @type {Object.<string, number>} */ this.hash_ = {}; for (var i = 0, feature; feature = arguments[i]; i++) { this.add(feature); } }; storeLocator['FeatureSet'] = storeLocator.FeatureSet; /** * Adds the given feature to the set, if it doesn't exist in the set already. * Else, removes the feature from the set. * @param {!storeLocator.Feature} feature the feature to toggle. */ storeLocator.FeatureSet.prototype.toggle = function(feature) { if (this.contains(feature)) { this.remove(feature); } else { this.add(feature); } }; /** * Check if a feature exists within this set. * @param {!storeLocator.Feature} feature the feature. * @return {boolean} true if the set contains the given feature. */ storeLocator.FeatureSet.prototype.contains = function(feature) { return feature.getId() in this.hash_; }; /** * Gets a Feature object from the set, by the feature id. * @param {string} featureId the feature's id. * @return {storeLocator.Feature} the feature, if the set contains it. */ storeLocator.FeatureSet.prototype.getById = function(featureId) { if (featureId in this.hash_) { return this.array_[this.hash_[featureId]]; } return null; }; /** * Adds a feature to the set. * @param {storeLocator.Feature} feature the feature to add. */ storeLocator.FeatureSet.prototype.add = function(feature) { if (!feature) { return; } this.array_.push(feature); this.hash_[feature.getId()] = this.array_.length - 1; }; /** * Removes a feature from the set, if it already exists in the set. If it does * not already exist in the set, this function is a no op. * @param {!storeLocator.Feature} feature the feature to remove. */ storeLocator.FeatureSet.prototype.remove = function(feature) { if (!this.contains(feature)) { return; } this.array_[this.hash_[feature.getId()]] = null; delete this.hash_[feature.getId()]; }; /** * Get the contents of this set as an Array. * @return {Array.<!storeLocator.Feature>} the features in the set, in the order * they were inserted. */ storeLocator.FeatureSet.prototype.asList = function() { var filtered = []; for (var i = 0, ii = this.array_.length; i < ii; i++) { var elem = this.array_[i]; if (elem !== null) { filtered.push(elem); } } return filtered; }; /** * Empty feature set. * @type storeLocator.FeatureSet * @const */ storeLocator.FeatureSet.NONE = new storeLocator.FeatureSet;
JavaScript
/** @interface */ function storeLocator_Feature() {}; storeLocator_Feature.prototype.getId = function(var_args) {}; storeLocator_Feature.prototype.getDisplayName = function(var_args) {}; /** @interface */ function storeLocator_FeatureSet() {}; storeLocator_FeatureSet.prototype.toggle = function(var_args) {}; storeLocator_FeatureSet.prototype.contains = function(var_args) {}; storeLocator_FeatureSet.prototype.getById = function(var_args) {}; storeLocator_FeatureSet.prototype.add = function(var_args) {}; storeLocator_FeatureSet.prototype.remove = function(var_args) {}; storeLocator_FeatureSet.prototype.asList = function(var_args) {}; /** @interface */ function storeLocator_GMEDataFeed() {}; /** @interface */ function storeLocator_Panel() {}; storeLocator_Panel.prototype.searchPosition = function(var_args) {}; storeLocator_Panel.prototype.setView = function(var_args) {}; storeLocator_Panel.prototype.view_changed = function(var_args) {}; storeLocator_Panel.prototype.stores_changed = function(var_args) {}; storeLocator_Panel.prototype.selectedStore_changed = function(var_args) {}; storeLocator_Panel.prototype.hideDirections = function(var_args) {}; storeLocator_Panel.prototype.showDirections = function(var_args) {}; storeLocator_Panel.prototype.featureFilter_changed = function(var_args) {}; /** @interface */ function storeLocator_StaticDataFeed() {}; storeLocator_StaticDataFeed.prototype.setStores = function(var_args) {}; storeLocator_StaticDataFeed.prototype.getStores = function(var_args) {}; /** @interface */ function storeLocator_Store() {}; storeLocator_Store.prototype.setMarker = function(var_args) {}; storeLocator_Store.prototype.getMarker = function(var_args) {}; storeLocator_Store.prototype.getId = function(var_args) {}; storeLocator_Store.prototype.getLocation = function(var_args) {}; storeLocator_Store.prototype.getFeatures = function(var_args) {}; storeLocator_Store.prototype.hasFeature = function(var_args) {}; storeLocator_Store.prototype.hasAllFeatures = function(var_args) {}; storeLocator_Store.prototype.getDetails = function(var_args) {}; storeLocator_Store.prototype.getInfoWindowContent = function(var_args) {}; storeLocator_Store.prototype.getInfoPanelContent = function(var_args) {}; storeLocator_Store.prototype.getInfoPanelItem = function(var_args) {}; storeLocator_Store.prototype.distanceTo = function(var_args) {}; /** @interface */ function storeLocator_View() {}; storeLocator_View.prototype.updateOnPan_changed = function(var_args) {}; storeLocator_View.prototype.addStoreToMap = function(var_args) {}; storeLocator_View.prototype.createMarker = function(var_args) {}; storeLocator_View.prototype.getMarker = function(var_args) {}; storeLocator_View.prototype.getInfoWindow = function(var_args) {}; storeLocator_View.prototype.getFeatures = function(var_args) {}; storeLocator_View.prototype.getFeatureById = function(var_args) {}; storeLocator_View.prototype.featureFilter_changed = function(var_args) {}; storeLocator_View.prototype.clearMarkers = function(var_args) {}; storeLocator_View.prototype.refreshView = function(var_args) {}; storeLocator_View.prototype.stores_changed = function(var_args) {}; storeLocator_View.prototype.getMap = function(var_args) {}; storeLocator_View.prototype.highlight = function(var_args) {}; storeLocator_View.prototype.selectedStore_changed = function(var_args) {};
JavaScript
// A simple demo showing how to grab places using the Maps API Places Library. // Useful extensions may include using "name" filtering or "keyword" search. google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new PlacesDataSource(map); var view = new storeLocator.View(map, data); var markerSize = new google.maps.Size(24, 24); view.createMarker = function(store) { return new google.maps.Marker({ position: store.getLocation(), icon: new google.maps.MarkerImage(store.getDetails().icon, null, null, null, markerSize) }); }; new storeLocator.Panel(panelDiv, { view: view }); }); /** * Creates a new PlacesDataSource. * @param {google.maps.Map} map * @constructor */ function PlacesDataSource(map) { this.service_ = new google.maps.places.PlacesService(map); } /** * @inheritDoc */ PlacesDataSource.prototype.getStores = function(bounds, features, callback) { this.service_.search({ bounds: bounds }, function(results, status) { var stores = []; for (var i = 0, result; result = results[i]; i++) { var latLng = result.geometry.location; var store = new storeLocator.Store(result.id, latLng, null, { title: result.name, address: result.types.join(', '), icon: result.icon }); stores.push(store); } callback(stores); }); };
JavaScript
google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new storeLocator.GMEDataFeed({ tableId: '12421761926155747447-06672618218968397709', apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', propertiesModifier: function(props) { var shop = join([props.Shp_num_an, props.Shp_centre], ', '); var locality = join([props.Locality, props.Postcode], ', '); return { id: props.uuid, title: props.Fcilty_nam, address: join([shop, props.Street_add, locality], '<br>'), hours: props.Hrs_of_bus }; } }); var view = new storeLocator.View(map, data, { geolocation: false }); new storeLocator.Panel(panelDiv, { view: view }); }); /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ function join(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }
JavaScript
/** * @implements storeLocator.DataFeed * @constructor */ function MedicareDataSource() { } MedicareDataSource.prototype.getStores = function(bounds, features, callback) { var that = this; var center = bounds.getCenter(); var audioFeature = this.FEATURES_.getById('Audio-YES'); var wheelchairFeature = this.FEATURES_.getById('Wheelchair-YES'); var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' + ' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)'; if (features.contains(audioFeature)) { where += " AND Audio='YES'"; } if (features.contains(wheelchairFeature)) { where += " AND Wheelchair='YES'"; } var tableId = '12421761926155747447-06672618218968397709'; var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + tableId + '/features?callback=?'; $.getJSON(url, { key: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM', where: where, version: 'published', maxResults: 300 }, function(resp) { var stores = that.parse_(resp); that.sortByDistance_(center, stores); callback(stores); }); }; MedicareDataSource.prototype.latLngToWkt_ = function(point) { return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')'; }; MedicareDataSource.prototype.boundsToWkt_ = function(bounds) { var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); return [ "ST_GEOMFROMTEXT('POLYGON ((", sw.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', sw.lat(), ', ', ne.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', ne.lat(), ', ', sw.lng(), ' ', sw.lat(), "))')" ].join(''); }; MedicareDataSource.prototype.parse_ = function(data) { var stores = []; for (var i = 0, row; row = data.features[i]; i++) { var props = row.properties; var features = new storeLocator.FeatureSet; features.add(this.FEATURES_.getById('Wheelchair-' + props.Wheelchair)); features.add(this.FEATURES_.getById('Audio-' + props.Audio)); var position = new google.maps.LatLng(row.geometry.coordinates[1], row.geometry.coordinates[0]); var shop = this.join_([props.Shp_num_an, props.Shp_centre], ', '); var locality = this.join_([props.Locality, props.Postcode], ', '); var store = new storeLocator.Store(props.uuid, position, features, { title: props.Fcilty_nam, address: this.join_([shop, props.Street_add, locality], '<br>'), hours: props.Hrs_of_bus }); stores.push(store); } return stores; }; /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Sorts a list of given stores by distance from a point in ascending order. * Directly manipulates the given array (has side effects). * @private * @param {google.maps.LatLng} latLng the point to sort from. * @param {!Array.<!storeLocator.Store>} stores the stores to sort. */ MedicareDataSource.prototype.sortByDistance_ = function(latLng, stores) { stores.sort(function(a, b) { return a.distanceTo(latLng) - b.distanceTo(latLng); }); };
JavaScript
google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new MedicareDataSource; var view = new storeLocator.View(map, data, { geolocation: false, features: data.getFeatures() }); new storeLocator.Panel(panelDiv, { view: view }); });
JavaScript
/** * @extends storeLocator.StaticDataFeed * @constructor */ function MedicareDataSource() { $.extend(this, new storeLocator.StaticDataFeed); var that = this; $.get('medicare.csv', function(data) { that.setStores(that.parse_(data)); }); } /** * @const * @type {!storeLocator.FeatureSet} * @private */ MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet( new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'), new storeLocator.Feature('Audio-YES', 'Audio') ); /** * @return {!storeLocator.FeatureSet} */ MedicareDataSource.prototype.getFeatures = function() { return this.FEATURES_; }; /** * @private * @param {string} csv * @return {!Array.<!storeLocator.Store>} */ MedicareDataSource.prototype.parse_ = function(csv) { var stores = []; var rows = csv.split('\n'); var headings = this.parseRow_(rows[0]); for (var i = 1, row; row = rows[i]; i++) { row = this.toObject_(headings, this.parseRow_(row)); var features = new storeLocator.FeatureSet; features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair)); features.add(this.FEATURES_.getById('Audio-' + row.Audio)); var position = new google.maps.LatLng(row.Ycoord, row.Xcoord); var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', '); var locality = this.join_([row.Locality, row.Postcode], ', '); var store = new storeLocator.Store(row.uuid, position, features, { title: row.Fcilty_nam, address: this.join_([shop, row.Street_add, locality], '<br>'), hours: row.Hrs_of_bus }); stores.push(store); } return stores; }; /** * Joins elements of an array that are non-empty and non-null. * @private * @param {!Array} arr array of elements to join. * @param {string} sep the separator. * @return {string} */ MedicareDataSource.prototype.join_ = function(arr, sep) { var parts = []; for (var i = 0, ii = arr.length; i < ii; i++) { arr[i] && parts.push(arr[i]); } return parts.join(sep); }; /** * Very rudimentary CSV parsing - we know how this particular CSV is formatted. * IMPORTANT: Don't use this for general CSV parsing! * @private * @param {string} row * @return {Array.<string>} */ MedicareDataSource.prototype.parseRow_ = function(row) { // Strip leading quote. if (row.charAt(0) == '"') { row = row.substring(1); } // Strip trailing quote. There seems to be a character between the last quote // and the line ending, hence 2 instead of 1. if (row.charAt(row.length - 2) == '"') { row = row.substring(0, row.length - 2); } row = row.split('","'); return row; }; /** * Creates an object mapping headings to row elements. * @private * @param {Array.<string>} headings * @param {Array.<string>} row * @return {Object} */ MedicareDataSource.prototype.toObject_ = function(headings, row) { var result = {}; for (var i = 0, ii = row.length; i < ii; i++) { result[headings[i]] = row[i]; } return result; };
JavaScript
// Store locator with customisations // - custom marker // - custom info window (using Info Bubble) // - custom info window content (+ store hours) var ICON = new google.maps.MarkerImage('medicare.png', null, null, new google.maps.Point(14, 13)); var SHADOW = new google.maps.MarkerImage('medicare-shadow.png', null, null, new google.maps.Point(14, 13)); google.maps.event.addDomListener(window, 'load', function() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: new google.maps.LatLng(-28, 135), zoom: 4, mapTypeId: google.maps.MapTypeId.ROADMAP }); var panelDiv = document.getElementById('panel'); var data = new MedicareDataSource; var view = new storeLocator.View(map, data, { geolocation: false, features: data.getFeatures() }); view.createMarker = function(store) { var markerOptions = { position: store.getLocation(), icon: ICON, shadow: SHADOW, title: store.getDetails().title }; return new google.maps.Marker(markerOptions); } var infoBubble = new InfoBubble; view.getInfoWindow = function(store) { if (!store) { return infoBubble; } var details = store.getDetails(); var html = ['<div class="store"><div class="title">', details.title, '</div><div class="address">', details.address, '</div>', '<div class="hours misc">', details.hours, '</div></div>'].join(''); infoBubble.setContent($(html)[0]); return infoBubble; }; new storeLocator.Panel(panelDiv, { view: view }); });
JavaScript
/** * http://github.com/Valums-File-Uploader/file-uploader * * Multiple file upload component with progress-bar, drag-and-drop. * * Have ideas for improving this JS for the general community? * Submit your changes at: https://github.com/Valums-File-Uploader/file-uploader * * VERSION 2.0 beta * Original version 1.0 © 2010 Andrew Valums ( andrew(at)valums.com ) * Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt. */ // // Helper functions // var qq = qq || {}; /** * Adds all missing properties from second obj to first obj */ qq.extend = function(first, second){ for (var prop in second){ first[prop] = second[prop]; } }; /** * Searches for a given element in the array, returns -1 if it is not present. * @param {Number} [from] The index at which to begin the search */ qq.indexOf = function(arr, elt, from){ if (arr.indexOf) return arr.indexOf(elt, from); from = from || 0; var len = arr.length; if (from < 0) from += len; for (; from < len; from++){ if (from in arr && arr[from] === elt){ return from; } } return -1; }; qq.getUniqueId = (function(){ var id = 0; return function(){ return id++; }; })(); // // Browsers and platforms detection qq.ie = function(){ return navigator.userAgent.indexOf('MSIE') != -1; }; qq.safari = function(){ return navigator.vendor != undefined && navigator.vendor.indexOf("Apple") != -1; }; qq.chrome = function(){ return navigator.vendor != undefined && navigator.vendor.indexOf('Google') != -1; }; qq.firefox = function(){ return (navigator.userAgent.indexOf('Mozilla') != -1 && navigator.vendor != undefined && navigator.vendor == ''); }; qq.windows = function(){ return navigator.platform == "Win32"; }; // // Events /** Returns the function which detaches attached event */ qq.attach = function(element, type, fn){ if (element.addEventListener){ element.addEventListener(type, fn, false); } else if (element.attachEvent){ element.attachEvent('on' + type, fn); } return function() { qq.detach(element, type, fn) } }; qq.detach = function(element, type, fn){ if (element.removeEventListener){ element.removeEventListener(type, fn, false); } else if (element.attachEvent){ element.detachEvent('on' + type, fn); } }; qq.preventDefault = function(e){ if (e.preventDefault){ e.preventDefault(); } else{ e.returnValue = false; } }; // // Node manipulations /** * Insert node a before node b. */ qq.insertBefore = function(a, b){ b.parentNode.insertBefore(a, b); }; qq.remove = function(element){ element.parentNode.removeChild(element); }; qq.contains = function(parent, descendant){ // compareposition returns false in this case if (parent == descendant) return true; if (parent.contains){ return parent.contains(descendant); } else { return !!(descendant.compareDocumentPosition(parent) & 8); } }; /** * Creates and returns element from html string * Uses innerHTML to create an element */ qq.toElement = (function(){ var div = document.createElement('div'); return function(html){ div.innerHTML = html; var element = div.firstChild; div.removeChild(element); return element; }; })(); // // Node properties and attributes /** * Sets styles for an element. * Fixes opacity in IE6-8. */ qq.css = function(element, styles){ if (styles.opacity != null){ if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){ styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')'; } } qq.extend(element.style, styles); }; qq.hasClass = function(element, name){ var re = new RegExp('(^| )' + name + '( |$)'); return re.test(element.className); }; qq.addClass = function(element, name){ if (!qq.hasClass(element, name)){ element.className += ' ' + name; } }; qq.removeClass = function(element, name){ var re = new RegExp('(^| )' + name + '( |$)'); element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, ""); }; qq.setText = function(element, text){ element.innerText = text; element.textContent = text; }; // // Selecting elements qq.children = function(element){ var children = [], child = element.firstChild; while (child){ if (child.nodeType == 1){ children.push(child); } child = child.nextSibling; } return children; }; qq.getByClass = function(element, className){ if (element.querySelectorAll){ return element.querySelectorAll('.' + className); } var result = []; var candidates = element.getElementsByTagName("*"); var len = candidates.length; for (var i = 0; i < len; i++){ if (qq.hasClass(candidates[i], className)){ result.push(candidates[i]); } } return result; }; /** * obj2url() takes a json-object as argument and generates * a querystring. pretty much like jQuery.param() * * how to use: * * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');` * * will result in: * * `http://any.url/upload?otherParam=value&a=b&c=d` * * @param Object JSON-Object * @param String current querystring-part * @return String encoded querystring */ qq.obj2url = function(obj, temp, prefixDone){ var uristrings = [], prefix = '&', add = function(nextObj, i){ var nextTemp = temp ? (/\[\]$/.test(temp)) // prevent double-encoding ? temp : temp+'['+i+']' : i; if ((nextTemp != 'undefined') && (i != 'undefined')) { uristrings.push( (typeof nextObj === 'object') ? qq.obj2url(nextObj, nextTemp, true) : (Object.prototype.toString.call(nextObj) === '[object Function]') ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj) ); } }; if (!prefixDone && temp) { prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?'; uristrings.push(temp); uristrings.push(qq.obj2url(obj)); } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) { // we wont use a for-in-loop on an array (performance) for (var i = 0, len = obj.length; i < len; ++i){ add(obj[i], i); } } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){ // for anything else but a scalar, we will use for-in-loop for (var i in obj){ add(obj[i], i); } } else { uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj)); } return uristrings.join(prefix) .replace(/^&/, '') .replace(/%20/g, '+'); }; // // // Uploader Classes // // var qq = qq || {}; /** * Creates upload button, validates upload, but doesn't create file list or dd. */ qq.FileUploaderBasic = function(o){ this._options = { // set to true to see the server response debug: false, action: '/server/upload', params: {}, customHeaders: {}, button: null, multiple: true, maxConnections: 3, // validation allowedExtensions: [], acceptFiles: null, // comma separated string of mime-types for browser to display in browse dialog sizeLimit: 0, minSizeLimit: 0, abortOnFailure: true, // Fail all files if one doesn't meet the criteria // events // return false to cancel submit onSubmit: function(id, fileName){}, onProgress: function(id, fileName, loaded, total){}, onComplete: function(id, fileName, responseJSON){}, onCancel: function(id, fileName){}, onUpload: function(id, fileName, xhr){}, onError: function(id, fileName, xhr) {}, // messages messages: { typeError: "Unfortunately the file(s) you selected weren't the type we were expecting. Only {extensions} files are allowed.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", onLeave: "The files are being uploaded, if you leave now the upload will be cancelled." }, showMessage: function(message){ alert(message); }, inputName: 'qqfile', extraDropzones : [] }; qq.extend(this._options, o); qq.extend(this, qq.DisposeSupport); // number of files being uploaded this._filesInProgress = 0; this._handler = this._createUploadHandler(); if (this._options.button){ this._button = this._createUploadButton(this._options.button); } this._preventLeaveInProgress(); }; qq.FileUploaderBasic.prototype = { setParams: function(params){ this._options.params = params; }, getInProgress: function(){ return this._filesInProgress; }, _createUploadButton: function(element){ var self = this; var button = new qq.UploadButton({ element: element, multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(), acceptFiles: this._options.acceptFiles, onChange: function(input){ self._onInputChange(input); } }); this.addDisposer(function() { button.dispose(); }); return button; }, _createUploadHandler: function(){ var self = this, handlerClass; if(qq.UploadHandlerXhr.isSupported()){ handlerClass = 'UploadHandlerXhr'; } else { handlerClass = 'UploadHandlerForm'; } var handler = new qq[handlerClass]({ debug: this._options.debug, action: this._options.action, encoding: this._options.encoding, maxConnections: this._options.maxConnections, customHeaders: this._options.customHeaders, inputName: this._options.inputName, extraDropzones: this._options.extraDropzones, onProgress: function(id, fileName, loaded, total){ self._onProgress(id, fileName, loaded, total); self._options.onProgress(id, fileName, loaded, total); }, onComplete: function(id, fileName, result){ self._onComplete(id, fileName, result); self._options.onComplete(id, fileName, result); }, onCancel: function(id, fileName){ self._onCancel(id, fileName); self._options.onCancel(id, fileName); }, onError: self._options.onError, onUpload: function(id, fileName, xhr){ self._onUpload(id, fileName, xhr); self._options.onUpload(id, fileName, xhr); } }); return handler; }, _preventLeaveInProgress: function(){ var self = this; this._attach(window, 'beforeunload', function(e){ if (!self._filesInProgress){return;} var e = e || window.event; // for ie, ff e.returnValue = self._options.messages.onLeave; // for webkit return self._options.messages.onLeave; }); }, _onSubmit: function(id, fileName){ this._filesInProgress++; }, _onProgress: function(id, fileName, loaded, total){ }, _onComplete: function(id, fileName, result){ this._filesInProgress--; if (result.error){ this._options.showMessage(result.error); } }, _onCancel: function(id, fileName){ this._filesInProgress--; }, _onUpload: function(id, fileName, xhr){ }, _onInputChange: function(input){ if (this._handler instanceof qq.UploadHandlerXhr){ this._uploadFileList(input.files); } else { if (this._validateFile(input)){ this._uploadFile(input); } } this._button.reset(); }, _uploadFileList: function(files){ var goodFiles = []; for (var i=0; i<files.length; i++){ if (this._validateFile(files[i])){ goodFiles.push(files[i]); } else { if (this._options.abortOnFailure) return; } } for (var i=0; i<goodFiles.length; i++){ this._uploadFile(goodFiles[i]); } }, _uploadFile: function(fileContainer){ var id = this._handler.add(fileContainer); var fileName = this._handler.getName(id); if (this._options.onSubmit(id, fileName) !== false){ this._onSubmit(id, fileName); this._handler.upload(id, this._options.params); } }, _validateFile: function(file){ var name, size; if (file.value){ // it is a file input // get input value and remove path to normalize name = file.value.replace(/.*(\/|\\)/, ""); } else { // fix missing properties in Safari 4 and firefox 11.0a2 name = (file.fileName !== null && file.fileName !== undefined) ? file.fileName : file.name; size = (file.fileSize !== null && file.fileSize !== undefined) ? file.fileSize : file.size; } if (! this._isAllowedExtension(name)){ this._error('typeError', name); return false; } else if (size === 0){ this._error('emptyError', name); return false; } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){ this._error('sizeError', name); return false; } else if (size && size < this._options.minSizeLimit){ this._error('minSizeError', name); return false; } return true; }, _error: function(code, fileName){ var message = this._options.messages[code]; function r(name, replacement){ message = message.replace(name, replacement); } r('{file}', this._formatFileName(fileName)); r('{extensions}', this._options.allowedExtensions.join(', ')); r('{sizeLimit}', this._formatSize(this._options.sizeLimit)); r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit)); this._options.showMessage(message); }, _formatFileName: function(name){ if (name.length > 33){ name = name.slice(0, 19) + '...' + name.slice(-13); } return name; }, _isAllowedExtension: function(fileName){ var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : ''; var allowed = this._options.allowedExtensions; if (!allowed.length){return true;} for (var i=0; i<allowed.length; i++){ if (allowed[i].toLowerCase() == ext){ return true;} } return false; }, _formatSize: function(bytes){ var i = -1; do { bytes = bytes / 1024; i++; } while (bytes > 99); return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i]; } }; /** * Class that creates upload widget with drag-and-drop and file list * @inherits qq.FileUploaderBasic */ qq.FileUploader = function(o){ // call parent constructor qq.FileUploaderBasic.apply(this, arguments); // additional options qq.extend(this._options, { element: null, // if set, will be used instead of qq-upload-list in template listElement: null, dragText: 'Drop files here to upload', uploadButtonText: 'Upload File', cancelButtonText: 'Cancel', failUploadText: 'Upload failed', hideShowDropArea: true, template: '<div class="qq-uploader">' + '<div class="qq-upload-drop-area"><span>{dragText}</span></div>' + '<div class="qq-upload-button">{uploadButtonText}</div>' + '<ul class="qq-upload-list"></ul>' + '</div>', // template for one item in file list fileTemplate: '<li>' + '<span class="qq-progress-bar"></span>' + '<span class="qq-upload-file"></span>' + '<span class="qq-upload-spinner"></span>' + '<span class="qq-upload-size"></span>' + '<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' + '<span class="qq-upload-failed-text">{failUploadtext}</span>' + '</li>', classes: { // used to get elements from templates button: 'qq-upload-button', drop: 'qq-upload-drop-area', dropActive: 'qq-upload-drop-area-active', dropDisabled: 'qq-upload-drop-area-disabled', list: 'qq-upload-list', progressBar: 'qq-progress-bar', file: 'qq-upload-file', spinner: 'qq-upload-spinner', size: 'qq-upload-size', cancel: 'qq-upload-cancel', // added to list item <li> when upload completes // used in css to hide progress spinner success: 'qq-upload-success', fail: 'qq-upload-fail' } }); // overwrite options with user supplied qq.extend(this._options, o); // overwrite the upload button text if any // same for the Cancel button and Fail message text this._options.template = this._options.template.replace(/\{dragText\}/g, this._options.dragText); this._options.template = this._options.template.replace(/\{uploadButtonText\}/g, this._options.uploadButtonText); this._options.fileTemplate = this._options.fileTemplate.replace(/\{cancelButtonText\}/g, this._options.cancelButtonText); this._options.fileTemplate = this._options.fileTemplate.replace(/\{failUploadtext\}/g, this._options.failUploadText); this._element = this._options.element; this._element.innerHTML = this._options.template; this._listElement = this._options.listElement || this._find(this._element, 'list'); this._classes = this._options.classes; this._button = this._createUploadButton(this._find(this._element, 'button')); this._bindCancelEvent(); this._setupDragDrop(); }; // inherit from Basic Uploader qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype); qq.extend(qq.FileUploader.prototype, { addExtraDropzone: function(element){ this._setupExtraDropzone(element); }, removeExtraDropzone: function(element){ var dzs = this._options.extraDropzones; for(var i in dzs) if (dzs[i] === element) return this._options.extraDropzones.splice(i,1); }, _leaving_document_out: function(e){ return ((qq.chrome() || (qq.safari() && qq.windows())) && e.clientX == 0 && e.clientY == 0) // null coords for Chrome and Safari Windows || (qq.firefox() && !e.relatedTarget); // null e.relatedTarget for Firefox }, /** * Gets one of the elements listed in this._options.classes **/ _find: function(parent, type){ var element = qq.getByClass(parent, this._options.classes[type])[0]; if (!element){ throw new Error('element not found ' + type); } return element; }, _setupExtraDropzone: function(element){ this._options.extraDropzones.push(element); this._setupDropzone(element); }, _setupDropzone: function(dropArea){ var self = this; var dz = new qq.UploadDropZone({ element: dropArea, onEnter: function(e){ qq.addClass(dropArea, self._classes.dropActive); e.stopPropagation(); }, onLeave: function(e){ //e.stopPropagation(); }, onLeaveNotDescendants: function(e){ qq.removeClass(dropArea, self._classes.dropActive); }, onDrop: function(e){ if (self._options.hideShowDropArea) { dropArea.style.display = 'none'; } qq.removeClass(dropArea, self._classes.dropActive); self._uploadFileList(e.dataTransfer.files); } }); this.addDisposer(function() { dz.dispose(); }); if (this._options.hideShowDropArea) { dropArea.style.display = 'none'; } }, _setupDragDrop: function(){ var dropArea = this._find(this._element, 'drop'); var self = this; this._options.extraDropzones.push(dropArea); var dropzones = this._options.extraDropzones; var i; for (i=0; i < dropzones.length; i++){ this._setupDropzone(dropzones[i]); } // IE <= 9 does not support the File API used for drag+drop uploads // Any volunteers to enable & test this for IE10? if (!qq.ie()) { this._attach(document, 'dragenter', function(e){ // console.log(); if (!self._isValidFileDrag(e)) return; // now causing error. Need it be here? if (qq.hasClass(dropArea, self._classes.dropDisabled)) return; dropArea.style.display = 'block'; for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'block'; } }); } this._attach(document, 'dragleave', function(e){ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); // only fire when leaving document out if (self._options.hideShowDropArea && qq.FileUploader.prototype._leaving_document_out(e)) { for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'none'; } } }); qq.attach(document, 'drop', function(e){ if (self._options.hideShowDropArea) { for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'none'; } } e.preventDefault(); }); }, _onSubmit: function(id, fileName){ qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments); this._addToList(id, fileName); }, // Update the progress bar & percentage as the file is uploaded _onProgress: function(id, fileName, loaded, total){ qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments); var item = this._getItemByFileId(id); var size = this._find(item, 'size'); size.style.display = 'inline'; var text; var percent = Math.round(loaded / total * 100); if (loaded != total) { // If still uploading, display percentage text = percent + '% from ' + this._formatSize(total); } else { // If complete, just display final size text = this._formatSize(total); } // Update progress bar <span> tag this._find(item, 'progressBar').style.width = percent + '%'; qq.setText(size, text); }, _onComplete: function(id, fileName, result){ qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments); // mark completed var item = this._getItemByFileId(id); qq.remove(this._find(item, 'cancel')); qq.remove(this._find(item, 'spinner')); if (result.success){ qq.addClass(item, this._classes.success); } else { qq.addClass(item, this._classes.fail); } }, _addToList: function(id, fileName){ var item = qq.toElement(this._options.fileTemplate); item.qqFileId = id; var fileElement = this._find(item, 'file'); qq.setText(fileElement, this._formatFileName(fileName)); this._find(item, 'size').style.display = 'none'; if (!this._options.multiple) this._clearList(); this._listElement.appendChild(item); }, _clearList: function(){ this._listElement.innerHTML = ''; }, _getItemByFileId: function(id){ var item = this._listElement.firstChild; // there can't be txt nodes in dynamically created list // and we can use nextSibling while (item){ if (item.qqFileId == id) return item; item = item.nextSibling; } }, /** * delegate click event for cancel link **/ _bindCancelEvent: function(){ var self = this, list = this._listElement; this._attach(list, 'click', function(e){ e = e || window.event; var target = e.target || e.srcElement; if (qq.hasClass(target, self._classes.cancel)){ qq.preventDefault(e); var item = target.parentNode; self._handler.cancel(item.qqFileId); qq.remove(item); } }); } }); qq.UploadDropZone = function(o){ this._options = { element: null, onEnter: function(e){}, onLeave: function(e){}, // is not fired when leaving element by hovering descendants onLeaveNotDescendants: function(e){}, onDrop: function(e){} }; qq.extend(this._options, o); qq.extend(this, qq.DisposeSupport); this._element = this._options.element; this._disableDropOutside(); this._attachEvents(); }; qq.UploadDropZone.prototype = { _dragover_should_be_canceled: function(){ return qq.safari() || (qq.firefox() && qq.windows()); }, _disableDropOutside: function(e){ // run only once for all instances if (!qq.UploadDropZone.dropOutsideDisabled ){ // for these cases we need to catch onDrop to reset dropArea if (this._dragover_should_be_canceled){ qq.attach(document, 'dragover', function(e){ e.preventDefault(); }); } else { qq.attach(document, 'dragover', function(e){ if (e.dataTransfer){ e.dataTransfer.dropEffect = 'none'; e.preventDefault(); } }); } qq.UploadDropZone.dropOutsideDisabled = true; } }, _attachEvents: function(){ var self = this; self._attach(self._element, 'dragover', function(e){ if (!self._isValidFileDrag(e)) return; var effect = qq.ie() ? null : e.dataTransfer.effectAllowed; if (effect == 'move' || effect == 'linkMove'){ e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed) } else { e.dataTransfer.dropEffect = 'copy'; // for Chrome } e.stopPropagation(); e.preventDefault(); }); self._attach(self._element, 'dragenter', function(e){ if (!self._isValidFileDrag(e)) return; self._options.onEnter(e); }); self._attach(self._element, 'dragleave', function(e){ if (!self._isValidFileDrag(e)) return; self._options.onLeave(e); var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); // do not fire when moving a mouse over a descendant if (qq.contains(this, relatedTarget)) return; self._options.onLeaveNotDescendants(e); }); self._attach(self._element, 'drop', function(e){ if (!self._isValidFileDrag(e)) return; e.preventDefault(); self._options.onDrop(e); }); }, _isValidFileDrag: function(e){ // e.dataTransfer currently causing IE errors // IE9 does NOT support file API, so drag-and-drop is not possible // IE10 should work, but currently has not been tested - any volunteers? if (qq.ie()) return false; var dt = e.dataTransfer, // do not check dt.types.contains in webkit, because it crashes safari 4 isSafari = qq.safari(); // dt.effectAllowed is none in Safari 5 // dt.types.contains check is for firefox return dt && dt.effectAllowed != 'none' && (dt.files || (!isSafari && dt.types.contains && dt.types.contains('Files'))); } }; qq.UploadButton = function(o){ this._options = { element: null, // if set to true adds multiple attribute to file input multiple: false, acceptFiles: null, // name attribute of file input name: 'file', onChange: function(input){}, hoverClass: 'qq-upload-button-hover', focusClass: 'qq-upload-button-focus' }; qq.extend(this._options, o); qq.extend(this, qq.DisposeSupport); this._element = this._options.element; // make button suitable container for input qq.css(this._element, { position: 'relative', overflow: 'hidden', // Make sure browse button is in the right side // in Internet Explorer direction: 'ltr' }); this._input = this._createInput(); }; qq.UploadButton.prototype = { /* returns file input element */ getInput: function(){ return this._input; }, /* cleans/recreates the file input */ reset: function(){ if (this._input.parentNode){ qq.remove(this._input); } qq.removeClass(this._element, this._options.focusClass); this._input = this._createInput(); }, _createInput: function(){ var input = document.createElement("input"); if (this._options.multiple){ input.setAttribute("multiple", "multiple"); } if (this._options.acceptFiles) input.setAttribute("accept", this._options.acceptFiles); input.setAttribute("type", "file"); input.setAttribute("name", this._options.name); qq.css(input, { position: 'absolute', // in Opera only 'browse' button // is clickable and it is located at // the right side of the input right: 0, top: 0, fontFamily: 'Arial', // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118 fontSize: '118px', margin: 0, padding: 0, cursor: 'pointer', opacity: 0 }); this._element.appendChild(input); var self = this; this._attach(input, 'change', function(){ self._options.onChange(input); }); this._attach(input, 'mouseover', function(){ qq.addClass(self._element, self._options.hoverClass); }); this._attach(input, 'mouseout', function(){ qq.removeClass(self._element, self._options.hoverClass); }); this._attach(input, 'focus', function(){ qq.addClass(self._element, self._options.focusClass); }); this._attach(input, 'blur', function(){ qq.removeClass(self._element, self._options.focusClass); }); // IE and Opera, unfortunately have 2 tab stops on file input // which is unacceptable in our case, disable keyboard access if (window.attachEvent){ // it is IE or Opera input.setAttribute('tabIndex', "-1"); } return input; } }; /** * Class for uploading files, uploading itself is handled by child classes */ qq.UploadHandlerAbstract = function(o){ // Default options, can be overridden by the user this._options = { debug: false, action: '/upload.php', // maximum number of concurrent uploads maxConnections: 999, onProgress: function(id, fileName, loaded, total){}, onComplete: function(id, fileName, response){}, onCancel: function(id, fileName){}, onUpload: function(id, fileName, xhr){} }; qq.extend(this._options, o); this._queue = []; // params for files in queue this._params = []; }; qq.UploadHandlerAbstract.prototype = { log: function(str){ if (this._options.debug && window.console) console.log('[uploader] ' + str); }, /** * Adds file or file input to the queue * @returns id **/ add: function(file){}, /** * Sends the file identified by id and additional query params to the server */ upload: function(id, params){ var len = this._queue.push(id); var copy = {}; qq.extend(copy, params); this._params[id] = copy; // if too many active uploads, wait... if (len <= this._options.maxConnections){ this._upload(id, this._params[id]); } }, /** * Cancels file upload by id */ cancel: function(id){ this._cancel(id); this._dequeue(id); }, /** * Cancells all uploads */ cancelAll: function(){ for (var i=0; i<this._queue.length; i++){ this._cancel(this._queue[i]); } this._queue = []; }, /** * Returns name of the file identified by id */ getName: function(id){}, /** * Returns size of the file identified by id */ getSize: function(id){}, /** * Returns id of files being uploaded or * waiting for their turn */ getQueue: function(){ return this._queue; }, /** * Actual upload method */ _upload: function(id){}, /** * Actual cancel method */ _cancel: function(id){}, /** * Removes element from queue, starts upload of next */ _dequeue: function(id){ var i = qq.indexOf(this._queue, id); this._queue.splice(i, 1); var max = this._options.maxConnections; if (this._queue.length >= max && i < max){ var nextId = this._queue[max-1]; this._upload(nextId, this._params[nextId]); } } }; /** * Class for uploading files using form and iframe * @inherits qq.UploadHandlerAbstract */ qq.UploadHandlerForm = function(o){ qq.UploadHandlerAbstract.apply(this, arguments); this._inputs = {}; }; // @inherits qq.UploadHandlerAbstract qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype); qq.extend(qq.UploadHandlerForm.prototype, { add: function(fileInput){ fileInput.setAttribute('name', this._options.inputName); var id = 'qq-upload-handler-iframe' + qq.getUniqueId(); this._inputs[id] = fileInput; // remove file input from DOM if (fileInput.parentNode){ qq.remove(fileInput); } return id; }, getName: function(id){ // get input value and remove path to normalize return this._inputs[id].value.replace(/.*(\/|\\)/, ""); }, _cancel: function(id){ this._options.onCancel(id, this.getName(id)); delete this._inputs[id]; var iframe = document.getElementById(id); if (iframe){ // to cancel request set src to something else // we use src="javascript:false;" because it doesn't // trigger ie6 prompt on https iframe.setAttribute('src', 'javascript:false;'); qq.remove(iframe); } }, _upload: function(id, params){ this._options.onUpload(id, this.getName(id), false); var input = this._inputs[id]; if (!input){ throw new Error('file with passed id was not added, or already uploaded or cancelled'); } var fileName = this.getName(id); var iframe = this._createIframe(id); var form = this._createForm(iframe, params); form.appendChild(input); var self = this; this._attachLoadEvent(iframe, function(){ self.log('iframe loaded'); var response = self._getIframeContentJSON(iframe); self._options.onComplete(id, fileName, response); self._dequeue(id); delete self._inputs[id]; // timeout added to fix busy state in FF3.6 setTimeout(function(){ self._detach_event(); qq.remove(iframe); }, 1); }); form.submit(); qq.remove(form); return id; }, _attachLoadEvent: function(iframe, callback){ this._detach_event = qq.attach(iframe, 'load', function(){ // when we remove iframe from dom // the request stops, but in IE load // event fires if (!iframe.parentNode){ return; } // fixing Opera 10.53 if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false"){ // In Opera event is fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec // when we upload file with iframe return; } callback(); }); }, /** * Returns json object received by iframe from server. */ _getIframeContentJSON: function(iframe){ // iframe.contentWindow.document - for IE<7 var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document, response; var innerHTML = doc.body.innerHTML; this.log("converting iframe's innerHTML to JSON"); this.log("innerHTML = " + innerHTML); //plain text response may be wrapped in <pre> tag if (innerHTML.slice(0, 5).toLowerCase() == '<pre>' && innerHTML.slice(-6).toLowerCase() == '</pre>') { innerHTML = doc.body.firstChild.firstChild.nodeValue; } try { response = eval("(" + innerHTML + ")"); } catch(err){ response = {}; } return response; }, /** * Creates iframe with unique name */ _createIframe: function(id){ // We can't use following code as the name attribute // won't be properly registered in IE6, and new window // on form submit will open // var iframe = document.createElement('iframe'); // iframe.setAttribute('name', id); var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />'); // src="javascript:false;" removes ie6 prompt on https iframe.setAttribute('id', id); iframe.style.display = 'none'; document.body.appendChild(iframe); return iframe; }, /** * Creates form, that will be submitted to iframe */ _createForm: function(iframe, params){ // We can't use the following code in IE6 // var form = document.createElement('form'); // form.setAttribute('method', 'post'); // form.setAttribute('enctype', 'multipart/form-data'); // Because in this case file won't be attached to request var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>'); var queryString = qq.obj2url(params, this._options.action); form.setAttribute('action', queryString); form.setAttribute('target', iframe.name); form.style.display = 'none'; document.body.appendChild(form); return form; } }); /** * Class for uploading files using xhr * @inherits qq.UploadHandlerAbstract */ qq.UploadHandlerXhr = function(o){ qq.UploadHandlerAbstract.apply(this, arguments); this._files = []; this._xhrs = []; // current loaded size in bytes for each file this._loaded = []; }; // static method qq.UploadHandlerXhr.isSupported = function(){ var input = document.createElement('input'); input.type = 'file'; return ( 'multiple' in input && typeof File != "undefined" && typeof FormData != "undefined" && typeof (new XMLHttpRequest()).upload != "undefined" ); }; // @inherits qq.UploadHandlerAbstract qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype); qq.extend(qq.UploadHandlerXhr.prototype, { /** * Adds file to the queue * Returns id to use with upload, cancel **/ add: function(file){ if (!(file instanceof File)){ throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)'); } return this._files.push(file) - 1; }, getName: function(id){ var file = this._files[id]; // fix missing name in Safari 4 //NOTE: fixed missing name firefox 11.0a2 file.fileName is actually undefined return (file.fileName !== null && file.fileName !== undefined) ? file.fileName : file.name; }, getSize: function(id){ var file = this._files[id]; return file.fileSize != null ? file.fileSize : file.size; }, /** * Returns uploaded bytes for file identified by id */ getLoaded: function(id){ return this._loaded[id] || 0; }, /** * Sends the file identified by id and additional query params to the server * @param {Object} params name-value string pairs */ _upload: function(id, params){ this._options.onUpload(id, this.getName(id), true); var file = this._files[id], name = this.getName(id), size = this.getSize(id); this._loaded[id] = 0; var xhr = this._xhrs[id] = new XMLHttpRequest(); var self = this; xhr.upload.onprogress = function(e){ if (e.lengthComputable){ self._loaded[id] = e.loaded; self._options.onProgress(id, name, e.loaded, e.total); } }; xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ self._onComplete(id, xhr); } }; // build query string params = params || {}; params[this._options.inputName] = name; var queryString = qq.obj2url(params, this._options.action); xhr.open("POST", queryString, true); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-File-Name", encodeURIComponent(name)); if (this._options.encoding == 'multipart') { var formData = new FormData(); formData.append(name, file); file = formData; } else { xhr.setRequestHeader("Content-Type", "application/octet-stream"); //NOTE: return mime type in xhr works on chrome 16.0.9 firefox 11.0a2 xhr.setRequestHeader("X-Mime-Type",file.type ); } for (key in this._options.customHeaders){ xhr.setRequestHeader(key, this._options.customHeaders[key]); }; xhr.send(file); }, _onComplete: function(id, xhr){ // the request was aborted/cancelled if (!this._files[id]) return; var name = this.getName(id); var size = this.getSize(id); this._options.onProgress(id, name, size, size); if (xhr.status == 200){ this.log("xhr - server response received"); this.log("responseText = " + xhr.responseText); var response; try { response = eval("(" + xhr.responseText + ")"); } catch(err){ response = {}; } this._options.onComplete(id, name, response); } else { this._options.onError(id, name, xhr); this._options.onComplete(id, name, {}); } this._files[id] = null; this._xhrs[id] = null; this._dequeue(id); }, _cancel: function(id){ this._options.onCancel(id, this.getName(id)); this._files[id] = null; if (this._xhrs[id]){ this._xhrs[id].abort(); this._xhrs[id] = null; } } }); /** * A generic module which supports object disposing in dispose() method. * */ qq.DisposeSupport = { _disposers: [], /** Run all registered disposers */ dispose: function() { var disposer; while (disposer = this._disposers.shift()) { disposer(); } }, /** Add disposer to the collection */ addDisposer: function(disposeFunction) { this._disposers.push(disposeFunction); }, /** Attach event handler and register de-attacher as a disposer */ _attach: function() { this.addDisposer(qq.attach.apply(this, arguments)); } };
JavaScript
$(function() { function setupTablesorter() { // Method money $.tablesorter.addParser({ id: "money", is: function(s) { return true; }, format: function(s) { return $.tablesorter.formatFloat(s.replace(/ /, '').replace('R$', '').replace(/\./, '').replace(/\,/, '.').replace(new RegExp(/[^0-9,]/g),"")); }, type: "numeric" }); var classHeaders = { 'text': '.sorter-text', 'digit': '.sorter-digit', 'currency': '.sorter-currency', 'ipAddress': '.sorter-ipAddress', 'url': '.sorter-url', 'isoDate': '.sorter-isoDate', 'usLongDate': '.sorter-usLongDate', 'shortDate': '.sorter-shortDate', 'time': '.sorter-time', 'metadata': '.sorter-metadata', 'money': '.sorter-money', }; var tableHeaders = '', separator; $('.tablesorter').each(function (i, e) { $.each(classHeaders, function(key, value){ $(this).find(value).each(function (pos) { if(separator == undefined) separator = ','; tableHeaders += separator +' '+ $(this).index()+' : { sorter: "'+key+'"}'; }); }); console.log(tableHeaders); $(this).tablesorter({dateFormat: 'uk', noSorterClass: 'no-sorter', headers: tableHeaders }); }); } if($('.tablesorter')[0]) setupTablesorter(); });
JavaScript
/*! * jQuery Form Plugin * version: 2.72 (28-APR-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') { options = { success: options }; } var action = this.attr('action'); var url = (typeof action === 'string') ? $.trim(action) : ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } url = url || window.location.href || ''; options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var $form = this, callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, fileUpload); } else { fileUpload(); } } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } var s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id; var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, e); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; var g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } var timedOut = 0, timeoutHandle; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') { form.setAttribute('method', 'POST'); } if (form.getAttribute('action') != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout); } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />') .appendTo(form)[0]); } } // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } if (e === true && xhr) { xhr.abort('timeout'); return; } var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (!xhr.responseText && xhr.responseXML && !s.dataType) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; var scr = /(json|script|text)/.test(s.dataType); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = httpData(xhr, s.dataType, s); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); } if (xhr.aborted) { log('upload aborted'); ok = false; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error'); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } }; })(jQuery);
JavaScript
function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+escape(value)+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length)); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }
JavaScript
$(function(){ var save_and_close = false; if($('#fancybox-loading')[0]){ $('#fancybox-loading').remove(); } // Salva as informações e retorna a listagem inicial $('#save-and-go-back-button').click(function(){ save_and_close = true; submitCrudForm($('#crudForm'), save_and_close); }); // Faz as verificações e submete o formulario $('.submit-form').on('click', function(){ submitCrudForm($('#crudForm'), save_and_close); }); $('.return-to-list').on('click', function() { goToList('Confirmation', message_alert_edit_form); $('.ok-confirmation').data('target-url', $(this).data('target-url')); return false; }); }); // Mensagens para a aplicação var alert_message = function(type_message, text_message){ $('.modal-message.'+type_message).remove(); $('#message-box').prepend('<div class="alert '+type_message+' modal-message"><span class="icon"></span><span class="close">x</span>'+text_message+'</div>'); $('html, body').animate({ scrollTop:0 }, 600); $("#ajax-loading").fadeOut('fast'); window.setTimeout( function(){ $('.modal-message.'+type_message).slideUp(); }, 7000); return false; }; // Simula o efeito RESET no formulário de inserção de conteudo function clearForm() { $('#crudForm').find(':input').each(function() { switch(this.type) { case 'password': case 'select-multiple': case 'select-one': case 'text': case 'textarea': $(this).val(''); break; case 'checkbox': case 'radio': this.checked = false; } }); /* Clear upload inputs */ $('.open-file, .gc-file-upload, .hidden-upload-input').each(function(){ $(this).val(''); }); $('.upload-success-url').hide(); $('.fileinput-button').fadeIn("normal"); /* -------------------- */ $('.remove-all').each(function(){ $(this).trigger('click'); }); $('.chosen-multiple-select, .chosen-select, .ajax-chosen-select').each(function(){ $(this).trigger("liszt:updated"); }); } // Submete o formulário para inserir os dados no BD function submitCrudForm( crud_form, save_and_close ){ crud_form.ajaxSubmit({ url: validation_url, dataType: 'json', cache: 'false', beforeSend: function(){ $("#ajax-loading").fadeIn('fast'); }, afterSend: function(){ $("#ajax-loading").fadeOut('fast'); }, success: function(data){ $("#ajax-loading").fadeOut('fast'); if(data.success) { $('#crudForm').ajaxSubmit({ dataType: 'text', cache: 'false', beforeSend: function(){ $("#ajax-loading").addClass('show loading'); }, success: function(result){ $("#ajax-loading").fadeOut("slow"); data = $.parseJSON( result ); if(data.success) { if(save_and_close) { window.location = data.success_list_url; return true; } alert_message('sucess', data.success_message); } else { alert_message('error', message_update_error); } }, error: function(){ alert_message('error', message_update_error); } }); } else { $('.field_error').each(function(){ $(this).removeClass('field_error'); }); alert_message('error', data.error_message); $.each(data.error_fields, function(index,value){ $('input[name='+index+']').addClass('field_error'); }); } }, error: function(){ $("#ajax-loading").fadeOut('fast'); alert_message('error', message_update_error); } }); return false; } // Retornar para a tabela de listagem de dados inicial function goToList(title_modal, message_text){ if ($('#dialog_modal_message')[0]){ $('#dialog_modal_message').remove(); } var modal_content = '<div id="dialog_modal_message" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="dialog_modal_message_label" aria-hidden="true"><div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="dialog_modal_message_label">' + title_modal + '</h3></div><div class="modal-body"> <p>'+ message_text + '</p></div><div class="modal-footer"> <button class="btn cancel-confirmation" data-dismiss="modal" aria-hidden="true">Cancel</button> <button class="btn btn-primary ok-confirmation">Ok</button></div></div>'; $('#message-box').after(modal_content); $('#dialog_modal_message') .modal({ keyboard: false }) .on('shown', function(){ $(this).find('button.cancel-confirmation').click(function(){ $('button.close').trigger('click'); }).end().find('button.ok-confirmation').click(function(){ window.location = list_url; $('button.close').trigger('click'); }); }); }
JavaScript
$(function(){ var save_and_close = false; if($('#fancybox-loading')[0]){ $('#fancybox-loading').remove(); } // Salva as informações e retorna a listagem inicial $('#save-and-go-back-button').click(function(){ save_and_close = true; submitCrudForm($('#crudForm'), save_and_close); }); // Faz as verificações e submete o formulario $('.submit-form').on('click', function(){ submitCrudForm($('#crudForm'), save_and_close); }); $('.return-to-list').on('click', function() { goToList('Confirmation', message_alert_add_form); $('.ok-confirmation').data('target-url', $(this).data('target-url')); return false; }); }); // Mensagens para a aplicação var alert_message = function(type_message, text_message){ $('.modal-message.'+type_message).remove(); $('#message-box').prepend('<div class="alert '+type_message+' modal-message"><span class="icon"></span><span class="close">x</span>'+text_message+'</div>'); $('html, body').animate({ scrollTop:0 }, 600); $("#ajax-loading").fadeOut('fast'); window.setTimeout( function(){ $('.modal-message.'+type_message).slideUp(); }, 7000); return false; }; // Simula o efeito RESET no formulário de inserção de conteudo function clearForm() { $('#crudForm').find(':input').each(function() { switch(this.type) { case 'password': case 'select-multiple': case 'select-one': case 'text': case 'textarea': $(this).val(''); break; case 'checkbox': case 'radio': this.checked = false; } }); /* Clear upload inputs */ $('.open-file, .gc-file-upload, .hidden-upload-input').each(function(){ $(this).val(''); }); $('.upload-success-url').hide(); $('.fileinput-button').fadeIn("normal"); /* -------------------- */ $('.remove-all').each(function(){ $(this).trigger('click'); }); $('.chosen-multiple-select, .chosen-select, .ajax-chosen-select').each(function(){ $(this).trigger("liszt:updated"); }); } // Submete o formulário para inserir os dados no BD function submitCrudForm( crud_form, save_and_close ){ crud_form.ajaxSubmit({ url: validation_url, dataType: 'json', cache: 'false', beforeSend: function(){ $("#ajax-loading").fadeIn('fast'); }, afterSend: function(){ $("#ajax-loading").fadeOut('fast'); }, success: function(data){ $("#ajax-loading").fadeOut('fast'); if(data.success) { $('#crudForm').ajaxSubmit({ dataType: 'text', cache: 'false', beforeSend: function(){ $("#ajax-loading").addClass('show loading'); }, success: function(result){ data = $.parseJSON( result ); if(data.success) { if(save_and_close) { window.location = data.success_list_url; return true; } $('.form-input-box').each(function(){ $(this).removeClass('error'); }); clearForm(); alert_message('success', data.success_message); } else { alert_message('error', message_insert_error); } }, error: function(){ alert_message('error', message_insert_error); } }); } else { $('.form-input-box').removeClass('error'); alert_message('error', data.error_message); $.each(data.error_fields, function(index,value){ $('input[name='+index+']').addClass('error'); }); } }, error: function(){ $("#ajax-loading").fadeOut('fast'); alert_message('error', message_insert_error); } }); return false; } // Retornar para a tabela de listagem de dados inicial function goToList(title_modal, message_text){ if ($('#dialog_modal_message')[0]){ $('#dialog_modal_message').remove(); } var modal_content = '<div id="dialog_modal_message" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="dialog_modal_message_label" aria-hidden="true"><div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="dialog_modal_message_label">' + title_modal + '</h3></div><div class="modal-body"> <p>'+ message_text + '</p></div><div class="modal-footer"> <button class="btn cancel-confirmation" data-dismiss="modal" aria-hidden="true">Cancel</button> <button class="btn btn-primary ok-confirmation">Ok</button></div></div>'; $('#message-box').after(modal_content); $('#dialog_modal_message') .modal({ keyboard: false }) .on('shown', function(){ $(this).find('button.cancel-confirmation').click(function(){ $('button.close').trigger('click'); }).end().find('button.ok-confirmation').click(function(){ window.location = list_url; $('button.close').trigger('click'); }); }); }
JavaScript
/** * Arquivo com as configurações iniciais do Grocery CRUD * * - list_template.php * - list.php */ // Mensagens para a aplicação var alert_message = function(type_message, text_message){ $('.alert-'+type_message).remove(); $('#message-box').prepend('<div class="alert alert-'+type_message+' fade in"><a class="close" data-dismiss="alert" href="#"> x </a>'+text_message+'</div>'); $('html, body').animate({ scrollTop:0 }, 600); window.setTimeout( function(){ $('.alert-'+type_message).slideUp(); }, 7000); $("#ajax-loading").addClass('hide'); return false; }; $(function(){ var call_fancybox = function(){} if($('.image-thumbnail')[0]){ var call_fancybox = function(){ $('.image-thumbnail').fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, 'speedOut' : 200, 'overlayShow' : false }); }; } call_fancybox(); /** * Retornando a busca feita na aplicacao * @param int crud_page paginacao inicial * @param int last_page paginacao final * @return false */ $('#filtering_form').submit(function(){ var crud_page = parseInt($('#tb_crud_page').val()), last_page = parseInt($('#last-page-number').html()), this_form = $(this); $('#ajax-loading').removeClass('hide'); $('.first-button, .last-button').removeClass('disabled'); if(crud_page > last_page){ $('#tb_crud_page').val(last_page); }else if(crud_page <= 1){ $('#tb_crud_page').val('1'); $('.first-button').addClass('disabled'); }else if(crud_page >= last_page){ $('.last-button').addClass('disabled'); } // Inserindo valores da quantidade de registros e pagina atual no formulario $('input[name="per_page"]').val($('#tb_per_page').val()); $('input[name="page"]').val($('#tb_crud_page').val()); $(this).ajaxSubmit({ url: ajax_list_info_url, dataType: 'json', success: function(data){ $('#total_items').html( data.total_results); displaying_and_pages(); this_form.ajaxSubmit({ success: function(data){ $('#ajax_list').html(data); call_fancybox(); } }); } }); // Criando os cookies para a paginacao createCookie('crud_page_'+unique_hash, crud_page, 1); createCookie('per_page_'+unique_hash, $('#per_page').val(), 1); createCookie('hidden_ordering_'+unique_hash, $('#hidden-ordering').val(), 1); createCookie('hidden_sorting_'+unique_hash, $('#hidden-sorting').val(), 1); createCookie('search_text_'+unique_hash, $('#search_text').val(), 1); createCookie('search_field_'+unique_hash, $('#search_field').val(), 1); $('#ajax-loading').addClass('hide'); return false; }).trigger('submit'); // Submete a busca com as informacoes a serem buscadas $('#crud_search').click(function(){ $('#crud_page').val('1'); $('#filtering_form').trigger('submit'); }); // Limpa o formulario de busca E Submete o formulario de busca vazio para que retorne a listagem original $('#search_clear').click(function(){ $('#crud_page').val('1'); $('#search_text').val(''); $('#filtering_form').trigger('submit'); }); // Verifica o modificador de quantidade de registros por paginação $('#tb_per_page').change(function(){ $('#tb_crud_page').val('1'); $('#filtering_form').trigger('submit'); }); // Insere a imagem de Loading ajax $('#filtering_form').ajaxStart(function(){ $('#ajax-loading').removeClass('hide'); }); // Remove a imagem de loading ajax $('#filtering_form').ajaxStop(function(){ $('#ajax-loading').addClass('hide'); }); // Submete a busca $('#ajax-loading').click(function(){ $('#filtering_form').trigger('submit'); }); // Insere a visualização a partir do primeiro índice da paginação $('.first-button').click(function(){ $('#tb_crud_page').val('1'); $('#filtering_form').trigger('submit'); }); // Insere a visualização a partir do índice anterior da paginação $('.prev-button').click(function(){ if( $('#tb_crud_page').val() != "1") { $('#tb_crud_page').val( parseInt($('#tb_crud_page').val()) - 1 ); $('#tb_crud_page').trigger('change'); } }); // Insere a visualização a partir do último índice da paginação $('.last-button').click(function(){ $('#tb_crud_page').val( $('#last-page-number').html()); $('#filtering_form').trigger('submit'); }); // Insere a visualização a partir do próximo índice da paginação $('.next-button').click(function(){ $('#tb_crud_page').val( parseInt($('#tb_crud_page').val()) + 1 ); $('#tb_crud_page').trigger('change'); }); // Submete a busca caso o valor da paginação seja modificada manualmente $('#tb_crud_page').change(function(){ $('#filtering_form').trigger('submit'); }); // Modifica a ordenação da tabela com base no nome do campo no banco de dados que está no REL da classe // ".field-sorting" inserida no th da tabela $('.field-sorting').live('click', function(){ $('#hidden-sorting').val($(this).attr('rel')); if($(this).hasClass('asc')) $('#hidden-ordering').val('desc'); else $('#hidden-ordering').val('asc'); $('#crud_page').val('1'); $('#filtering_form').trigger('submit'); }); // Exporta as importações da tabela para um arquivo .CSV $('.export-anchor').click(function(){ var export_url = $(this).attr('data-url'); var form_input_html = ''; $.each($('#filtering_form').serializeArray(), function(i, field) { form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">'; }); var form_on_demand = $("<form/>").attr("id","export_form").attr("method","post").attr("target","_blank") .attr("action",export_url).html(form_input_html); $('#hidden-operations').html(form_on_demand); $('#export_form').submit(); }); // Imprime a visualização atual da tabela $('.print-anchor').click(function(){ printTable($(this), $('#filtering_form').serializeArray()); }); $('#crud_page').numeric(); var cookie_crud_page = readCookie('crud_page_'+unique_hash), cookie_per_page = readCookie('per_page_'+unique_hash), hidden_ordering = readCookie('hidden_ordering_'+unique_hash), hidden_sorting = readCookie('hidden_sorting_'+unique_hash), cookie_search_text = readCookie('search_text_'+unique_hash), cookie_search_field = readCookie('search_field_'+unique_hash) ; if(cookie_crud_page !== null && cookie_per_page !== null) { $('#crud_page').val(cookie_crud_page); $('#per_page').val(cookie_per_page); $('#hidden-ordering').val(hidden_ordering); $('#hidden-sorting').val(hidden_sorting); $('#search_text').val(cookie_search_text); $('#search_field').val(cookie_search_field); if(cookie_search_text !== '') $('#quickSearchButton').trigger('click'); $('#filtering_form').trigger('submit'); } $('.delete-row').live('click', function() { confirmationModalDialog('Confirmation', message_alert_delete); $('.ok-confirmation').data('target-url', $(this).data('target-url')); return false; }); }); /** * Print the table visualization's * @param obj class_name objeto de click * @param obj filtering_form Classe serializada para verificação * @return void */ function printTable(class_name, filtering_form){ var print_url = class_name.attr('data-url'); var form_input_html = ''; $.each( filtering_form, function(i, field) { form_input_html += '<input type="hidden" name="'+field.name+'" value="'+field.value+'">'; }); var form_on_demand = $("<form/>").attr("id", "print_form").attr("method", "post").attr("action", print_url).html(form_input_html); $('#hidden-operations').html(form_on_demand); var _this_button = $(this); $('#print_form').ajaxSubmit({ beforeSend: function(){ class_name.find('.fbutton').addClass('loading'); class_name.find('.fbutton>div').css('opacity','0.4'); }, complete: function(){ class_name.find('.fbutton').removeClass('loading'); class_name.find('.fbutton>div').css('opacity','1'); }, success: function(html_data){ $("<div/>").html(html_data).printElement(); } }); return; } /** * Mostra a visualização e paginação da tabela * @return void */ function displaying_and_pages() { if($('#crud_page').val() == 0){ $('#crud_page').val('1'); } var crud_page = parseInt( $('#crud_page').val()), per_page = parseInt( $('#per_page').val() ), total_items = parseInt( $('#total_items').html() ) ; $('#last-page-number').html( Math.ceil( total_items / per_page) ); if (total_items == 0) { $('#page-starts-from').html( '0'); } else { $('#page-starts-from').html( (crud_page - 1)*per_page + 1 ); } if (crud_page*per_page > total_items) { $('#page-ends-to').html( total_items ); } else { $('#page-ends-to').html( crud_page*per_page ); } } // Chama o método para excluir o registro de informação do BD function confirmationModalDialog(title_modal, message_text){ if ($('#dialog_modal_message')[0]){ $('#dialog_modal_message').remove(); } var modal_content = '<div id="dialog_modal_message" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="dialog_modal_message_label" aria-hidden="true"><div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="dialog_modal_message_label">' + title_modal + '</h3></div><div class="modal-body"> <p>'+ message_text + '</p></div><div class="modal-footer"> <button class="btn cancel-confirmation" data-dismiss="modal" aria-hidden="true">Cancel</button> <button class="btn btn-primary ok-confirmation">Ok</button></div></div>'; $('#ajax_list').after(modal_content); $('#dialog_modal_message') .modal({ keyboard: false }) .on('shown', function(){ $(this).find('button.cancel-confirmation').click(function(){ $('button.close').trigger('click'); }).end().find('button.ok-confirmation').click(function(){ deteleGroceryCrudInformation($(this).data('target-url')); $('button.close').trigger('click'); }); }); } // Chama o método para excluir o registro de informação do BD function deteleGroceryCrudInformation(delete_url){ $('#ajax-loading').removeClass('hide'); $.post(delete_url, function(data){ if(data.success) { $('#filtering_form').trigger('submit'); alert_message('success', data.success_message.replace('<p>', '').replace('</p>', '')); } else { alert_message('success', data.error_message.replace('<p>', '').replace('</p>', '')); } }, 'json'); $('#ajax-loading').addClass('hide'); return true; $.ajax({ url: delete_url, dataType: 'json', success: function(data) { if(data.success) { $('#filtering_form').trigger('submit'); alert_message('success', data.success_message.replace('<p>', '').replace('</p>', '')); } else { alert_message('success', data.error_message.replace('<p>', '').replace('</p>', '')); } } }); }
JavaScript
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $(function(){ var $window = $(window) // Disable certain links in docs $('section [href^=#]').click(function (e) { e.preventDefault() }) // side bar $('.bs-docs-sidenav').affix({ offset: { top: function () { return $window.width() <= 980 ? 290 : 210 } , bottom: 270 } }) // make code pretty window.prettyPrint && prettyPrint() // add-ons $('.add-on :checkbox').on('click', function () { var $this = $(this) , method = $this.attr('checked') ? 'addClass' : 'removeClass' $(this).parents('.add-on')[method]('active') }) // add tipsies to grid for scaffolding if ($('#gridSystem').length) { $('#gridSystem').tooltip({ selector: '.show-grid > div' , title: function () { return $(this).width() + 'px' } }) } // tooltip demo $('.tooltip-demo').tooltip({ selector: "a[rel=tooltip]" }) $('.tooltip-test').tooltip() $('.popover-test').popover() // popover demo $("a[rel=popover]") .popover() .click(function(e) { e.preventDefault() }) // button state demo $('#fat-btn') .click(function () { var btn = $(this) btn.button('loading') setTimeout(function () { btn.button('reset') }, 3000) }) // carousel demo $('#myCarousel').carousel() // javascript build logic var inputsComponent = $("#components.download input") , inputsPlugin = $("#plugins.download input") , inputsVariables = $("#variables.download input") // toggle all plugin checkboxes $('#components.download .toggle-all').on('click', function (e) { e.preventDefault() inputsComponent.attr('checked', !inputsComponent.is(':checked')) }) $('#plugins.download .toggle-all').on('click', function (e) { e.preventDefault() inputsPlugin.attr('checked', !inputsPlugin.is(':checked')) }) $('#variables.download .toggle-all').on('click', function (e) { e.preventDefault() inputsVariables.val('') }) // request built javascript $('.download-btn').on('click', function () { var css = $("#components.download input:checked") .map(function () { return this.value }) .toArray() , js = $("#plugins.download input:checked") .map(function () { return this.value }) .toArray() , vars = {} , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png'] $("#variables.download input") .each(function () { $(this).val() && (vars[ $(this).prev().text() ] = $(this).val()) }) $.ajax({ type: 'POST' , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com' , dataType: 'jsonpi' , params: { js: js , css: css , vars: vars , img: img } }) }) }) // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi $.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) { var url = opts.url; return { send: function(_, completeCallback) { var name = 'jQuery_iframe_' + jQuery.now() , iframe, form iframe = $('<iframe>') .attr('name', name) .appendTo('head') form = $('<form>') .attr('method', opts.type) // GET or POST .attr('action', url) .attr('target', name) $.each(opts.params, function(k, v) { $('<input>') .attr('type', 'hidden') .attr('name', k) .attr('value', typeof v == 'string' ? v : JSON.stringify(v)) .appendTo(form) }) form.appendTo('body').submit() } } }) }(window.jQuery)
JavaScript
/* * * TableSorter 2.0 - Client-side table sorting with ease! * Version 2.0.5b * @requires jQuery v1.2.3 * * Copyright (c) 2007 Christian Bach * Examples and docs at: http://tablesorter.com * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * * @description Create a sortable table with multi-column sorting capabilitys * * @example $('table').tablesorter(); * @desc Create a simple tablesorter interface. * * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] }); * @desc Create a tablesorter interface and sort on the first and secound column column headers. * * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } }); * * @desc Create a tablesorter interface and disableing the first and second column headers. * * * @example $('table').tablesorter({ headers: { 0: {sorter:"integer"}, 1: {sorter:"currency"} } }); * * @desc Create a tablesorter interface and set a column parser for the first * and second column. * * * @param Object * settings An object literal containing key/value pairs to provide * optional settings. * * * @option String cssHeader (optional) A string of the class name to be appended * to sortable tr elements in the thead of the table. Default value: * "header" * * @option String cssAsc (optional) A string of the class name to be appended to * sortable tr elements in the thead on a ascending sort. Default value: * "headerSortUp" * * @option String cssDesc (optional) A string of the class name to be appended * to sortable tr elements in the thead on a descending sort. Default * value: "headerSortDown" * * @option String sortInitialOrder (optional) A string of the inital sorting * order can be asc or desc. Default value: "asc" * * @option String sortMultisortKey (optional) A string of the multi-column sort * key. Default value: "shiftKey" * * @option String textExtraction (optional) A string of the text-extraction * method to use. For complex html structures inside td cell set this * option to "complex", on large tables the complex option can be slow. * Default value: "simple" * * @option Object headers (optional) An array containing the forces sorting * rules. This option let's you specify a default sorting rule. Default * value: null * * @option Array sortList (optional) An array containing the forces sorting * rules. This option let's you specify a default sorting rule. Default * value: null * * @option Array sortForce (optional) An array containing forced sorting rules. * This option let's you specify a default sorting rule, which is * prepended to user-selected rules. Default value: null * * @option Boolean sortLocaleCompare (optional) Boolean flag indicating whatever * to use String.localeCampare method or not. Default set to true. * * * @option Array sortAppend (optional) An array containing forced sorting rules. * This option let's you specify a default sorting rule, which is * appended to user-selected rules. Default value: null * * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter * should apply fixed widths to the table columns. This is usefull when * using the pager companion plugin. This options requires the dimension * jquery plugin. Default value: false * * @option Boolean cancelSelection (optional) Boolean flag indicating if * tablesorter should cancel selection of the table headers text. * Default value: true * * @option Boolean debug (optional) Boolean flag indicating if tablesorter * should display debuging information usefull for development. * * @type jQuery * * @name tablesorter * * @cat Plugins/Tablesorter * * @author Christian Bach/christian.bach@polyester.se */ (function ($) { $.extend({ tablesorter: new function () { var parsers = [], widgets = []; this.defaults = { cssHeader: "header", cssAsc: "headerSortUp", cssDesc: "headerSortDown", cssChildRow: "expand-child", sortInitialOrder: "asc", sortMultiSortKey: "shiftKey", sortForce: null, sortAppend: null, sortLocaleCompare: true, textExtraction: "simple", parsers: {}, widgets: [], widgetZebra: { css: ["even", "odd"] }, headers: {}, widthFixed: false, cancelSelection: true, sortList: [], headerList: [], dateFormat: "us", decimal: '/\.|\,/g', onRenderHeader: null, selectorHeaders: 'thead th', debug: false, noSorterClass: 'no-sorter' }; /* debuging utils */ function benchmark(s, d) { log(s + "," + (new Date().getTime() - d.getTime()) + "ms"); } this.benchmark = benchmark; function log(s) { if (typeof console != "undefined" && typeof console.debug != "undefined") { console.log(s); } else { alert(s); } } /* parsers utils */ function buildParserCache(table, $headers) { if (table.config.debug) { var parsersDebug = ""; } if (table.tBodies.length == 0) return; // In the case of empty tables var rows = table.tBodies[0].rows; if (rows[0]) { var list = [], cells = rows[0].cells, l = cells.length; for (var i = 0; i < l; i++) { var p = false; if ($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter)) { p = getParserById($($headers[i]).metadata().sorter); } else if ((table.config.headers[i] && table.config.headers[i].sorter)) { p = getParserById(table.config.headers[i].sorter); } if (!p) { p = detectParserForColumn(table, rows, -1, i); } if (table.config.debug) { parsersDebug += "column:" + i + " parser:" + p.id + "\n"; } list.push(p); } } if (table.config.debug) { log(parsersDebug); } return list; }; function detectParserForColumn(table, rows, rowIndex, cellIndex) { var l = parsers.length, node = false, nodeValue = false, keepLooking = true; while (nodeValue == '' && keepLooking) { rowIndex++; if (rows[rowIndex]) { node = getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex); nodeValue = trimAndGetNodeText(table.config, node); if (table.config.debug) { log('Checking if value was empty on row:' + rowIndex); } } else { keepLooking = false; } } for (var i = 1; i < l; i++) { if (parsers[i].is(nodeValue, table, node)) { return parsers[i]; } } // 0 is always the generic parser (text) return parsers[0]; } function getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex) { return rows[rowIndex].cells[cellIndex]; } function trimAndGetNodeText(config, node) { return $.trim(getElementText(config, node)); } function getParserById(name) { var l = parsers.length; for (var i = 0; i < l; i++) { if (parsers[i].id.toLowerCase() == name.toLowerCase()) { return parsers[i]; } } return false; } /* utils */ function buildCache(table) { if (table.config.debug) { var cacheTime = new Date(); } var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0, totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0, parsers = table.config.parsers, cache = { row: [], normalized: [] }; for (var i = 0; i < totalRows; ++i) { /** Add the table data to main data array */ var c = $(table.tBodies[0].rows[i]), cols = []; // if this is a child row, add it to the last row's children and // continue to the next row if (c.hasClass(table.config.cssChildRow)) { cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add(c); // go to the next for loop continue; } cache.row.push(c); for (var j = 0; j < totalCells; ++j) { cols.push(parsers[j].format(getElementText(table.config, c[0].cells[j]), table, c[0].cells[j])); } cols.push(cache.normalized.length); // add position for rowCache cache.normalized.push(cols); cols = null; }; if (table.config.debug) { benchmark("Building cache for " + totalRows + " rows:", cacheTime); } return cache; }; function getElementText(config, node) { var text = ""; if (!node) return ""; if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false; if (config.textExtraction == "simple") { if (config.supportsTextContent) { text = node.textContent; } else { if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) { text = node.childNodes[0].innerHTML; } else { text = node.innerHTML; } } } else { if (typeof(config.textExtraction) == "function") { text = config.textExtraction(node); } else { text = $(node).text(); } } return text; } function appendToTable(table, cache) { if (table.config.debug) { var appendTime = new Date() } var c = cache, r = c.row, n = c.normalized, totalRows = n.length, checkCell = (n[0].length - 1), tableBody = $(table.tBodies[0]), rows = []; for (var i = 0; i < totalRows; i++) { var pos = n[i][checkCell]; rows.push(r[pos]); if (!table.config.appender) { //var o = ; var l = r[pos].length; for (var j = 0; j < l; j++) { tableBody[0].appendChild(r[pos][j]); } // } } if (table.config.appender) { table.config.appender(table, rows); } rows = null; if (table.config.debug) { benchmark("Rebuilt table:", appendTime); } // apply table widgets applyWidget(table); // trigger sortend setTimeout(function () { $(table).trigger("sortEnd"); }, 0); }; function buildHeaders(table) { if (table.config.debug) { var time = new Date(); } var meta = ($.metadata) ? true : false; var header_index = computeTableHeaderCellIndexes(table); $tableHeaders = $(table.config.selectorHeaders, table).each(function (index) { this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex]; // this.column = index; this.order = formatSortingOrder(table.config.sortInitialOrder); this.count = this.order; if (checkHeaderMetadata(this, table.config.noSorterClass) || checkHeaderOptions(table, index)) this.sortDisabled = true; if (checkHeaderOptionsSortingLocked(table, index)) this.order = this.lockedOrder = checkHeaderOptionsSortingLocked(table, index); if (!this.sortDisabled) { var $th = $(this).addClass(table.config.cssHeader); if (table.config.onRenderHeader) table.config.onRenderHeader.apply($th); } // add cell to headerList table.config.headerList[index] = this; }); if (table.config.debug) { benchmark("Built headers:", time); log($tableHeaders); } return $tableHeaders; }; // from: // http://www.javascripttoolbox.com/lib/table/examples.php // http://www.javascripttoolbox.com/temp/table_cellindex.html function computeTableHeaderCellIndexes(t) { var matrix = []; var lookup = {}; var thead = t.getElementsByTagName('THEAD')[0]; var trs = thead.getElementsByTagName('TR'); for (var i = 0; i < trs.length; i++) { var cells = trs[i].cells; for (var j = 0; j < cells.length; j++) { var c = cells[j]; var rowIndex = c.parentNode.rowIndex; var cellId = rowIndex + "-" + c.cellIndex; var rowSpan = c.rowSpan || 1; var colSpan = c.colSpan || 1 var firstAvailCol; if (typeof(matrix[rowIndex]) == "undefined") { matrix[rowIndex] = []; } // Find first available column in the first row for (var k = 0; k < matrix[rowIndex].length + 1; k++) { if (typeof(matrix[rowIndex][k]) == "undefined") { firstAvailCol = k; break; } } lookup[cellId] = firstAvailCol; for (var k = rowIndex; k < rowIndex + rowSpan; k++) { if (typeof(matrix[k]) == "undefined") { matrix[k] = []; } var matrixrow = matrix[k]; for (var l = firstAvailCol; l < firstAvailCol + colSpan; l++) { matrixrow[l] = "x"; } } } } return lookup; } function checkCellColSpan(table, rows, row) { var arr = [], r = table.tHead.rows, c = r[row].cells; for (var i = 0; i < c.length; i++) { var cell = c[i]; if (cell.colSpan > 1) { arr = arr.concat(checkCellColSpan(table, headerArr, row++)); } else { if (table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row + 1])) { arr.push(cell); } // headerArr[row] = (i+row); } } return arr; }; function checkHeaderMetadata(cell, noSorterClass) { if ((($.metadata) && ($(cell).metadata().sorter === false)) || $(cell).hasClass(noSorterClass)) { return true; }; return false; } function checkHeaderOptions(table, i) { if ((table.config.headers[i]) && (table.config.headers[i].sorter === false)) { return true; }; return false; } function checkHeaderOptionsSortingLocked(table, i) { if ((table.config.headers[i]) && (table.config.headers[i].lockedOrder)) return table.config.headers[i].lockedOrder; return false; } function applyWidget(table) { var c = table.config.widgets; var l = c.length; for (var i = 0; i < l; i++) { getWidgetById(c[i]).format(table); } } function getWidgetById(name) { var l = widgets.length; for (var i = 0; i < l; i++) { if (widgets[i].id.toLowerCase() == name.toLowerCase()) { return widgets[i]; } } }; function formatSortingOrder(v) { if (typeof(v) != "Number") { return (v.toLowerCase() == "desc") ? 1 : 0; } else { return (v == 1) ? 1 : 0; } } function isValueInArray(v, a) { var l = a.length; for (var i = 0; i < l; i++) { if (a[i][0] == v) { return true; } } return false; } function setHeadersCss(table, $headers, list, css) { // remove all header information $headers.removeClass(css[0]).removeClass(css[1]); var h = []; $headers.each(function (offset) { if (!this.sortDisabled) { h[this.column] = $(this); } }); var l = list.length; for (var i = 0; i < l; i++) { h[list[i][0]].addClass(css[list[i][1]]); } } function fixColumnWidth(table, $headers) { var c = table.config; if (c.widthFixed) { var colgroup = $('<colgroup>'); $("tr:first td", table.tBodies[0]).each(function () { colgroup.append($('<col>').css('width', $(this).width())); }); $(table).prepend(colgroup); }; } function updateHeaderSortCount(table, sortList) { var c = table.config, l = sortList.length; for (var i = 0; i < l; i++) { var s = sortList[i], o = c.headerList[s[0]]; o.count = s[1]; o.count++; } } /* sorting methods */ function multisort(table, sortList, cache) { if (table.config.debug) { var sortTime = new Date(); } var dynamicExp = "var sortWrapper = function(a,b) {", l = sortList.length; // TODO: inline functions. for (var i = 0; i < l; i++) { var c = sortList[i][0]; var order = sortList[i][1]; // var s = (getCachedSortType(table.config.parsers,c) == "text") ? // ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ? // "sortNumeric" : "sortNumericDesc"); // var s = (table.config.parsers[c].type == "text") ? ((order == 0) // ? makeSortText(c) : makeSortTextDesc(c)) : ((order == 0) ? // makeSortNumeric(c) : makeSortNumericDesc(c)); var s = (table.config.parsers[c].type == "text") ? ((order == 0) ? makeSortFunction("text", "asc", c) : makeSortFunction("text", "desc", c)) : ((order == 0) ? makeSortFunction("numeric", "asc", c) : makeSortFunction("numeric", "desc", c)); var e = "e" + i; dynamicExp += "var " + e + " = " + s; // + "(a[" + c + "],b[" + c // + "]); "; dynamicExp += "if(" + e + ") { return " + e + "; } "; dynamicExp += "else { "; } // if value is the same keep orignal order var orgOrderCol = cache.normalized[0].length - 1; dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];"; for (var i = 0; i < l; i++) { dynamicExp += "}; "; } dynamicExp += "return 0; "; dynamicExp += "}; "; if (table.config.debug) { benchmark("Evaling expression:" + dynamicExp, new Date()); } eval(dynamicExp); cache.normalized.sort(sortWrapper); if (table.config.debug) { benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time:", sortTime); } return cache; }; function makeSortFunction(type, direction, index) { var a = "a[" + index + "]", b = "b[" + index + "]"; if (type == 'text' && direction == 'asc') { return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + a + " < " + b + ") ? -1 : 1 )));"; } else if (type == 'text' && direction == 'desc') { return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + b + " < " + a + ") ? -1 : 1 )));"; } else if (type == 'numeric' && direction == 'asc') { return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + a + " - " + b + "));"; } else if (type == 'numeric' && direction == 'desc') { return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + b + " - " + a + "));"; } }; function makeSortText(i) { return "((a[" + i + "] < b[" + i + "]) ? -1 : ((a[" + i + "] > b[" + i + "]) ? 1 : 0));"; }; function makeSortTextDesc(i) { return "((b[" + i + "] < a[" + i + "]) ? -1 : ((b[" + i + "] > a[" + i + "]) ? 1 : 0));"; }; function makeSortNumeric(i) { return "a[" + i + "]-b[" + i + "];"; }; function makeSortNumericDesc(i) { return "b[" + i + "]-a[" + i + "];"; }; function sortText(a, b) { if (table.config.sortLocaleCompare) return a.localeCompare(b); return ((a < b) ? -1 : ((a > b) ? 1 : 0)); }; function sortTextDesc(a, b) { if (table.config.sortLocaleCompare) return b.localeCompare(a); return ((b < a) ? -1 : ((b > a) ? 1 : 0)); }; function sortNumeric(a, b) { return a - b; }; function sortNumericDesc(a, b) { return b - a; }; function getCachedSortType(parsers, i) { return parsers[i].type; }; /* public methods */ this.construct = function (settings) { return this.each(function () { // if no thead or tbody quit. if (!this.tHead || !this.tBodies) return; // declare var $this, $document, $headers, cache, config, shiftDown = 0, sortOrder; // new blank config object this.config = {}; // merge and extend. config = $.extend(this.config, $.tablesorter.defaults, settings); // store common expression for speed $this = $(this); // save the settings where they read $.data(this, "tablesorter", config); // build headers $headers = buildHeaders(this); // try to auto detect column type, and store in tables config this.config.parsers = buildParserCache(this, $headers); // build the cache for the tbody cells cache = buildCache(this); // get the css class names, could be done else where. var sortCSS = [config.cssDesc, config.cssAsc]; // fixate columns if the users supplies the fixedWidth option fixColumnWidth(this); // apply event handling to headers // this is to big, perhaps break it out? $headers.click( function (e) { var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0; if (!this.sortDisabled && totalRows > 0) { // Only call sortStart if sorting is // enabled. $this.trigger("sortStart"); // store exp, for speed var $cell = $(this); // get current column index var i = this.column; // get current column sort order this.order = this.count++ % 2; // always sort on the locked order. if(this.lockedOrder) this.order = this.lockedOrder; // user only whants to sort on one // column if (!e[config.sortMultiSortKey]) { // flush the sort list config.sortList = []; if (config.sortForce != null) { var a = config.sortForce; for (var j = 0; j < a.length; j++) { if (a[j][0] != i) { config.sortList.push(a[j]); } } } // add column to sort list config.sortList.push([i, this.order]); // multi column sorting } else { // the user has clicked on an all // ready sortet column. if (isValueInArray(i, config.sortList)) { // revers the sorting direction // for all tables. for (var j = 0; j < config.sortList.length; j++) { var s = config.sortList[j], o = config.headerList[s[0]]; if (s[0] == i) { o.count = s[1]; o.count++; s[1] = o.count % 2; } } } else { // add column to sort list array config.sortList.push([i, this.order]); } }; setTimeout(function () { // set css for headers setHeadersCss($this[0], $headers, config.sortList, sortCSS); appendToTable( $this[0], multisort( $this[0], config.sortList, cache) ); }, 1); // stop normal event by returning false return false; } // cancel selection }).mousedown(function () { if (config.cancelSelection) { this.onselectstart = function () { return false }; return false; } }); // apply easy methods that trigger binded events $this.bind("update", function () { var me = this; setTimeout(function () { // rebuild parsers. me.config.parsers = buildParserCache( me, $headers); // rebuild the cache map cache = buildCache(me); }, 1); }).bind("updateCell", function (e, cell) { var config = this.config; // get position from the dom. var pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex]; // update cache cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format( getElementText(config, cell), cell); }).bind("sorton", function (e, list) { $(this).trigger("sortStart"); config.sortList = list; // update and store the sortlist var sortList = config.sortList; // update header count index updateHeaderSortCount(this, sortList); // set css for headers setHeadersCss(this, $headers, sortList, sortCSS); // sort the table and append it to the dom appendToTable(this, multisort(this, sortList, cache)); }).bind("appendCache", function () { appendToTable(this, cache); }).bind("applyWidgetId", function (e, id) { getWidgetById(id).format(this); }).bind("applyWidgets", function () { // apply widgets applyWidget(this); }); if ($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) { config.sortList = $(this).metadata().sortlist; } // if user has supplied a sort list to constructor. if (config.sortList.length > 0) { $this.trigger("sorton", [config.sortList]); } // apply widgets applyWidget(this); }); }; this.addParser = function (parser) { var l = parsers.length, a = true; for (var i = 0; i < l; i++) { if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) { a = false; } } if (a) { parsers.push(parser); }; }; this.addWidget = function (widget) { widgets.push(widget); }; this.formatFloat = function (s) { var i = parseFloat(s); return (isNaN(i)) ? 0 : i; }; this.formatInt = function (s) { var i = parseInt(s); return (isNaN(i)) ? 0 : i; }; this.isDigit = function (s, config) { // replace all an wanted chars and match. return /^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g, ''))); }; this.clearTableBody = function (table) { if ($.browser.msie) { function empty() { while (this.firstChild) this.removeChild(this.firstChild); } empty.apply(table.tBodies[0]); } else { table.tBodies[0].innerHTML = ""; } }; } }); // extend plugin scope $.fn.extend({ tablesorter: $.tablesorter.construct }); // make shortcut var ts = $.tablesorter; // add default parsers ts.addParser({ id: "text", is: function (s) { return true; }, format: function (s) { return $.trim(s.toLocaleLowerCase()); }, type: "text" }); ts.addParser({ id: "digit", is: function (s, table) { var c = table.config; return $.tablesorter.isDigit(s, c); }, format: function (s) { return $.tablesorter.formatFloat(s); }, type: "numeric" }); ts.addParser({ id: "currency", is: function (s) { return /^[£$€?.]/.test(s); }, format: function (s) { return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g), "")); }, type: "numeric" }); ts.addParser({ id: "ipAddress", is: function (s) { return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s); }, format: function (s) { var a = s.split("."), r = "", l = a.length; for (var i = 0; i < l; i++) { var item = a[i]; if (item.length == 2) { r += "0" + item; } else { r += item; } } return $.tablesorter.formatFloat(r); }, type: "numeric" }); ts.addParser({ id: "url", is: function (s) { return /^(https?|ftp|file):\/\/$/.test(s); }, format: function (s) { return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//), '')); }, type: "text" }); ts.addParser({ id: "isoDate", is: function (s) { return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s); }, format: function (s) { return $.tablesorter.formatFloat((s != "") ? new Date(s.replace( new RegExp(/-/g), "/")).getTime() : "0"); }, type: "numeric" }); ts.addParser({ id: "percent", is: function (s) { return /\%$/.test($.trim(s)); }, format: function (s) { return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g), "")); }, type: "numeric" }); ts.addParser({ id: "usLongDate", is: function (s) { return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/)); }, format: function (s) { return $.tablesorter.formatFloat(new Date(s).getTime()); }, type: "numeric" }); ts.addParser({ id: "shortDate", is: function (s) { return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s); }, format: function (s, table) { var c = table.config; s = s.replace(/\-/g, "/"); if (c.dateFormat == "us") { // reformat the string in ISO format s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2"); } else if (c.dateFormat == "uk") { // reformat the string in ISO format s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1"); } else if (c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") { s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3"); } return $.tablesorter.formatFloat(new Date(s).getTime()); }, type: "numeric" }); ts.addParser({ id: "time", is: function (s) { return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s); }, format: function (s) { return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime()); }, type: "numeric" }); ts.addParser({ id: "metadata", is: function (s) { return false; }, format: function (s, table, cell) { var c = table.config, p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName; return $(cell).metadata()[p]; }, type: "numeric" }); // add default widgets ts.addWidget({ id: "zebra", format: function (table) { if (table.config.debug) { var time = new Date(); } var $tr, row = -1, odd; // loop through the visible rows $("tr:visible", table.tBodies[0]).each(function (i) { $tr = $(this); // style children rows the same way the parent // row was styled if (!$tr.hasClass(table.config.cssChildRow)) row++; odd = (row % 2 == 0); $tr.removeClass( table.config.widgetZebra.css[odd ? 0 : 1]).addClass( table.config.widgetZebra.css[odd ? 1 : 0]) }); if (table.config.debug) { $.tablesorter.benchmark("Applying Zebra widget", time); } } }); })(jQuery);
JavaScript
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" /> /* * Print Element Plugin 1.2 * * Copyright (c) 2010 Erik Zaadi * * Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and * http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome * * Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement * Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement * jQuery plugin page : http://plugins.jquery.com/project/printElement * * Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100) * For their great contributions! * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead */ ; (function (window, undefined) { var document = window["document"]; var $ = window["jQuery"]; $.fn["printElement"] = function (options) { var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options); //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page). //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en if (mainOptions["printMode"] == 'iframe') { if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) mainOptions["printMode"] = 'popup'; } //Remove previously printed iframe if exists $("[id^='printElement_']").remove(); return this.each(function () { //Support Metadata Plug-in if available var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions; _printElement($(this), opts); }); }; $.fn["printElement"]["defaults"] = { "printMode": 'iframe', //Usage : iframe / popup "pageTitle": '', //Print Page Title "overrideElementCSS": null, /* Can be one of the following 3 options: * 1 : boolean (pass true for stripping all css linked) * 2 : array of $.fn.printElement.cssElement (s) * 3 : array of strings with paths to alternate css files (optimized for print) */ "printBodyOptions": { "styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document "classNameToAdd": '' //css class to add to the body of print document }, "leaveOpen": false, // in case of popup, leave the print page open or not "iframeElementOptions": { "styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element "classNameToAdd": '' //css class to add to the iframe element } }; $.fn["printElement"]["cssElement"] = { "href": '', "media": '' }; function _printElement(element, opts) { //Create markup to be printed var html = _getMarkup(element, opts); var popupOrIframe = null; var documentToWriteTo = null; if (opts["printMode"].toLowerCase() == 'popup') { popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes'); documentToWriteTo = popupOrIframe.document; } else { //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString(); //Native creation of the element is faster.. var iframe = document.createElement('IFRAME'); $(iframe).attr({ style: opts["iframeElementOptions"]["styleToAdd"], id: printElementID, className: opts["iframeElementOptions"]["classNameToAdd"], frameBorder: 0, scrolling: 'no', src: 'about:blank' }); document.body.appendChild(iframe); documentToWriteTo = (iframe.contentWindow || iframe.contentDocument); if (documentToWriteTo.document) documentToWriteTo = documentToWriteTo.document; iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID); popupOrIframe = iframe.contentWindow || iframe; } focus(); documentToWriteTo.open(); documentToWriteTo.write(html); documentToWriteTo.close(); _callPrint(popupOrIframe); }; function _callPrint(element) { if (element && element["printPage"]) element["printPage"](); else setTimeout(function () { _callPrint(element); }, 50); } function _getElementHTMLIncludingFormElements(element) { var $element = $(element); //Radiobuttons and checkboxes $(":checked", $element).each(function () { this.setAttribute('checked', 'checked'); }); //simple text inputs $("input[type='text']", $element).each(function () { this.setAttribute('value', $(this).val()); }); $("select", $element).each(function () { var $select = $(this); $("option", $select).each(function () { if ($select.val() == $(this).val()) this.setAttribute('selected', 'selected'); }); }); $("textarea", $element).each(function () { //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/ var value = $(this).attr('value'); //fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7) if ($.browser.mozilla && this.firstChild) this.firstChild.textContent = value; else this.innerHTML = value; }); //http://dbj.org/dbj/?p=91 var elementHtml = $('<div></div>').append($element.clone()).html(); return elementHtml; } function _getBaseHref() { var port = (window.location.port) ? ':' + window.location.port : ''; return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname; } function _getMarkup(element, opts) { var $element = $(element); var elementHtml = _getElementHTMLIncludingFormElements(element); var html = new Array(); html.push('<html><head><title>' + opts["pageTitle"] + '</title>'); if (opts["overrideElementCSS"]) { if (opts["overrideElementCSS"].length > 0) { for (var x = 0; x < opts["overrideElementCSS"].length; x++) { var current = opts["overrideElementCSS"][x]; if (typeof (current) == 'string') html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >'); else html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >'); } } } else { $("link", document).filter(function () { return $(this).attr("rel").toLowerCase() == "stylesheet"; }).each(function () { html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >'); }); } //Ensure that relative links work html.push('<base href="' + _getBaseHref() + '" />'); html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">'); html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>'); html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>'); html.push('</body></html>'); return html.join(''); }; })(window);
JavaScript
$(function(){ var save_and_close = false; $('.ptogtitle').click(function(){ if($(this).hasClass('vsble')) { $(this).removeClass('vsble'); $('#main-table-box #crudForm').slideDown("slow"); } else { $(this).addClass('vsble'); $('#main-table-box #crudForm').slideUp("slow"); } }); $('#save-and-go-back-button').click(function(){ save_and_close = true; $('#crudForm').trigger('submit'); return false; }); $('#crudForm').submit(function(){ var my_crud_form = $(this); $(this).ajaxSubmit({ url: validation_url, dataType: 'json', cache: 'false', beforeSend: function(){ $("#FormLoading").show(); }, success: function(data){ $("#FormLoading").hide(); if(data.success) { $('#crudForm').ajaxSubmit({ dataType: 'text', cache: 'false', beforeSend: function(){ $("#FormLoading").show(); }, success: function(result){ $("#FormLoading").fadeOut("slow"); data = $.parseJSON( result ); if($('#crudForm').data('callback')) { $('#crudForm').data('callback')(data,$('#crudForm').serializeArray()); } if(data.success) { var data_unique_hash = my_crud_form.closest(".flexigrid").attr("data-unique-hash"); $('.flexigrid[data-unique-hash='+data_unique_hash+']').find('.ajax_refresh_and_loading').trigger('click'); if(save_and_close) { if ($('#save-and-go-back-button').closest('.ui-dialog').length === 0) { window.location = data.success_list_url; } else { $(".ui-dialog-content").dialog("close"); success_message(data.success_message); } return true; } form_success_message(data.success_message); } else { form_error_message(message_update_error); } }, error: function(){ form_error_message( message_update_error ); } }); } else { $('.field_error').each(function(){ $(this).removeClass('field_error'); }); $('#report-error').slideUp('fast'); $('#report-error').html(data.error_message); $.each(data.error_fields, function(index,value){ $('input[name='+index+']').addClass('field_error'); }); $('#report-error').slideDown('normal'); $('#report-success').slideUp('fast').html(''); } }, error: function(){ error_alert( message_update_error ); $("#FormLoading").hide(); } }); return false; }); if( $('#cancel-button').closest('.ui-dialog').length === 0 ) { $('#cancel-button').click(function(){ // if($('#cancel-button').attr('mt') == 'read') // { window.location = list_url; return false; // } // try{ // confirm_alert('Confirmation',message_alert_edit_form,function(){ // window.location = list_url; // },function(){ // }); // } // catch(e) // { // //console.log(e); // } // return false; }); } });
JavaScript
$(function(){ $('.ptogtitle').click(function(){ if($(this).hasClass('vsble')) { $(this).removeClass('vsble'); $('#main-table-box #crudForm').slideDown("slow"); } else { $(this).addClass('vsble'); $('#main-table-box #crudForm').slideUp("slow"); } }); var save_and_close = false; $('#save-and-go-back-button').click(function(){ save_and_close = true; $('#crudForm').trigger('submit'); return false; }); $('#crudForm').submit(function(){ var my_crud_form = $(this); $(this).ajaxSubmit({ url: validation_url, dataType: 'json', cache: 'false', beforeSend: function(){ $("#FormLoading").show(); }, success: function(data){ $("#FormLoading").hide(); if(data.success) { $('#crudForm').ajaxSubmit({ dataType: 'text', cache: 'false', beforeSend: function(){ $("#FormLoading").show(); }, success: function(result){ $("#FormLoading").fadeOut("slow"); data = $.parseJSON( result ); if($('#crudForm').data('callback')) { $('#crudForm').data('callback')(data,$('#crudForm').serializeArray()); } if(data.success) { var data_unique_hash = my_crud_form.closest(".flexigrid").attr("data-unique-hash"); $('.flexigrid[data-unique-hash='+data_unique_hash+']').find('.ajax_refresh_and_loading').trigger('click'); if(save_and_close) { if ($('#save-and-go-back-button').closest('.ui-dialog').length === 0) { window.location = data.success_list_url; } else { $(".ui-dialog-content").dialog("close"); success_message(data.success_message); } return true; } $('.field_error').each(function(){ $(this).removeClass('field_error'); }); clearForm(); form_success_message(data.success_message); } else { alert( message_insert_error ); } }, error: function(){ alert( message_insert_error ); $("#FormLoading").hide(); } }); } else { $('.field_error').removeClass('field_error'); form_error_message(data.error_message); $.each(data.error_fields, function(index,value){ $('input[name='+index+']').addClass('field_error'); }); } }, error: function(){ error_message (message_insert_error); $("#FormLoading").hide(); } }); return false; }); if( $('#cancel-button').closest('.ui-dialog').length === 0 ) { $('#cancel-button').click(function(){ // try{ // confirm_alert('Confirmation',message_alert_add_form,function(){ window.location = list_url; // },function(){ // }); // } // catch(e) // { // //console.log(e); // } //if( confirm( message_alert_add_form ) ) //{ //} return false; }); } }); function clearForm() { $('#crudForm').find(':input').each(function() { switch(this.type) { case 'password': case 'select-multiple': case 'select-one': case 'text': case 'textarea': $(this).val(''); break; case 'checkbox': case 'radio': this.checked = false; } }); /* Clear upload inputs */ $('.open-file,.gc-file-upload,.hidden-upload-input').each(function(){ $(this).val(''); }); $('.upload-success-url').hide(); $('.fileinput-button').fadeIn("normal"); /* -------------------- */ $('.remove-all').each(function(){ $(this).trigger('click'); }); $('.chosen-multiple-select, .chosen-select, .ajax-chosen-select').each(function(){ $(this).trigger("liszt:updated"); }); }
JavaScript
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" /> /* * Print Element Plugin 1.2 * * Copyright (c) 2010 Erik Zaadi * * Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and * http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome * * Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement * Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement * jQuery plugin page : http://plugins.jquery.com/project/printElement * * Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100) * For their great contributions! * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead */ ; (function (window, undefined) { var document = window["document"]; var $ = window["jQuery"]; $.fn["printElement"] = function (options) { var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options); //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page). //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en if (mainOptions["printMode"] == 'iframe') { if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) mainOptions["printMode"] = 'popup'; } //Remove previously printed iframe if exists $("[id^='printElement_']").remove(); return this.each(function () { //Support Metadata Plug-in if available var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions; _printElement($(this), opts); }); }; $.fn["printElement"]["defaults"] = { "printMode": 'iframe', //Usage : iframe / popup "pageTitle": '', //Print Page Title "overrideElementCSS": null, /* Can be one of the following 3 options: * 1 : boolean (pass true for stripping all css linked) * 2 : array of $.fn.printElement.cssElement (s) * 3 : array of strings with paths to alternate css files (optimized for print) */ "printBodyOptions": { "styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document "classNameToAdd": '' //css class to add to the body of print document }, "leaveOpen": false, // in case of popup, leave the print page open or not "iframeElementOptions": { "styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element "classNameToAdd": '' //css class to add to the iframe element } }; $.fn["printElement"]["cssElement"] = { "href": '', "media": '' }; function _printElement(element, opts) { //Create markup to be printed var html = _getMarkup(element, opts); var popupOrIframe = null; var documentToWriteTo = null; if (opts["printMode"].toLowerCase() == 'popup') { popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes'); documentToWriteTo = popupOrIframe.document; } else { //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString(); //Native creation of the element is faster.. var iframe = document.createElement('IFRAME'); $(iframe).attr({ style: opts["iframeElementOptions"]["styleToAdd"], id: printElementID, className: opts["iframeElementOptions"]["classNameToAdd"], frameBorder: 0, scrolling: 'no', src: 'about:blank' }); document.body.appendChild(iframe); documentToWriteTo = (iframe.contentWindow || iframe.contentDocument); if (documentToWriteTo.document) documentToWriteTo = documentToWriteTo.document; iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID); popupOrIframe = iframe.contentWindow || iframe; } focus(); documentToWriteTo.open(); documentToWriteTo.write(html); documentToWriteTo.close(); _callPrint(popupOrIframe); }; function _callPrint(element) { if (element && element["printPage"]) element["printPage"](); else setTimeout(function () { _callPrint(element); }, 50); } function _getElementHTMLIncludingFormElements(element) { var $element = $(element); //Radiobuttons and checkboxes $(":checked", $element).each(function () { this.setAttribute('checked', 'checked'); }); //simple text inputs $("input[type='text']", $element).each(function () { this.setAttribute('value', $(this).val()); }); $("select", $element).each(function () { var $select = $(this); $("option", $select).each(function () { if ($select.val() == $(this).val()) this.setAttribute('selected', 'selected'); }); }); $("textarea", $element).each(function () { //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/ var value = $(this).attr('value'); //fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7) if ($.browser.mozilla && this.firstChild) this.firstChild.textContent = value; else this.innerHTML = value; }); //http://dbj.org/dbj/?p=91 var elementHtml = $('<div></div>').append($element.clone()).html(); return elementHtml; } function _getBaseHref() { var port = (window.location.port) ? ':' + window.location.port : ''; return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname; } function _getMarkup(element, opts) { var $element = $(element); var elementHtml = _getElementHTMLIncludingFormElements(element); var html = new Array(); html.push('<html><head><title>' + opts["pageTitle"] + '</title>'); if (opts["overrideElementCSS"]) { if (opts["overrideElementCSS"].length > 0) { for (var x = 0; x < opts["overrideElementCSS"].length; x++) { var current = opts["overrideElementCSS"][x]; if (typeof (current) == 'string') html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >'); else html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >'); } } } else { $("link", document).filter(function () { return $(this).attr("rel").toLowerCase() == "stylesheet"; }).each(function () { html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >'); }); } //Ensure that relative links work html.push('<base href="' + _getBaseHref() + '" />'); html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">'); html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>'); html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>'); html.push('</body></html>'); return html.join(''); }; })(window);
JavaScript
$(document).ready(function(){ $('.popup_grid .quickSearchButton').click(function(){ $(this).closest('.flexigrid').find('.quickSearchBox').slideToggle('normal'); }); $('.popup_grid .ptogtitle').click(function(){ if ($(this).hasClass('vsble')) { $(this).removeClass('vsble'); $(this).closest('.flexigrid').find('.main-table-box').slideDown("slow"); } else { $(this).addClass('vsble'); $(this).closest('.flexigrid').find('.main-table-box').slideUp("slow"); } }); var call_fancybox = function(){ $('.popup_grid .image-thumbnail').fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, 'speedOut' : 200, 'overlayShow' : false }); }; call_fancybox(); add_edit_button_listener(); $('.popup_grid .filtering_form').submit(function(){ var crud_page = parseInt($(this).closest('.flexigrid').find('.crud_page').val(), 10); var last_page = parseInt($(this).closest('.flexigrid').find('.last-page-number').html(), 10); if (crud_page > last_page) { $(this).closest('.flexigrid').find('.crud_page').val(last_page); } if (crud_page <= 0) { $(this).closest('.flexigrid').find('.crud_page').val('1'); } var this_form = $(this); var ajax_list_info_url = $(this).attr('data-ajax-list-info-url'); $(this).ajaxSubmit({ url: ajax_list_info_url, dataType: 'json', beforeSend: function(){ this_form.closest('.flexigrid').find('.ajax_refresh_and_loading').addClass('loading'); }, complete: function(){ this_form.closest('.flexigrid').find('.ajax_refresh_and_loading').removeClass('loading'); }, success: function(data){ this_form.closest('.flexigrid').find('.total_items').html( data.total_results); displaying_and_pages(this_form.closest('.flexigrid')); this_form.ajaxSubmit({ //console.log(data); success: function(data){ this_form.closest('.flexigrid').find('.ajax_list').html(data); call_fancybox(); add_edit_button_listener(); } }); } }); if ($('.popup_grid .flexigrid').length == 1) { //disable cookie storing for multiple grids in one page createCookie('crud_page_'+unique_hash,crud_page,1); createCookie('per_page_'+unique_hash,$('.popup_grid #per_page').val(),1); createCookie('hidden_ordering_'+unique_hash,$('.popup_grid #hidden-ordering').val(),1); createCookie('hidden_sorting_'+unique_hash,$('.popup_grid #hidden-sorting').val(),1); createCookie('search_text_'+unique_hash,$(this).closest('.flexigrid').find('.search_text').val(),1); createCookie('search_field_'+unique_hash,$('.popup_grid #search_field').val(),1); } return false; }); $('.popup_grid .crud_search').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .search_clear').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.search_text').val(''); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .per_page').change(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .ajax_refresh_and_loading').click(function(){ $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .first-button').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .prev-button').click(function(){ if( $(this).closest('.flexigrid').find('.crud_page').val() != "1") { $(this).closest('.flexigrid').find('.crud_page').val( parseInt($(this).closest('.flexigrid').find('.crud_page').val(),10) - 1 ); $(this).closest('.flexigrid').find('.crud_page').trigger('change'); } }); $('.popup_grid .last-button').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val( $(this).closest('.flexigrid').find('.last-page-number').html()); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .next-button').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val( parseInt($(this).closest('.flexigrid').find('.crud_page').val()) + 1 ); $(this).closest('.flexigrid').find('.crud_page').trigger('change'); }); $('.popup_grid .crud_page').change(function(){ $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .ajax_list').on('click','.field-sorting', function(){ $(this).closest('.flexigrid').find('.hidden-sorting').val($(this).attr('rel')); if ($(this).hasClass('asc')) { $(this).closest('.flexigrid').find('.hidden-ordering').val('desc'); } else { $(this).closest('.flexigrid').find('.hidden-ordering').val('asc'); } $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.popup_grid .ajax_list').on('click','.delete-row', function(){ var delete_url = $(this).attr('href'); var this_element = this; var this_container = $(this).closest('.flexigrid'); try{ confirm_alert('Notifikasi', message_alert_delete, function(){ $.ajax({ url: delete_url, dataType: 'json', success: function(data) { if(data.success) { if($(this_element).attr('invoke_after')) { var fn_invoke_after = $(this_element).attr('invoke_after'); if(typeof window[fn_invoke_after] == 'function') { window[fn_invoke_after](this_element); } } else this_container.find('.ajax_refresh_and_loading').trigger('click'); success_message(data.success_message); } else { error_message(data.error_message); } } }); }, function(){ }); } catch(e) { //console.log(e); } return false; }); $('.popup_grid .export-anchor').click(function(){ var export_url = $(this).attr('data-url'); var form_input_html = ''; $.each($(this).closest('.flexigrid').find('.filtering_form').serializeArray(), function(i, field) { form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">'; }); var form_on_demand = $("<form/>").attr("id","export_form").attr("method","post").attr("target","_blank") .attr("action",export_url).html(form_input_html); $(this).closest('.flexigrid').find('.hidden-operations').html(form_on_demand); $(this).closest('.flexigrid').find('.hidden-operations').find('#export_form').submit(); }); $('.popup_grid .print-anchor').click(function(){ var print_url = $(this).attr('data-url'); var form_input_html = ''; $.each($(this).closest('.flexigrid').find('.filtering_form').serializeArray(), function(i, field) { form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">'; }); var form_on_demand = $("<form/>").attr("id","print_form").attr("method","post").attr("action",print_url).html(form_input_html); $(this).closest('.flexigrid').find('.hidden-operations').html(form_on_demand); var _this_button = $(this); $(this).closest('.flexigrid').find('#print_form').ajaxSubmit({ beforeSend: function(){ _this_button.find('.fbutton').addClass('loading'); _this_button.find('.fbutton>div').css('opacity','0.4'); }, complete: function(){ _this_button.find('.fbutton').removeClass('loading'); _this_button.find('.fbutton>div').css('opacity','1'); }, success: function(html_data){ $("<div/>").html(html_data).printElement(); } }); }); $('.popup_grid .crud_page').numeric(); if ($('.popup_grid .flexigrid').length == 1) { //disable cookie storing for multiple grids in one page var cookie_crud_page = readCookie('crud_page_'+unique_hash); var cookie_per_page = readCookie('per_page_'+unique_hash); var hidden_ordering = readCookie('hidden_ordering_'+unique_hash); var hidden_sorting = readCookie('hidden_sorting_'+unique_hash); var cookie_search_text = readCookie('search_text_'+unique_hash); var cookie_search_field = readCookie('search_field_'+unique_hash); if(cookie_crud_page !== null && cookie_per_page !== null) { $('.popup_grid #crud_page').val(cookie_crud_page); $('.popup_grid #per_page').val(cookie_per_page); $('.popup_grid #hidden-ordering').val(hidden_ordering); $('.popup_grid #hidden-sorting').val(hidden_sorting); $('.popup_grid #search_text').val(cookie_search_text); $('.popup_grid #search_field').val(cookie_search_field); if(cookie_search_text !== '') $('.popup_grid #quickSearchButton').trigger('click'); $('.popup_grid #filtering_form').trigger('submit'); } } }); function displaying_and_pages(this_container) { if (this_container.find('.crud_page').val() == 0) { this_container.find('.crud_page').val('1'); } var crud_page = parseInt( this_container.find('.crud_page').val(), 10) ; var per_page = parseInt( this_container.find('.per_page').val(), 10 ); var total_items = parseInt( this_container.find('.total_items').html(), 10 ); this_container.find('.last-page-number').html( Math.ceil( total_items / per_page) ); if (total_items == 0) { this_container.find('.page-starts-from').html( '0'); } else { this_container.find('.page-starts-from').html( (crud_page - 1)*per_page + 1 ); } if (crud_page*per_page > total_items) { this_container.find('.page-ends-to').html( total_items ); } else { this_container.find('.page-ends-to').html( crud_page*per_page ); } }
JavaScript
/*! * jQuery Form Plugin * version: 2.72 (28-APR-2011) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') { options = { success: options }; } var action = this.attr('action'); var url = (typeof action === 'string') ? $.trim(action) : ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } url = url || window.location.href || ''; options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: this[0].getAttribute('method') || 'GET', // IE7 massage (see issue 57) iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var n,v,a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) { a.push( { name: n, value: options.data[n][k] } ); } } else { v = options.data[n]; v = $.isFunction(v) ? v() : v; // if value is fn, invoke it a.push( { name: n, value: v } ); } } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var $form = this, callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || options; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; // are there files to upload? var fileInputs = $('input:file', this).length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (fileInputs || options.iframe || multipart)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, fileUpload); } else { fileUpload(); } } else { $.ajax(options); } // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit],:input[id=submit]', form).length) { // if there is an input with a name or id of 'submit' then we won't be // able to invoke the submit fn on the form (at least not x-browser) alert('Error: Form elements must not have name or id of "submit".'); return; } var s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; var id = 'jqFormIO' + (new Date().getTime()), fn = '_'+id; var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ s.iframeSrc +'" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; s.error && s.error.call(s.context, xhr, e, e); g && $.event.trigger("ajaxError", [xhr, s, e]); s.complete && s.complete.call(s.context, xhr, e); } }; var g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } return; } if (xhr.aborted) { return; } var timedOut = 0, timeoutHandle; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') { form.setAttribute('method', 'POST'); } if (form.getAttribute('action') != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(true); }, s.timeout); } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+s.extraData[n]+'" />') .appendTo(form)[0]); } } // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } if (e === true && xhr) { xhr.abort('timeout'); return; } var doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); xhr.responseText = doc.body ? doc.body.innerHTML : doc.documentElement ? doc.documentElement.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (!xhr.responseText && xhr.responseXML && !s.dataType) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; var scr = /(json|script|text)/.test(s.dataType); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent; } else if (b) { xhr.responseText = b.innerHTML; } } } else if (s.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = httpData(xhr, s.dataType, s); } catch(e){ log('error caught:',e); ok = false; xhr.error = e; s.error && s.error.call(s.context, xhr, 'error', e); g && $.event.trigger("ajaxError", [xhr, s, e]); } if (xhr.aborted) { log('upload aborted'); ok = false; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { s.success && s.success.call(s.context, data, 'success', xhr); g && $.event.trigger("ajaxSuccess", [xhr, s]); } g && $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } s.complete && s.complete.call(s.context, xhr, ok ? 'success' : 'error'); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { $.error && $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { // in jQuery 1.3+ we can fix mistakes with the ready state if (this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) { if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } }).bind('click.form-plugin', function(e) { var target = e.target; var $el = $(target); if (!($el.is(":submit,input:image"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest(':submit'); if (t.length == 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) { a.push({name: n, value: $(el).val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: n, value: v}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug) { var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } }; })(jQuery);
JavaScript
function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+escape(value)+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length)); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }
JavaScript
$(document).ready(function(){ $('.quickSearchButton').click(function(){ $(this).closest('.flexigrid').find('.quickSearchBox').slideToggle('normal'); }); $('.ptogtitle').click(function(){ if ($(this).hasClass('vsble')) { $(this).removeClass('vsble'); $(this).closest('.flexigrid').find('.main-table-box').slideDown("slow"); } else { $(this).addClass('vsble'); $(this).closest('.flexigrid').find('.main-table-box').slideUp("slow"); } }); var call_fancybox = function(){ $('.image-thumbnail').fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, 'speedOut' : 200, 'overlayShow' : false }); }; call_fancybox(); add_edit_button_listener(); $('.filtering_form').submit(function(){ var crud_page = parseInt($(this).closest('.flexigrid').find('.crud_page').val(), 10); var last_page = parseInt($(this).closest('.flexigrid').find('.last-page-number').html(), 10); if (crud_page > last_page) { $(this).closest('.flexigrid').find('.crud_page').val(last_page); } if (crud_page <= 0) { $(this).closest('.flexigrid').find('.crud_page').val('1'); } var this_form = $(this); var ajax_list_info_url = $(this).attr('data-ajax-list-info-url'); $(this).ajaxSubmit({ url: ajax_list_info_url, dataType: 'json', beforeSend: function(){ this_form.closest('.flexigrid').find('.ajax_refresh_and_loading').addClass('loading'); }, complete: function(){ this_form.closest('.flexigrid').find('.ajax_refresh_and_loading').removeClass('loading'); }, success: function(data){ this_form.closest('.flexigrid').find('.total_items').html( data.total_results); displaying_and_pages(this_form.closest('.flexigrid')); this_form.ajaxSubmit({ //console.log(data); success: function(data){ this_form.closest('.flexigrid').find('.ajax_list').html(data); call_fancybox(); add_edit_button_listener(); } }); } }); if ($('.flexigrid').length == 1) { //disable cookie storing for multiple grids in one page createCookie('crud_page_'+unique_hash,crud_page,1); createCookie('per_page_'+unique_hash,$('#per_page').val(),1); createCookie('hidden_ordering_'+unique_hash,$('#hidden-ordering').val(),1); createCookie('hidden_sorting_'+unique_hash,$('#hidden-sorting').val(),1); createCookie('search_text_'+unique_hash,$(this).closest('.flexigrid').find('.search_text').val(),1); createCookie('search_field_'+unique_hash,$('#search_field').val(),1); } return false; }); $('.crud_search').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.search_clear').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.search_text').val(''); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.per_page').change(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.ajax_refresh_and_loading').click(function(){ $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.first-button').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.prev-button').click(function(){ if( $(this).closest('.flexigrid').find('.crud_page').val() != "1") { $(this).closest('.flexigrid').find('.crud_page').val( parseInt($(this).closest('.flexigrid').find('.crud_page').val(),10) - 1 ); $(this).closest('.flexigrid').find('.crud_page').trigger('change'); } }); $('.last-button').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val( $(this).closest('.flexigrid').find('.last-page-number').html()); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.next-button').click(function(){ $(this).closest('.flexigrid').find('.crud_page').val( parseInt($(this).closest('.flexigrid').find('.crud_page').val()) + 1 ); $(this).closest('.flexigrid').find('.crud_page').trigger('change'); }); $('.crud_page').change(function(){ $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.ajax_list').on('click','.field-sorting', function(){ $(this).closest('.flexigrid').find('.hidden-sorting').val($(this).attr('rel')); if ($(this).hasClass('asc')) { $(this).closest('.flexigrid').find('.hidden-ordering').val('desc'); } else { $(this).closest('.flexigrid').find('.hidden-ordering').val('asc'); } $(this).closest('.flexigrid').find('.crud_page').val('1'); $(this).closest('.flexigrid').find('.filtering_form').trigger('submit'); }); $('.ajax_list').on('click','.delete-row', function(){ var delete_url = $(this).attr('href'); var this_element = this; var this_container = $(this).closest('.flexigrid'); try{ confirm_alert('Confirmation', message_alert_delete, function(){ $.ajax({ url: delete_url, dataType: 'json', success: function(data) { if(data.success) { if($(this_element).attr('invoke_after')) { var fn_invoke_after = $(this_element).attr('invoke_after'); if(typeof window[fn_invoke_after] == 'function') { window[fn_invoke_after](this_element); } } else this_container.find('.ajax_refresh_and_loading').trigger('click'); success_message(data.success_message); } else { error_message(data.error_message); } } }); }, function(){ }); } catch(e) { //console.log(e); } return false; }); $('.export-anchor').click(function(){ var export_url = $(this).attr('data-url'); var form_input_html = ''; $.each($(this).closest('.flexigrid').find('.filtering_form').serializeArray(), function(i, field) { form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">'; }); var form_on_demand = $("<form/>").attr("id","export_form").attr("method","post").attr("target","_blank") .attr("action",export_url).html(form_input_html); $(this).closest('.flexigrid').find('.hidden-operations').html(form_on_demand); $(this).closest('.flexigrid').find('.hidden-operations').find('#export_form').submit(); }); $('.print-anchor').click(function(){ var print_url = $(this).attr('data-url'); var form_input_html = ''; $.each($(this).closest('.flexigrid').find('.filtering_form').serializeArray(), function(i, field) { form_input_html = form_input_html + '<input type="hidden" name="'+field.name+'" value="'+field.value+'">'; }); var form_on_demand = $("<form/>").attr("id","print_form").attr("method","post").attr("action",print_url).html(form_input_html); $(this).closest('.flexigrid').find('.hidden-operations').html(form_on_demand); var _this_button = $(this); $(this).closest('.flexigrid').find('#print_form').ajaxSubmit({ beforeSend: function(){ _this_button.find('.fbutton').addClass('loading'); _this_button.find('.fbutton>div').css('opacity','0.4'); }, complete: function(){ _this_button.find('.fbutton').removeClass('loading'); _this_button.find('.fbutton>div').css('opacity','1'); }, success: function(html_data){ $("<div/>").html(html_data).printElement(); } }); }); $('.crud_page').numeric(); if ($('.flexigrid').length == 1) { //disable cookie storing for multiple grids in one page var cookie_crud_page = readCookie('crud_page_'+unique_hash); var cookie_per_page = readCookie('per_page_'+unique_hash); var hidden_ordering = readCookie('hidden_ordering_'+unique_hash); var hidden_sorting = readCookie('hidden_sorting_'+unique_hash); var cookie_search_text = readCookie('search_text_'+unique_hash); var cookie_search_field = readCookie('search_field_'+unique_hash); if(cookie_crud_page !== null && cookie_per_page !== null) { $('#crud_page').val(cookie_crud_page); $('#per_page').val(cookie_per_page); $('#hidden-ordering').val(hidden_ordering); $('#hidden-sorting').val(hidden_sorting); $('#search_text').val(cookie_search_text); $('#search_field').val(cookie_search_field); if(cookie_search_text !== '') $('#quickSearchButton').trigger('click'); $('#filtering_form').trigger('submit'); } } }); function displaying_and_pages(this_container) { if (this_container.find('.crud_page').val() == 0) { this_container.find('.crud_page').val('1'); } var crud_page = parseInt( this_container.find('.crud_page').val(), 10) ; var per_page = parseInt( this_container.find('.per_page').val(), 10 ); var total_items = parseInt( this_container.find('.total_items').html(), 10 ); this_container.find('.last-page-number').html( Math.ceil( total_items / per_page) ); if (total_items == 0) { this_container.find('.page-starts-from').html( '0'); } else { this_container.find('.page-starts-from').html( (crud_page - 1)*per_page + 1 ); } if (crud_page*per_page > total_items) { this_container.find('.page-ends-to').html( total_items ); } else { this_container.find('.page-ends-to').html( crud_page*per_page ); } }
JavaScript
// Simple Set Clipboard System // Author: Joseph Huckaby var ZeroClipboard_TableTools = { version: "1.0.4-TableTools2", clients: {}, // registered upload clients on page, indexed by id moviePath: '', // URL to movie nextId: 1, // ID of next movie $: function(thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function() { this.style.display = 'none'; }; thingy.show = function() { this.style.display = ''; }; thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function(name) { this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, ''); }; thingy.hasClass = function(name) { return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); } } return thingy; }, setMoviePath: function(path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function(id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function(id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function(obj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; if ( obj.style.width != "" ) info.width = obj.style.width.replace("px",""); if ( obj.style.height != "" ) info.height = obj.style.height.replace("px",""); while (obj) { info.left += obj.offsetLeft; info.top += obj.offsetTop; obj = obj.offsetParent; } return info; }, Client: function(elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard_TableTools.nextId++; this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard_TableTools.register(this.id, this); // create movie if (elem) this.glue(elem); } }; ZeroClipboard_TableTools.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard fileName: '', // default file save name action: 'copy', // action to perform handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers sized: false, glue: function(elem, title) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard_TableTools.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex) + 1; } // find X/Y position of domElement var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); // create floating DIV above element this.div = document.createElement('div'); var style = this.div.style; style.position = 'absolute'; style.left = '0px'; style.top = '0px'; style.width = (box.width) + 'px'; style.height = box.height + 'px'; style.zIndex = zIndex; if ( typeof title != "undefined" && title != "" ) { this.div.title = title; } if ( box.width != 0 && box.height != 0 ) { this.sized = true; } // style.backgroundColor = '#f00'; // debug if ( this.domElement ) { this.domElement.appendChild(this.div); this.div.innerHTML = this.getHTML( box.width, box.height ); } }, positionElement: function() { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.position = 'absolute'; style.left = (this.domElement.offsetLeft)+'px'; style.top = this.domElement.offsetTop+'px'; style.width = box.width + 'px'; style.height = box.height + 'px'; if ( box.width != 0 && box.height != 0 ) { this.sized = true; } else { return; } var flash = this.div.childNodes[0]; flash.width = box.width; flash.height = box.height; }, getHTML: function(width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'; } return html; }, hide: function() { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function() { // show ourselves after a call to hide() this.reposition(); }, destroy: function() { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild( this.div ); } catch(e) {;} this.domElement = null; this.div = null; } }, reposition: function(elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard_TableTools.$(elem); if (!this.domElement) this.hide(); } if (this.domElement && this.div) { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, clearText: function() { // clear the text to be copy / saved this.clipText = ''; if (this.ready) this.movie.clearText(); }, appendText: function(newText) { // append text to that which is to be copied / saved this.clipText += newText; if (this.ready) { this.movie.appendText(newText) ;} }, setText: function(newText) { // set text to be copied to be copied / saved this.clipText = newText; if (this.ready) { this.movie.setText(newText) ;} }, setCharSet: function(charSet) { // set the character set (UTF16LE or UTF8) this.charSet = charSet; if (this.ready) { this.movie.setCharSet(charSet) ;} }, setBomInc: function(bomInc) { // set if the BOM should be included or not this.incBom = bomInc; if (this.ready) { this.movie.setBomInc(bomInc) ;} }, setFileName: function(newText) { // set the file name this.fileName = newText; if (this.ready) this.movie.setFileName(newText); }, setAction: function(newText) { // set action (save or copy) this.action = newText; if (this.ready) this.movie.setAction(newText); }, addEventListener: function(eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) this.handlers[eventName] = []; this.handlers[eventName].push(func); }, setHandCursor: function(enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) this.movie.setHandCursor(enabled); }, setCSSEffects: function(enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !!enabled; }, receiveEvent: function(eventName, args) { // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 1 ); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 100 ); this.ready = true; return; } this.ready = true; this.movie.clearText(); this.movie.appendText( this.clipText ); this.movie.setFileName( this.fileName ); this.movie.setAction( this.action ); this.movie.setCharSet( this.charSet ); this.movie.setBomInc( this.incBom ); this.movie.setHandCursor( this.handCursorEnabled ); break; case 'mouseover': if (this.domElement && this.cssEffects) { //this.domElement.addClass('hover'); if (this.recoverActive) this.domElement.addClass('active'); } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } //this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][ func[1] ](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } };
JavaScript
/* * File: TableTools.js * Version: 2.1.2 * Description: Tools and buttons for DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * * Copyright 2009-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ /* Global scope for TableTools */ var TableTools; (function($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function( oDT, oOpts ) { /* Santiy check that we are a new instance */ if ( ! this instanceof TableTools ) { alert( "Warning: TableTools must be initialised with the keyword 'new'" ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retreieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": oDT.fnSettings(), /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () {} }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying tellng the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend( true, {}, TableTools.classes ); if ( this.s.dt.bJUI ) { $.extend( true, this.classes, TableTools.classes_themeroller ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if ( typeof oOpts == 'undefined' ) { oOpts = {}; } this._fnConstruct( oOpts ); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected */ "fnGetSelected": function () { var out=[]; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( data[i].nTr ); } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( this.s.dt.oInstance.fnGetData(i) ); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }, /** * Select all rows in the table */ "fnSelectAll": function () { var s = this._fnGetMasterSettings(); this._fnRowSelect( s.dt.aoData ); }, /** * Deselect all rows in the table */ "fnSelectNone": function () { var s = this._fnGetMasterSettings(); this._fnRowDeselect( s.dt.aoData ); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function ( n ) { if ( this.s.select.type == "single" ) { this.fnSelectNone(); this._fnRowSelect( n ); } else if ( this.s.select.type == "multi" ) { this._fnRowSelect( n ); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function ( n ) { this._fnRowDeselect( n ); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function ( oConfig ) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if ( this.s.dt ) { return this._fnGetDataTablesData( oConfig ); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function ( clip, text ) { this._fnFlashSetText( clip, text ); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode ) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function ( message, time ) { var nInfo = document.createElement( "div" ); nInfo.className = this.classes.print.info; nInfo.innerHTML = message; document.body.appendChild( nInfo ); setTimeout( function() { $(nInfo).fadeOut( "normal", function() { document.body.removeChild( nInfo ); } ); }, time ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function ( oOpts ) { var that = this; this._fnCustomiseSettings( oOpts ); /* Container element */ this.dom.container = document.createElement( this.s.tags.container ); this.dom.container.className = this.classes.container; /* Row selection config */ if ( this.s.select.type != 'none' ) { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations( this.s.buttonSet, this.dom.container ); /* Destructor - need to wipe the DOM for IE's garbage collector */ this.s.dt.aoDestroyCallback.push( { "sName": "TableTools", "fn": function () { that.dom.container.innerHTML = ""; } } ); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } wrapper.appendChild( this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ) ); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if ( this.s.master ) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for ( var i=0, iLen=instances.length ; i<iLen ; i++ ) { if ( this.dom.table == instances[i].s.dt.nTable ) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop downlist of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function ( nButton, oConfig ) { var nHidden = document.createElement( this.s.tags.collection.container ); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild( nHidden ); this._fnButtonDefinations( oConfig.aButtons, nHidden ); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if ( this.s.master ) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass( this.classes.select.table ); $('tr', dt.nTBody).live( 'click', function(e) { /* Sub-table must be ignored (odd that the selector won't do this with >) */ if ( this.parentNode != dt.nTBody ) { return; } /* Check that we are actually working with a DataTables controlled row */ if ( dt.oInstance.fnGetData(this) === null ) { return; } /* User defined selection function */ if ( that.s.select.preRowSelect !== null && !that.s.select.preRowSelect.call(that, e) ) { return; } if ( that.fnIsSelected( this ) ) { that._fnRowDeselect( this ); } else if ( that.s.select.type == "single" ) { that.fnSelectNone(); that._fnRowSelect( this ); } else if ( that.s.select.type == "multi" ) { that._fnRowSelect( this ); } } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) { if ( dt.aoData[index]._DTTT_selected ) { $(tr).addClass( that.classes.select.row ); } }, 'TableTools-SelectAll' ); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function ( src ) { var data = this._fnSelectData( src ); var firstTr = data.length===0 ? null : data[0].nTr; for ( var i=0, iLen=data.length ; i<iLen ; i++ ) { data[i]._DTTT_selected = true; if ( data[i].nTr ) { $(data[i].nTr).addClass( this.classes.select.row ); } } if ( this.s.select.postSelected !== null ) { this.s.select.postSelected.call( this, firstTr ); } TableTools._fnEventDispatch( this, 'select', firstTr ); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function ( src ) { var data = this._fnSelectData( src ); var firstTr = data.length===0 ? null : data[0].nTr; for ( var i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i].nTr && data[i]._DTTT_selected ) { $(data[i].nTr).removeClass( this.classes.select.row ); } data[i]._DTTT_selected = false; } if ( this.s.select.postDeselected !== null ) { this.s.select.postDeselected.call( this, firstTr ); } TableTools._fnEventDispatch( this, 'select', firstTr ); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables or an array of aoData * points. * @returns {array} An array of aoData points */ "_fnSelectData": function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery oject or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else { out.push( src[i] ); } } return out; } else { // A single aoData point out.push( src ); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function ( nButton, oConfig ) { var that = this; if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } if ( oConfig.sToolTip !== "" ) { nButton.title = oConfig.sToolTip; } $(nButton).hover( function () { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( this, nButton, oConfig, null ); } }, function () { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( this, nButton, oConfig, null ); } } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } $(nButton).click( function (e) { //e.preventDefault(); if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, null ); } /* Provide a complete function to match the behaviour of the flash elements */ if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, null, null ); } that._fnCollectionHide( nButton, oConfig ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function ( flash, node, text ) { var that = this; var id = node.getAttribute('id'); if ( document.getElementById(id) ) { flash.glue( node, text ); } else { setTimeout( function () { that._fnFlashGlue( flash, node, text ); }, 100 ); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transfered between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocuments, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retreieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function ( mColumns ) { var aColumns = []; var dt = this.s.dt; if ( typeof mColumns == "object" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( false ); } for ( i=0, iLen=mColumns.length ; i<iLen ; i++ ) { aColumns[ mColumns[i] ] = true; } } else if ( mColumns == "visible" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? true : false ); } } else if ( mColumns == "hidden" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? false : true ); } } else if ( mColumns == "sortable" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bSortable ? true : false ); } } else /* all */ { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( true ); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function ( oConfig ) { if ( oConfig.sNewLine == "auto" ) { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field seperator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatinated string of data * @private */ "_fnGetDataTablesData": function ( oConfig ) { var i, iLen, j, jLen; var aRow, aData=[], sLoopData='', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets( oConfig.mColumns ); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if ( oConfig.bHeader ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,""); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } /* * Body */ var aDataIndex = dt.aiDisplay; var aSelected = this.fnGetSelected(); if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 ) { aDataIndex = []; for ( i=0, iLen=aSelected.length ; i<iLen ; i++ ) { aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) ); } } for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ ) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' ); if ( oConfig.fnCellRender ) { sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+""; } else if ( typeof mTypeData == "string" ) { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g," "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace( /<.*?>/g, "" ); } else { sLoopData = mTypeData+""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode( sLoopData ); /* Bound it and add it to the total data */ aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); /* Details rows from fnOpen */ if ( oConfig.bOpenRows ) { arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; }); if ( arr.length === 1 ) { sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex ); aData.push( sLoopData ); } } } /* * Footer */ if ( oConfig.bFooter && dt.nTFoot !== null ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null ) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" ); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } _sLastData = aData.join( this._fnNewline(oConfig) ); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficincy * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function ( sData ) { if ( sData.indexOf('&') == -1 ) { return sData; } var aData = this._fnChunkData( sData, 2048 ), n = document.createElement('div'), i, iLen, iIndex, sReturn = "", sInner; /* nodeValue has a limit in browsers - so we chunk the data into smaller segments to build * up the string. Note that the 'trick' here is to remember than we might have split over * an HTML entity, so we backtrack a little to make sure this doesn't happen */ for ( i=0, iLen=aData.length ; i<iLen ; i++ ) { /* Magic number 8 is because no entity is longer then strlen 8 in ISO 8859-1 */ iIndex = aData[i].lastIndexOf( '&' ); if ( iIndex != -1 && aData[i].length >= 8 && iIndex > aData[i].length - 8 ) { sInner = aData[i].substr( iIndex ); aData[i] = aData[i].substr( 0, iIndex ); } n.innerHTML = aData[i]; sReturn += n.childNodes[0].nodeValue; } return sReturn; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function ( oConfig ) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes( oSetDT.nTable ); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if ( oConfig.bShowAll ) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); } /* Adjust the display for scrolling which might be done by DataTables */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollStart( oSetDT ); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for ( var cFeature in anFeature ) { if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 ) { for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ ) { this.dom.print.hidden.push( { "node": anFeature[cFeature][i], "display": "block" } ); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass( this.classes.print.body ); /* Show information message to let the user know what is happening */ if ( oConfig.sInfo !== "" ) { this.fnInfo( oConfig.sInfo, 3000 ); } /* Add a message at the top of the page */ if ( oConfig.sMessage ) { this.dom.print.message = document.createElement( "div" ); this.dom.print.message.className = this.classes.print.message; this.dom.print.message.innerHTML = oConfig.sMessage; document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] ); } /* Cache the scrolling and the jump to the top of the t=page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo( 0, 0 ); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind( "keydown.DTTT", function(e) { /* Only interested in the escape key */ if ( e.keyCode == 27 ) { e.preventDefault(); that._fnPrintEnd.call( that, e ); } } ); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ if ( oDomPrint.message !== null ) { document.body.removeChild( oDomPrint.message ); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ var nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hardword here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName != "BODY" ) { this._fnPrintHideNodes( nParent ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master ) { a.push( TableTools._aInstances[i] ); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function ( node ) { if ( typeof node != 'object' ) { node = document.getElementById(node); } for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node ) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function ( that, type, fn ) { TableTools._aListeners.push( { "that": that, "type": type, "fn": fn } ); }; /** * An event has occured - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occured on (may be null) * @returns void * @private * @static */ TableTools._fnEventDispatch = function ( that, type, node ) { var listeners = TableTools._aListeners; for ( var i=0, iLen=listeners.length ; i<iLen ; i++ ) { if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type ) { listeners[i].fn( node ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "xls": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "copy": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); }, "fnComplete": function(nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines-1 : lines-2, plural = (len==1) ? "" : "s"; this.fnInfo( '<h6>Table copied</h6>'+ '<p>Copied '+len+' row'+plural+' to the clipboard.</p>', 1500 ); } } ), "pdf": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } } ), "print": $.extend( {}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+ "print this table. Press escape when finished.", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function ( nButton, oConfig ) { this.fnPrint( true, oConfig ); } } ), "text": $.extend( {}, TableTools.buttonBase ), "select": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_single": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { var iSelected = this.fnGetSelected().length; if ( iSelected == 1 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_all": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function( nButton, oConfig ) { this.fnSelectAll(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) { $(nButton).addClass( this.classes.buttons.disabled ); } else { $(nButton).removeClass( this.classes.buttons.disabled ); } } } ), "select_none": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function( nButton, oConfig ) { this.fnSelectNone(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "ajax": $.extend( {}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function( nButton, oConfig ) { var sData = this.fnGetTableData(oConfig); $.ajax( { "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert( "Error detected when sending table data to server" ); } } ); }, "fnAjaxComplete": function( json ) { alert( 'Ajax complete' ); } } ), "div": $.extend( {}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" } ), "collection": $.extend( {}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function( nButton, oConfig ) { this._fnCollectionShow(nButton, oConfig); } } ) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ /** * @namespace Classes used by TableTools - allows the styles to be overriden easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compability with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.VERSION = "2.1.2"; TableTools.prototype.VERSION = TableTools.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools( oDTSettings.oInstance, oOpts ); TableTools._aInstances.push( oTT ); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" } ); } else { alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document);
JavaScript
$.fn.dataTableExt.oApi.fnFilterClear = function ( oSettings ) { /* Remove global filter */ oSettings.oPreviousSearch.sSearch = ""; /* Remove the text of the global filter in the input boxes */ if ( typeof oSettings.aanFeatures.f != 'undefined' ) { var n = oSettings.aanFeatures.f; for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { $('input', n[i]).val( '' ); } } /* Remove the search text for the column filters - NOTE - if you have input boxes for these * filters, these will need to be reset */ for ( var i=0, iLen=oSettings.aoPreSearchCols.length ; i<iLen ; i++ ) { oSettings.aoPreSearchCols[i].sSearch = ""; } /* Redraw */ oSettings.oApi._fnReDraw( oSettings ); };
JavaScript
var default_per_page = typeof default_per_page !== 'undefined' ? default_per_page : 25; var oTable = null; var oTableArray = []; var oTableMapping = []; function supports_html5_storage() { try { JSON.parse("{}"); return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } var use_storage = supports_html5_storage(); var aButtons = []; var mColumns = []; $(document).ready(function() { $('table.groceryCrudTable thead tr th').each(function(index){ if(!$(this).hasClass('actions')) { mColumns[index] = index; } }); if(!unset_export) { aButtons.push( { "sExtends": "xls", "sButtonText": export_text, "mColumns": mColumns }); } if(!unset_print) { aButtons.push({ "sExtends": "print", "sButtonText": print_text, "mColumns": mColumns }); } //For mutliplegrids disable bStateSave as it is causing many problems if ($('.groceryCrudTable').length > 1) { use_storage = false; } $('.groceryCrudTable').each(function(index){ if (typeof oTableArray[index] !== 'undefined') { return false; } oTableMapping[$(this).attr('id')] = index; oTableArray[index] = loadDataTable(this); }); $(".groceryCrudTable tfoot input").keyup( function () { chosen_table = datatables_get_chosen_table($(this).closest('.groceryCrudTable')); chosen_table.fnFilter( this.value, chosen_table.find("tfoot input").index(this) ); if(use_storage) { var search_values_array = []; chosen_table.find("tfoot tr th").each(function(index,value){ search_values_array[index] = $(this).children(':first').val(); }); localStorage.setItem( 'datatables_search_'+ unique_hash ,'["' + search_values_array.join('","') + '"]'); } } ); var search_values = localStorage.getItem('datatables_search_'+ unique_hash); if( search_values !== null) { $.each($.parseJSON(search_values),function(num,val){ if(val !== '') { $(".groceryCrudTable tfoot tr th:eq("+num+")").children(':first').val(val); } }); } $('.clear-filtering').click(function(){ localStorage.removeItem( 'DataTables_' + unique_hash); localStorage.removeItem( 'datatables_search_'+ unique_hash); chosen_table = datatables_get_chosen_table($(this).closest('.groceryCrudTable')); chosen_table.fnFilterClear(); $(this).closest('.groceryCrudTable').find("tfoot tr th input").val(""); }); loadListenersForDatatables(); $('a[role=button],button[role=button]').live("mouseover mouseout", function(event) { if ( event.type == "mouseover" ) { $(this).addClass('ui-state-hover'); } else { $(this).removeClass('ui-state-hover'); } }); $('th.actions').unbind('click'); $('th.actions>div .DataTables_sort_icon').remove(); } ); function loadListenersForDatatables() { $('.refresh-data').click(function(){ var this_container = $(this).closest('.dataTablesContainer'); var new_container = $("<div/>").addClass('dataTablesContainer'); this_container.after(new_container); this_container.remove(); $.ajax({ url: $(this).attr('data-url'), success: function(my_output){ new_container.html(my_output); loadDataTable(new_container.find('.groceryCrudTable')); loadListenersForDatatables(); } }); }); } function loadDataTable(this_datatables) { return $(this_datatables).dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers", "bStateSave": use_storage, "fnStateSave": function (oSettings, oData) { localStorage.setItem( 'DataTables_' + unique_hash, JSON.stringify(oData) ); }, "fnStateLoad": function (oSettings) { return JSON.parse( localStorage.getItem('DataTables_'+unique_hash) ); }, "iDisplayLength": default_per_page, "aaSorting": datatables_aaSorting, "oLanguage":{ "sProcessing": list_loading, "sLengthMenu": show_entries_string, "sZeroRecords": list_no_items, "sInfo": displaying_paging_string, "sInfoEmpty": list_zero_entries, "sInfoFiltered": filtered_from_string, "sSearch": search_string+":", "oPaginate": { "sFirst": paging_first, "sPrevious": paging_previous, "sNext": paging_next, "sLast": paging_last } }, "bDestory": true, "bRetrieve": true, "fnDrawCallback": function() { $('.image-thumbnail').fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, 'speedOut' : 200, 'overlayShow' : false }); add_edit_button_listener(); }, "sDom": 'T<"clear"><"H"lfr>t<"F"ip>', "oTableTools": { "aButtons": aButtons, "sSwfPath": base_url+"assets/grocery_crud/themes/datatables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf" } }); } function datatables_get_chosen_table(table_as_object) { chosen_table_index = oTableMapping[table_as_object.attr('id')]; return oTableArray[chosen_table_index]; } function delete_row(delete_url , row_id) { if(confirm(message_alert_delete)) { $.ajax({ url: delete_url, dataType: 'json', success: function(data) { if(data.success) { success_message(data.success_message); chosen_table = datatables_get_chosen_table($('tr#row-'+row_id).closest('.groceryCrudTable')); $('tr#row-'+row_id).addClass('row_selected'); var anSelected = fnGetSelected( chosen_table ); chosen_table.fnDeleteRow( anSelected[0] ); } else { error_message(data.error_message); } } }); } return false; } function fnGetSelected( oTableLocal ) { var aReturn = new Array(); var aTrs = oTableLocal.fnGetNodes(); for ( var i=0 ; i<aTrs.length ; i++ ) { if ( $(aTrs[i]).hasClass('row_selected') ) { aReturn.push( aTrs[i] ); } } return aReturn; }
JavaScript
$(function(){ $('.ptogtitle').click(function(){ if($(this).hasClass('vsble')) { $(this).removeClass('vsble'); $('#main-table-box').slideDown("slow"); } else { $(this).addClass('vsble'); $('#main-table-box').slideUp("slow"); } }); var save_and_close = false; $('#save-and-go-back-button').click(function(){ save_and_close = true; $('#crudForm').trigger('submit'); }); $('#crudForm').submit(function(){ $(this).ajaxSubmit({ url: validation_url, dataType: 'json', beforeSend: function(){ $("#FormLoading").show(); }, success: function(data){ $("#FormLoading").hide(); if(data.success) { $('#crudForm').ajaxSubmit({ dataType: 'text', cache: 'false', beforeSend: function(){ $("#FormLoading").show(); }, success: function(result){ $("#FormLoading").fadeOut("slow"); data = $.parseJSON( result ); if(data.success) { if(save_and_close) { if ($('#save-and-go-back-button').closest('.ui-dialog').length === 0) { window.location = data.success_list_url; } else { $(".ui-dialog-content").dialog("close"); success_message(data.success_message); } return true; } $('.field_error').removeClass('field_error'); form_success_message(data.success_message); clearForm(); } else { form_error_message('An error has been occured at the insert.'); } } }); } else { $('.field_error').removeClass('field_error'); form_error_message(data.error_message); $.each(data.error_fields, function(index,value){ $('#crudForm input[name='+index+']').addClass('field_error'); }); } } }); return false; }); $('.ui-input-button').button(); $('.gotoListButton').button({ icons: { primary: "ui-icon-triangle-1-w" } }); if( $('#cancel-button').closest('.ui-dialog').length === 0 ) { $('#cancel-button').click(function(){ if( confirm( message_alert_add_form ) ) { window.location = list_url; } return false; }); } }); function clearForm() { $('#crudForm').find(':input').each(function() { switch(this.type) { case 'password': case 'select-multiple': case 'select-one': case 'text': case 'textarea': $(this).val(''); break; case 'checkbox': case 'radio': this.checked = false; } }); /* Clear upload inputs */ $('.open-file,.gc-file-upload,.hidden-upload-input').each(function(){ $(this).val(''); }); $('.upload-success-url').hide(); $('.fileinput-button').fadeIn("normal"); /* -------------------- */ $('.remove-all').each(function(){ $(this).trigger('click'); }); $('.chosen-multiple-select, .chosen-select, .ajax-chosen-select').each(function(){ $(this).trigger("liszt:updated"); }); }
JavaScript
$(function(){ var save_and_close = false; $('#save-and-go-back-button').click(function(){ save_and_close = true; $('#crudForm').trigger('submit'); }); $('#crudForm').submit(function(){ $(this).ajaxSubmit({ url: validation_url, dataType: 'json', beforeSend: function(){ $("#FormLoading").show(); }, cache: false, success: function(data){ $("#FormLoading").hide(); if(data.success) { $('#crudForm').ajaxSubmit({ dataType: 'text', cache: false, beforeSend: function(){ $("#FormLoading").show(); }, success: function(result){ $("#FormLoading").fadeOut("slow"); data = $.parseJSON( result ); if(data.success) { if(save_and_close) { if ($('#save-and-go-back-button').closest('.ui-dialog').length === 0) { window.location = data.success_list_url; } else { $(".ui-dialog-content").dialog("close"); success_message(data.success_message); } return true; } $('.field_error').removeClass('field_error'); form_success_message(data.success_message); } else { form_error_message(message_update_error); } }, error: function(){ form_error_message( message_update_error ); } }); } else { $('.field_error').removeClass('field_error'); form_error_message(data.error_message); $.each(data.error_fields, function(index,value){ $('#crudForm input[name='+index+']').addClass('field_error'); }); } } }); return false; }); $('.ui-input-button').button(); $('.gotoListButton').button({ icons: { primary: "ui-icon-triangle-1-w" } }); if( $('#cancel-button').closest('.ui-dialog').length === 0 ) { $('#cancel-button').click(function(){ if( $(this).hasClass('back-to-list') || confirm( message_alert_edit_form ) ) { window.location = list_url; } return false; }); } });
JavaScript
/* <script type="text/javascript" src=""></script> <script type="text/javascript" src="<?php echo base_url()?>assets/grocery_crud/js/jquery_plugins/jquery.layout-latest.js"></script> <!--script type="text/javascript" src="<?php echo base_url()?>assets/grocery_crud/js/jquery_plugins/jquery.ba-hashchange-1.3.min.js"></script--> */ head.load( "assets/grocery_crud/js/jquery_plugins/ui/jquery.ui.core.js", "assets/grocery_crud/js/jquery_plugins/ui/jquery.ui.widget.js", "assets/grocery_crud/js/jquery_plugins/ui/jquery.ui.accordion.js");
JavaScript
function text(){} function error_alert(title,content) { var dlg = $('<div id="ualertdlg"></div>'); var content = $('<div class="content"></div>').append(content); var closeBtn = $('<button class="btn"><i class="fa fa-times"></i>&nbsp;Close</button>'); dlg.append(content); dlg.append(closeBtn); dlg.dialog({ modal:true, title:title, width:300, height:130, close:function(){ dlg.remove(); } }); closeBtn.click(function(){dlg.dialog('close')}); $('div[aria-describedby=ualertdlg]').addClass('err-dlg'); }; window.confirm_alert=function(title,content,onConfirm,onCancel){ console.log('hello') // var dlg = $('<div id="ualertdlg"></div>'); // dlg.append(content); // dlg.dialog({ // modal:true, // title:title, // width:300, // height:130, // close:function(){ // dlg.remove(); // } // }); // dlg.dialog('option', 'buttons', { // "Confirm" : function(){ // $(this).dialog("close"); // onConfirm(dlg); // }, // "Cancel" : function() { // $(this).dialog("close"); // onCancel(dlg); // } // }); // dlg.dialog("open"); // $('div[aria-describedby=ualertdlg]').addClass('err-dlg'); };
JavaScript
var js_libraries = []; var fnOpenEditForm = function(this_element){ var href_url = this_element.attr("href"); var dialog_height = $(window).height() - 80; //Close all $(".ui-dialog-content").dialog("close"); $.ajax({ url: href_url, data: { is_ajax: 'true' }, type: 'post', dataType: 'json', beforeSend: function() { $(this_element).trigger('onloading');//this_element.closest('.flexigrid').addClass('loading-opacity'); }, complete: function(){ $(this_element).trigger('oncomplete');//this_element.closest('.flexigrid').removeClass('loading-opacity'); }, success: function (data) { if (typeof CKEDITOR !== 'undefined' && typeof CKEDITOR.instances !== 'undefined') { $.each(CKEDITOR.instances,function(index){ delete CKEDITOR.instances[index]; }); } LazyLoad.loadOnce(data.js_lib_files); LazyLoad.load(data.js_config_files); $.each(data.css_files,function(index,css_file){ load_css_file(css_file); }); //console.log(data); var dTitle = (gcConf.state == 'Add' ? 'Tambah' : 'Edit') + ' ' + gcConf.subject; var cdlg = $("<div/>").html(data.output).addClass('flexigrid-dlg-form '+window.gcConf.subject_cls).dialog({ width: 'auto', modal: true, title: dTitle, height: 'auto', close: function(){ if($(this_element).attr('invoke_after')) { var fn_invoke_after = $(this_element).attr('invoke_after'); if(typeof window[fn_invoke_after] == 'function') { window[fn_invoke_after](this_element); } } $(this).remove(); }, open: function(){ var this_dialog = $(this); var dlg_title = this_dialog.closest('.ui-dialog').find('.ui-dialog-title'); if(gcConf.state == 'Read'){ dlg_title.text(dlg_title.text().replace(/edit/ig,'View')); this_dialog.closest('.ui-dialog').find('.tDiv').hide() } //console.log(dlg_title.text()); if(typeof window.gcConf.onDialogOpen!='undefined') { if( typeof window.gcConf.onDialogOpen == 'function') { var frmContainer = $(cdlg).find('.flexigrid.crud-form'); var frmObj = $(cdlg).find('#crudForm'); window.gcConf.onDialogOpen(this,cdlg,frmContainer,frmObj); } } $('#cancel-button').click(function(){ this_dialog.dialog("close"); }); // setTimeout(function(){ // // $(cdlg.find('textarea,input').get(0)).focus(); // // console.log('autofocus'); // var title = cdlg.find('.ftitle').text(); // cdlg.dialog('option','title',title); // },50); } }); } }); }; var add_edit_button_listener = function () { //If dialog AJAX forms is turned on from grocery CRUD config if (dialog_forms) { //$('.add_button').attr('onclick',''); $('.edit_button,.add_button').unbind('click'); $('.edit_button,.add_button').click(function(){ if($(this).hasClass('add_button')) window.gcConf.state = 'Add'; else window.gcConf.state = 'Edit'; fnOpenEditForm($(this)); //console.log(window.gcConf); return false; }); } } var load_css_file = function(css_file) { if ($('head').find('link[href="'+css_file+'"]').length == 0) { $('head').append($('<link/>').attr("type","text/css") .attr("rel","stylesheet").attr("href",css_file)); } };
JavaScript
function exchange_field(form,fields) { //var fields = ["no_srt","tgl_srt","id_afiliasi","to","to_attn","to_address","to_telp","to_fax","to_email","from","from_attn","from_address","from_telp","from_fax","from_email","subject","name","subject_oi","description_og","importer","importer_attn","importer_address","importer_telp","importer_fax","importer_email","exporter","exporter_attn","exporter_address","exporter_telp","exporter_fax","exporter_email","place_oi","date_oi","import_permit_no","invoice_no","quotation_no","quotation_date","company_name","company_npwp","company_address","regard","applicants_name"]; //var data = {}; //console.log(data) //var frm = template(r,data); //$(form).find('.form-div').append(r); $.each(fields,function(i,field){ var el = $(form).find('div#'+field+'_field_box'); var input = el.find('#field-'+field); //console.log(input) var tpl = $(form).find('#tpl_'+field); tpl.replaceWith(input); //console.log(tpl) el.hide(); }); } function template(str, data) { var o = data; return str.replace(/\{\{(.*?)\}\}/g, function (match, token) { return eval("o." + token); }); } $(document).ready(function() { $("body").on({ click:function(){ var url = $(this).prop('href'); var dlg = $('<div id="upwdlg"></div>'); var cnt = '<div class="pengguna-password">'+ '<div>'+ '<label style="display: block; width: 87px; float: left; line-height: 22px;">New Password :</label>'+ '<input style="float:left;margin-top:1px;" type="password" name="pengguna_password"/>' + '</div><div><input style="float:left;cursor:pointer;margin-left:2px" type="button" value="Change" class="cmd_set_passwd"/></div>' + '</div>'; var dlg_title = 'Change Password - ' + $.trim($(this).parent().parent().prev().prev().text()); dlg.html(cnt).dialog({ modal:true, title:dlg_title, width:358, height:80, close:function(){ dlg.remove(); } }); dlg.find('input.cmd_set_passwd').click(function(){ var new_passwd = dlg.find('input[name=pengguna_password]').val(); if(!new_passwd.length){ alert('Password Anda kosong !') return; } $.post(url,{passwd:new_passwd},function(o){ alert(o.m); if(o.s) dlg.dialog('close') ; else $('input[name=pengguna_password]').val('').focus(); },'json'); }) dlg.find('input[name=pengguna_password]').keydown(function(e){ if(e.keyCode==13){ dlg.find('input.cmd_set_passwd').click(); } }); dlg.dialog('open'); return false; }, mouseover:function(){ $(this).prop('title','Ubah Password');} },'.grd-user a.pengguna_password_cmd'); });
JavaScript
/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh) * Licensed under the MIT License (LICENSE.txt). * * Version: 3.1.9 * * Requires: jQuery 1.2.2+ */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } var special = $.event.special.mousewheel = { version: '3.1.9', setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = handler; } // Store the line height and page height for this particular element $.data(this, 'mousewheel-line-height', special.getLineHeight(this)); $.data(this, 'mousewheel-page-height', special.getPageHeight(this)); }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = null; } }, getLineHeight: function(elem) { return parseInt($(elem)['offsetParent' in $.fn ? 'offsetParent' : 'parent']().css('fontSize'), 10); }, getPageHeight: function(elem) { return $(elem).height(); }, settings: { adjustOldDeltas: true } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); }, unmousewheel: function(fn) { return this.unbind('mousewheel', fn); } }); function handler(event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0; event = $.event.fix(orgEvent); event.type = 'mousewheel'; // Old school scrollwheel delta if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) if ( 'deltaY' in orgEvent ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( 'deltaX' in orgEvent ) { deltaX = orgEvent.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } // No change actually happened, no reason to go any further if ( deltaY === 0 && deltaX === 0 ) { return; } // Need to convert lines and pages to pixels if we aren't already in pixels // There are three delta modes: // * deltaMode 0 is by pixels, nothing to do // * deltaMode 1 is by lines // * deltaMode 2 is by pages if ( orgEvent.deltaMode === 1 ) { var lineHeight = $.data(this, 'mousewheel-line-height'); delta *= lineHeight; deltaY *= lineHeight; deltaX *= lineHeight; } else if ( orgEvent.deltaMode === 2 ) { var pageHeight = $.data(this, 'mousewheel-page-height'); delta *= pageHeight; deltaY *= pageHeight; deltaX *= pageHeight; } // Store lowest absolute delta to normalize the delta values absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) ); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { lowestDelta /= 40; } } // Adjust older deltas if necessary if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) { // Divide all the things by 40! delta /= 40; deltaX /= 40; deltaY /= 40; } // Get a whole, normalized value for the deltas delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); // Add information to the event object event.deltaX = deltaX; event.deltaY = deltaY; event.deltaFactor = lowestDelta; // Go ahead and set deltaMode to 0 since we converted to pixels // Although this is a little odd since we overwrite the deltaX/Y // properties with normalized deltas. event.deltaMode = 0; // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); // Clearout lowestDelta after sometime to better // handle multiple device types that give different // a different lowestDelta // Ex: trackpad = 3 and mouse wheel = 120 if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); } nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200); return ($.event.dispatch || $.event.handle).apply(this, args); } function nullLowestDelta() { lowestDelta = null; } function shouldAdjustOldDeltas(orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas // by 40 to try and get a more usable deltaFactor. // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; } }));
JavaScript
/** * @author trixta * @version 1.2 */ (function($){ var mwheelI = { pos: [-260, -260] }, minDif = 3, doc = document, root = doc.documentElement, body = doc.body, longDelay, shortDelay ; function unsetPos(){ if(this === mwheelI.elem){ mwheelI.pos = [-260, -260]; mwheelI.elem = false; minDif = 3; } } $.event.special.mwheelIntent = { setup: function(){ var jElm = $(this).bind('mousewheel', $.event.special.mwheelIntent.handler); if( this !== doc && this !== root && this !== body ){ jElm.bind('mouseleave', unsetPos); } jElm = null; return true; }, teardown: function(){ $(this) .unbind('mousewheel', $.event.special.mwheelIntent.handler) .unbind('mouseleave', unsetPos) ; return true; }, handler: function(e, d){ var pos = [e.clientX, e.clientY]; if( this === mwheelI.elem || Math.abs(mwheelI.pos[0] - pos[0]) > minDif || Math.abs(mwheelI.pos[1] - pos[1]) > minDif ){ mwheelI.elem = this; mwheelI.pos = pos; minDif = 250; clearTimeout(shortDelay); shortDelay = setTimeout(function(){ minDif = 10; }, 200); clearTimeout(longDelay); longDelay = setTimeout(function(){ minDif = 3; }, 1500); e = $.extend({}, e, {type: 'mwheelIntent'}); return ($.event.dispatch || $.event.handle).apply(this, arguments); } } }; $.fn.extend({ mwheelIntent: function(fn) { return fn ? this.bind("mwheelIntent", fn) : this.trigger("mwheelIntent"); }, unmwheelIntent: function(fn) { return this.unbind("mwheelIntent", fn); } }); $(function(){ body = doc.body; //assume that document is always scrollable, doesn't hurt if not $(doc).bind('mwheelIntent.mwheelIntentDefault', $.noop); }); })(jQuery);
JavaScript
/* * jQuery Iframe Transport Plugin 1.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts three additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s) // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] $.ajaxTransport('iframe', function (options) { if (options.async && (options.type === 'POST' || options.type === 'GET')) { var form, iframe; return { send: function (_, completeCallback) { form = $('<form style="display:none;"></form>'); // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6. // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: iframe = $( '<iframe src="javascript:false;" name="iframe-transport-' + (counter += 1) + '"></iframe>' ).bind('load', function () { var fileInputClones; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('<iframe src="javascript:false;"></iframe>') .appendTo(form); form.remove(); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('<input type="hidden"/>') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function () { $(this).prop('name', options.paramName); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); $(input).prop('name', clone.prop('name')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', 'javascript'.concat(':false;')); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, and script: $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return $(iframe[0].body).html(); }, 'iframe script': function (iframe) { return $.globalEval($(iframe[0].body).text()); } } }); }));
JavaScript
/* Uniform v2.0.0 Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC http://pixelmatrixdesign.com Requires jQuery 1.3 or newer Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this. Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/> and his noSelect plugin. <https://github.com/mathiasbynens/jquery-noselect>, which is embedded. Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin. Tyler Akins has also rewritten chunks of the plugin, helped close many issues, and ensured version 2 got out the door. License: MIT License - http://www.opensource.org/licenses/mit-license.php Enjoy! */ /*global jQuery, window, document*/ (function ($, undef) { "use strict"; /** * Use .prop() if jQuery supports it, otherwise fall back to .attr() * * @param jQuery $el jQuery'd element on which we're calling attr/prop * @param ... All other parameters are passed to jQuery's function * @return The result from jQuery */ function attrOrProp($el) { var args = Array.prototype.slice.call(arguments, 1); if ($el.prop) { // jQuery 1.6+ return $el.prop.apply($el, args); } // jQuery 1.5 and below return $el.attr.apply($el, args); } /** * For backwards compatibility with older jQuery libraries, only bind * one thing at a time. Also, this function adds our namespace to * events in one consistent location, shrinking the minified code. * * The properties on the events object are the names of the events * that we are supposed to add to. It can be a space separated list. * The namespace will be added automatically. * * @param jQuery $el * @param Object options Uniform options for this element * @param Object events Events to bind, properties are event names */ function bindMany($el, options, events) { var name, namespaced; for (name in events) { if (events.hasOwnProperty(name)) { namespaced = name.replace(/ |$/g, options.eventNamespace); $el.bind(name, events[name]); } } } /** * Bind the hover, active, focus, and blur UI updates * * @param jQuery $el Original element * @param jQuery $target Target for the events (our div/span) * @param Object options Uniform options for the element $target */ function bindUi($el, $target, options) { bindMany($el, options, { focus: function () { $target.addClass(options.focusClass); }, blur: function () { $target.removeClass(options.focusClass); $target.removeClass(options.activeClass); }, mouseenter: function () { $target.addClass(options.hoverClass); }, mouseleave: function () { $target.removeClass(options.hoverClass); $target.removeClass(options.activeClass); }, "mousedown touchbegin": function () { if (!$el.is(":disabled")) { $target.addClass(options.activeClass); } }, "mouseup touchend": function () { $target.removeClass(options.activeClass); } }); } /** * Remove the hover, focus, active classes. * * @param jQuery $el Element with classes * @param Object options Uniform options for the element */ function classClearStandard($el, options) { $el.removeClass(options.hoverClass + " " + options.focusClass + " " + options.activeClass); } /** * Add or remove a class, depending on if it's "enabled" * * @param jQuery $el Element that has the class added/removed * @param String className Class or classes to add/remove * @param Boolean enabled True to add the class, false to remove */ function classUpdate($el, className, enabled) { if (enabled) { $el.addClass(className); } else { $el.removeClass(className); } } /** * Updating the "checked" property can be a little tricky. This * changed in jQuery 1.6 and now we can pass booleans to .prop(). * Prior to that, one either adds an attribute ("checked=checked") or * removes the attribute. * * @param jQuery $tag Our Uniform span/div * @param jQuery $el Original form element * @param Object options Uniform options for this element */ function classUpdateChecked($tag, $el, options) { var c = "checked", isChecked = $el.is(":" + c); if ($el.prop) { // jQuery 1.6+ $el.prop(c, isChecked); } else { // jQuery 1.5 and below if (isChecked) { $el.attr(c, c); } else { $el.removeAttr(c); } } classUpdate($tag, options.checkedClass, isChecked); } /** * Set or remove the "disabled" class for disabled elements, based on * if the * * @param jQuery $tag Our Uniform span/div * @param jQuery $el Original form element * @param Object options Uniform options for this element */ function classUpdateDisabled($tag, $el, options) { classUpdate($tag, options.disabledClass, $el.is(":disabled")); } /** * Wrap an element inside of a container or put the container next * to the element. See the code for examples of the different methods. * * Returns the container that was added to the HTML. * * @param jQuery $el Element to wrap * @param jQuery $container Add this new container around/near $el * @param String method One of "after", "before" or "wrap" * @return $container after it has been cloned for adding to $el */ function divSpanWrap($el, $container, method) { switch (method) { case "after": // Result: <element /> <container /> $el.after($container); return $el.next(); case "before": // Result: <container /> <element /> $el.before($container); return $el.prev(); case "wrap": // Result: <container> <element /> </container> $el.wrap($container); return $el.parent(); } return null; } /** * Create a div/span combo for uniforming an element * * @param jQuery $el Element to wrap * @param Object options Options for the element, set by the user * @param Object divSpanConfig Options for how we wrap the div/span * @return Object Contains the div and span as properties */ function divSpan($el, options, divSpanConfig) { var $div, $span, id; if (!divSpanConfig) { divSpanConfig = {}; } divSpanConfig = $.extend({ bind: {}, divClass: null, divWrap: "wrap", spanClass: null, spanHtml: null, spanWrap: "wrap" }, divSpanConfig); $div = $('<div />'); $span = $('<span />'); // Automatically hide this div/span if the element is hidden. // Do not hide if the element is hidden because a parent is hidden. if (options.autoHide && $el.is(':hidden') && $el.css('display') === 'none') { $div.hide(); } if (divSpanConfig.divClass) { $div.addClass(divSpanConfig.divClass); } if (divSpanConfig.spanClass) { $span.addClass(divSpanConfig.spanClass); } id = attrOrProp($el, 'id'); if (options.useID && id) { attrOrProp($div, 'id', options.idPrefix + '-' + id); } if (divSpanConfig.spanHtml) { $span.html(divSpanConfig.spanHtml); } $div = divSpanWrap($el, $div, divSpanConfig.divWrap); $span = divSpanWrap($el, $span, divSpanConfig.spanWrap); classUpdateDisabled($div, $el, options); return { div: $div, span: $span }; } /** * Test if high contrast mode is enabled. * * In high contrast mode, background images can not be set and * they are always returned as 'none'. * * @return boolean True if in high contrast mode */ function highContrast() { var c, $div, el, rgb; // High contrast mode deals with white and black rgb = 'rgb(120,2,153)'; $div = $('<div style="width:0;height:0;color:' + rgb + '">'); $('body').append($div); el = $div.get(0); // $div.css() will get the style definition, not // the actually displaying style if (window.getComputedStyle) { c = window.getComputedStyle(el, '').color; } else { c = (el.currentStyle || el.style || {}).color; } $div.remove(); return c.replace(/ /g, '') !== rgb; } /** * Change text into safe HTML * * @param String text * @return String HTML version */ function htmlify(text) { if (!text) { return ""; } return $('<span />').text(text).html(); } /** * Test if the element is a multiselect * * @param jQuery $el Element * @return boolean true/false */ function isMultiselect($el) { var elSize; if ($el[0].multiple) { return true; } elSize = attrOrProp($el, "size"); if (!elSize || elSize <= 1) { return false; } return true; } /** * Meaningless utility function. Used mostly for improving minification. * * @return false */ function returnFalse() { return false; } /** * noSelect plugin, very slightly modified * http://mths.be/noselect v1.0.3 * * @param jQuery $elem Element that we don't want to select * @param Object options Uniform options for the element */ function noSelect($elem, options) { var none = 'none'; bindMany($elem, options, { 'selectstart dragstart mousedown': returnFalse }); $elem.css({ MozUserSelect: none, msUserSelect: none, webkitUserSelect: none, userSelect: none }); } /** * Updates the filename tag based on the value of the real input * element. * * @param jQuery $el Actual form element * @param jQuery $filenameTag Span/div to update * @param Object options Uniform options for this element */ function setFilename($el, $filenameTag, options) { var filename = $el.val(); if (filename === "") { filename = options.fileDefaultHtml; } else { filename = filename.split(/[\/\\]+/); filename = filename[(filename.length - 1)]; } $filenameTag.text(filename); } /** * Function from jQuery to swap some CSS values, run a callback, * then restore the CSS. Modified to pass JSLint and handle undefined * values with 'use strict'. * * @param jQuery $el Element * @param object newCss CSS values to swap out * @param Function callback Function to run */ function swap($el, newCss, callback) { var restore, item; restore = []; $el.each(function () { var name; for (name in newCss) { if (Object.prototype.hasOwnProperty.call(newCss, name)) { restore.push({ el: this, name: name, old: this.style[name] }); this.style[name] = newCss[name]; } } }); callback(); while (restore.length) { item = restore.pop(); item.el.style[item.name] = item.old; } } /** * The browser doesn't provide sizes of elements that are not visible. * This will clone an element and add it to the DOM for calculations. * * @param jQuery $el * @param String method */ function sizingInvisible($el, callback) { swap($el.parents().andSelf().not(':visible'), { visibility: "hidden", display: "block", position: "absolute" }, callback); } /** * Standard way to unwrap the div/span combination from an element * * @param jQuery $el Element that we wish to preserve * @param Object options Uniform options for the element * @return Function This generated function will perform the given work */ function unwrapUnwrapUnbindFunction($el, options) { return function () { $el.unwrap().unwrap().unbind(options.eventNamespace); }; } var allowStyling = true, // False if IE6 or other unsupported browsers highContrastTest = false, // Was the high contrast test ran? uniformHandlers = [ // Objects that take care of "unification" { // Buttons match: function ($el) { return $el.is("a, button, :submit, :reset, input[type='button']"); }, apply: function ($el, options) { var $div, defaultSpanHtml, ds, getHtml, doingClickEvent; defaultSpanHtml = options.submitDefaultHtml; if ($el.is(":reset")) { defaultSpanHtml = options.resetDefaultHtml; } if ($el.is("a, button")) { // Use the HTML inside the tag getHtml = function () { return $el.html() || defaultSpanHtml; }; } else { // Use the value property of the element getHtml = function () { return htmlify(attrOrProp($el, "value")) || defaultSpanHtml; }; } ds = divSpan($el, options, { divClass: options.buttonClass, spanHtml: getHtml() }); $div = ds.div; bindUi($el, $div, options); doingClickEvent = false; bindMany($div, options, { "click touchend": function () { var ev, res, target, href; if (doingClickEvent) { return; } doingClickEvent = true; if ($el[0].dispatchEvent) { ev = document.createEvent("MouseEvents"); ev.initEvent("click", true, true); res = $el[0].dispatchEvent(ev); // What about Chrome and Opera? // Should the browser check be removed? if ((jQuery.browser.msie || jQuery.browser.mozilla) && $el.is('a') && res) { target = attrOrProp($el, 'target'); href = attrOrProp($el, 'href'); if (!target || target === '_self') { document.location.href = href; } else { window.open(href, target); } } } else { $el.click(); } doingClickEvent = false; } }); noSelect($div, options); return { remove: function () { // Move $el out $div.after($el); // Remove div and span $div.remove(); // Unbind events $el.unbind(options.eventNamespace); return $el; }, update: function () { classClearStandard($div, options); classUpdateDisabled($div, $el, options); ds.span.html(getHtml()); } }; } }, { // Checkboxes match: function ($el) { return $el.is(":checkbox"); }, apply: function ($el, options) { var ds, $div, $span; ds = divSpan($el, options, { divClass: options.checkboxClass }); $div = ds.div; $span = ds.span; // Add focus classes, toggling, active, etc. bindUi($el, $div, options); bindMany($el, options, { "click touchend": function () { classUpdateChecked($span, $el, options); } }); classUpdateChecked($span, $el, options); return { remove: unwrapUnwrapUnbindFunction($el, options), update: function () { classClearStandard($div, options); $span.removeClass(options.checkedClass); classUpdateChecked($span, $el, options); classUpdateDisabled($div, $el, options); } }; } }, { // File selection / uploads match: function ($el) { return $el.is(":file"); }, apply: function ($el, options) { var ds, $div, $filename, $button; // The "span" is the button ds = divSpan($el, options, { divClass: options.fileClass, spanClass: options.fileButtonClass, spanHtml: options.fileButtonHtml, spanWrap: "after" }); $div = ds.div; $button = ds.span; $filename = $("<span />").html(options.fileDefaultHtml); $filename.addClass(options.filenameClass); $filename = divSpanWrap($el, $filename, "after"); // Set the size if (!attrOrProp($el, "size")) { attrOrProp($el, "size", $div.width() / 10); } // Actions function filenameUpdate() { setFilename($el, $filename, options); } bindUi($el, $div, options); // Account for input saved across refreshes filenameUpdate(); // IE7 doesn't fire onChange until blur or second fire. if ($.browser.msie) { // IE considers browser chrome blocking I/O, so it // suspends tiemouts until after the file has // been selected. bindMany($el, options, { click: function () { $el.trigger("change"); setTimeout(filenameUpdate, 0); } }); } else { // All other browsers behave properly bindMany($el, options, { change: filenameUpdate }); } noSelect($filename, options); noSelect($button, options); return { remove: function () { // Remove filename and button $filename.remove(); $button.remove(); // Unwrap parent div, remove events return $el.unwrap().unbind(options.eventNamespace); }, update: function () { classClearStandard($div, options); setFilename($el, $filename, options); classUpdateDisabled($div, $el, options); } }; } }, { // Input fields (text) match: function ($el) { if ($el.is("input")) { var t = (" " + attrOrProp($el, "type") + " ").toLowerCase(), allowed = " color date datetime datetime-local email month number password search tel text time url week "; return allowed.indexOf(t) >= 0; } return false; }, apply: function ($el) { var elType = attrOrProp($el, "type"); $el.addClass(elType); return { remove: function () { $el.removeClass(elType); }, update: returnFalse }; } }, { // Radio buttons match: function ($el) { return $el.is(":radio"); }, apply: function ($el, options) { var ds, $div, $span; ds = divSpan($el, options, { divClass: options.radioClass }); $div = ds.div; $span = ds.span; // Add classes for focus, handle active, checked bindUi($el, $div, options); bindMany($el, options, { "click touchend": function () { // Find all radios with the same name, then update // them with $.uniform.update() so the right // per-element options are used $.uniform.update($(':radio[name="' + attrOrProp($el, "name") + '"]')); } }); classUpdateChecked($span, $el, options); return { remove: unwrapUnwrapUnbindFunction($el, options), update: function () { classClearStandard($div, options); classUpdateChecked($span, $el, options); classUpdateDisabled($div, $el, options); } }; } }, { // Select lists, but do not style multiselects here match: function ($el) { if ($el.is("select") && !isMultiselect($el)) { return true; } return false; }, apply: function ($el, options) { var ds, $div, $span, origElemWidth; if (options.selectAutoWidth) { sizingInvisible($el, function () { origElemWidth = $el.width(); }); } ds = divSpan($el, options, { divClass: options.selectClass, spanHtml: ($el.find(":selected:first") || $el.find("option:first")).html(), spanWrap: "before" }); $div = ds.div; $span = ds.span; if (options.selectAutoWidth) { // Use the width of the select and adjust the // span and div accordingly sizingInvisible($el, function () { var spanPad; spanPad = $span.outerWidth() - $span.width(); $div.width(origElemWidth + spanPad); $span.width(origElemWidth); }); } else { // Force the select to fill the size of the div $div.addClass('fixedWidth'); } // Take care of events bindUi($el, $div, options); bindMany($el, options, { change: function () { $span.html($el.find(":selected").html()); $div.removeClass(options.activeClass); }, "click touchend": function () { // IE7 and IE8 may not update the value right // until after click event - issue #238 var selHtml = $el.find(":selected").html(); if ($span.html() !== selHtml) { // Change was detected // Fire the change event on the select tag $el.trigger('change'); } }, keyup: function () { $span.html($el.find(":selected").html()); } }); noSelect($span, options); return { remove: function () { // Remove sibling span $span.remove(); // Unwrap parent div $el.unwrap().unbind(options.eventNamespace); return $el; }, update: function () { if (options.selectAutoWidth) { // Easier to remove and reapply formatting $.uniform.restore($el); $el.uniform(options); } else { classClearStandard($div, options); // Reset current selected text $span.html($el.find(":selected").html()); classUpdateDisabled($div, $el, options); } } }; } }, { // Select lists - multiselect lists only match: function ($el) { if ($el.is("select") && isMultiselect($el)) { return true; } return false; }, apply: function ($el, options) { $el.addClass(options.selectMultiClass); return { remove: function () { $el.removeClass(options.selectMultiClass); }, update: returnFalse }; } }, { // Textareas match: function ($el) { return $el.is("textarea"); }, apply: function ($el, options) { $el.addClass(options.textareaClass); return { remove: function () { $el.removeClass(options.textareaClass); }, update: returnFalse }; } } ]; // IE6 can't be styled - can't set opacity on select if ($.browser.msie && $.browser.version < 7) { allowStyling = false; } $.uniform = { // Default options that can be overridden globally or when uniformed // globally: $.uniform.defaults.fileButtonHtml = "Pick A File"; // on uniform: $('input').uniform({fileButtonHtml: "Pick a File"}); defaults: { activeClass: "active", autoHide: true, buttonClass: "button", checkboxClass: "checker", checkedClass: "checked", disabledClass: "disabled", eventNamespace: ".uniform", fileButtonClass: "action", fileButtonHtml: "Choose File", fileClass: "uploader", fileDefaultHtml: "No file selected", filenameClass: "filename", focusClass: "focus", hoverClass: "hover", idPrefix: "uniform", radioClass: "radio", resetDefaultHtml: "Reset", resetSelector: false, // We'll use our own function when you don't specify one selectAutoWidth: true, selectClass: "selector", selectMultiClass: "uniform-multiselect", submitDefaultHtml: "Submit", // Only text allowed textareaClass: "uniform", useID: true }, // All uniformed elements - DOM objects elements: [] }; $.fn.uniform = function (options) { var el = this; options = $.extend({}, $.uniform.defaults, options); // If we are in high contrast mode, do not allow styling if (!highContrastTest) { highContrastTest = true; if (highContrast()) { allowStyling = false; } } // Only uniform on browsers that work if (!allowStyling) { return this; } // Code for specifying a reset button if (options.resetSelector) { $(options.resetSelector).mouseup(function () { window.setTimeout(function () { $.uniform.update(el); }, 10); }); } return this.each(function () { var $el = $(this), i, handler, callbacks; // Avoid uniforming elements already uniformed - just update if ($el.data("uniformed")) { $.uniform.update($el); return; } // See if we have any handler for this type of element for (i = 0; i < uniformHandlers.length; i = i + 1) { handler = uniformHandlers[i]; if (handler.match($el, options)) { callbacks = handler.apply($el, options); $el.data("uniformed", callbacks); // Store element in our global array $.uniform.elements.push($el.get(0)); return; } } // Could not style this element }); }; $.uniform.restore = $.fn.uniform.restore = function (elem) { if (elem === undef) { elem = $.uniform.elements; } $(elem).each(function () { var $el = $(this), index, elementData; elementData = $el.data("uniformed"); // Skip elements that are not uniformed if (!elementData) { return; } // Unbind events, remove additional markup that was added elementData.remove(); // Remove item from list of uniformed elements index = $.inArray(this, $.uniform.elements); if (index >= 0) { $.uniform.elements.splice(index, 1); } $el.removeData("uniformed"); }); }; $.uniform.update = $.fn.uniform.update = function (elem) { if (elem === undef) { elem = $.uniform.elements; } $(elem).each(function () { var $el = $(this), elementData; elementData = $el.data("uniformed"); // Skip elements that are not uniformed if (!elementData) { return; } elementData.update($el, elementData.options); }); }; }(jQuery));
JavaScript
/** * noty - jQuery Notification Plugin v2.0.3 * Contributors: https://github.com/needim/noty/graphs/contributors * * Examples and Documentation - http://needim.github.com/noty/ * * Licensed under the MIT licenses: * http://www.opensource.org/licenses/mit-license.php * **/ if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {}; F.prototype = o; return new F(); }; }; ;(function($) { var NotyObject = { init: function(options) { // Mix in the passed in options with the default options this.options = $.extend({}, $.noty.defaults, options); this.options.layout = (this.options.custom) ? $.noty.layouts['inline'] : $.noty.layouts[this.options.layout]; this.options.theme = $.noty.themes[this.options.theme]; delete options.layout, delete options.theme; this.options = $.extend({}, this.options, this.options.layout.options); this.options.id = 'noty_' + (new Date().getTime() * Math.floor(Math.random()* 1000000)); this.options = $.extend({}, this.options, options); // Build the noty dom initial structure this._build(); // return this so we can chain/use the bridge with less code. return this; }, // end init _build: function() { // Generating noty bar var $bar = $('<div class="noty_bar"/>').attr('id', this.options.id); $bar.append(this.options.template).find('.noty_text').html(this.options.text); this.$bar = (this.options.layout.parent.object !== null) ? $(this.options.layout.parent.object).css(this.options.layout.parent.css).append($bar) : $bar; // Set buttons if available if (this.options.buttons) { // If we have button disable closeWith & timeout options this.options.closeWith = [], this.options.timeout = false; var $buttons = $('<div/>').addClass('noty_buttons'); (this.options.layout.parent.object !== null) ? this.$bar.find('.noty_bar').append($buttons) : this.$bar.append($buttons); var self = this; $.each(this.options.buttons, function(i, button) { var $button = $('<button/>').addClass((button.addClass) ? button.addClass : 'gray').html(button.text) .appendTo(self.$bar.find('.noty_buttons')) .bind('click', function(e) { if ($.isFunction(button.onClick)) { button.onClick.call($button, self); } }); }); } // For easy access this.$message = this.$bar.find('.noty_message'); this.$closeButton = this.$bar.find('.noty_close'); this.$buttons = this.$bar.find('.noty_buttons'); $.noty.store[this.options.id] = this; // store noty for api }, // end _build show: function() { var self = this; $(self.options.layout.container.selector).append(self.$bar); self.options.theme.style.apply(self); ($.type(self.options.layout.css) === 'function') ? this.options.layout.css.apply(self.$bar) : self.$bar.css(this.options.layout.css || {}); self.$bar.addClass(self.options.layout.addClass); self.options.layout.container.style.apply($(self.options.layout.container.selector)); self.options.theme.callback.onShow.apply(this); if ($.inArray('click', self.options.closeWith) > -1) self.$bar.css('cursor', 'pointer').one('click', function() { self.close(); }); if ($.inArray('hover', self.options.closeWith) > -1) self.$bar.one('mouseenter', function() { self.close(); }); if ($.inArray('button', self.options.closeWith) > -1) self.$closeButton.one('click', function() { self.close(); }); if ($.inArray('button', self.options.closeWith) == -1) self.$closeButton.remove(); if (self.options.callback.onShow) self.options.callback.onShow.apply(self); self.$bar.animate( self.options.animation.open, self.options.animation.speed, self.options.animation.easing, function() { if (self.options.callback.afterShow) self.options.callback.afterShow.apply(self); self.shown = true; }); // If noty is have a timeout option if (self.options.timeout) self.$bar.delay(self.options.timeout).promise().done(function() { self.close(); }); return this; }, // end show close: function() { if (this.closed) return; var self = this; if (!this.shown) { // If we are still waiting in the queue just delete from queue $.each($.noty.queue, function(i, n) { if (n.options.id == self.options.id) { $.noty.queue.splice(i, 1); } }); return; } self.$bar.addClass('i-am-closing-now'); if (self.options.callback.onClose) { self.options.callback.onClose.apply(self); } self.$bar.clearQueue().stop().animate( self.options.animation.close, self.options.animation.speed, self.options.animation.easing, function() { if (self.options.callback.afterClose) self.options.callback.afterClose.apply(self); }) .promise().done(function() { // Modal Cleaning if (self.options.modal) { $.notyRenderer.setModalCount(-1); if ($.notyRenderer.getModalCount() == 0) $('.noty_modal').fadeOut('fast', function() { $(this).remove(); }); } // Layout Cleaning $.notyRenderer.setLayoutCountFor(self, -1); if ($.notyRenderer.getLayoutCountFor(self) == 0) $(self.options.layout.container.selector).remove(); self.$bar.remove(); self.$bar = null; self.closed = true; delete $.noty.store[self.options.id]; // deleting noty from store if (!self.options.dismissQueue) { // Queue render $.noty.ontap = true; $.notyRenderer.render(); } }); }, // end close setText: function(text) { if (!this.closed) { this.options.text = text; this.$bar.find('.noty_text').html(text); } return this; }, setType: function(type) { if (!this.closed) { this.options.type = type; this.options.theme.style.apply(this); this.options.theme.callback.onShow.apply(this); } return this; }, closed: false, shown: false }; // end NotyObject $.notyRenderer = {}; $.notyRenderer.init = function(options) { // Renderer creates a new noty var notification = Object.create(NotyObject).init(options); (notification.options.force) ? $.noty.queue.unshift(notification) : $.noty.queue.push(notification); $.notyRenderer.render(); return ($.noty.returns == 'object') ? notification : notification.options.id; }; $.notyRenderer.render = function() { var instance = $.noty.queue[0]; if ($.type(instance) === 'object') { if (instance.options.dismissQueue) { $.notyRenderer.show($.noty.queue.shift()); } else { if ($.noty.ontap) { $.notyRenderer.show($.noty.queue.shift()); $.noty.ontap = false; } } } else { $.noty.ontap = true; // Queue is over } }; $.notyRenderer.show = function(notification) { if (notification.options.modal) { $.notyRenderer.createModalFor(notification); $.notyRenderer.setModalCount(+1); } // Where is the container? if ($(notification.options.layout.container.selector).length == 0) { if (notification.options.custom) { notification.options.custom.append($(notification.options.layout.container.object).addClass('i-am-new')); } else { $('body').append($(notification.options.layout.container.object).addClass('i-am-new')); } } else { $(notification.options.layout.container.selector).removeClass('i-am-new'); } $.notyRenderer.setLayoutCountFor(notification, +1); notification.show(); }; $.notyRenderer.createModalFor = function(notification) { if ($('.noty_modal').length == 0) $('<div/>').addClass('noty_modal').data('noty_modal_count', 0).css(notification.options.theme.modal.css).prependTo($('body')).fadeIn('fast'); }; $.notyRenderer.getLayoutCountFor = function(notification) { return $(notification.options.layout.container.selector).data('noty_layout_count') || 0; }; $.notyRenderer.setLayoutCountFor = function(notification, arg) { return $(notification.options.layout.container.selector).data('noty_layout_count', $.notyRenderer.getLayoutCountFor(notification) + arg); }; $.notyRenderer.getModalCount = function() { return $('.noty_modal').data('noty_modal_count') || 0; }; $.notyRenderer.setModalCount = function(arg) { return $('.noty_modal').data('noty_modal_count', $.notyRenderer.getModalCount() + arg); }; // This is for custom container $.fn.noty = function(options) { options.custom = $(this); return $.notyRenderer.init(options); }; $.noty = {}; $.noty.queue = []; $.noty.ontap = true; $.noty.layouts = {}; $.noty.themes = {}; $.noty.returns = 'object'; $.noty.store = {}; $.noty.get = function(id) { return $.noty.store.hasOwnProperty(id) ? $.noty.store[id] : false; }; $.noty.close = function(id) { return $.noty.get(id) ? $.noty.get(id).close() : false; }; $.noty.setText = function(id, text) { return $.noty.get(id) ? $.noty.get(id).setText(text) : false; }; $.noty.setType = function(id, type) { return $.noty.get(id) ? $.noty.get(id).setType(type) : false; }; $.noty.clearQueue = function() { $.noty.queue = []; }; $.noty.closeAll = function() { $.noty.clearQueue(); $.each($.noty.store, function(id, noty) { noty.close(); }); }; var windowAlert = window.alert; $.noty.consumeAlert = function(options) { window.alert = function(text) { if (options) options.text = text; else options = {text:text}; $.notyRenderer.init(options); }; }; $.noty.stopConsumeAlert = function(){ window.alert = windowAlert; }; $.noty.defaults = { layout: 'top', theme: 'default', type: 'alert', text: '', dismissQueue: true, template: '<div class="noty_message" style="padding:0 !important"><span class="noty_text" style="background:#dedede !important"></span><div class="noty_close"></div></div>', animation: { open: {height: 'toggle'}, close: {height: 'toggle'}, easing: 'swing', speed: 500 }, timeout: 2200, force: false, modal: false, closeWith: ['click'], callback: { onShow: function() {}, afterShow: function() {}, onClose: function() {}, afterClose: function() {} }, buttons: false }; $(window).resize(function() { $.each($.noty.layouts, function(index, layout) { layout.container.style.apply($(layout.container.selector)); }); }); })(jQuery); // Helpers function noty(options) { // This is for BC - Will be deleted on v2.2.0 var using_old = 0 , old_to_new = { 'animateOpen': 'animation.open', 'animateClose': 'animation.close', 'easing': 'animation.easing', 'speed': 'animation.speed', 'onShow': 'callback.onShow', 'onShown': 'callback.afterShow', 'onClose': 'callback.onClose', 'onClosed': 'callback.afterClose' } jQuery.each(options, function(key, value) { if (old_to_new[key]) { using_old++; var _new = old_to_new[key].split('.'); if (!options[_new[0]]) options[_new[0]] = {}; options[_new[0]][_new[1]] = (value) ? value : function() {}; delete options[key]; } }); if (!options.closeWith) { options.closeWith = jQuery.noty.defaults.closeWith; } if (options.hasOwnProperty('closeButton')) { using_old++; if (options.closeButton) options.closeWith.push('button'); delete options.closeButton; } if (options.hasOwnProperty('closeOnSelfClick')) { using_old++; if (options.closeOnSelfClick) options.closeWith.push('click'); delete options.closeOnSelfClick; } if (options.hasOwnProperty('closeOnSelfOver')) { using_old++; if (options.closeOnSelfOver) options.closeWith.push('hover'); delete options.closeOnSelfOver; } if (options.hasOwnProperty('custom')) { using_old++; if (options.custom.container != 'null') options.custom = options.custom.container; } if (options.hasOwnProperty('cssPrefix')) { using_old++; delete options.cssPrefix; } if (options.theme == 'noty_theme_default') { using_old++; options.theme = 'default'; } if (!options.hasOwnProperty('dismissQueue')) { if (options.layout == 'topLeft' || options.layout == 'topRight' || options.layout == 'bottomLeft' || options.layout == 'bottomRight') { options.dismissQueue = true; } else { options.dismissQueue = false; } } if (options.buttons) { jQuery.each(options.buttons, function(i, button) { if (button.click) { using_old++; button.onClick = button.click; delete button.click; } if (button.type) { using_old++; button.addClass = button.type; delete button.type; } }); } if (using_old) console.warn('You are using noty v2 with v1.x.x options. @deprecated until v2.2.0 - Please update your options.'); // console.log(options); // End of the BC return jQuery.notyRenderer.init(options); } /** Jquery noty top */ ;(function($) { $.noty.layouts.top = { name: 'top', options: {}, container: { object: '<ul id="noty_top_layout_container" />', selector: 'ul#noty_top_layout_container', style: function() { $(this).css({ top: 0, left: '5%', position: 'fixed', width: '90%', height: 'auto', margin: 0, padding: 0, listStyleType: 'none', zIndex: 9999999 }); } }, parent: { object: '<li />', selector: 'li', css: {} }, css: { display: 'none' }, addClass: '' }; })(jQuery); /** Jquery noty default theme */ ;(function($) { $.noty.themes['default'] = { name: 'default', helpers: { borderFix: function() { if (this.options.dismissQueue) { var selector = this.options.layout.container.selector + ' ' + this.options.layout.parent.selector; switch (this.options.layout.name) { case 'top': $(selector).css({borderRadius: '0px 0px 0px 0px'}); $(selector).last().css({borderRadius: '0px 0px 5px 5px'}); break; case 'topCenter': case 'topLeft': case 'topRight': case 'bottomCenter': case 'bottomLeft': case 'bottomRight': case 'center': case 'centerLeft': case 'centerRight': case 'inline': $(selector).css({borderRadius: '0px 0px 0px 0px'}); $(selector).first().css({'border-top-left-radius': '5px', 'border-top-right-radius': '5px'}); $(selector).last().css({'border-bottom-left-radius': '5px', 'border-bottom-right-radius': '5px'}); break; case 'bottom': $(selector).css({borderRadius: '0px 0px 0px 0px'}); $(selector).first().css({borderRadius: '5px 5px 0px 0px'}); break; default: break; } } } }, modal: { css: { position: 'fixed', width: '100%', height: '100%', backgroundColor: '#000', zIndex: 10000, opacity: 0.6, display: 'none', left: 0, top: 0, } }, style: function() { this.$bar.css({ overflow: 'hidden', background: "#dedede" }); this.$message.css({ fontSize: '13px', lineHeight: '16px', textAlign: 'center', padding: '8px 10px 9px', width: 'auto', position: 'relative', opacity:'.8' }); this.$closeButton.css({ position: 'absolute', top: 4, right: 4, width: 10, height: 10, background: "#dedede", display: 'none', cursor: 'pointer', opacity:'.8' }); this.$buttons.css({ padding: 5, textAlign: 'right', borderTop: '1px solid #ccc', backgroundColor: '#fff', }); this.$buttons.find('button').css({ marginLeft: 5 }); this.$buttons.find('button:first').css({ marginLeft: 0 }); this.$bar.bind({ mouseenter: function() { $(this).find('.noty_close').fadeIn(); }, mouseleave: function() { $(this).find('.noty_close').fadeOut(); } }); switch (this.options.layout.name) { case 'top': this.$bar.css({ borderRadius: '0px 0px 5px 5px', borderBottom: '2px solid #eee', borderLeft: '2px solid #eee', borderRight: '2px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); break; case 'topCenter': case 'center': case 'bottomCenter': case 'inline': this.$bar.css({ borderRadius: '5px', border: '1px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); this.$message.css({fontSize: '13px', textAlign: 'center'}); break; case 'topLeft': case 'topRight': case 'bottomLeft': case 'bottomRight': case 'centerLeft': case 'centerRight': this.$bar.css({ borderRadius: '5px', border: '1px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); this.$message.css({fontSize: '13px', textAlign: 'left'}); break; case 'bottom': this.$bar.css({ borderRadius: '5px 5px 0px 0px', borderTop: '2px solid #eee', borderLeft: '2px solid #eee', borderRight: '2px solid #eee', boxShadow: "0 -2px 4px rgba(0, 0, 0, 0.1)" }); break; default: this.$bar.css({ border: '2px solid #eee', boxShadow: "0 2px 4px rgba(0, 0, 0, 0.1)" }); break; } switch (this.options.type) { case 'alert': case 'notification': this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break; case 'warning': this.$bar.css({backgroundColor: '#FFEAA8', borderColor: '#FFC237', color: '#826200'}); this.$buttons.css({borderTop: '1px solid #FFC237'}); break; case 'error': this.$bar.css({backgroundColor: 'red', borderColor: 'darkred', color: '#FFF'}); this.$message.css({fontWeight: 'bold'}); this.$buttons.css({borderTop: '1px solid darkred'}); break; case 'information': this.$bar.css({backgroundColor: '#57B7E2', borderColor: '#0B90C4', color: '#FFF'}); this.$buttons.css({borderTop: '1px solid #0B90C4'}); break; case 'success': this.$bar.css({backgroundColor: '#dedede', borderColor: '#dedede', color: 'darkgreen'}); this.$buttons.css({borderTop: '1px solid #50C24E'});break; default: this.$bar.css({backgroundColor: '#FFF', borderColor: '#CCC', color: '#444'}); break; } }, callback: { onShow: function() { $.noty.themes['default'].helpers.borderFix.apply(this); }, onClose: function() { $.noty.themes['default'].helpers.borderFix.apply(this); } } }; })(jQuery);
JavaScript
/* * FancyBox - jQuery Plugin * Simple and fancy lightbox alternative * * Examples and documentation at: http://fancybox.net * * Copyright (c) 2008 - 2010 Janis Skarnelis * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated. * * Version: 1.3.4 (11/11/2010) * Requires: jQuery v1.3+ * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { var tmp, loading, overlay, wrap, outer, content, close, title, nav_left, nav_right, selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [], ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i, loadingTimer, loadingFrame = 1, titleHeight = 0, titleStr = '', start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], { prop: 0 }), isIE6 = navigator.userAgent.match(/msie/i) && navigator.userAgent.match(/6/) && !window.XMLHttpRequest, /* * Private methods */ _abort = function() { loading.hide(); imgPreloader.onerror = imgPreloader.onload = null; if (ajaxLoader) { ajaxLoader.abort(); } tmp.empty(); }, _error = function() { if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) { loading.hide(); busy = false; return; } selectedOpts.titleShow = false; selectedOpts.width = 'auto'; selectedOpts.height = 'auto'; tmp.html( '<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' ); _process_inline(); }, _start = function() { var obj = selectedArray[ selectedIndex ], href, type, title, str, emb, ret; _abort(); selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox'))); ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts); if (ret === false) { busy = false; return; } else if (typeof ret == 'object') { selectedOpts = $.extend(selectedOpts, ret); } title = selectedOpts.title || (obj.nodeName ? $(obj).attr('title') : obj.title) || ''; if (obj.nodeName && !selectedOpts.orig) { selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj); } if (title === '' && selectedOpts.orig && selectedOpts.titleFromAlt) { title = selectedOpts.orig.attr('alt'); } href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null; if ((/^(?:javascript)/i).test(href) || href == '#') { href = null; } if (selectedOpts.type) { type = selectedOpts.type; if (!href) { href = selectedOpts.content; } } else if (selectedOpts.content) { type = 'html'; } else if (href) { if (href.match(imgRegExp)) { type = 'image'; } else if (href.match(swfRegExp)) { type = 'swf'; } else if ($(obj).hasClass("iframe")) { type = 'iframe'; } else if (href.indexOf("#") === 0) { type = 'inline'; } else { type = 'ajax'; } } if (!type) { _error(); return; } if (type == 'inline') { obj = href.substr(href.indexOf("#")); type = $(obj).length > 0 ? 'inline' : 'ajax'; } selectedOpts.type = type; selectedOpts.href = href; selectedOpts.title = title; if (selectedOpts.autoDimensions) { if (selectedOpts.type == 'html' || selectedOpts.type == 'inline' || selectedOpts.type == 'ajax') { selectedOpts.width = 'auto'; selectedOpts.height = 'auto'; } else { selectedOpts.autoDimensions = false; } } if (selectedOpts.modal) { selectedOpts.overlayShow = true; selectedOpts.hideOnOverlayClick = false; selectedOpts.hideOnContentClick = false; selectedOpts.enableEscapeButton = false; selectedOpts.showCloseButton = false; } selectedOpts.padding = parseInt(selectedOpts.padding, 10); selectedOpts.margin = parseInt(selectedOpts.margin, 10); tmp.css('padding', (selectedOpts.padding + selectedOpts.margin)); $('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() { $(this).replaceWith(content.children()); }); switch (type) { case 'html' : tmp.html( selectedOpts.content ); _process_inline(); break; case 'inline' : if ( $(obj).parent().is('#fancybox-content') === true) { busy = false; return; } $('<div class="fancybox-inline-tmp" />') .hide() .insertBefore( $(obj) ) .bind('fancybox-cleanup', function() { $(this).replaceWith(content.children()); }).bind('fancybox-cancel', function() { $(this).replaceWith(tmp.children()); }); $(obj).appendTo(tmp); _process_inline(); break; case 'image': busy = false; $.fancybox.showActivity(); imgPreloader = new Image(); imgPreloader.onerror = function() { _error(); }; imgPreloader.onload = function() { busy = true; imgPreloader.onerror = imgPreloader.onload = null; _process_image(); }; imgPreloader.src = href; break; case 'swf': selectedOpts.scrolling = 'no'; str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>'; emb = ''; $.each(selectedOpts.swf, function(name, val) { str += '<param name="' + name + '" value="' + val + '"></param>'; emb += ' ' + name + '="' + val + '"'; }); str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>'; tmp.html(str); _process_inline(); break; case 'ajax': busy = false; $.fancybox.showActivity(); selectedOpts.ajax.win = selectedOpts.ajax.success; ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, { url : href, data : selectedOpts.ajax.data || {}, error : function(XMLHttpRequest, textStatus, errorThrown) { if ( XMLHttpRequest.status > 0 ) { _error(); } }, success : function(data, textStatus, XMLHttpRequest) { var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader; if (o.status == 200) { if ( typeof selectedOpts.ajax.win == 'function' ) { ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest); if (ret === false) { loading.hide(); return; } else if (typeof ret == 'string' || typeof ret == 'object') { data = ret; } } tmp.html( data ); _process_inline(); } } })); break; case 'iframe': _show(); break; } }, _process_inline = function() { var w = selectedOpts.width, h = selectedOpts.height; if (w.toString().indexOf('%') > -1) { w = parseInt( ($(window).width() - (selectedOpts.margin * 2)) * parseFloat(w) / 100, 10) + 'px'; } else { w = w == 'auto' ? 'auto' : w + 'px'; } if (h.toString().indexOf('%') > -1) { h = parseInt( ($(window).height() - (selectedOpts.margin * 2)) * parseFloat(h) / 100, 10) + 'px'; } else { h = h == 'auto' ? 'auto' : h + 'px'; } tmp.wrapInner('<div style="width:' + w + ';height:' + h + ';overflow: ' + (selectedOpts.scrolling == 'auto' ? 'auto' : (selectedOpts.scrolling == 'yes' ? 'scroll' : 'hidden')) + ';position:relative;"></div>'); selectedOpts.width = tmp.width(); selectedOpts.height = tmp.height(); _show(); }, _process_image = function() { selectedOpts.width = imgPreloader.width; selectedOpts.height = imgPreloader.height; $("<img />").attr({ 'id' : 'fancybox-img', 'src' : imgPreloader.src, 'alt' : selectedOpts.title }).appendTo( tmp ); _show(); }, _show = function() { var pos, equal; loading.hide(); if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) { $.event.trigger('fancybox-cancel'); busy = false; return; } busy = true; $(content.add( overlay )).unbind(); $(window).unbind("resize.fb scroll.fb"); $(document).unbind('keydown.fb'); if (wrap.is(":visible") && currentOpts.titlePosition !== 'outside') { wrap.css('height', wrap.height()); } currentArray = selectedArray; currentIndex = selectedIndex; currentOpts = selectedOpts; if (currentOpts.overlayShow) { overlay.css({ 'background-color' : currentOpts.overlayColor, 'opacity' : currentOpts.overlayOpacity, 'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto', 'height' : $(document).height() }); if (!overlay.is(':visible')) { if (isIE6) { $('select:not(#fancybox-tmp select)').filter(function() { return this.style.visibility !== 'hidden'; }).css({'visibility' : 'hidden'}).one('fancybox-cleanup', function() { this.style.visibility = 'inherit'; }); } overlay.show(); } } else { overlay.hide(); } final_pos = _get_zoom_to(); _process_title(); if (wrap.is(":visible")) { $( close.add( nav_left ).add( nav_right ) ).hide(); pos = wrap.position(), start_pos = { top : pos.top, left : pos.left, width : wrap.width(), height : wrap.height() }; equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height); content.fadeTo(currentOpts.changeFade, 0.3, function() { var finish_resizing = function() { content.html( tmp.contents() ).fadeTo(currentOpts.changeFade, 1, _finish); }; $.event.trigger('fancybox-change'); content .empty() .removeAttr('filter') .css({ 'border-width' : currentOpts.padding, 'width' : final_pos.width - currentOpts.padding * 2, 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2 }); if (equal) { finish_resizing(); } else { fx.prop = 0; $(fx).animate({prop: 1}, { duration : currentOpts.changeSpeed, easing : currentOpts.easingChange, step : _draw, complete : finish_resizing }); } }); return; } wrap.removeAttr("style"); content.css('border-width', currentOpts.padding); if (currentOpts.transitionIn == 'elastic') { start_pos = _get_zoom_from(); content.html( tmp.contents() ); wrap.show(); if (currentOpts.opacity) { final_pos.opacity = 0; } fx.prop = 0; $(fx).animate({prop: 1}, { duration : currentOpts.speedIn, easing : currentOpts.easingIn, step : _draw, complete : _finish }); return; } if (currentOpts.titlePosition == 'inside' && titleHeight > 0) { title.show(); } content .css({ 'width' : final_pos.width - currentOpts.padding * 2, 'height' : selectedOpts.autoDimensions ? 'auto' : final_pos.height - titleHeight - currentOpts.padding * 2 }) .html( tmp.contents() ); wrap .css(final_pos) .fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish ); }, _format_title = function(title) { if (title && title.length) { if (currentOpts.titlePosition == 'float') { return '<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">' + title + '</td><td id="fancybox-title-float-right"></td></tr></table>'; } return '<div id="fancybox-title-' + currentOpts.titlePosition + '">' + title + '</div>'; } return false; }, _process_title = function() { titleStr = currentOpts.title || ''; titleHeight = 0; title .empty() .removeAttr('style') .removeClass(); if (currentOpts.titleShow === false) { title.hide(); return; } titleStr = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(titleStr, currentArray, currentIndex, currentOpts) : _format_title(titleStr); if (!titleStr || titleStr === '') { title.hide(); return; } title .addClass('fancybox-title-' + currentOpts.titlePosition) .html( titleStr ) .appendTo( 'body' ) .show(); switch (currentOpts.titlePosition) { case 'inside': title .css({ 'width' : final_pos.width - (currentOpts.padding * 2), 'marginLeft' : currentOpts.padding, 'marginRight' : currentOpts.padding }); titleHeight = title.outerHeight(true); title.appendTo( outer ); final_pos.height += titleHeight; break; case 'over': title .css({ 'marginLeft' : currentOpts.padding, 'width' : final_pos.width - (currentOpts.padding * 2), 'bottom' : currentOpts.padding }) .appendTo( outer ); break; case 'float': title .css('left', parseInt((title.width() - final_pos.width - 40)/ 2, 10) * -1) .appendTo( wrap ); break; default: title .css({ 'width' : final_pos.width - (currentOpts.padding * 2), 'paddingLeft' : currentOpts.padding, 'paddingRight' : currentOpts.padding }) .appendTo( wrap ); break; } title.hide(); }, _set_navigation = function() { if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) { $(document).bind('keydown.fb', function(e) { if (e.keyCode == 27 && currentOpts.enableEscapeButton) { e.preventDefault(); $.fancybox.close(); } else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') { e.preventDefault(); $.fancybox[ e.keyCode == 37 ? 'prev' : 'next'](); } }); } if (!currentOpts.showNavArrows) { nav_left.hide(); nav_right.hide(); return; } if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) { nav_left.show(); } if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) { nav_right.show(); } }, _finish = function () { if (!$.support.opacity) { content.get(0).style.removeAttribute('filter'); wrap.get(0).style.removeAttribute('filter'); } if (selectedOpts.autoDimensions) { content.css('height', 'auto'); } wrap.css('height', 'auto'); if (titleStr && titleStr.length) { title.show(); } if (currentOpts.showCloseButton) { close.show(); } _set_navigation(); if (currentOpts.hideOnContentClick) { content.bind('click', $.fancybox.close); } if (currentOpts.hideOnOverlayClick) { overlay.bind('click', $.fancybox.close); } $(window).bind("resize.fb", $.fancybox.resize); if (currentOpts.centerOnScroll) { $(window).bind("scroll.fb", $.fancybox.center); } if (currentOpts.type == 'iframe') { $('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" ' + ($.browser.msie ? 'allowtransparency="true""' : '') + ' scrolling="' + selectedOpts.scrolling + '" src="' + currentOpts.href + '"></iframe>').appendTo(content); } wrap.show(); busy = false; $.fancybox.center(); currentOpts.onComplete(currentArray, currentIndex, currentOpts); _preload_images(); }, _preload_images = function() { var href, objNext; if ((currentArray.length -1) > currentIndex) { href = currentArray[ currentIndex + 1 ].href; if (typeof href !== 'undefined' && href.match(imgRegExp)) { objNext = new Image(); objNext.src = href; } } if (currentIndex > 0) { href = currentArray[ currentIndex - 1 ].href; if (typeof href !== 'undefined' && href.match(imgRegExp)) { objNext = new Image(); objNext.src = href; } } }, _draw = function(pos) { var dim = { width : parseInt(start_pos.width + (final_pos.width - start_pos.width) * pos, 10), height : parseInt(start_pos.height + (final_pos.height - start_pos.height) * pos, 10), top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10), left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10) }; if (typeof final_pos.opacity !== 'undefined') { dim.opacity = pos < 0.5 ? 0.5 : pos; } wrap.css(dim); content.css({ 'width' : dim.width - currentOpts.padding * 2, 'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2 }); }, _get_viewport = function() { return [ $(window).width() - (currentOpts.margin * 2), $(window).height() - (currentOpts.margin * 2), $(document).scrollLeft() + currentOpts.margin, $(document).scrollTop() + currentOpts.margin ]; }, _get_zoom_to = function () { var view = _get_viewport(), to = {}, resize = currentOpts.autoScale, double_padding = currentOpts.padding * 2, ratio; if (currentOpts.width.toString().indexOf('%') > -1) { to.width = parseInt((view[0] * parseFloat(currentOpts.width)) / 100, 10); } else { to.width = currentOpts.width + double_padding; } if (currentOpts.height.toString().indexOf('%') > -1) { to.height = parseInt((view[1] * parseFloat(currentOpts.height)) / 100, 10); } else { to.height = currentOpts.height + double_padding; } if (resize && (to.width > view[0] || to.height > view[1])) { if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') { ratio = (currentOpts.width ) / (currentOpts.height ); if ((to.width ) > view[0]) { to.width = view[0]; to.height = parseInt(((to.width - double_padding) / ratio) + double_padding, 10); } if ((to.height) > view[1]) { to.height = view[1]; to.width = parseInt(((to.height - double_padding) * ratio) + double_padding, 10); } } else { to.width = Math.min(to.width, view[0]); to.height = Math.min(to.height, view[1]); } } to.top = parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - to.height - 40) * 0.5)), 10); to.left = parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - to.width - 40) * 0.5)), 10); return to; }, _get_obj_pos = function(obj) { var pos = obj.offset(); pos.top += parseInt( obj.css('paddingTop'), 10 ) || 0; pos.left += parseInt( obj.css('paddingLeft'), 10 ) || 0; pos.top += parseInt( obj.css('border-top-width'), 10 ) || 0; pos.left += parseInt( obj.css('border-left-width'), 10 ) || 0; pos.width = obj.width(); pos.height = obj.height(); return pos; }, _get_zoom_from = function() { var orig = selectedOpts.orig ? $(selectedOpts.orig) : false, from = {}, pos, view; if (orig && orig.length) { pos = _get_obj_pos(orig); from = { width : pos.width + (currentOpts.padding * 2), height : pos.height + (currentOpts.padding * 2), top : pos.top - currentOpts.padding - 20, left : pos.left - currentOpts.padding - 20 }; } else { view = _get_viewport(); from = { width : currentOpts.padding * 2, height : currentOpts.padding * 2, top : parseInt(view[3] + view[1] * 0.5, 10), left : parseInt(view[2] + view[0] * 0.5, 10) }; } return from; }, _animate_loading = function() { if (!loading.is(':visible')){ clearInterval(loadingTimer); return; } $('div', loading).css('top', (loadingFrame * -40) + 'px'); loadingFrame = (loadingFrame + 1) % 12; }; /* * Public methods */ $.fn.fancybox = function(options) { if (!$(this).length) { return this; } $(this) .data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {}))) .unbind('click.fb') .bind('click.fb', function(e) { e.preventDefault(); if (busy) { return; } busy = true; $(this).blur(); selectedArray = []; selectedIndex = 0; var rel = $(this).attr('rel') || ''; if (!rel || rel == '' || rel === 'nofollow') { selectedArray.push(this); } else { selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]"); selectedIndex = selectedArray.index( this ); } _start(); return; }); return this; }; $.fancybox = function(obj) { var opts; if (busy) { return; } busy = true; opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {}; selectedArray = []; selectedIndex = parseInt(opts.index, 10) || 0; if ($.isArray(obj)) { for (var i = 0, j = obj.length; i < j; i++) { if (typeof obj[i] == 'object') { $(obj[i]).data('fancybox', $.extend({}, opts, obj[i])); } else { obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts)); } } selectedArray = jQuery.merge(selectedArray, obj); } else { if (typeof obj == 'object') { $(obj).data('fancybox', $.extend({}, opts, obj)); } else { obj = $({}).data('fancybox', $.extend({content : obj}, opts)); } selectedArray.push(obj); } if (selectedIndex > selectedArray.length || selectedIndex < 0) { selectedIndex = 0; } _start(); }; $.fancybox.showActivity = function() { clearInterval(loadingTimer); loading.show(); loadingTimer = setInterval(_animate_loading, 66); }; $.fancybox.hideActivity = function() { loading.hide(); }; $.fancybox.next = function() { return $.fancybox.pos( currentIndex + 1); }; $.fancybox.prev = function() { return $.fancybox.pos( currentIndex - 1); }; $.fancybox.pos = function(pos) { if (busy) { return; } pos = parseInt(pos); selectedArray = currentArray; if (pos > -1 && pos < currentArray.length) { selectedIndex = pos; _start(); } else if (currentOpts.cyclic && currentArray.length > 1) { selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1; _start(); } return; }; $.fancybox.cancel = function() { if (busy) { return; } busy = true; $.event.trigger('fancybox-cancel'); _abort(); selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts); busy = false; }; // Note: within an iframe use - parent.$.fancybox.close(); $.fancybox.close = function() { if (busy || wrap.is(':hidden')) { return; } busy = true; if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) { busy = false; return; } _abort(); $(close.add( nav_left ).add( nav_right )).hide(); $(content.add( overlay )).unbind(); $(window).unbind("resize.fb scroll.fb"); $(document).unbind('keydown.fb'); content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank'); if (currentOpts.titlePosition !== 'inside') { title.empty(); } wrap.stop(); function _cleanup() { overlay.fadeOut('fast'); title.empty().hide(); wrap.hide(); $.event.trigger('fancybox-cleanup'); content.empty(); currentOpts.onClosed(currentArray, currentIndex, currentOpts); currentArray = selectedOpts = []; currentIndex = selectedIndex = 0; currentOpts = selectedOpts = {}; busy = false; } if (currentOpts.transitionOut == 'elastic') { start_pos = _get_zoom_from(); var pos = wrap.position(); final_pos = { top : pos.top , left : pos.left, width : wrap.width(), height : wrap.height() }; if (currentOpts.opacity) { final_pos.opacity = 1; } title.empty().hide(); fx.prop = 1; $(fx).animate({ prop: 0 }, { duration : currentOpts.speedOut, easing : currentOpts.easingOut, step : _draw, complete : _cleanup }); } else { wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup); } }; $.fancybox.resize = function() { if (overlay.is(':visible')) { overlay.css('height', $(document).height()); } $.fancybox.center(true); }; $.fancybox.center = function() { var view, align; if (busy) { return; } align = arguments[0] === true ? 1 : 0; view = _get_viewport(); if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) { return; } wrap .stop() .animate({ 'top' : parseInt(Math.max(view[3] - 20, view[3] + ((view[1] - content.height() - 40) * 0.5) - currentOpts.padding)), 'left' : parseInt(Math.max(view[2] - 20, view[2] + ((view[0] - content.width() - 40) * 0.5) - currentOpts.padding)) }, typeof arguments[0] == 'number' ? arguments[0] : 200); }; $.fancybox.init = function() { if ($("#fancybox-wrap").length) { return; } $('body').append( tmp = $('<div id="fancybox-tmp"></div>'), loading = $('<div id="fancybox-loading"><div></div></div>'), overlay = $('<div id="fancybox-overlay"></div>'), wrap = $('<div id="fancybox-wrap"></div>') ); outer = $('<div id="fancybox-outer"></div>') .append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>') .appendTo( wrap ); outer.append( content = $('<div id="fancybox-content"></div>'), close = $('<a id="fancybox-close"></a>'), title = $('<div id="fancybox-title"></div>'), nav_left = $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'), nav_right = $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>') ); close.click($.fancybox.close); loading.click($.fancybox.cancel); nav_left.click(function(e) { e.preventDefault(); $.fancybox.prev(); }); nav_right.click(function(e) { e.preventDefault(); $.fancybox.next(); }); if ($.fn.mousewheel) { wrap.bind('mousewheel.fb', function(e, delta) { if (busy) { e.preventDefault(); } else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) { e.preventDefault(); $.fancybox[ delta > 0 ? 'prev' : 'next'](); } }); } if (!$.support.opacity) { wrap.addClass('fancybox-ie'); } if (isIE6) { loading.addClass('fancybox-ie6'); wrap.addClass('fancybox-ie6'); $('<iframe id="fancybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer); } }; $.fn.fancybox.defaults = { padding : 10, margin : 40, opacity : false, modal : false, cyclic : false, scrolling : 'auto', // 'auto', 'yes' or 'no' width : 560, height : 340, autoScale : true, autoDimensions : true, centerOnScroll : false, ajax : {}, swf : { wmode: 'transparent' }, hideOnOverlayClick : true, hideOnContentClick : false, overlayShow : true, overlayOpacity : 0.7, overlayColor : '#777', titleShow : true, titlePosition : 'float', // 'float', 'outside', 'inside' or 'over' titleFormat : null, titleFromAlt : false, transitionIn : 'fade', // 'elastic', 'fade' or 'none' transitionOut : 'fade', // 'elastic', 'fade' or 'none' speedIn : 300, speedOut : 300, changeSpeed : 300, changeFade : 'fast', easingIn : 'swing', easingOut : 'swing', showCloseButton : true, showNavArrows : true, enableEscapeButton : true, enableKeyboardNav : true, onStart : function(){}, onCancel : function(){}, onComplete : function(){}, onCleanup : function(){}, onClosed : function(){}, onError : function(){} }; $(document).ready(function() { $.fancybox.init(); }); })(jQuery);
JavaScript
// Utility for creating objects in older browsers if ( typeof Object.create !== 'function' ) { Object.create = function( obj ) { function F() {} F.prototype = obj; return new F(); }; } /*! * jQuery panelSnap * Version 0.12.0 * * Requires: * - jQuery 1.7 or higher (no jQuery.migrate needed) * * https://github.com/guidobouman/jquery-panelsnap * * Copyright 2013, Guido Bouman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Date: Wed Feb 13 16:05:00 2013 +0100 */ (function($, window, document, undefined) { var pluginName = 'panelSnap'; var storageName = 'plugin_' + pluginName; var pluginObject = { isMouseDown: false, isSnapping: false, enabled: true, scrollInterval: 0, scrollOffset: 0, init: function(options, container) { var self = this; self.container = container; self.$container = $(container); self.$eventContainer = self.$container; self.$snapContainer = self.$container; if(self.$container.is('body')) { self.$eventContainer = $(document); self.$snapContainer = $(document.documentElement); var ua = navigator.userAgent; if(~ua.indexOf('WebKit')) { self.$snapContainer = $('body'); } } self.scrollInterval = self.$container.height(); self.options = $.extend(true, {}, $.fn.panelSnap.options, options); self.bind(); if(self.options.$menu !== false && $('.active', self.options.$menu).length > 0) { $('.active', self.options.$menu).click(); } else { var $target = self.getPanel(':first'); self.activatePanel($target); } return self; }, bind: function() { var self = this; self.bindProxied(self.$eventContainer, 'scrollstop', self.scrollStop); self.bindProxied(self.$eventContainer, 'mousewheel', self.mouseWheel); self.bindProxied(self.$eventContainer, 'mousedown', self.mouseDown); self.bindProxied(self.$eventContainer, 'mouseup', self.mouseUp); self.bindProxied($(window), 'resizestop', self.resize); if(self.options.keyboardNavigation.enabled) { self.bindProxied($(window), 'keydown', self.keyDown, self.$eventContainer); } if(self.options.$menu !== false) { self.bindProxied($(self.options.$menu), 'click', self.captureMenuClick, self.options.menuSelector); } }, bindProxied: function($element, event, method, selector) { var self = this; selector = typeof selector === 'string' ? selector : null; $element.on(event + self.options.namespace, selector, $.proxy(function(e) { return method.call(self, e); }, self)); }, destroy: function() { var self = this; // Gotta love namespaced events! self.$eventContainer.off(self.options.namespace); $(window).off(self.options.namespace); if(self.options.$menu !== false) { $(self.options.menuSelector, self.options.$menu).off(self.options.namespace); } self.$container.removeData(storageName); }, scrollStop: function(e) { var self = this; e.stopPropagation(); if(!self.enabled) { return; } if(self.isMouseDown) { self.$eventContainer.one('mouseup' + self.options.namespace, self.processScroll); return; } if(self.isSnapping) { return; } var offset = self.$snapContainer.scrollTop(); var scrollDifference = offset - self.scrollOffset; var maxOffset = self.$container[0].scrollHeight - self.scrollInterval; var panelCount = self.getPanel().length; var childNumber; if( scrollDifference < -self.options.directionThreshold && scrollDifference > -self.scrollInterval ) { childNumber = Math.floor(offset / self.scrollInterval); } else if( scrollDifference > self.options.directionThreshold && scrollDifference < self.scrollInterval ) { childNumber = Math.ceil(offset / self.scrollInterval); } else { childNumber = Math.round(offset / self.scrollInterval); } childNumber = Math.max(0, Math.min(childNumber, panelCount)); var $target = self.getPanel(':eq(' + childNumber + ')'); if(scrollDifference === 0) { // Do nothing } else if (offset <= 0 || offset >= maxOffset) { // Only activate, prevent stuttering self.activatePanel($target); // Set scrollOffset to a sane number for next scroll self.scrollOffset = offset < 0 ? 0 : maxOffset; } else { self.snapToPanel($target); } }, mouseWheel: function(e) { var self = this; // This event only fires when the user actually scrolls with their input device. // Be it a trackpad, legacy mouse or anything else. self.$container.stop(true); self.isSnapping = false; }, mouseDown: function(e) { var self = this; self.isMouseDown = true; }, mouseUp: function(e) { var self = this; self.isMouseDown = false; if(self.scrollOffset !== self.$snapContainer.scrollTop()) { self.scrollStop(e); } }, keyDown: function(e) { var self = this; var nav = self.options.keyboardNavigation; if (self.isSnapping) { if(e.which == nav.previousPanelKey || e.which == nav.nextPanelKey) { e.preventDefault(); return false; } return; } switch(e.which) { case nav.previousPanelKey: e.preventDefault(); self.snapTo('prev', nav.wrapAround); break; case nav.nextPanelKey: e.preventDefault(); self.snapTo('next', nav.wrapAround); break; } }, resize: function(e) { var self = this; self.scrollInterval = self.$container.height(); if(!self.enabled) { return; } var $target = self.getPanel('.active'); self.snapToPanel($target); }, captureMenuClick: function(e) { var self = this; var panel = $(e.currentTarget).data('panel'); var $target = self.getPanel('[data-panel="' + panel + '"]'); self.snapToPanel($target); return false; }, snapToPanel: function($target) { var self = this; if (!($target instanceof jQuery)) { return; } self.isSnapping = true; self.options.onSnapStart.call(self, $target); self.$container.trigger('panelsnap:start', [$target]); var scrollTarget = 0; if(self.$container.is('body')) { scrollTarget = $target.offset().top; } else { scrollTarget = self.$snapContainer.scrollTop() + $target.position().top; } self.$snapContainer.stop(true).animate({ scrollTop: scrollTarget }, self.options.slideSpeed, function() { self.scrollOffset = scrollTarget; self.isSnapping = false; // Call callback self.options.onSnapFinish.call(self, $target); self.$container.trigger('panelsnap:finish', [$target]); }); self.activatePanel($target); }, activatePanel: function($target) { var self = this; self.getPanel('.active').removeClass('active'); $target.addClass('active'); if(self.options.$menu !== false) { var activeItemSelector = '> ' + self.options.menuSelector + '.active'; $(activeItemSelector, self.options.$menu).removeClass('active'); var attribute = '[data-panel="' + $target.data('panel') + '"]'; var itemSelector = '> ' + self.options.menuSelector + attribute; var $itemToActivate = $(itemSelector, self.options.$menu); $itemToActivate.addClass('active'); } self.options.onActivate.call(self, $target); self.$container.trigger('panelsnap:activate', [$target]); }, getPanel: function(selector) { var self = this; if(typeof selector === 'undefined') { selector = ''; } var panelSelector = '> ' + self.options.panelSelector + selector; return $(panelSelector, self.$container); }, snapTo: function(target, wrap) { var self = this; if(typeof wrap !== 'boolean') { wrap = true; } var $target; switch(target) { case 'prev': $target = self.getPanel('.active').prev(self.options.panelSelector); if($target.length < 1 && wrap) { $target = self.getPanel(':last'); } break; case 'next': $target = self.getPanel('.active').next(self.options.panelSelector); if($target.length < 1 && wrap) { $target = self.getPanel(':first'); } break; case 'first': $target = self.getPanel(':first'); break; case 'last': $target = self.getPanel(':last'); break; } if($target.length > 0) { self.snapToPanel($target); } }, enable: function() { var self = this; // Gather scrollOffset for next scroll self.scrollOffset = self.$container[0].scrollHeight; self.enabled = true; }, disable: function() { var self = this; self.enabled = false; }, toggle: function() { var self = this; if(self.enabled) { self.disable(); } else { self.enable(); } } }; $.fn[pluginName] = function(options) { var args = Array.prototype.slice.call(arguments); return this.each(function() { var pluginInstance = $.data(this, storageName); if(typeof options === 'object' || options === 'init' || ! options) { if(!pluginInstance) { if(options === 'init') { options = args[1] || {}; } pluginInstance = Object.create(pluginObject).init(options, this); $.data(this, storageName, pluginInstance); } else { $.error('Plugin is already initialized for this object.'); return; } } else if(!pluginInstance) { $.error('Plugin is not initialized for this object yet.'); return; } else if(pluginInstance[options]) { var method = options; options = args.slice(1); pluginInstance[method].apply(pluginInstance, options); } else { $.error('Method ' + options + ' does not exist on jQuery.panelSnap.'); return; } }); }; $.fn[pluginName].options = { $menu: false, menuSelector: 'a', panelSelector: 'section', namespace: '.panelSnap', onSnapStart: function(){}, onSnapFinish: function(){}, onActivate: function(){}, directionThreshold: 50, slideSpeed: 200, keyboardNavigation: { enabled: false, nextPanelKey: 40, previousPanelKey: 38, wrapAround: true } }; })(jQuery, window, document); /*! * Special flavoured jQuery Mobile scrollstart & scrollstop events. * Version 0.1.3 * * Requires: * - jQuery 1.7.1 or higher (no jQuery.migrate needed) * * Copyright 2013, Guido Bouman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Date: Wed Feb 13 16:05:00 2013 +0100 */ (function($) { // Also handles the scrollstop event $.event.special.scrollstart = { enabled: true, setup: function() { var thisObject = this; var $this = $(thisObject); var scrolling; var timer; $this.data('scrollwatch', true); function trigger(event, scrolling) { event.type = scrolling ? "scrollstart" : "scrollstop"; $this.trigger(event); } $this.on("touchmove scroll", function(event) { if(!$.event.special.scrollstart.enabled) { return; } if(!$.event.special.scrollstart.scrolling) { $.event.special.scrollstart.scrolling = true; trigger(event, true); } clearTimeout(timer); timer = setTimeout(function() { $.event.special.scrollstart.scrolling = false; trigger(event, false); }, 50); }); } }; // Proxies scrollstart when needed $.event.special.scrollstop = { setup: function() { var thisObject = this; var $this = $(thisObject); if(!$this.data('scrollwatch')) { $(this).on('scrollstart', function(){}); } } }; })(jQuery); /*! * Resizestart and resizestop events. * Version 0.0.1 * * Requires: * - jQuery 1.7.1 or higher (no jQuery.migrate needed) * * Copyright 2013, Guido Bouman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Date: Fri Oct 25 15:05:00 2013 +0100 */ (function($) { // Also handles the resizestop event $.event.special.resizestart = { enabled: true, setup: function() { var thisObject = this; var $this = $(thisObject); var resizing; var timer; $this.data('resizewatch', true); function trigger(event, resizing) { event.type = resizing ? "resizestart" : "resizestop"; $this.trigger(event); } $this.on("resize", function(event) { if(!$.event.special.resizestart.enabled) { return; } if(!$.event.special.resizestart.resizing) { $.event.special.resizestart.resizing = true; trigger(event, true); } clearTimeout(timer); timer = setTimeout(function() { $.event.special.resizestart.resizing = false; trigger(event, false); }, 200); }); } }; // Proxies resizestart when needed $.event.special.resizestop = { setup: function() { var thisObject = this; var $this = $(thisObject); if(!$this.data('resizewatch')) { $(this).on('resizestart', function(){}); } } }; })(jQuery); /*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function($) { var types = ['DOMMouseScroll', 'mousewheel']; if ($.event.fixHooks) { for ( var i=types.length; i; ) { $.event.fixHooks[ types[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i=types.length; i; ) { this.addEventListener( types[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i=types.length; i; ) { this.removeEventListener( types[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; } if ( orgEvent.detail ) { delta = -orgEvent.detail/3; } // New school multidimensional scroll (touchpads) deltas deltaY = delta; // Gecko if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaY = 0; deltaX = -1*delta; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; } // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })(jQuery);
JavaScript
/* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright © 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{})) /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright © 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */
JavaScript
$(function(){ $(".radio-uniform").uniform(); });
JavaScript
$(function(){ $('.datepicker-input').datepicker({ dateFormat: js_date_format, showButtonPanel: true, changeMonth: true, changeYear: true, onSelect: function() { $(this).trigger('change'); } }); $('.datepicker-input-clear').button(); $('.datepicker-input-clear').click(function(){ $(this).parent().find('.datepicker-input').val(""); return false; }); });
JavaScript
function success_message(success_message) { noty({ text: success_message, type: 'success', dismissQueue: true, layout: 'top', callback: { afterShow: function() { setTimeout(function(){ $.noty.closeAll(); },7000); } } }); } function error_message(error_message) { noty({ text: error_message, type: 'error', layout: 'top', dismissQueue: true }); } function form_success_message(success_message) { $('#report-success').slideUp('fast'); $('#report-success').html(success_message); if ($('#report-success').closest('.ui-dialog').length !== 0) { $('.go-to-edit-form').click(function(){ fnOpenEditForm($(this)); return false; }); } $('#report-success').slideDown('normal'); $('#report-error').slideUp('fast').html(''); } function form_error_message(error_message) { $('#report-error').slideUp('fast'); $('#report-error').html(error_message); $('#report-error').slideDown('normal'); $('#report-success').slideUp('fast').html(''); }
JavaScript
// ---------------------------------------------------------------------------- // markItUp! // ---------------------------------------------------------------------------- // Copyright (C) 2011 Jay Salvat // http://markitup.jaysalvat.com/ // ---------------------------------------------------------------------------- // Html tags // http://en.wikipedia.org/wiki/html // ---------------------------------------------------------------------------- // Basic set. Feel free to add more tags // ---------------------------------------------------------------------------- var mySettings = { onShiftEnter: {keepDefault:false, replaceWith:'<br />\n'}, onCtrlEnter: {keepDefault:false, openWith:'\n<p>', closeWith:'</p>'}, onTab: {keepDefault:false, replaceWith:' '}, markupSet: [ {name:'Bold', key:'B', openWith:'(!(<strong>|!|<b>)!)', closeWith:'(!(</strong>|!|</b>)!)' }, {name:'Italic', key:'I', openWith:'(!(<em>|!|<i>)!)', closeWith:'(!(</em>|!|</i>)!)' }, {name:'Stroke through', key:'S', openWith:'<del>', closeWith:'</del>' }, {separator:'---------------' }, {name:'Bulleted List', openWith:' <li>', closeWith:'</li>', multiline:true, openBlockWith:'<ul>\n', closeBlockWith:'\n</ul>'}, {name:'Numeric List', openWith:' <li>', closeWith:'</li>', multiline:true, openBlockWith:'<ol>\n', closeBlockWith:'\n</ol>'}, {separator:'---------------' }, {name:'Picture', key:'P', replaceWith:'<img src="[![Source:!:http://]!]" alt="[![Alternative text]!]" />' }, {name:'Link', key:'L', openWith:'<a href="[![Link:!:http://]!]"(!( title="[![Title]!]")!)>', closeWith:'</a>', placeHolder:'Your text to link...' }, {separator:'---------------' }, {name:'Clean', className:'clean', replaceWith:function(markitup) { return markitup.selection.replace(/<(.*?)>/g, "") } }, {name:'Preview', className:'preview', call:'preview'} ] }; $(document).ready(function() { $('.texteditor').markItUp(mySettings); $( 'textarea.mini-texteditor' ).markItUp(mySettings); });
JavaScript
$(function(){ $( 'textarea.texteditor' ).ckeditor({toolbar:'Full'}); $( 'textarea.mini-texteditor' ).ckeditor({toolbar:'Basic',width:700}); });
JavaScript
$(function(){ $('.datetime-input').datetime({ userLang : 'en', americanMode: true, }); $('.datetime-input-clear').button(); $('.datetime-input-clear').click(function(){ $(this).parent().find('.datetime-input').val(""); return false; }); });
JavaScript
$(function(){ $('.numeric').numeric(); $('.numeric').keydown(function(e){ if(e.keyCode == 38) { if(IsNumeric($(this).val())) { var new_number = parseInt($(this).val()) + 1; $(this).val(new_number); }else if($(this).val().length == 0) { var new_number = 1; $(this).val(new_number); } } else if(e.keyCode == 40) { if(IsNumeric($(this).val())) { var new_number = parseInt($(this).val()) - 1; $(this).val(new_number); }else if($(this).val().length == 0) { var new_number = -1; $(this).val(new_number); } } }); }); function IsNumeric(input) { return (input - 0) == input && input.length > 0; }
JavaScript
function show_upload_button(unique_id, uploader_element) { $('#upload-state-message-'+unique_id).html(''); $("#loading-"+unique_id).hide(); $('#upload-button-'+unique_id).slideDown('fast'); $("input[rel="+uploader_element.attr('name')+"]").val(''); $('#success_'+unique_id).slideUp('fast'); } function load_fancybox(elem) { elem.fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, 'speedOut' : 200, 'overlayShow' : false }); } $(function(){ /////////////// $('.gc-file-upload').each(function(){ var unique_id = $(this).attr('id'); var uploader_url = $(this).attr('rel'); var uploader_element = $(this); var delete_url = $('#delete_url_'+unique_id).attr('href'); eval("var file_upload_info = upload_info_"+unique_id+""); $(this).fileupload({ dataType: 'json', url: uploader_url, cache: false, acceptFileTypes: file_upload_info.accepted_file_types, beforeSend: function(){ $('#upload-state-message-'+unique_id).html(string_upload_file); $("#loading-"+unique_id).show(); $("#upload-button-"+unique_id).slideUp("fast"); }, limitMultiFileUploads: 1, maxFileSize: file_upload_info.max_file_size, send: function (e, data) { var errors = ''; if (data.files.length > 1) { errors += error_max_number_of_files + "\n" ; } $.each(data.files,function(index, file){ if (!(data.acceptFileTypes.test(file.type) || data.acceptFileTypes.test(file.name))) { errors += error_accept_file_types + "\n"; } if (data.maxFileSize && file.size > data.maxFileSize) { errors += error_max_file_size + "\n"; } if (typeof file.size === 'number' && file.size < data.minFileSize) { errors += error_min_file_size + "\n"; } }); if(errors != '') { error_alert('Error',errors); return false; } return true; }, done: function (e, data) { if(typeof data.result.success != 'undefined' && data.result.success) { $("#loading-"+unique_id).hide(); $("#progress-"+unique_id).html(''); $.each(data.result.files, function (index, file) { $('#upload-state-message-'+unique_id).html(''); $("input[rel="+uploader_element.attr('name')+"]").val(file.name); var file_name = file.name; file_name = file_name.split('-'); file_name.splice(0,1); file_name = file_name.join(''); var file_name_base64 = file.base64; var is_image = (file_name.substr(-4) == '.jpg' || file_name.substr(-4) == '.png' || file_name.substr(-5) == '.jpeg' || file_name.substr(-4) == '.gif' || file_name.substr(-5) == '.tiff') && !gcConf.unset_image_preview ? true : false; if(is_image) { $('#file_'+unique_id).addClass('image-thumbnail'); load_fancybox($('#file_'+unique_id)); $('#file_'+unique_id).html('<img src="'+file.url+'" height="50" />'); } else { //$('#file_'+unique_id).removeClass('image-thumbnail'); $('#file_'+unique_id).addClass('image-thumbnail'); load_fancybox($('#file_'+unique_id)); //$('#file_'+unique_id).unbind("click"); $('#file_'+unique_id).html(file_name); } $('#file_'+unique_id).attr('href',file.url); $('#hidden_'+unique_id).val(file_name); $('#success_'+unique_id).fadeIn('slow'); $('#delete_url_'+unique_id).attr('rel',file_name_base64); $('#upload-button-'+unique_id).slideUp('fast'); }); } else if(typeof data.result.message != 'undefined') { error_alert('Error',data.result.message); show_upload_button(unique_id, uploader_element); } else { error_alert('Error',error_on_uploading); show_upload_button(unique_id, uploader_element); } }, autoUpload: true, error: function() { error_alert('Error',error_on_uploading); show_upload_button(unique_id, uploader_element); }, fail: function(e, data) { // data.errorThrown // data.textStatus; // data.jqXHR; error_alert('Error',error_on_uploading); show_upload_button(unique_id, uploader_element); }, progress: function (e, data) { $("#progress-"+unique_id).html(string_progress + parseInt(data.loaded / data.total * 100, 10) + '%'); } }); $('#delete_'+unique_id).click(function(){ confirm_alert('Confirmation',message_prompt_delete_file,function(){ var file_name = $('#delete_url_'+unique_id).attr('rel'); $.ajax({ url: delete_url+"/"+file_name, cache: false, success:function(){ show_upload_button(unique_id, uploader_element); }, beforeSend: function(){ $('#upload-state-message-'+unique_id).html(string_delete_file); $('#success_'+unique_id).hide(); $("#loading-"+unique_id).show(); $("#upload-button-"+unique_id).slideUp("fast"); } }); },function(){ }); return false; }); }); });
JavaScript
$(function(){ // $(".chosen-select,.chosen-multiple-select").chosen({width:120,allow_single_deselect:true}); });
JavaScript
// $(function(){ // $('.datetime-input').datetimepicker({ // timeFormat: 'hh:mm:ss', // dateFormat: js_date_format, // showButtonPanel: true, // changeMonth: true, // changeYear: true // }); // $('.datetime-input-clear').button(); // $('.datetime-input-clear').click(function(){ // $(this).parent().find('.datetime-input').val(""); // return false; // }); // }); $(function(){ $('.datetime-input').datetimepicker({ timeFormat: 'hh:mm:ss', dateFormat: js_date_format, showButtonPanel: true, changeMonth: true, changeYear: true, onSelect: function() { $(this).trigger('change'); } }); $('.datetime-input-clear').button(); $('.datetime-input-clear').click(function(){ $(this).parent().find('.datetime-input').val(""); return false; }); $('.time-input').timepicker({ stepMinute: 5, timeFormat: 'HH:mm', hourMin: 0, hourMax: 23, addSliderAccess: true, sliderAccessArgs: { touchonly: false } }); $('.time-input-clear').button(); $('.time-input-clear').click(function(){ $(this).parent().find('.time-input').val(""); return false; }); });
JavaScript