diff --git a/admin/controller/module/d_quickcheckout.php b/admin/controller/module/d_quickcheckout.php new file mode 100755 index 0000000..85362d0 --- /dev/null +++ b/admin/controller/module/d_quickcheckout.php @@ -0,0 +1,747 @@ +load->language($this->route); + $this->load->model('setting/setting'); + + //stores + if (isset($this->request->get['store_id'])) { + $store_id = $this->request->get['store_id']; + }else{ + $store_id = 0; + } + + //save settings + if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { + + $this->session->data['success'] = $this->language->get('text_success'); + unset($this->session->data['aqc_settings']); + + if(isset($this->request->post[$store_id]['general']['settings']['value'])) + { + $settings = str_replace("amp;", "", urldecode($this->request->post[$store_id]['general']['settings']['bulk'])); + parse_str($settings, $this->request->post ); + } + + $this->model_setting_setting->editSetting($this->id, $this->request->post, $store_id); + + if(!isset($this->request->post['save'])){ + $this->response->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL')); + } + } + + //scripts + $this->document->addLink('//fonts.googleapis.com/css?family=PT+Sans:400,700,700italic,400italic&subset=latin,cyrillic-ext,latin-ext,cyrillic', "stylesheet"); + $this->document->addStyle('view/stylesheet/shopunity/bootstrap.css'); + + $this->document->addScript('view/javascript/shopunity/tinysort/jquery.tinysort.min.js'); + $this->document->addScript('view/javascript/shopunity/bootstrap-sortable.js'); + $this->document->addScript('view/javascript/shopunity/bootstrap-slider/js/bootstrap-slider.js'); + $this->document->addStyle('view/javascript/shopunity/bootstrap-slider/css/slider.css'); + + + + + + // $this->document->addStyle('view/stylesheet/shopunity/normalize.css'); + + // if(!defined('_JEXEC')){ + // $this->document->addStyle('view/stylesheet/shopunity/icons.css'); + // $this->document->addStyle('view/stylesheet/shopunity/shopunity.css'); + // $this->document->addScript('view/javascript/shopunity/shopunity.js'); + // }else{ + // $this->document->addStyle('view/stylesheet/shopunity/joomla.css'); + // $this->document->addScript('view/javascript/shopunity/joomla.js'); + // } + + + // $this->document->addScript('view/javascript/shopunity/jquery.nicescroll.min.js'); + // $this->document->addScript('view/javascript/shopunity/jquery.tinysort.min.js'); + // $this->document->addScript('view/javascript/shopunity/jquery.autosize.min.js'); + // $this->document->addScript('view/javascript/shopunity/tooltip/tooltip.js'); + // $this->document->addStyle('view/javascript/shopunity/codemirror/codemirror.css'); + // $this->document->addScript('view/javascript/shopunity/codemirror/codemirror.js'); + // $this->document->addScript('view/javascript/shopunity/codemirror/css.js'); + // $this->document->addStyle('view/javascript/shopunity/uniform/css/uniform.default.css'); + // $this->document->addScript('view/javascript/shopunity/uniform/jquery.uniform.min.js'); + + $this->document->addStyle('view/stylesheet/d_quickcheckout.css'); + + //languages + $this->document->setTitle($this->language->get('heading_title_main')); + $this->data['heading_title'] = $this->language->get('heading_title_main'); + $this->data['text_edit'] = $this->language->get('text_edit'); + $this->data['id'] = $this->id; + $this->data['version'] = $this->get_version(); + $this->data['token'] = $this->session->data['token']; + $this->data['route'] = $this->route; + $this->data['store_id'] = $store_id; + $this->data['shopunity'] = $this->check_shopunity(); + $this->data['module_link'] = $this->url->link($this->route, 'token=' . $this->session->data['token'], 'SSL'); + $this->data['button_save'] = $this->language->get('button_save'); + $this->data['button_save_and_stay'] = $this->language->get('button_save_and_stay'); + $this->data['button_cancel'] = $this->language->get('button_cancel'); + $this->data['button_add_module'] = $this->language->get('button_add_module'); + $this->data['button_remove'] = $this->language->get('button_remove'); + $this->data['text_yes'] = $this->language->get('text_yes'); + $this->data['text_no'] = $this->language->get('text_no'); + $this->data['text_display'] = $this->language->get('text_display'); + $this->data['text_require'] = $this->language->get('text_require'); + $this->data['text_always_show'] = $this->language->get('text_always_show'); + $this->data['text_enable'] = $this->language->get('text_enable'); + $this->data['text_enabled'] = $this->language->get('text_enabled'); + $this->data['text_disabled'] = $this->language->get('text_disabled'); + $this->data['text_register'] = $this->language->get('text_register'); + $this->data['text_guest'] = $this->language->get('text_guest'); + $this->data['text_logged_in'] = $this->language->get('text_logged_in'); + $this->data['text_guest_customer'] = $this->language->get('text_guest_customer'); + $this->data['text_registrating_customer'] = $this->language->get('text_registrating_customer'); + $this->data['text_logged_in_customer'] = $this->language->get('text_logged_in_customer'); + $this->data['text_content_top'] = $this->language->get('text_content_top'); + $this->data['text_content_bottom'] = $this->language->get('text_content_bottom'); + $this->data['text_column_left'] = $this->language->get('text_column_left'); + $this->data['text_column_right'] = $this->language->get('text_column_right'); + $this->data['text_input_radio'] = $this->language->get('text_input_radio'); + $this->data['text_input_select'] = $this->language->get('text_input_select'); + $this->data['text_row'] = $this->language->get('text_row'); + $this->data['text_block'] = $this->language->get('text_block'); + $this->data['text_popup'] = $this->language->get('text_popup'); + $this->data['text_width'] = $this->language->get('text_width'); + $this->data['text_height'] = $this->language->get('text_height'); + + $this->data['entry_product'] = $this->language->get('entry_product'); + $this->data['entry_limit'] = $this->language->get('entry_limit'); + $this->data['entry_image'] = $this->language->get('entry_image'); + $this->data['entry_layout'] = $this->language->get('entry_layout'); + $this->data['entry_position'] = $this->language->get('entry_position'); + $this->data['entry_status'] = $this->language->get('entry_status'); + $this->data['entry_sort_order'] = $this->language->get('entry_sort_order'); + + // Tabs + $this->data['text_home'] = $this->language->get('text_home'); + $this->data['text_general'] = $this->language->get('text_general'); + $this->data['text_login'] = $this->language->get('text_login'); + $this->data['text_payment_address'] = $this->language->get('text_payment_address'); + $this->data['text_shipping_address'] = $this->language->get('text_shipping_address'); + $this->data['text_shipping_method'] = $this->language->get('text_shipping_method'); + $this->data['text_payment_method'] = $this->language->get('text_payment_method'); + $this->data['text_cart'] = $this->language->get('text_cart'); + $this->data['text_confirm'] = $this->language->get('text_confirm'); + $this->data['text_payment'] = $this->language->get('text_payment'); + $this->data['text_design'] = $this->language->get('text_design'); + $this->data['text_analytics'] = $this->language->get('text_analytics'); + + // Home + $this->data['text_intro_home'] = $this->language->get('text_intro_home'); + $this->data['text_intro_general'] = $this->language->get('text_intro_general'); + $this->data['text_intro_login'] = $this->language->get('text_intro_login'); + $this->data['text_intro_payment_address'] = $this->language->get('text_intro_payment_address'); + $this->data['text_intro_shipping_address'] = $this->language->get('text_intro_shipping_address'); + $this->data['text_intro_shipping_method'] = $this->language->get('text_intro_shipping_method'); + $this->data['text_intro_payment_method'] = $this->language->get('text_intro_payment_method'); + $this->data['text_intro_confirm'] = $this->language->get('text_intro_confirm'); + $this->data['text_intro_design'] = $this->language->get('text_intro_design'); + $this->data['text_intro_plugins'] = $this->language->get('text_intro_plugins'); + $this->data['text_intro_analytics'] = $this->language->get('text_intro_analytics'); + + // General + $this->data['entry_general_enable'] = $this->language->get('entry_general_enable'); + $this->data['help_general_enable'] = $this->language->get('help_general_enable'); + $this->data['entry_general_default_option'] = $this->language->get('entry_general_default_option'); + $this->data['help_general_default_option'] = $this->language->get('help_general_default_option'); + $this->data['entry_general_main_checkout'] = $this->language->get('entry_general_main_checkout'); + $this->data['help_general_main_checkout'] = $this->language->get('help_general_main_checkout'); + $this->data['entry_general_clear_session'] = $this->language->get('entry_general_clear_session'); + $this->data['help_general_clear_session'] = $this->language->get('help_general_clear_session'); + $this->data['entry_general_login_refresh'] = $this->language->get('entry_general_login_refresh'); + $this->data['help_general_login_refresh'] = $this->language->get('help_general_login_refresh'); + $this->data['entry_general_default_email'] = $this->language->get('entry_general_default_email'); + $this->data['help_general_default_email'] = $this->language->get('help_general_default_email'); + $this->data['entry_general_version'] = $this->language->get('entry_general_version'); + $this->data['help_general_version'] = $this->language->get('help_general_version'); + $this->data['button_version_check'] = $this->language->get('button_version_check'); + $this->data['entry_general_debug'] = $this->language->get('entry_general_debug'); + $this->data['help_general_debug'] = $this->language->get('help_general_debug'); + $this->data['entry_general_min_order'] = $this->language->get('entry_general_min_order'); + $this->data['help_general_min_order'] = $this->language->get('help_general_min_order'); + $this->data['text_value_min_order'] = $this->language->get('text_value_min_order'); + $this->data['entry_general_min_quantity'] = $this->language->get('entry_general_min_quantity'); + $this->data['help_general_min_quantity'] = $this->language->get('help_general_min_quantity'); + $this->data['text_value_min_quantity'] = $this->language->get('text_value_min_quantity'); + $this->data['entry_general_trigger'] = $this->language->get('entry_general_trigger'); + $this->data['help_general_trigger'] = $this->language->get('help_general_trigger'); + $this->data['text_position_module'] = $this->language->get('text_position_module'); + $this->data['help_position_module'] = $this->language->get('help_position_module'); + $this->data['button_add_module'] = $this->language->get('button_add_module'); + $this->data['entry_general_settings'] = $this->language->get('entry_general_settings'); + $this->data['text_general_settings_value'] = $this->language->get('text_general_settings_value'); + $this->data['help_general_settings'] = $this->language->get('help_general_settings'); + + //social login + $this->data['text_social_login_required'] = $this->language->get('text_social_login_required'); + $this->data['entry_socila_login_style'] = $this->language->get('entry_socila_login_style'); + $this->data['help_socila_login_style'] = $this->language->get('help_socila_login_style'); + $this->data['text_icons'] = $this->language->get('text_icons'); + $this->data['text_small'] = $this->language->get('text_small'); + $this->data['text_medium'] = $this->language->get('text_medium'); + $this->data['text_large'] = $this->language->get('text_large'); + $this->data['text_huge'] = $this->language->get('text_huge'); + $this->data['button_social_login_edit'] = $this->language->get('button_social_login_edit'); + $this->data['link_social_login_edit'] = $this->url->link('module/d_social_login', 'token=' . $this->session->data['token'] . '&store_id='.$store_id, 'SSL'); + + //Payment address + $this->data['entry_payment_address_display'] = $this->language->get('entry_payment_address_display'); + $this->data['help_payment_address_display'] = $this->language->get('help_payment_address_display'); + + //Shipping address + $this->data['entry_shipping_address_display'] = $this->language->get('entry_shipping_address_display'); + $this->data['help_shipping_address_display'] = $this->language->get('help_shipping_address_display'); + + //Shipping method + $this->data['entry_shipping_method_display'] = $this->language->get('entry_shipping_method_display'); + $this->data['help_shipping_method_display'] = $this->language->get('help_shipping_method_display'); + $this->data['entry_shipping_method_display_options'] = $this->language->get('entry_shipping_method_display_options'); + $this->data['help_shipping_method_display_options'] = $this->language->get('help_shipping_method_display_options'); + $this->data['entry_shipping_method_display_title'] = $this->language->get('entry_shipping_method_display_title'); + $this->data['help_shipping_method_display_title'] = $this->language->get('help_shipping_method_display_title'); + $this->data['entry_shipping_method_input_style'] = $this->language->get('entry_shipping_method_input_style'); + $this->data['help_shipping_method_input_style'] = $this->language->get('help_shipping_method_input_style'); + $this->data['entry_shipping_method_default_option'] = $this->language->get('entry_shipping_method_default_option'); + $this->data['help_shipping_method_default_option'] = $this->language->get('help_shipping_method_default_option'); + + //Payment method + $this->data['entry_payment_method_display'] = $this->language->get('entry_payment_method_display'); + $this->data['help_payment_method_display'] = $this->language->get('help_payment_method_display'); + $this->data['entry_payment_method_display_options'] = $this->language->get('entry_payment_method_display_options'); + $this->data['help_payment_method_display_options'] = $this->language->get('help_payment_method_display_options'); + $this->data['entry_payment_method_display_images'] = $this->language->get('entry_payment_method_display_images'); + $this->data['help_payment_method_display_images'] = $this->language->get('help_payment_method_display_images'); + $this->data['entry_payment_method_display_title'] = $this->language->get('entry_payment_method_display_title'); + $this->data['help_payment_method_display_title'] = $this->language->get('help_payment_method_display_title'); + $this->data['entry_payment_method_input_style'] = $this->language->get('entry_payment_method_input_style'); + $this->data['help_payment_method_input_style'] = $this->language->get('help_payment_method_input_style'); + $this->data['entry_payment_method_default_option'] = $this->language->get('entry_payment_method_default_option'); + $this->data['help_payment_method_default_option'] = $this->language->get('help_payment_method_default_option'); + + //Cart + $this->data['entry_cart_display'] = $this->language->get('entry_cart_display'); + $this->data['help_cart_display'] = $this->language->get('help_cart_display'); + $this->data['entry_cart_columns_image'] = $this->language->get('entry_cart_columns_image'); + $this->data['entry_cart_columns_name'] = $this->language->get('entry_cart_columns_name'); + $this->data['entry_cart_columns_model'] = $this->language->get('entry_cart_columns_model'); + $this->data['entry_cart_columns_quantity'] = $this->language->get('entry_cart_columns_quantity'); + $this->data['entry_cart_columns_price'] = $this->language->get('entry_cart_columns_price'); + $this->data['entry_cart_columns_total'] = $this->language->get('entry_cart_columns_total'); + $this->data['entry_cart_option_coupon'] = $this->language->get('entry_cart_option_coupon'); + $this->data['help_cart_option_coupon'] = $this->language->get('help_cart_option_coupon'); + $this->data['entry_cart_option_voucher'] = $this->language->get('entry_cart_option_voucher'); + $this->data['help_cart_option_voucher'] = $this->language->get('help_cart_option_voucher'); + $this->data['entry_cart_option_reward'] = $this->language->get('entry_cart_option_reward'); + $this->data['help_cart_option_reward'] = $this->language->get('help_cart_option_reward'); + + //Design + $this->data['entry_design_theme'] = $this->language->get('entry_design_theme'); + $this->data['help_design_theme'] = $this->language->get('help_design_theme'); + $this->data['entry_design_field'] = $this->language->get('entry_design_field'); + $this->data['help_design_field'] = $this->language->get('help_design_field'); + $this->data['entry_design_login_option'] = $this->language->get('entry_design_login_option'); + $this->data['help_design_login_option'] = $this->language->get('help_design_login_option'); + $this->data['entry_design_login'] = $this->language->get('entry_design_login'); + $this->data['help_design_login'] = $this->language->get('help_design_login'); + $this->data['entry_design_address'] = $this->language->get('entry_design_address'); + $this->data['help_design_address'] = $this->language->get('help_design_address'); + $this->data['entry_design_cart_image_size'] = $this->language->get('entry_design_cart_image_size'); + $this->data['help_design_cart_image_size'] = $this->language->get('help_design_cart_image_size'); + $this->data['entry_design_max_width'] = $this->language->get('entry_design_max_width'); + $this->data['help_design_max_width'] = $this->language->get('help_design_max_width'); + $this->data['entry_design_uniform'] = $this->language->get('entry_design_uniform'); + $this->data['help_design_uniform'] = $this->language->get('help_design_uniform'); + $this->data['entry_design_only_quickcheckout'] = $this->language->get('entry_design_only_quickcheckout'); + $this->data['help_design_only_quickcheckout'] = $this->language->get('help_design_only_quickcheckout'); + $this->data['entry_design_column'] = $this->language->get('entry_design_column'); + $this->data['help_design_column'] = $this->language->get('help_design_column'); + $this->data['help_payment_address'] = $this->language->get('help_payment_address'); + $this->data['help_shipping_address'] = $this->language->get('help_shipping_address'); + $this->data['help_shipping_method'] = $this->language->get('help_shipping_method'); + $this->data['help_payment_method'] = $this->language->get('help_payment_method'); + $this->data['help_cart'] = $this->language->get('help_cart'); + $this->data['help_payment'] = $this->language->get('help_payment'); + $this->data['help_confirm'] = $this->language->get('help_confirm'); + $this->data['entry_design_custom_style'] = $this->language->get('entry_design_custom_style'); + $this->data['help_design_custom_style'] = $this->language->get('help_design_custom_style'); + + $this->data['text_need_full_version'] = $this->language->get('text_need_full_version'); + + //Plugins + $this->data['text_plugins'] = $this->language->get('text_plugins'); + + $this->data['action'] = $this->url->link($this->route, 'token=' . $this->session->data['token'] . '&store_id='.$store_id, 'SSL'); + $this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'); + + // breadcrumbs + $this->data['breadcrumbs'] = array(); + $this->data['breadcrumbs'][] = array( + 'text' => $this->language->get('text_home'), + 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), + 'separator' => false + ); + + $this->data['breadcrumbs'][] = array( + 'text' => $this->language->get('text_module'), + 'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'), + 'separator' => ' :: ' + ); + + $this->data['breadcrumbs'][] = array( + 'text' => $this->language->get('heading_title_main'), + 'href' => $this->url->link($this->route, 'token=' . $this->session->data['token'], 'SSL'), + 'separator' => ' :: ' + ); + + if (isset($this->error['warning'])) { + $this->data['error_warning'] = $this->error['warning']; + } else { + $this->data['error_warning'] = ''; + } + + //shopunity + // if(!$this->check_shopunity()){ + // $this->data['error_warning'] = $this->language->get('error_shopunity_required'); + // } + //extra positions + if (!file_exists(DIR_CATALOG.'../vqmod/xml/vqmod_extra_positions.xml')) { + $this->data['positions_needed'] = $this->language->get('positions_needed'); + } + + //settings + $settings = array(); + if ($this->model_setting_setting->getSetting($this->id, $store_id)) + { + $settings = $this->model_setting_setting->getSetting($this->id, $store_id); + } + + $this->config->load($this->id); + $config[$this->id] = $this->config->get($this->id.'_settings'); + $config[$this->id]['general']['default_email'] = $this->config->get('config_email'); + $config[$this->id]['step']['payment_address']['fields']['agree']['information_id'] = $this->config->get('config_account_id'); + $config[$this->id]['step']['payment_address']['fields']['agree']['error'][0]['information_id'] = $this->config->get('config_account_id'); + $config[$this->id]['step']['confirm']['fields']['agree']['information_id'] = $this->config->get('config_checkout_id'); + $config[$this->id]['step']['confirm']['fields']['agree']['error'][0]['information_id'] = $this->config->get('config_checkout_id'); + + $settings = $this->array_merge_recursive_distinct($config, $settings); + + $this->data[$this->id] = array(); + if (isset($this->request->post[$this->id])) + { + $this->data[$this->id] = $this->request->post[$this->id]; + + } elseif(isset($settings[$this->id])) + { + $this->data[$this->id] = $settings[$this->id]; + } + + //modules + $this->data[$this->id.'_modules'] = array(); + if (isset($this->request->post[$this->id.'_module'])) + { + $this->data[$this->id.'_modules'] = $this->request->post[$this->id.'_module']; + + } elseif(isset($settings[$this->id.'_module'])) + { + $this->data[$this->id.'_modules'] = $settings[$this->id.'_module']; + } + + //These are default settings (located in system/config/d_quickcheckout.php) + // $settings = $this->config->get('quickcheckout_settings'); + // if(empty($settings)){ + // $this->config->load('quickcheckout_settings'); + // $settings = $this->config->get('quickcheckout_settings'); + // } + + //System settings + + // if(!empty($this->data[$this->id])){ + // $this->data[$this->id] = $this->array_merge_recursive_distinct($settings, $this->data['quickcheckout']); + // }else{ + // $this->data[$this->id] = $settings[$this->id]; + // } + + $this->data[$this->id]['general']['store_id'] = $store_id; + + $lang = $this->language_merge($this->data[$this->id]['step']['payment_address']['fields'], $this->texts); + $this->data[$this->id]['step']['payment_address']['fields'] = $this->array_merge_recursive_distinct($this->data[$this->id]['step']['payment_address']['fields'], $lang); + + $lang = $this->language_merge($this->data[$this->id]['step']['shipping_address']['fields'], $this->texts); + $this->data[$this->id]['step']['shipping_address']['fields'] = $this->array_merge_recursive_distinct($this->data[$this->id]['step']['shipping_address']['fields'], $lang); + + $lang = $this->language_merge($this->data[$this->id]['step']['confirm']['fields'], $this->texts); + $this->data[$this->id]['step']['confirm']['fields'] = $this->array_merge_recursive_distinct($this->data[$this->id]['step']['confirm']['fields'], $lang); + + //Get Design Steps + $this->data['steps'] = array(); + + + + + foreach($this->data[$this->id]['step'] as $step => $value){ + if(isset($value['column'])){ + $this->data['steps'][$step] = array('column' => $value['column'], 'row' => $value['row']); + } + } + + $this->data['steps']['payment_address']['icon'] = 'book'; + $this->data['steps']['shipping_address']['icon'] = 'book'; + $this->data['steps']['shipping_method']['icon'] = 'truck'; + $this->data['steps']['payment_method']['icon'] = 'credit-card'; + $this->data['steps']['cart']['icon'] = 'shopping-cart'; + $this->data['steps']['payment']['icon'] = 'money'; + $this->data['steps']['confirm']['icon'] = 'check'; + unset($this->data['steps']['login']); + + + $sort_order = array(); + foreach ($this->data['steps'] as $key => $value) { + + $sort_order[$key]['column'] = $value['column']; + $sort_order[$key]['row'] = $value['row']; + } + array_multisort($sort_order, SORT_ASC, $this->data['steps'] ); + + + //Get Shipping methods + $this->data['shipping_methods'] = $this->get_shipping_methods(); + + //Get Payment methods + $this->data['payment_methods'] = $this->get_payment_methods(); + + //Get designes + $this->data['themes'] = $this->get_themes(); + + //Get stores + $this->data['stores'] = $this->get_stores(); + + //Social login + $this->data['social_login'] = false; + if($this->check_d_social_login()){ + $this->data['social_login'] = true; + $this->load->language('module/d_social_login'); + + $this->config->load($this->check_d_social_login()); + $social_login_settings = $this->config->get('d_social_login_settings'); + + if(!isset($this->data[$this->id]['general']['social_login'])){ + $this->data[$this->id]['general']['social_login'] = array(); + } + + $this->data[$this->id]['general']['social_login'] = $this->array_merge_recursive_distinct($social_login_settings, $this->data[$this->id]['general']['social_login']); + + $sort_order = array(); + foreach ($this->data[$this->id]['general']['social_login']['providers'] as $key => $value) { + if(isset($value['sort_order'])){ + $sort_order[$key] = $value['sort_order']; + }else{ + unset($providers[$key]); + } + } + array_multisort($sort_order, SORT_ASC, $this->data[$this->id]['general']['social_login']['providers']); + + foreach($this->data[$this->id]['general']['social_login']['providers'] as $provoder){ + if(isset($provoder['id'])){ + $this->data['text_'.$provoder['id']] = $this->language->get('text_'.$provoder['id']); + } + } + } + + $this->data['socila_login_styles'] = array( 'icons', 'small', 'medium', 'large', 'huge'); + + $this->load->model('design/layout'); + + $this->data['layouts'] = $this->model_design_layout->getLayouts(); + + $this->load->model('localisation/language'); + + $this->data['languages'] = $this->model_localisation_language->getLanguages(); + + if(preg_match("/1.5/i", VERSION)){ + $this->template = $this->route.'.tpl'; + $this->children = array( + 'common/header', + 'common/footer' + ); + $this->data['column_left'] = ''; + + $this->response->setOutput($this->render()); + }else{ + $this->data['header'] = $this->load->controller('common/header'); + $this->data['column_left'] = $this->load->controller('common/column_left'); + $this->data['footer'] = $this->load->controller('common/footer'); + + $this->response->setOutput($this->load->view($this->route.'.tpl', $this->data)); + } + + } + + private function validate() { + if (!$this->user->hasPermission('modify', $this->route)) { + $this->error['warning'] = $this->language->get('error_permission'); + } + + if (!$this->error) { + return true; + } else { + return false; + } + } + + private function get_shipping_methods() { + $shipping_methods = glob(DIR_APPLICATION . 'controller/shipping/*.php'); + $result = array(); + foreach ($shipping_methods as $shipping){ + $shipping = basename($shipping, '.php'); + $this->load->language('shipping/' . $shipping); + $result[] = array( + 'code' => $shipping, + 'title' => $this->language->get('heading_title') + ); + } + return $result; + } + + private function get_payment_methods(){ + $payment_methods = glob(DIR_APPLICATION . 'controller/payment/*.php'); + $result = array(); + foreach ($payment_methods as $payment){ + $payment = basename($payment, '.php'); + $this->load->language('payment/' . $payment); + $result[] = array( + 'code' => $payment, + 'title' => $this->language->get('heading_title') + ); + } + return $result; + } + + private function get_themes(){ + $dir = DIR_CATALOG.'view/theme/default/stylesheet/d_quickcheckout/theme'; + $files = scandir($dir); + $result = array(); + foreach($files as $file){ + if(strlen($file) > 6){ + $result[] = substr($file, 0, -4); + } + } + return $result; + } + + private function get_stores(){ + $this->load->model('setting/store'); + $stores = $this->model_setting_store->getStores(); + $result = array(); + if($stores){ + $result[] = array( + 'store_id' => 0, + 'name' => $this->config->get('config_name') + ); + foreach ($stores as $store) { + $result[] = array( + 'store_id' => $store['store_id'], + 'name' => $store['name'] + ); + } + } + return $result; + } + + public function check_d_social_login(){ + $result = false; + if($this->isInstalled('d_social_login')){ + $full = DIR_SYSTEM . "config/d_social_login_settings.php"; + $light = DIR_SYSTEM . "config/d_social_login_light_settings.php"; + if (file_exists($full)) { + $result = 'd_social_login_settings'; + } elseif (file_exists($light)) { + $result = 'd_social_login_light_settings'; + } + } + return $result; + } + + + public function install() { + $this->load->model('setting/setting'); + $from = str_replace("system", "vqmod/xml", DIR_SYSTEM) . "a_vqmod_d_quickcheckout.xml_"; + $to = str_replace("system", "vqmod/xml", DIR_SYSTEM) . "a_vqmod_d_quickcheckout.xml"; + if (file_exists($from)) rename($from, $to); + $this->version_check(1); + + } + + public function uninstall() { + $this->load->model('setting/setting'); + $from = str_replace("system", "vqmod/xml", DIR_SYSTEM) . "a_vqmod_d_quickcheckout.xml"; + $to = str_replace("system", "vqmod/xml", DIR_SYSTEM) . "a_vqmod_d_quickcheckout.xml_"; + if (file_exists($from)) rename($from, $to); + $this->version_check(0); + + } + + public function language_merge($array, $texts){ + $this->load->model('catalog/information'); + $array_full = $array; + $result = array(); + foreach ($array as $key => $value){ + foreach ($texts as $text){ + if(isset($array_full[$text])){ + if(!is_array($array_full[$text])){ + $result[$text] = $this->language->get($array_full[$text]); + }else{ + if(isset($array_full[$text][(int)$this->config->get('config_language_id')])){ + $result[$text] = $array_full[$text][(int)$this->config->get('config_language_id')]; + }else{ + $result[$text] = current($array_full[$text]); + } + } + if((strpos($result[$text], '%s') !== false) && isset($array_full['information_id'])){ + $information_info = $this->model_catalog_information->getInformation($array_full['information_id']); + $result[$text] = sprintf($result[$text], $information_info['title']); + } + } + } + if(is_array($array_full[$key])){ + $result[$key] = $this->language_merge($array_full[$key], $texts); + } + + } + + return $result; + + } + + public function array_merge_recursive_distinct( array &$array1, array &$array2 ) + { + $merged = $array1; + foreach ( $array2 as $key => &$value ) + { + if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) ) + { + $merged [$key] = $this->array_merge_recursive_distinct ( $merged [$key], $value ); + } + else + { + $merged [$key] = $value; + } + } + + return $merged; + } + + public function check_shopunity(){ + $file1 = DIR_SYSTEM . "mbooth/xml/mbooth_shopunity_admin.xml"; + $file2 = DIR_SYSTEM . "mbooth/xml/mbooth_shopunity_admin_patch.xml"; + if (file_exists($file1) || file_exists($file2)) { + return true; + } else { + return false; + } + + } + + public function get_version(){ + $xml = file_get_contents(DIR_SYSTEM . 'mbooth/xml/' . $this->mbooth); + + $mbooth = new SimpleXMLElement($xml); + + return $mbooth->version ; + } + + public function version_check($status = 1){ + $json = array(); + $this->load->language($this->route); + $this->mboot_script_dir = DIR_SYSTEM . 'mbooth/xml/'; + $str = file_get_contents($this->mboot_script_dir . $this->mbooth); + $xml = new SimpleXMLElement($str); + + $current_version = $xml->version ; + + if (isset($this->request->get['mbooth'])) { + $mbooth = $this->request->get['mbooth']; + } else { + $mbooth = $this->mbooth; + } + + $customer_url = HTTP_SERVER; + $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "language` WHERE language_id = " . (int)$this->config->get('config_language_id') ); + $language_code = $query->row['code']; + $ip = $this->request->server['REMOTE_ADDR']; + + $check_version_url = 'http://opencart.dreamvention.com/api/1/index.php?route=extension/check&mbooth=' . $mbooth . '&store_url=' . $customer_url . '&module_version=' . $current_version . '&language_code=' . $language_code . '&opencart_version=' . VERSION . '&ip='.$ip . '&status=' .$status; + + $curl = curl_init(); + curl_setopt($curl, CURLOPT_URL, $check_version_url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + $return_data = curl_exec($curl); + $return_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); + curl_close($curl); + + if ($return_code == 200) { + $data = simplexml_load_string($return_data); + + if ((string) $data->version == (string) $current_version || (string) $data->version <= (string) $current_version) { + + $json['success'] = $this->language->get('text_no_update') ; + + } elseif ((string) $data->version > (string) $current_version) { + + $json['attention'] = $this->language->get('text_new_update'); + + foreach($data->updates->update as $update){ + + if((string) $update->attributes()->version > (string)$current_version){ + $version = (string)$update->attributes()->version; + $json['update'][$version] = (string) $update[0]; + } + } + } else { + + $json['error'] = $this->language->get('text_error_update'); + } + } else { + $json['error'] = $this->language->get('text_error_failed'); + + } + + if (file_exists(DIR_SYSTEM.'library/json.php')) { + $this->load->library('json'); + $this->response->setOutput(Json::encode($json)); + } else { + $this->response->setOutput(json_encode($json)); + } + } + + public function isInstalled($code) { + $extension_data = array(); + + $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "extension WHERE `code` = '" . $this->db->escape($code) . "'"); + + if($query->row) { + return true; + }else{ + return false; + } + } +} +?> \ No newline at end of file diff --git a/admin/language/english/module/d_quickcheckout.php b/admin/language/english/module/d_quickcheckout.php new file mode 100755 index 0000000..d4e45a8 --- /dev/null +++ b/admin/language/english/module/d_quickcheckout.php @@ -0,0 +1,245 @@ + Ajax Quick Checkout by Dreamvention'; +$_['heading_title_main'] = 'Ajax Quick Checkout'; +$_['text_edit'] = 'Edit Ajax Quick Checkout settings'; + +// Text +$_['text_module'] = 'Modules'; +$_['text_success'] = 'Success: You have modified module welcome!'; +$_['text_content_top'] = 'Content Top'; +$_['text_content_bottom'] = 'Content Bottom'; +$_['text_column_left'] = 'Column Left'; +$_['text_column_right'] = 'Column Right'; +$_['button_save_and_stay'] = 'Save and stay'; + +$_['text_enable'] = 'Enable'; +$_['text_guest'] = 'Guest'; +$_['text_register'] = 'Register'; +$_['text_login'] = 'Login'; +$_['text_yes'] = 'Yes'; +$_['text_no'] = 'No'; +$_['text_display'] = 'Display'; +$_['text_always_show'] = 'Always show'; +$_['text_require'] = 'Require'; +$_['text_input_radio'] = 'Radio'; +$_['text_input_select'] = 'Select'; +$_['text_row'] = 'Row'; +$_['text_block'] = 'Block'; +$_['text_popup'] = 'Popup'; +$_['text_width'] = 'Width:'; +$_['text_height'] = 'Height:'; + +$_['text_home'] = 'Home'; +$_['text_intro_home'] = 'Customize your One-step checkout to increase your sales'; + +$_['text_intro_general'] = 'Set up the general settings of your Ajax Quick Checkout (AQC). You can also define positions as a module.'; +$_['text_intro_login'] = 'Add settings for google, facebook, linked, twitter, paypal, tumblr, VK and more login options.'; +$_['text_intro_payment_address'] = 'Display and hide, then sort the fields you want to have in your checkout. If you don\'t need this step - simply hide it.'; +$_['text_intro_shipping_address'] = 'Like with payment address, you can display/hide and sort the fields. Sorting is easy - simply drag and drop.'; +$_['text_intro_shipping_method'] = 'Set a default value, show/hide the step and select the style of the options - radio or select.'; +$_['text_intro_payment_method'] = 'Like shipping method, you can define the default option, show or hide the step and set the style of the options.'; +$_['text_intro_confirm'] = 'Style your cart - define the columns of the cart as well as the coupon, voucher and reward.'; +$_['text_intro_design'] = 'Set the number of columns in the checkout: there width and the position of steps in it. Use drag-and-drop to do it.'; +$_['text_intro_analytics'] = 'Get insites on how your customers use your checkout and make the best out of it.'; +$_['text_intro_plugins'] = 'Add more plugins to the checkout to increase its functionality. Extra fields, analytics and more.'; + + +$_['text_general'] = 'General settings'; +$_['text_payment_address'] = 'Payment address'; +$_['text_shipping_address'] = 'Shipping address'; +$_['text_shipping_method'] = 'Shipping method'; +$_['text_payment_method'] = 'Payment method'; +$_['text_confirm'] = 'Confirm'; +$_['text_design'] = 'Design'; +$_['text_cart'] = 'Cart'; +$_['text_payment'] = 'Payment'; +$_['text_analytics'] = 'Analytics'; +$_['text_plugins'] = 'Plugins'; + +//general +$_['entry_general_enable'] = 'Enable/Disable AQC:'; +$_['help_general_enable'] = 'Enable the checkout or disable AQC. This option will turn on all the modules and extensions, that are connected with AQC.'; +$_['entry_general_default_option'] = 'Select default option at checkout:'; +$_['help_general_default_option'] = 'Set the default option for the visitor - it can be guest checkout or registration. Please remeber that if you select guest, but you have downloadable items or items that require a registration - the checkout will still show registrated, so that we do not break any of the opencart defualt functions.'; +$_['entry_general_main_checkout'] = 'Replace the main checkout:'; +$_['help_general_main_checkout'] = 'Replace the main checkout with the AQC'; +$_['entry_general_clear_session'] = 'Clear checkout session after page refresh:'; +$_['help_general_clear_session'] = 'When enabled, after the checkout page is refreshed - the personal data will be cleared.'; +$_['entry_general_login_refresh'] = 'Refresh page after login is successful:'; +$_['help_general_login_refresh'] = 'When you login, the system will refresh the page compleatly to update the values in the header.'; +$_['entry_general_default_email'] = 'Set default email:'; +$_['help_general_default_email'] = 'If you remove the email field from the registration, you need to specify an email which will receive the client\'s order information. Otherwise you will also not receive orders as a store administrator'; +$_['entry_general_version'] = 'Check for new version:'; +$_['help_general_version'] = 'When there is a new version available, you can download it from the location you have purchased the module.'; +$_['button_version_check'] = 'Check for update'; +$_['entry_general_debug'] = 'Debug mode:'; +$_['help_general_debug'] = 'Enable the debug option. You will start seeing varibles in the console'; +$_['entry_general_min_order'] = 'Set min order amount:'; +$_['help_general_min_order'] = 'Set the minimum order value to allow checkout'; +$_['text_value_min_order'] = 'The minimum order is %s'; +$_['entry_general_min_quantity'] = 'Set min order quantity:'; +$_['help_general_min_quantity'] = 'Set the minimum order quantity to allow checkout'; +$_['text_value_min_quantity'] = 'The minimum quantity is %s'; +$_['entry_general_trigger'] = 'Payment Tiggers'; +$_['help_general_trigger'] = 'Opencart has many paypemt methods and every payment method has a PAY button. There are no standards for this button and some developers add different types of buttons: divs, input buttons, a etc with different classes. Over time we have come to this pattern, But in some rare cases you may need to add another trigger to this field for the AQC to see the paybutton. it can be a class or an id of the tag. List them here separating by comma , ex. #confirm_payment .button, #confirm_payment .btn, #confirm_payment .button_oc, #confirm_payment input[type=submit]'; + + +//modules +$_['text_position_module'] = 'Position modules:'; +$_['help_position_module'] = 'If you want the AQC to show up in other locations, then you can use this option. If you just want to replace the main checkout - then do not use this option and use the optiob "Replace main checkout"'; +$_['button_add_module'] = 'Add module'; + +$_['entry_general_settings'] = 'Bulk settings:'; +$_['text_general_settings_value'] = 'Use bulk settings'; +$_['help_general_settings'] = 'Copy and save to a file the settings or use the saved settings and set the checkout to them by coping them into the textarea'; + + +//social login +$_['text_social_login_required'] = '

Social Login Required

To use social login option in AQC, you need to install the Social Login module from Dreamvention, and setup the Social Apps. To learn how to do it follow the instructions from the Social login module.

By activating the social login buttons here, you are displaying them in the Ajax Quick Checkout in the step Login

'; +$_['entry_socila_login_style'] = 'Select Social login style'; +$_['help_socila_login_style'] = 'Social login for AQC uses its own settigns so that you can set different sizes of login buttons for different locations on your shop. The rest of the settings is pulled from the social login module.'; +$_['text_icons'] = 'Icons'; +$_['text_small'] = 'Small'; +$_['text_medium'] = 'Medium'; +$_['text_large'] = 'Large'; +$_['text_huge'] = 'Huge'; +$_['button_social_login_edit'] = 'Edit Social login Settings'; + +//payment_address +$_['entry_payment_address_display'] = 'Enable payment address:'; +$_['help_payment_address_display'] = 'If you disable payment address - the payment address step will not show. Be sure no not have any required input fields in the payment address list.'; + +//shipping_address +$_['entry_shipping_address_display'] = 'Enable shipping address:'; +$_['help_shipping_address_display'] = 'If you disable shipping address - the shipping address step will not show. But the option in the payment address block will still be visible. You will need to turn it off so that it doesn\'t show as well. You can require the shipping address - this will make the option always show no matter what the checkbox value is. This is made to force the customer input his shipping address.'; + +//shipping_method +$_['entry_shipping_method_display'] = 'Enable shipping method step'; +$_['entry_shipping_method_display_options'] = 'Display shipping methods'; +$_['entry_shipping_method_display_title'] = 'Display shipping method group title'; +$_['entry_shipping_method_input_style'] = 'Shipping method style'; +$_['entry_shipping_method_default_option'] = 'Select a default shipping method'; +$_['help_shipping_method_display'] = 'You can display the shipping step or hide it. you must still have at least one shipping method that will be selected by default'; +$_['help_shipping_method_display_options'] = 'You can display just the shipping methods or hide them. If you have plugins for the shipping method step, this will allow you to show the plugins but hide the shipping method options'; +$_['help_shipping_method_display_title'] = 'You can hide the title of the groups for the shipping methods and just keep their names'; +$_['help_shipping_method_input_style'] = 'Choose the style for displaying the shipping methods: select or radio'; +$_['help_shipping_method_default_option'] = 'This shipping method option will be selected by default for every new visitor. If the visitor is not new, it will use the saved values from the earlier select options. If this shipping method is not available for the current geo zone, the first shipping method will be selected.'; + + +//payment_method +$_['entry_payment_method_display'] = 'Enable payment method step'; +$_['entry_payment_method_display_options'] = 'Display payment methods'; +$_['entry_payment_method_display_images'] = 'Display payment method images'; +$_['entry_payment_method_input_style'] = 'Payment method style'; +$_['entry_payment_method_default_option'] = 'Select a default payment method'; +$_['entry_payment_method_input_style'] = 'Payment method style'; +$_['help_payment_method_display'] = 'You can display the payment step or hide it. you must still have at least one payment method that will be selected by default'; +$_['help_payment_method_display_options'] = 'You can display just the payment methods or hide them. If you have plugins for the payment method step, this will allow you to show the plugins but hide the payment method options'; +$_['help_payment_method_display_images'] = 'You can display the payment images for the radio style of payment methods. If you have selected the select style - the images will not show.'; +$_['help_payment_method_input_style'] = 'Choose the style for displaying the payment methods: select or radio'; +$_['help_payment_method_default_option'] = 'This payment method option will be selected by default for every new visitor. If the visitor is not new, it will use the saved values from the earlier select options. If this payment method is not available for the current geo zone, the first payment method will be selected.'; + +//cart +$_['entry_cart_display'] = 'Display cart'; +$_['entry_cart_columns_image'] = 'Display column image'; +$_['entry_cart_columns_name'] = 'Display column name'; +$_['entry_cart_columns_model'] = 'Display column model'; +$_['entry_cart_columns_quantity'] = 'Display column quantity'; +$_['entry_cart_columns_price'] = 'Display column price'; +$_['entry_cart_columns_total'] = 'Display column total'; +$_['entry_cart_option_coupon'] = 'Display coupon input'; +$_['entry_cart_option_voucher'] = 'Display voucher input'; +$_['entry_cart_option_reward'] = 'Display reward input'; +$_['entry_confirm_display'] = 'Display confirm'; +$_['help_cart_display'] = 'By hiding the cart, you are hiding the cart and the options in it. the confirm button stays to still complete the order.'; +$_['help_cart_option_coupon'] = 'Show or hide the coupon option. Remember, if the coupon option is disabled in the checkout totals - it will not show up in the AQC as well. You must turn it on and then select which option gets to display it.'; +$_['help_cart_option_voucher'] = 'Show or hide the voucher option. Remember, if the voucher option is disabled in the checkout totals - it will not show up in the AQC as well. You must turn it on and then select which option gets to display it.'; +$_['help_cart_option_reward'] = 'Show or hide the reward option. Remeber, if the reward option is disabled in the checkout totals - it will not show up in the AQC as well. Also rewards are for logged in customers. You must turn it on and then select which option gets to display it.'; + + +//design +$_['entry_design_theme'] = 'Select theme for AQC'; +$_['entry_design_field'] = 'Select field design'; +$_['entry_design_login_option'] = 'Set Login options'; +$_['entry_design_login'] = 'Select login design'; +$_['entry_design_address'] = 'Select address design'; +$_['entry_design_cart_image_size'] = 'Set product image size on hover'; +$_['entry_design_max_width'] = 'Max width of the checkout'; +$_['entry_design_uniform'] = 'Checkbox styles'; +$_['entry_design_only_quickcheckout'] = 'Show only the checkout'; +$_['entry_design_column'] = 'Set columns'; +$_['entry_design_custom_style'] = 'Set Custom styles'; + +$_['help_payment_address'] = 'Customer information and payment address.'; +$_['help_shipping_address'] = 'Extra address for shipping purposes.'; +$_['help_shipping_method'] = 'Third step. You can set a default method and hide this step.'; +$_['help_payment_method'] = 'Fourth step. You can set a default method and hide this step.'; +$_['help_cart'] = 'Part of the last step - the cart. You can move to the top as well.'; +$_['help_payment'] = 'Some payment methods have more options to fill - like paypal pro.'; +$_['help_confirm'] = 'The last step is the confirm. Edit fields.'; + + +$_['help_design_theme'] = 'Select a style for the frontend of AQC. You can install other designs or create your own.'; +$_['help_design_field'] = 'Set the style of the fields in payment and shipping address blocks. Row style - the labels will be on one line with the input. Block style - the labels will be above the inputs.'; +$_['help_design_login_option'] = 'Show or hide the options that are at the beggining of the checkout'; +$_['help_design_login'] = 'Select the style of the login block. you can select to show the block or use a popup for login, while the option for registration or guest checkout is a simple checkbox.'; +$_['help_design_address'] = 'Select the style of the address block for logged in users. you can select to show address as a list or as radio button options.'; +$_['help_design_cart_image_size'] = 'Set the width and height of the product pop up image when you hover on the smal product thumb image in the cart.'; +$_['help_design_max_width'] = 'If you see the checkout fill the whole screen, set the max width of the checkout and it will fit nicly in the middle. i.e. 960'; +$_['help_design_uniform'] = 'You can disable the checkbox and radio buttons styles on the checkout.'; +$_['help_design_only_quickcheckout'] = 'Enable this option to hide all the information in header, footer and columns to make the checkout process as simple and clean as possible.'; +$_['help_design_column'] = 'Set the number of columns. You can set up to 3 columns and there widths.'; +$_['help_design_custom_style'] = 'Add custom styles to the checkout. Follow the right CSS standards.'; + +// Entry +$_['text_your_address'] = 'Your Address'; +$_['entry_email_address'] = 'E-Mail Address:'; +$_['entry_email'] = 'E-Mail:'; +$_['entry_email_confirm'] = 'Confirm E-mail'; +$_['entry_password'] = 'Password:'; +$_['entry_confirm'] = 'Password Confirm:'; +$_['entry_firstname'] = 'First Name:'; +$_['entry_lastname'] = 'Last Name:'; +$_['entry_telephone'] = 'Telephone:'; +$_['entry_fax'] = 'Fax:'; +$_['entry_company'] = 'Company:'; +$_['entry_customer_group'] = 'Business Type:'; +$_['entry_company_id'] = 'Company ID:'; +$_['entry_tax_id'] = 'Tax ID:'; +$_['entry_address_1'] = 'Address 1:'; +$_['entry_address_2'] = 'Address 2:'; +$_['entry_postcode'] = 'Post Code:'; +$_['entry_city'] = 'City:'; +$_['entry_country'] = 'Country:'; +$_['entry_zone'] = 'Region / State:'; +$_['entry_newsletter'] = 'I wish to subscribe to the newsletter.'; +$_['entry_shipping'] = 'My delivery and billing addresses are the same.'; +$_['text_agree'] = 'I agree to the conditions.'; +$_['text_comments'] = 'Leave a comment for the order.'; + + +// Entry +$_['entry_layout'] = 'Layout:'; +$_['entry_position'] = 'Position:'; +$_['entry_status'] = 'Status:'; +$_['entry_sort_order'] = 'Sort Order:'; + +$_['entry_status'] = 'Status:'; +$_['entry_sort_order'] = 'Sort Order:'; + + +$_['settings_select'] = 'Dropdown Select'; +$_['settings_image'] = 'Display images'; + +//Supporting +$_['text_no_update'] = 'Super! You have the latest version.'; +$_['text_new_update'] = 'Wow! There is a new version avalible for download.'; +$_['text_error_update'] = 'Sorry! Something went wrong. If this repeats, contact the support please.'; +$_['text_error_failed'] = 'Oops! We could not connect to the server. Please try again later.'; +$_['error_shopunity_required'] = 'Don\'t worry, to make your module look great, please install Shopunity Admin them. You can download it from here'; +$_['error_permission'] = 'Warning: You do not have permission to modify module welcome!'; + +$_['text_need_full_version'] = '

To use this function full version required

You can purchase the full version on opencart or from gumroad. It haa much more functions that will allow you to set up the perfect checkout.

'; + +?> diff --git a/admin/view/javascript/shopunity/.ds_store-1 b/admin/view/javascript/shopunity/.ds_store-1 new file mode 100755 index 0000000..1ad6d01 Binary files /dev/null and b/admin/view/javascript/shopunity/.ds_store-1 differ diff --git a/admin/view/javascript/shopunity/bootstrap-slider/css/slider.css b/admin/view/javascript/shopunity/bootstrap-slider/css/slider.css new file mode 100755 index 0000000..a7f8370 --- /dev/null +++ b/admin/view/javascript/shopunity/bootstrap-slider/css/slider.css @@ -0,0 +1,138 @@ +/*! + * Slider for Bootstrap + * + * Copyright 2012 Stefan Petre + * Licensed under the Apache License v2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + * + */ +.slider { + display: inline-block; + vertical-align: middle; + position: relative; +} +.slider.slider-horizontal { + width: 100%; + height: 20px; +} +.slider.slider-horizontal .slider-track { + height: 10px; + width: 100%; + margin-top: -5px; + top: 50%; + left: 0; +} +.slider.slider-horizontal .slider-selection { + height: 100%; + top: 0; + bottom: 0; +} +.slider.slider-horizontal .slider-handle { + margin-left: -10px; + margin-top: -5px; +} +.slider.slider-horizontal .slider-handle.triangle { + border-width: 0 10px 10px 10px; + width: 0; + height: 0; + border-bottom-color: #0480be; + margin-top: 0; +} +.slider.slider-vertical { + height: 210px; + width: 20px; +} +.slider.slider-vertical .slider-track { + width: 10px; + height: 100%; + margin-left: -5px; + left: 50%; + top: 0; +} +.slider.slider-vertical .slider-selection { + width: 100%; + left: 0; + top: 0; + bottom: 0; +} +.slider.slider-vertical .slider-handle { + margin-left: -5px; + margin-top: -10px; +} +.slider.slider-vertical .slider-handle.triangle { + border-width: 10px 0 10px 10px; + width: 1px; + height: 1px; + border-left-color: #0480be; + margin-left: 0; +} +.slider input { + display: none; +} +.slider .tooltip-inner { + white-space: nowrap; +} +.slider-track { + position: absolute; + cursor: pointer; + background-color: #f7f7f7; + background-image: -moz-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9)); + background-image: -webkit-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: -o-linear-gradient(top, #f5f5f5, #f9f9f9); + background-image: linear-gradient(to bottom, #f5f5f5, #f9f9f9); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0); + -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -moz-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.slider-selection { + position: absolute; + background-color: #f7f7f7; + background-image: -moz-linear-gradient(top, #f9f9f9, #f5f5f5); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f9f9f9), to(#f5f5f5)); + background-image: -webkit-linear-gradient(top, #f9f9f9, #f5f5f5); + background-image: -o-linear-gradient(top, #f9f9f9, #f5f5f5); + background-image: linear-gradient(to bottom, #f9f9f9, #f5f5f5); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff9f9f9', endColorstr='#fff5f5f5', GradientType=0); + -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15); + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + -webkit-border-radius: 4px; + -moz-border-radius: 4px; + border-radius: 4px; +} +.slider-handle { + position: absolute; + width: 20px; + height: 20px; + background-color: #0e90d2; + background-image: -moz-linear-gradient(top, #149bdf, #0480be); + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be)); + background-image: -webkit-linear-gradient(top, #149bdf, #0480be); + background-image: -o-linear-gradient(top, #149bdf, #0480be); + background-image: linear-gradient(to bottom, #149bdf, #0480be); + background-repeat: repeat-x; + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0); + -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); + opacity: 0.8; + border: 0px solid transparent; +} +.slider-handle.round { + -webkit-border-radius: 20px; + -moz-border-radius: 20px; + border-radius: 20px; +} +.slider-handle.triangle { + background: transparent none; +} \ No newline at end of file diff --git a/admin/view/javascript/shopunity/bootstrap-slider/js/bootstrap-slider.js b/admin/view/javascript/shopunity/bootstrap-slider/js/bootstrap-slider.js new file mode 100755 index 0000000..c689b7e --- /dev/null +++ b/admin/view/javascript/shopunity/bootstrap-slider/js/bootstrap-slider.js @@ -0,0 +1,388 @@ +/* ========================================================= + * bootstrap-slider.js v2.0.0 + * http://www.eyecon.ro/bootstrap-slider + * ========================================================= + * Copyright 2012 Stefan Petre + * + * 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. + * ========================================================= */ + +!function( $ ) { + + var Slider = function(element, options) { + this.element = $(element); + this.picker = $('
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
') + .insertBefore(this.element) + .append(this.element); + this.id = this.element.data('slider-id')||options.id; + if (this.id) { + this.picker[0].id = this.id; + } + + if (typeof Modernizr !== 'undefined' && Modernizr.touch) { + this.touchCapable = true; + } + + var tooltip = this.element.data('slider-tooltip')||options.tooltip; + + this.tooltip = this.picker.find('.tooltip'); + this.tooltipInner = this.tooltip.find('div.tooltip-inner'); + + this.orientation = this.element.data('slider-orientation')||options.orientation; + switch(this.orientation) { + case 'vertical': + this.picker.addClass('slider-vertical'); + this.stylePos = 'top'; + this.mousePos = 'pageY'; + this.sizePos = 'offsetHeight'; + this.tooltip.addClass('right')[0].style.left = '100%'; + break; + default: + this.picker + .addClass('slider-horizontal') + //.css('width', this.element.outerWidth()); + this.orientation = 'horizontal'; + this.stylePos = 'left'; + this.mousePos = 'pageX'; + this.sizePos = 'offsetWidth'; + this.tooltip.addClass('top')[0].style.top = -this.tooltip.outerHeight() - 14 + 'px'; + break; + } + + this.min = this.element.data('slider-min')||options.min; + this.max = this.element.data('slider-max')||options.max; + this.step = this.element.data('slider-step')||options.step; + this.value = this.element.data('slider-value')||options.value; + if (this.value[1]) { + this.range = true; + } + + this.selection = this.element.data('slider-selection')||options.selection; + this.selectionEl = this.picker.find('.slider-selection'); + if (this.selection === 'none') { + this.selectionEl.addClass('hide'); + } + this.selectionElStyle = this.selectionEl[0].style; + + + this.handle1 = this.picker.find('.slider-handle:first'); + this.handle1Stype = this.handle1[0].style; + this.handle2 = this.picker.find('.slider-handle:last'); + this.handle2Stype = this.handle2[0].style; + + var handle = this.element.data('slider-handle')||options.handle; + switch(handle) { + case 'round': + this.handle1.addClass('round'); + this.handle2.addClass('round'); + break + case 'triangle': + this.handle1.addClass('triangle'); + this.handle2.addClass('triangle'); + break + } + + if (this.range) { + this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); + this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); + } else { + this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; + this.handle2.addClass('hide'); + if (this.selection == 'after') { + this.value[1] = this.max; + } else { + this.value[1] = this.min; + } + } + this.diff = this.max - this.min; + this.percentage = [ + (this.value[0]-this.min)*100/this.diff, + (this.value[1]-this.min)*100/this.diff, + this.step*100/this.diff + ]; + + this.offset = this.picker.offset(); + this.size = this.picker[0][this.sizePos]; + + this.formater = options.formater; + + this.layout(); + + if (this.touchCapable) { + // Touch: Bind touch events: + this.picker.on({ + touchstart: $.proxy(this.mousedown, this) + }); + } else { + this.picker.on({ + mousedown: $.proxy(this.mousedown, this) + }); + } + + if (tooltip === 'show') { + this.picker.on({ + mouseenter: $.proxy(this.showTooltip, this), + mouseleave: $.proxy(this.hideTooltip, this) + }); + } else { + this.tooltip.addClass('hide'); + } + }; + + Slider.prototype = { + constructor: Slider, + + over: false, + inDrag: false, + + showTooltip: function(){ + this.tooltip.addClass('in'); + //var left = Math.round(this.percent*this.width); + //this.tooltip.css('left', left - this.tooltip.outerWidth()/2); + this.over = true; + }, + + hideTooltip: function(){ + if (this.inDrag === false) { + this.tooltip.removeClass('in'); + } + this.over = false; + }, + + layout: function(){ + this.handle1Stype[this.stylePos] = this.percentage[0]+'%'; + this.handle2Stype[this.stylePos] = this.percentage[1]+'%'; + if (this.orientation == 'vertical') { + this.selectionElStyle.top = Math.min(this.percentage[0], this.percentage[1]) +'%'; + this.selectionElStyle.height = Math.abs(this.percentage[0] - this.percentage[1]) +'%'; + } else { + this.selectionElStyle.left = Math.min(this.percentage[0], this.percentage[1]) +'%'; + this.selectionElStyle.width = Math.abs(this.percentage[0] - this.percentage[1]) +'%'; + } + if (this.range) { + this.tooltipInner.text( + this.formater(this.value[0]) + + ' : ' + + this.formater(this.value[1]) + ); + this.tooltip[0].style[this.stylePos] = this.size * (this.percentage[0] + (this.percentage[1] - this.percentage[0])/2)/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px'; + } else { + this.tooltipInner.text( + this.formater(this.value[0]) + ); + this.tooltip[0].style[this.stylePos] = this.size * this.percentage[0]/100 - (this.orientation === 'vertical' ? this.tooltip.outerHeight()/2 : this.tooltip.outerWidth()/2) +'px'; + } + }, + + mousedown: function(ev) { + + // Touch: Get the original event: + if (this.touchCapable && ev.type === 'touchstart') { + ev = ev.originalEvent; + } + + this.offset = this.picker.offset(); + this.size = this.picker[0][this.sizePos]; + + var percentage = this.getPercentage(ev); + + if (this.range) { + var diff1 = Math.abs(this.percentage[0] - percentage); + var diff2 = Math.abs(this.percentage[1] - percentage); + this.dragged = (diff1 < diff2) ? 0 : 1; + } else { + this.dragged = 0; + } + + this.percentage[this.dragged] = percentage; + this.layout(); + + if (this.touchCapable) { + // Touch: Bind touch events: + $(document).on({ + touchmove: $.proxy(this.mousemove, this), + touchend: $.proxy(this.mouseup, this) + }); + } else { + $(document).on({ + mousemove: $.proxy(this.mousemove, this), + mouseup: $.proxy(this.mouseup, this) + }); + } + + this.inDrag = true; + var val = this.calculateValue(); + this.element.trigger({ + type: 'slideStart', + value: val + }).trigger({ + type: 'slide', + value: val + }); + return false; + }, + + mousemove: function(ev) { + + // Touch: Get the original event: + if (this.touchCapable && ev.type === 'touchmove') { + ev = ev.originalEvent; + } + + var percentage = this.getPercentage(ev); + if (this.range) { + if (this.dragged === 0 && this.percentage[1] < percentage) { + this.percentage[0] = this.percentage[1]; + this.dragged = 1; + } else if (this.dragged === 1 && this.percentage[0] > percentage) { + this.percentage[1] = this.percentage[0]; + this.dragged = 0; + } + } + this.percentage[this.dragged] = percentage; + this.layout(); + var val = this.calculateValue(); + this.element + .trigger({ + type: 'slide', + value: val + }) + .data('value', val) + .prop('value', val); + return false; + }, + + mouseup: function(ev) { + if (this.touchCapable) { + // Touch: Bind touch events: + $(document).off({ + touchmove: this.mousemove, + touchend: this.mouseup + }); + } else { + $(document).off({ + mousemove: this.mousemove, + mouseup: this.mouseup + }); + } + + this.inDrag = false; + if (this.over == false) { + this.hideTooltip(); + } + this.element; + var val = this.calculateValue(); + this.element + .trigger({ + type: 'slideStop', + value: val + }) + .data('value', val) + .prop('value', val); + return false; + }, + + calculateValue: function() { + var val; + if (this.range) { + val = [ + (this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step), + (this.min + Math.round((this.diff * this.percentage[1]/100)/this.step)*this.step) + ]; + this.value = val; + } else { + val = (this.min + Math.round((this.diff * this.percentage[0]/100)/this.step)*this.step); + this.value = [val, this.value[1]]; + } + return val; + }, + + getPercentage: function(ev) { + if (this.touchCapable) { + ev = ev.touches[0]; + } + var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size; + percentage = Math.round(percentage/this.percentage[2])*this.percentage[2]; + return Math.max(0, Math.min(100, percentage)); + }, + + getValue: function() { + if (this.range) { + return this.value; + } + return this.value[0]; + }, + + setValue: function(val) { + this.value = val; + + if (this.range) { + this.value[0] = Math.max(this.min, Math.min(this.max, this.value[0])); + this.value[1] = Math.max(this.min, Math.min(this.max, this.value[1])); + } else { + this.value = [ Math.max(this.min, Math.min(this.max, this.value))]; + this.handle2.addClass('hide'); + if (this.selection == 'after') { + this.value[1] = this.max; + } else { + this.value[1] = this.min; + } + } + this.diff = this.max - this.min; + this.percentage = [ + (this.value[0]-this.min)*100/this.diff, + (this.value[1]-this.min)*100/this.diff, + this.step*100/this.diff + ]; + this.layout(); + } + }; + + $.fn.slider = function ( option, val ) { + return this.each(function () { + var $this = $(this), + data = $this.data('slider'), + options = typeof option === 'object' && option; + if (!data) { + $this.data('slider', (data = new Slider(this, $.extend({}, $.fn.slider.defaults,options)))); + } + if (typeof option == 'string') { + data[option](val); + } + }) + }; + + $.fn.slider.defaults = { + min: 0, + max: 10, + step: 1, + orientation: 'horizontal', + value: 5, + selection: 'before', + tooltip: 'show', + handle: 'round', + formater: function(value) { + return value; + } + }; + + $.fn.slider.Constructor = Slider; + +}( window.jQuery ); \ No newline at end of file diff --git a/admin/view/javascript/shopunity/bootstrap-sortable.js b/admin/view/javascript/shopunity/bootstrap-sortable.js new file mode 100755 index 0000000..71a56a3 --- /dev/null +++ b/admin/view/javascript/shopunity/bootstrap-sortable.js @@ -0,0 +1,679 @@ +/* =================================================== + * jquery-sortable.js v0.9.12 + * http://johnny.github.com/jquery-sortable/ + * =================================================== + * Copyright (c) 2012 Jonas von Andrian + * 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. + * * The name of the author may not 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 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. + * ========================================================== */ + + +!function ( $, window, pluginName, undefined){ + var eventNames, + containerDefaults = { + // If true, items can be dragged from this container + drag: true, + // If true, items can be droped onto this container + drop: true, + // Exclude items from being draggable, if the + // selector matches the item + exclude: "", + // If true, search for nested containers within an item + nested: true, + // If true, the items are assumed to be arranged vertically + vertical: true + }, // end container defaults + groupDefaults = { + // This is executed after the placeholder has been moved. + // $closestItemOrContainer contains the closest item, the placeholder + // has been put at or the closest empty Container, the placeholder has + // been appended to. + afterMove: function ($placeholder, container, $closestItemOrContainer) { + }, + // The exact css path between the container and its items, e.g. "> tbody" + containerPath: "", + // The css selector of the containers + containerSelector: "ol, ul", + // Distance the mouse has to travel to start dragging + distance: 0, + // Time in milliseconds after mousedown until dragging should start. + // This option can be used to prevent unwanted drags when clicking on an element. + delay: 0, + // The css selector of the drag handle + handle: "", + // The exact css path between the item and its subcontainers + itemPath: "", + // The css selector of the items + itemSelector: "li", + // Check if the dragged item may be inside the container. + // Use with care, since the search for a valid container entails a depth first search + // and may be quite expensive. + isValidTarget: function ($item, container) { + return true + }, + // Executed before onDrop if placeholder is detached. + // This happens if pullPlaceholder is set to false and the drop occurs outside a container. + onCancel: function ($item, container, _super, event) { + }, + // Executed at the beginning of a mouse move event. + // The Placeholder has not been moved yet. + onDrag: function ($item, position, _super, event) { + $item.css(position) + }, + // Called after the drag has been started, + // that is the mouse button is beeing held down and + // the mouse is moving. + // The container is the closest initialized container. + // Therefore it might not be the container, that actually contains the item. + onDragStart: function ($item, container, _super, event) { + $item.css({ + height: $item.height(), + width: $item.width() + }) + $item.addClass("dragged") + $("body").addClass("dragging") + }, + // Called when the mouse button is beeing released + onDrop: function ($item, container, _super, event) { + $item.removeClass("dragged").removeAttr("style") + $("body").removeClass("dragging") + }, + // Called on mousedown. If falsy value is returned, the dragging will not start. + // If clicked on input element, ignore + onMousedown: function ($item, _super, event) { + if (!event.target.nodeName.match(/^(input|select)$/i)) { + event.preventDefault() + return true + } + }, + // Template for the placeholder. Can be any valid jQuery input + // e.g. a string, a DOM element. + // The placeholder must have the class "placeholder" + placeholder: '
  • ', + // If true, the position of the placeholder is calculated on every mousemove. + // If false, it is only calculated when the mouse is above a container. + pullPlaceholder: true, + // Specifies serialization of the container group. + // The pair $parent/$children is either container/items or item/subcontainers. + serialize: function ($parent, $children, parentIsContainer) { + var result = $.extend({}, $parent.data()) + + if(parentIsContainer) + return [$children] + else if ($children[0]){ + result.children = $children + } + + delete result.subContainers + delete result.sortable + + return result + }, + // Set tolerance while dragging. Positive values decrease sensitivity, + // negative values increase it. + tolerance: 0 + }, // end group defaults + containerGroups = {}, + groupCounter = 0, + emptyBox = { + left: 0, + top: 0, + bottom: 0, + right:0 + }, + eventNames = { + start: "touchstart.sortable mousedown.sortable", + drop: "touchend.sortable touchcancel.sortable mouseup.sortable", + drag: "touchmove.sortable mousemove.sortable", + scroll: "scroll.sortable" + }, + subContainerKey = "subContainers" + + /* + * a is Array [left, right, top, bottom] + * b is array [left, top] + */ + function d(a,b) { + var x = Math.max(0, a[0] - b[0], b[0] - a[1]), + y = Math.max(0, a[2] - b[1], b[1] - a[3]) + return x+y; + } + + function setDimensions(array, dimensions, tolerance, useOffset) { + var i = array.length, + offsetMethod = useOffset ? "offset" : "position" + tolerance = tolerance || 0 + + while(i--){ + var el = array[i].el ? array[i].el : $(array[i]), + // use fitting method + pos = el[offsetMethod]() + pos.left += parseInt(el.css('margin-left'), 10) + pos.top += parseInt(el.css('margin-top'),10) + dimensions[i] = [ + pos.left - tolerance, + pos.left + el.outerWidth() + tolerance, + pos.top - tolerance, + pos.top + el.outerHeight() + tolerance + ] + } + } + + function getRelativePosition(pointer, element) { + var offset = element.offset() + return { + left: pointer.left - offset.left, + top: pointer.top - offset.top + } + } + + function sortByDistanceDesc(dimensions, pointer, lastPointer) { + pointer = [pointer.left, pointer.top] + lastPointer = lastPointer && [lastPointer.left, lastPointer.top] + + var dim, + i = dimensions.length, + distances = [] + + while(i--){ + dim = dimensions[i] + distances[i] = [i,d(dim,pointer), lastPointer && d(dim, lastPointer)] + } + distances = distances.sort(function (a,b) { + return b[1] - a[1] || b[2] - a[2] || b[0] - a[0] + }) + + // last entry is the closest + return distances + } + + function ContainerGroup(options) { + this.options = $.extend({}, groupDefaults, options) + this.containers = [] + + if(!this.options.rootGroup){ + this.scrollProxy = $.proxy(this.scroll, this) + this.dragProxy = $.proxy(this.drag, this) + this.dropProxy = $.proxy(this.drop, this) + this.placeholder = $(this.options.placeholder) + + if(!options.isValidTarget) + this.options.isValidTarget = undefined + } + } + + ContainerGroup.get = function (options) { + if(!containerGroups[options.group]) { + if(options.group === undefined) + options.group = groupCounter ++ + + containerGroups[options.group] = new ContainerGroup(options) + } + + return containerGroups[options.group] + } + + ContainerGroup.prototype = { + dragInit: function (e, itemContainer) { + this.$document = $(itemContainer.el[0].ownerDocument) + + // get item to drag + this.item = $(e.target).closest(this.options.itemSelector) + this.itemContainer = itemContainer + + if(this.item.is(this.options.exclude) || + !this.options.onMousedown(this.item, groupDefaults.onMousedown, e)){ + return + } + + this.setPointer(e) + this.toggleListeners('on') + + this.setupDelayTimer() + this.dragInitDone = true + }, + drag: function (e) { + if(!this.dragging){ + if(!this.distanceMet(e) || !this.delayMet) + return + + this.options.onDragStart(this.item, this.itemContainer, groupDefaults.onDragStart, e) + this.item.before(this.placeholder) + this.dragging = true + } + + this.setPointer(e) + // place item under the cursor + this.options.onDrag(this.item, + getRelativePosition(this.pointer, this.item.offsetParent()), + groupDefaults.onDrag, + e) + + var x = e.pageX || e.originalEvent.pageX, + y = e.pageY || e.originalEvent.pageY, + box = this.sameResultBox, + t = this.options.tolerance + + if(!box || box.top - t > y || box.bottom + t < y || box.left - t > x || box.right + t < x) + if(!this.searchValidTarget()) + this.placeholder.detach() + }, + drop: function (e) { + this.toggleListeners('off') + + this.dragInitDone = false + + if(this.dragging){ + // processing Drop, check if placeholder is detached + if(this.placeholder.closest("html")[0]) + this.placeholder.before(this.item).detach() + else + this.options.onCancel(this.item, this.itemContainer, groupDefaults.onCancel, e) + + this.options.onDrop(this.item, this.getContainer(this.item), groupDefaults.onDrop, e) + + // cleanup + this.clearDimensions() + this.clearOffsetParent() + this.lastAppendedItem = this.sameResultBox = undefined + this.dragging = false + } + }, + searchValidTarget: function (pointer, lastPointer) { + if(!pointer){ + pointer = this.relativePointer || this.pointer + lastPointer = this.lastRelativePointer || this.lastPointer + } + + var distances = sortByDistanceDesc(this.getContainerDimensions(), + pointer, + lastPointer), + i = distances.length + + while(i--){ + var index = distances[i][0], + distance = distances[i][1] + + if(!distance || this.options.pullPlaceholder){ + var container = this.containers[index] + if(!container.disabled){ + if(!this.$getOffsetParent()){ + var offsetParent = container.getItemOffsetParent() + pointer = getRelativePosition(pointer, offsetParent) + lastPointer = getRelativePosition(lastPointer, offsetParent) + } + if(container.searchValidTarget(pointer, lastPointer)) + return true + } + } + } + if(this.sameResultBox) + this.sameResultBox = undefined + }, + movePlaceholder: function (container, item, method, sameResultBox) { + var lastAppendedItem = this.lastAppendedItem + if(!sameResultBox && lastAppendedItem && lastAppendedItem[0] === item[0]) + return; + + item[method](this.placeholder) + this.lastAppendedItem = item + this.sameResultBox = sameResultBox + this.options.afterMove(this.placeholder, container, item) + }, + getContainerDimensions: function () { + if(!this.containerDimensions) + setDimensions(this.containers, this.containerDimensions = [], this.options.tolerance, !this.$getOffsetParent()) + return this.containerDimensions + }, + getContainer: function (element) { + return element.closest(this.options.containerSelector).data(pluginName) + }, + $getOffsetParent: function () { + if(this.offsetParent === undefined){ + var i = this.containers.length - 1, + offsetParent = this.containers[i].getItemOffsetParent() + + if(!this.options.rootGroup){ + while(i--){ + if(offsetParent[0] != this.containers[i].getItemOffsetParent()[0]){ + // If every container has the same offset parent, + // use position() which is relative to this parent, + // otherwise use offset() + // compare #setDimensions + offsetParent = false + break; + } + } + } + + this.offsetParent = offsetParent + } + return this.offsetParent + }, + setPointer: function (e) { + var pointer = this.getPointer(e) + + if(this.$getOffsetParent()){ + var relativePointer = getRelativePosition(pointer, this.$getOffsetParent()) + this.lastRelativePointer = this.relativePointer + this.relativePointer = relativePointer + } + + this.lastPointer = this.pointer + this.pointer = pointer + }, + distanceMet: function (e) { + var currentPointer = this.getPointer(e) + return (Math.max( + Math.abs(this.pointer.left - currentPointer.left), + Math.abs(this.pointer.top - currentPointer.top) + ) >= this.options.distance) + }, + getPointer: function(e) { + return { + left: e.pageX || e.originalEvent.pageX, + top: e.pageY || e.originalEvent.pageY + } + }, + setupDelayTimer: function () { + var that = this + this.delayMet = !this.options.delay + + // init delay timer if needed + if (!this.delayMet) { + clearTimeout(this._mouseDelayTimer); + this._mouseDelayTimer = setTimeout(function() { + that.delayMet = true + }, this.options.delay) + } + }, + scroll: function (e) { + this.clearDimensions() + this.clearOffsetParent() // TODO is this needed? + }, + toggleListeners: function (method) { + var that = this, + events = ['drag','drop','scroll'] + + $.each(events,function (i,event) { + that.$document[method](eventNames[event], that[event + 'Proxy']) + }) + }, + clearOffsetParent: function () { + this.offsetParent = undefined + }, + // Recursively clear container and item dimensions + clearDimensions: function () { + this.traverse(function(object){ + object._clearDimensions() + }) + }, + traverse: function(callback) { + callback(this) + var i = this.containers.length + while(i--){ + this.containers[i].traverse(callback) + } + }, + _clearDimensions: function(){ + this.containerDimensions = undefined + }, + _destroy: function () { + containerGroups[this.options.group] = undefined + } + } + + function Container(element, options) { + this.el = element + this.options = $.extend( {}, containerDefaults, options) + + this.group = ContainerGroup.get(this.options) + this.rootGroup = this.options.rootGroup || this.group + this.handle = this.rootGroup.options.handle || this.rootGroup.options.itemSelector + + var itemPath = this.rootGroup.options.itemPath + this.target = itemPath ? this.el.find(itemPath) : this.el + + this.target.on(eventNames.start, this.handle, $.proxy(this.dragInit, this)) + + if(this.options.drop) + this.group.containers.push(this) + } + + Container.prototype = { + dragInit: function (e) { + var rootGroup = this.rootGroup + + if( !this.disabled && + !rootGroup.dragInitDone && + this.options.drag && + this.isValidDrag(e)) { + rootGroup.dragInit(e, this) + } + }, + isValidDrag: function(e) { + return e.which == 1 || + e.type == "touchstart" && e.originalEvent.touches.length == 1 + }, + searchValidTarget: function (pointer, lastPointer) { + var distances = sortByDistanceDesc(this.getItemDimensions(), + pointer, + lastPointer), + i = distances.length, + rootGroup = this.rootGroup, + validTarget = !rootGroup.options.isValidTarget || + rootGroup.options.isValidTarget(rootGroup.item, this) + + if(!i && validTarget){ + rootGroup.movePlaceholder(this, this.target, "append") + return true + } else + while(i--){ + var index = distances[i][0], + distance = distances[i][1] + if(!distance && this.hasChildGroup(index)){ + var found = this.getContainerGroup(index).searchValidTarget(pointer, lastPointer) + if(found) + return true + } + else if(validTarget){ + this.movePlaceholder(index, pointer) + return true + } + } + }, + movePlaceholder: function (index, pointer) { + var item = $(this.items[index]), + dim = this.itemDimensions[index], + method = "after", + width = item.outerWidth(), + height = item.outerHeight(), + offset = item.offset(), + sameResultBox = { + left: offset.left, + right: offset.left + width, + top: offset.top, + bottom: offset.top + height + } + if(this.options.vertical){ + var yCenter = (dim[2] + dim[3]) / 2, + inUpperHalf = pointer.top <= yCenter + if(inUpperHalf){ + method = "before" + sameResultBox.bottom -= height / 2 + } else + sameResultBox.top += height / 2 + } else { + var xCenter = (dim[0] + dim[1]) / 2, + inLeftHalf = pointer.left <= xCenter + if(inLeftHalf){ + method = "before" + sameResultBox.right -= width / 2 + } else + sameResultBox.left += width / 2 + } + if(this.hasChildGroup(index)) + sameResultBox = emptyBox + this.rootGroup.movePlaceholder(this, item, method, sameResultBox) + }, + getItemDimensions: function () { + if(!this.itemDimensions){ + this.items = this.$getChildren(this.el, "item").filter(":not(.placeholder, .dragged)").get() + setDimensions(this.items, this.itemDimensions = [], this.options.tolerance) + } + return this.itemDimensions + }, + getItemOffsetParent: function () { + var offsetParent, + el = this.el + // Since el might be empty we have to check el itself and + // can not do something like el.children().first().offsetParent() + if(el.css("position") === "relative" || el.css("position") === "absolute" || el.css("position") === "fixed") + offsetParent = el + else + offsetParent = el.offsetParent() + return offsetParent + }, + hasChildGroup: function (index) { + return this.options.nested && this.getContainerGroup(index) + }, + getContainerGroup: function (index) { + var childGroup = $.data(this.items[index], subContainerKey) + if( childGroup === undefined){ + var childContainers = this.$getChildren(this.items[index], "container") + childGroup = false + + if(childContainers[0]){ + var options = $.extend({}, this.options, { + rootGroup: this.rootGroup, + group: groupCounter ++ + }) + childGroup = childContainers[pluginName](options).data(pluginName).group + } + $.data(this.items[index], subContainerKey, childGroup) + } + return childGroup + }, + $getChildren: function (parent, type) { + var options = this.rootGroup.options, + path = options[type + "Path"], + selector = options[type + "Selector"] + + parent = $(parent) + if(path) + parent = parent.find(path) + + return parent.children(selector) + }, + _serialize: function (parent, isContainer) { + var that = this, + childType = isContainer ? "item" : "container", + + children = this.$getChildren(parent, childType).not(this.options.exclude).map(function () { + return that._serialize($(this), !isContainer) + }).get() + + return this.rootGroup.options.serialize(parent, children, isContainer) + }, + traverse: function(callback) { + $.each(this.items || [], function(item){ + var group = $.data(this, subContainerKey) + if(group) + group.traverse(callback) + }); + + callback(this) + }, + _clearDimensions: function () { + this.itemDimensions = undefined + }, + _destroy: function() { + var that = this; + + this.target.off(eventNames.start, this.handle); + this.el.removeData(pluginName) + + if(this.options.drop) + this.group.containers = $.grep(this.group.containers, function(val){ + return val != that + }) + + $.each(this.items || [], function(){ + $.removeData(this, subContainerKey) + }) + } + } + + var API = { + enable: function() { + this.traverse(function(object){ + object.disabled = false + }) + }, + disable: function (){ + this.traverse(function(object){ + object.disabled = true + }) + }, + serialize: function () { + return this._serialize(this.el, true) + }, + refresh: function() { + this.traverse(function(object){ + object._clearDimensions() + }) + }, + destroy: function () { + this.traverse(function(object){ + object._destroy(); + }) + } + } + + $.extend(Container.prototype, API) + + /** + * jQuery API + * + * Parameters are + * either options on init + * or a method name followed by arguments to pass to the method + */ + $.fn[pluginName] = function(methodOrOptions) { + var args = Array.prototype.slice.call(arguments, 1) + + return this.map(function(){ + var $t = $(this), + object = $t.data(pluginName) + + if(object && API[methodOrOptions]) + return API[methodOrOptions].apply(object, args) || this + else if(!object && (methodOrOptions === undefined || + typeof methodOrOptions === "object")) + $t.data(pluginName, new Container($t, methodOrOptions)) + + return this + }); + }; + +}(jQuery, window, 'sortable'); diff --git a/admin/view/javascript/shopunity/charts_canvas/chart.js b/admin/view/javascript/shopunity/charts_canvas/chart.js new file mode 100755 index 0000000..ffbe16f --- /dev/null +++ b/admin/view/javascript/shopunity/charts_canvas/chart.js @@ -0,0 +1,1426 @@ +/*! + * Chart.js + * http://chartjs.org/ + * + * Copyright 2013 Nick Downie + * Released under the MIT license + * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md + */ + +//Define the global Chart Variable as a class. +window.Chart = function(context){ + + var chart = this; + + + //Easing functions adapted from Robert Penner's easing equations + //http://www.robertpenner.com/easing/ + + var animationOptions = { + linear : function (t){ + return t; + }, + easeInQuad: function (t) { + return t*t; + }, + easeOutQuad: function (t) { + return -1 *t*(t-2); + }, + easeInOutQuad: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t; + return -1/2 * ((--t)*(t-2) - 1); + }, + easeInCubic: function (t) { + return t*t*t; + }, + easeOutCubic: function (t) { + return 1*((t=t/1-1)*t*t + 1); + }, + easeInOutCubic: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t*t; + return 1/2*((t-=2)*t*t + 2); + }, + easeInQuart: function (t) { + return t*t*t*t; + }, + easeOutQuart: function (t) { + return -1 * ((t=t/1-1)*t*t*t - 1); + }, + easeInOutQuart: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t*t*t; + return -1/2 * ((t-=2)*t*t*t - 2); + }, + easeInQuint: function (t) { + return 1*(t/=1)*t*t*t*t; + }, + easeOutQuint: function (t) { + return 1*((t=t/1-1)*t*t*t*t + 1); + }, + easeInOutQuint: function (t) { + if ((t/=1/2) < 1) return 1/2*t*t*t*t*t; + return 1/2*((t-=2)*t*t*t*t + 2); + }, + easeInSine: function (t) { + return -1 * Math.cos(t/1 * (Math.PI/2)) + 1; + }, + easeOutSine: function (t) { + return 1 * Math.sin(t/1 * (Math.PI/2)); + }, + easeInOutSine: function (t) { + return -1/2 * (Math.cos(Math.PI*t/1) - 1); + }, + easeInExpo: function (t) { + return (t==0) ? 1 : 1 * Math.pow(2, 10 * (t/1 - 1)); + }, + easeOutExpo: function (t) { + return (t==1) ? 1 : 1 * (-Math.pow(2, -10 * t/1) + 1); + }, + easeInOutExpo: function (t) { + if (t==0) return 0; + if (t==1) return 1; + if ((t/=1/2) < 1) return 1/2 * Math.pow(2, 10 * (t - 1)); + return 1/2 * (-Math.pow(2, -10 * --t) + 2); + }, + easeInCirc: function (t) { + if (t>=1) return t; + return -1 * (Math.sqrt(1 - (t/=1)*t) - 1); + }, + easeOutCirc: function (t) { + return 1 * Math.sqrt(1 - (t=t/1-1)*t); + }, + easeInOutCirc: function (t) { + if ((t/=1/2) < 1) return -1/2 * (Math.sqrt(1 - t*t) - 1); + return 1/2 * (Math.sqrt(1 - (t-=2)*t) + 1); + }, + easeInElastic: function (t) { + var s=1.70158;var p=0;var a=1; + if (t==0) return 0; if ((t/=1)==1) return 1; if (!p) p=1*.3; + if (a < Math.abs(1)) { a=1; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (1/a); + return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )); + }, + easeOutElastic: function (t) { + var s=1.70158;var p=0;var a=1; + if (t==0) return 0; if ((t/=1)==1) return 1; if (!p) p=1*.3; + if (a < Math.abs(1)) { a=1; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (1/a); + return a*Math.pow(2,-10*t) * Math.sin( (t*1-s)*(2*Math.PI)/p ) + 1; + }, + easeInOutElastic: function (t) { + var s=1.70158;var p=0;var a=1; + if (t==0) return 0; if ((t/=1/2)==2) return 1; if (!p) p=1*(.3*1.5); + if (a < Math.abs(1)) { a=1; var s=p/4; } + else var s = p/(2*Math.PI) * Math.asin (1/a); + if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )); + return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*1-s)*(2*Math.PI)/p )*.5 + 1; + }, + easeInBack: function (t) { + var s = 1.70158; + return 1*(t/=1)*t*((s+1)*t - s); + }, + easeOutBack: function (t) { + var s = 1.70158; + return 1*((t=t/1-1)*t*((s+1)*t + s) + 1); + }, + easeInOutBack: function (t) { + var s = 1.70158; + if ((t/=1/2) < 1) return 1/2*(t*t*(((s*=(1.525))+1)*t - s)); + return 1/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2); + }, + easeInBounce: function (t) { + return 1 - animationOptions.easeOutBounce (1-t); + }, + easeOutBounce: function (t) { + if ((t/=1) < (1/2.75)) { + return 1*(7.5625*t*t); + } else if (t < (2/2.75)) { + return 1*(7.5625*(t-=(1.5/2.75))*t + .75); + } else if (t < (2.5/2.75)) { + return 1*(7.5625*(t-=(2.25/2.75))*t + .9375); + } else { + return 1*(7.5625*(t-=(2.625/2.75))*t + .984375); + } + }, + easeInOutBounce: function (t) { + if (t < 1/2) return animationOptions.easeInBounce (t*2) * .5; + return animationOptions.easeOutBounce (t*2-1) * .5 + 1*.5; + } + }; + + //Variables global to the chart + var width = context.canvas.width; + var height = context.canvas.height; + + + //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale. + if (window.devicePixelRatio) { + context.canvas.style.width = width + "px"; + context.canvas.style.height = height + "px"; + context.canvas.height = height * window.devicePixelRatio; + context.canvas.width = width * window.devicePixelRatio; + context.scale(window.devicePixelRatio, window.devicePixelRatio); + } + + this.PolarArea = function(data,options){ + + chart.PolarArea.defaults = { + scaleOverlay : true, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleShowLine : true, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : true, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowLabelBackdrop : true, + scaleBackdropColor : "rgba(255,255,255,0.75)", + scaleBackdropPaddingY : 2, + scaleBackdropPaddingX : 2, + segmentShowStroke : true, + segmentStrokeColor : "#fff", + segmentStrokeWidth : 2, + animation : true, + animationSteps : 100, + animationEasing : "easeOutBounce", + animateRotate : true, + animateScale : false, + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.PolarArea.defaults,options) : chart.PolarArea.defaults; + + return new PolarArea(data,config,context); + }; + + this.Radar = function(data,options){ + + chart.Radar.defaults = { + scaleOverlay : false, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleShowLine : true, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : false, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowLabelBackdrop : true, + scaleBackdropColor : "rgba(255,255,255,0.75)", + scaleBackdropPaddingY : 2, + scaleBackdropPaddingX : 2, + angleShowLineOut : true, + angleLineColor : "rgba(0,0,0,.1)", + angleLineWidth : 1, + pointLabelFontFamily : "'Arial'", + pointLabelFontStyle : "normal", + pointLabelFontSize : 12, + pointLabelFontColor : "#666", + pointDot : true, + pointDotRadius : 3, + pointDotStrokeWidth : 1, + datasetStroke : true, + datasetStrokeWidth : 2, + datasetFill : true, + animation : true, + animationSteps : 60, + animationEasing : "easeOutQuart", + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.Radar.defaults,options) : chart.Radar.defaults; + + return new Radar(data,config,context); + }; + + this.Pie = function(data,options){ + chart.Pie.defaults = { + segmentShowStroke : true, + segmentStrokeColor : "#fff", + segmentStrokeWidth : 2, + animation : true, + animationSteps : 100, + animationEasing : "easeOutBounce", + animateRotate : true, + animateScale : false, + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.Pie.defaults,options) : chart.Pie.defaults; + + return new Pie(data,config,context); + }; + + this.Doughnut = function(data,options){ + + chart.Doughnut.defaults = { + segmentShowStroke : true, + segmentStrokeColor : "#fff", + segmentStrokeWidth : 2, + percentageInnerCutout : 50, + animation : true, + animationSteps : 100, + animationEasing : "easeOutBounce", + animateRotate : true, + animateScale : false, + onAnimationComplete : null + }; + + var config = (options)? mergeChartConfig(chart.Doughnut.defaults,options) : chart.Doughnut.defaults; + + return new Doughnut(data,config,context); + + }; + + this.Line = function(data,options){ + + chart.Line.defaults = { + scaleOverlay : false, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : true, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowGridLines : true, + scaleGridLineColor : "rgba(0,0,0,.05)", + scaleGridLineWidth : 1, + bezierCurve : true, + pointDot : true, + pointDotRadius : 4, + pointDotStrokeWidth : 2, + datasetStroke : true, + datasetStrokeWidth : 2, + datasetFill : true, + animation : true, + animationSteps : 60, + animationEasing : "easeOutQuart", + onAnimationComplete : null + }; + var config = (options) ? mergeChartConfig(chart.Line.defaults,options) : chart.Line.defaults; + + return new Line(data,config,context); + } + + this.Bar = function(data,options){ + chart.Bar.defaults = { + scaleOverlay : false, + scaleOverride : false, + scaleSteps : null, + scaleStepWidth : null, + scaleStartValue : null, + scaleLineColor : "rgba(0,0,0,.1)", + scaleLineWidth : 1, + scaleShowLabels : true, + scaleLabel : "<%=value%>", + scaleFontFamily : "'Arial'", + scaleFontSize : 12, + scaleFontStyle : "normal", + scaleFontColor : "#666", + scaleShowGridLines : true, + scaleGridLineColor : "rgba(0,0,0,.05)", + scaleGridLineWidth : 1, + barShowStroke : true, + barStrokeWidth : 2, + barValueSpacing : 5, + barDatasetSpacing : 1, + animation : true, + animationSteps : 60, + animationEasing : "easeOutQuart", + onAnimationComplete : null + }; + var config = (options) ? mergeChartConfig(chart.Bar.defaults,options) : chart.Bar.defaults; + + return new Bar(data,config,context); + } + + var clear = function(c){ + c.clearRect(0, 0, width, height); + }; + + var PolarArea = function(data,config,ctx){ + var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString; + + + calculateDrawingSizes(); + + valueBounds = getValueBounds(); + + labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null; + + //Check and set the scale + if (!config.scaleOverride){ + + calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); + } + else { + calculatedScale = { + steps : config.scaleSteps, + stepValue : config.scaleStepWidth, + graphMin : config.scaleStartValue, + labels : [] + } + populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); + } + + scaleHop = maxSize/(calculatedScale.steps); + + //Wrap in an animation loop wrapper + animationLoop(config,drawScale,drawAllSegments,ctx); + + function calculateDrawingSizes(){ + maxSize = (Min([width,height])/2); + //Remove whatever is larger - the font size or line width. + + maxSize -= Max([config.scaleFontSize*0.5,config.scaleLineWidth*0.5]); + + labelHeight = config.scaleFontSize*2; + //If we're drawing the backdrop - add the Y padding to the label height and remove from drawing region. + if (config.scaleShowLabelBackdrop){ + labelHeight += (2 * config.scaleBackdropPaddingY); + maxSize -= config.scaleBackdropPaddingY*1.5; + } + + scaleHeight = maxSize; + //If the label height is less than 5, set it to 5 so we don't have lines on top of each other. + labelHeight = Default(labelHeight,5); + } + function drawScale(){ + for (var i=0; i upperValue) {upperValue = data[i].value;} + if (data[i].value < lowerValue) {lowerValue = data[i].value;} + }; + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + } + + var Radar = function (data,config,ctx) { + var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString; + + //If no labels are defined set to an empty array, so referencing length for looping doesn't blow up. + if (!data.labels) data.labels = []; + + calculateDrawingSizes(); + + var valueBounds = getValueBounds(); + + labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : null; + + //Check and set the scale + if (!config.scaleOverride){ + + calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); + } + else { + calculatedScale = { + steps : config.scaleSteps, + stepValue : config.scaleStepWidth, + graphMin : config.scaleStartValue, + labels : [] + } + populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); + } + + scaleHop = maxSize/(calculatedScale.steps); + + animationLoop(config,drawScale,drawAllDataPoints,ctx); + + //Radar specific functions. + function drawAllDataPoints(animationDecimal){ + var rotationDegree = (2*Math.PI)/data.datasets[0].data.length; + + ctx.save(); + //translate to the centre of the canvas. + ctx.translate(width/2,height/2); + + //We accept multiple data sets for radar charts, so show loop through each set + for (var i=0; i Math.PI){ + ctx.textAlign = "right"; + } + else{ + ctx.textAlign = "left"; + } + + ctx.textBaseline = "middle"; + + ctx.fillText(data.labels[k],opposite,-adjacent); + + } + ctx.restore(); + }; + function calculateDrawingSizes(){ + maxSize = (Min([width,height])/2); + + labelHeight = config.scaleFontSize*2; + + var labelLength = 0; + for (var i=0; ilabelLength) labelLength = textMeasurement; + } + + //Figure out whats the largest - the height of the text or the width of what's there, and minus it from the maximum usable size. + maxSize -= Max([labelLength,((config.pointLabelFontSize/2)*1.5)]); + + maxSize -= config.pointLabelFontSize; + maxSize = CapValue(maxSize, null, 0); + scaleHeight = maxSize; + //If the label height is less than 5, set it to 5 so we don't have lines on top of each other. + labelHeight = Default(labelHeight,5); + }; + function getValueBounds() { + var upperValue = Number.MIN_VALUE; + var lowerValue = Number.MAX_VALUE; + + for (var i=0; i upperValue){upperValue = data.datasets[i].data[j]} + if (data.datasets[i].data[j] < lowerValue){lowerValue = data.datasets[i].data[j]} + } + } + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + } + + var Pie = function(data,config,ctx){ + var segmentTotal = 0; + + //In case we have a canvas that is not a square. Minus 5 pixels as padding round the edge. + var pieRadius = Min([height/2,width/2]) - 5; + + for (var i=0; i 0){ + ctx.save(); + ctx.textAlign = "right"; + } + else{ + ctx.textAlign = "center"; + } + ctx.fillStyle = config.scaleFontColor; + for (var i=0; i 0){ + ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize); + ctx.rotate(-(rotateLabels * (Math.PI/180))); + ctx.fillText(data.labels[i], 0,0); + ctx.restore(); + } + + else{ + ctx.fillText(data.labels[i], yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize+3); + } + + ctx.beginPath(); + ctx.moveTo(yAxisPosX + i * valueHop, xAxisPosY+3); + + //Check i isnt 0, so we dont go over the Y axis twice. + if(config.scaleShowGridLines && i>0){ + ctx.lineWidth = config.scaleGridLineWidth; + ctx.strokeStyle = config.scaleGridLineColor; + ctx.lineTo(yAxisPosX + i * valueHop, 5); + } + else{ + ctx.lineTo(yAxisPosX + i * valueHop, xAxisPosY+3); + } + ctx.stroke(); + } + + //Y axis + ctx.lineWidth = config.scaleLineWidth; + ctx.strokeStyle = config.scaleLineColor; + ctx.beginPath(); + ctx.moveTo(yAxisPosX,xAxisPosY+5); + ctx.lineTo(yAxisPosX,5); + ctx.stroke(); + + ctx.textAlign = "right"; + ctx.textBaseline = "middle"; + for (var j=0; j longestText)? measuredText : longestText; + } + //Add a little extra padding from the y axis + longestText +=10; + } + xAxisLength = width - longestText - widestXLabel; + valueHop = Math.floor(xAxisLength/(data.labels.length-1)); + + yAxisPosX = width-widestXLabel/2-xAxisLength; + xAxisPosY = scaleHeight + config.scaleFontSize/2; + } + function calculateDrawingSizes(){ + maxSize = height; + + //Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees. + ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; + widestXLabel = 1; + for (var i=0; i widestXLabel)? textLength : widestXLabel; + } + if (width/data.labels.length < widestXLabel){ + rotateLabels = 45; + if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){ + rotateLabels = 90; + maxSize -= widestXLabel; + } + else{ + maxSize -= Math.sin(rotateLabels) * widestXLabel; + } + } + else{ + maxSize -= config.scaleFontSize; + } + + //Add a little padding between the x line and the text + maxSize -= 5; + + + labelHeight = config.scaleFontSize; + + maxSize -= labelHeight; + //Set 5 pixels greater than the font size to allow for a little padding from the X axis. + + scaleHeight = maxSize; + + //Then get the area above we can safely draw on. + + } + function getValueBounds() { + var upperValue = Number.MIN_VALUE; + var lowerValue = Number.MAX_VALUE; + for (var i=0; i upperValue) { upperValue = data.datasets[i].data[j] }; + if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] }; + } + }; + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + + + } + + var Bar = function(data,config,ctx){ + var maxSize, scaleHop, calculatedScale, labelHeight, scaleHeight, valueBounds, labelTemplateString, valueHop,widestXLabel, xAxisLength,yAxisPosX,xAxisPosY,barWidth, rotateLabels = 0; + + calculateDrawingSizes(); + + valueBounds = getValueBounds(); + //Check and set the scale + labelTemplateString = (config.scaleShowLabels)? config.scaleLabel : ""; + if (!config.scaleOverride){ + + calculatedScale = calculateScale(scaleHeight,valueBounds.maxSteps,valueBounds.minSteps,valueBounds.maxValue,valueBounds.minValue,labelTemplateString); + } + else { + calculatedScale = { + steps : config.scaleSteps, + stepValue : config.scaleStepWidth, + graphMin : config.scaleStartValue, + labels : [] + } + populateLabels(labelTemplateString, calculatedScale.labels,calculatedScale.steps,config.scaleStartValue,config.scaleStepWidth); + } + + scaleHop = Math.floor(scaleHeight/calculatedScale.steps); + calculateXAxisSize(); + animationLoop(config,drawScale,drawBars,ctx); + + function drawBars(animPc){ + ctx.lineWidth = config.barStrokeWidth; + for (var i=0; i 0){ + ctx.save(); + ctx.textAlign = "right"; + } + else{ + ctx.textAlign = "center"; + } + ctx.fillStyle = config.scaleFontColor; + for (var i=0; i 0){ + ctx.translate(yAxisPosX + i*valueHop,xAxisPosY + config.scaleFontSize); + ctx.rotate(-(rotateLabels * (Math.PI/180))); + ctx.fillText(data.labels[i], 0,0); + ctx.restore(); + } + + else{ + ctx.fillText(data.labels[i], yAxisPosX + i*valueHop + valueHop/2,xAxisPosY + config.scaleFontSize+3); + } + + ctx.beginPath(); + ctx.moveTo(yAxisPosX + (i+1) * valueHop, xAxisPosY+3); + + //Check i isnt 0, so we dont go over the Y axis twice. + ctx.lineWidth = config.scaleGridLineWidth; + ctx.strokeStyle = config.scaleGridLineColor; + ctx.lineTo(yAxisPosX + (i+1) * valueHop, 5); + ctx.stroke(); + } + + //Y axis + ctx.lineWidth = config.scaleLineWidth; + ctx.strokeStyle = config.scaleLineColor; + ctx.beginPath(); + ctx.moveTo(yAxisPosX,xAxisPosY+5); + ctx.lineTo(yAxisPosX,5); + ctx.stroke(); + + ctx.textAlign = "right"; + ctx.textBaseline = "middle"; + for (var j=0; j longestText)? measuredText : longestText; + } + //Add a little extra padding from the y axis + longestText +=10; + } + xAxisLength = width - longestText - widestXLabel; + valueHop = Math.floor(xAxisLength/(data.labels.length)); + + barWidth = (valueHop - config.scaleGridLineWidth*2 - (config.barValueSpacing*2) - (config.barDatasetSpacing*data.datasets.length-1) - ((config.barStrokeWidth/2)*data.datasets.length-1))/data.datasets.length; + + yAxisPosX = width-widestXLabel/2-xAxisLength; + xAxisPosY = scaleHeight + config.scaleFontSize/2; + } + function calculateDrawingSizes(){ + maxSize = height; + + //Need to check the X axis first - measure the length of each text metric, and figure out if we need to rotate by 45 degrees. + ctx.font = config.scaleFontStyle + " " + config.scaleFontSize+"px " + config.scaleFontFamily; + widestXLabel = 1; + for (var i=0; i widestXLabel)? textLength : widestXLabel; + } + if (width/data.labels.length < widestXLabel){ + rotateLabels = 45; + if (width/data.labels.length < Math.cos(rotateLabels) * widestXLabel){ + rotateLabels = 90; + maxSize -= widestXLabel; + } + else{ + maxSize -= Math.sin(rotateLabels) * widestXLabel; + } + } + else{ + maxSize -= config.scaleFontSize; + } + + //Add a little padding between the x line and the text + maxSize -= 5; + + + labelHeight = config.scaleFontSize; + + maxSize -= labelHeight; + //Set 5 pixels greater than the font size to allow for a little padding from the X axis. + + scaleHeight = maxSize; + + //Then get the area above we can safely draw on. + + } + function getValueBounds() { + var upperValue = Number.MIN_VALUE; + var lowerValue = Number.MAX_VALUE; + for (var i=0; i upperValue) { upperValue = data.datasets[i].data[j] }; + if ( data.datasets[i].data[j] < lowerValue) { lowerValue = data.datasets[i].data[j] }; + } + }; + + var maxSteps = Math.floor((scaleHeight / (labelHeight*0.66))); + var minSteps = Math.floor((scaleHeight / labelHeight*0.5)); + + return { + maxValue : upperValue, + minValue : lowerValue, + maxSteps : maxSteps, + minSteps : minSteps + }; + + + } + } + + function calculateOffset(val,calculatedScale,scaleHop){ + var outerValue = calculatedScale.steps * calculatedScale.stepValue; + var adjustedValue = val - calculatedScale.graphMin; + var scalingFactor = CapValue(adjustedValue/outerValue,1,0); + return (scaleHop*calculatedScale.steps) * scalingFactor; + } + + function animationLoop(config,drawScale,drawData,ctx){ + var animFrameAmount = (config.animation)? 1/CapValue(config.animationSteps,Number.MAX_VALUE,1) : 1, + easingFunction = animationOptions[config.animationEasing], + percentAnimComplete =(config.animation)? 0 : 1; + + + + if (typeof drawScale !== "function") drawScale = function(){}; + + requestAnimFrame(animLoop); + + function animateFrame(){ + var easeAdjustedAnimationPercent =(config.animation)? CapValue(easingFunction(percentAnimComplete),null,0) : 1; + clear(ctx); + if(config.scaleOverlay){ + drawData(easeAdjustedAnimationPercent); + drawScale(); + } else { + drawScale(); + drawData(easeAdjustedAnimationPercent); + } + } + function animLoop(){ + //We need to check if the animation is incomplete (less than 1), or complete (1). + percentAnimComplete += animFrameAmount; + animateFrame(); + //Stop the loop continuing forever + if (percentAnimComplete <= 1){ + requestAnimFrame(animLoop); + } + else{ + if (typeof config.onAnimationComplete == "function") config.onAnimationComplete(); + } + + } + + } + + //Declare global functions to be called within this namespace here. + + + // shim layer with setTimeout fallback + var requestAnimFrame = (function(){ + return window.requestAnimationFrame || + window.webkitRequestAnimationFrame || + window.mozRequestAnimationFrame || + window.oRequestAnimationFrame || + window.msRequestAnimationFrame || + function(callback) { + window.setTimeout(callback, 1000 / 60); + }; + })(); + + function calculateScale(drawingHeight,maxSteps,minSteps,maxValue,minValue,labelTemplateString){ + var graphMin,graphMax,graphRange,stepValue,numberOfSteps,valueRange,rangeOrderOfMagnitude,decimalNum; + + valueRange = maxValue - minValue; + + rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange); + + graphMin = Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude); + + graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude); + + graphRange = graphMax - graphMin; + + stepValue = Math.pow(10, rangeOrderOfMagnitude); + + numberOfSteps = Math.round(graphRange / stepValue); + + //Compare number of steps to the max and min for that size graph, and add in half steps if need be. + while(numberOfSteps < minSteps || numberOfSteps > maxSteps) { + if (numberOfSteps < minSteps){ + stepValue /= 2; + numberOfSteps = Math.round(graphRange/stepValue); + } + else{ + stepValue *=2; + numberOfSteps = Math.round(graphRange/stepValue); + } + }; + + var labels = []; + populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue); + + return { + steps : numberOfSteps, + stepValue : stepValue, + graphMin : graphMin, + labels : labels + + } + + function calculateOrderOfMagnitude(val){ + return Math.floor(Math.log(val) / Math.LN10); + } + + + } + + //Populate an array of all the labels by interpolating the string. + function populateLabels(labelTemplateString, labels, numberOfSteps, graphMin, stepValue) { + if (labelTemplateString) { + //Fix floating point errors by setting to fixed the on the same decimal as the stepValue. + for (var i = 1; i < numberOfSteps + 1; i++) { + labels.push(tmpl(labelTemplateString, {value: (graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))})); + } + } + } + + //Max value from array + function Max( array ){ + return Math.max.apply( Math, array ); + }; + //Min value from array + function Min( array ){ + return Math.min.apply( Math, array ); + }; + //Default if undefined + function Default(userDeclared,valueIfFalse){ + if(!userDeclared){ + return valueIfFalse; + } else { + return userDeclared; + } + }; + //Is a number function + function isNumber(n) { + return !isNaN(parseFloat(n)) && isFinite(n); + } + //Apply cap a value at a high or low number + function CapValue(valueToCap, maxValue, minValue){ + if(isNumber(maxValue)) { + if( valueToCap > maxValue ) { + return maxValue; + } + } + if(isNumber(minValue)){ + if ( valueToCap < minValue ){ + return minValue; + } + } + return valueToCap; + } + function getDecimalPlaces (num){ + var numberOfDecimalPlaces; + if (num%1!=0){ + return num.toString().split(".")[1].length + } + else{ + return 0; + } + + } + + function mergeChartConfig(defaults,userDefined){ + var returnObj = {}; + for (var attrname in defaults) { returnObj[attrname] = defaults[attrname]; } + for (var attrname in userDefined) { returnObj[attrname] = userDefined[attrname]; } + return returnObj; + } + + //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/ + var cache = {}; + + function tmpl(str, data){ + // Figure out if we're getting a template, or if we need to + // load the template - and be sure to cache the result. + var fn = !/\W/.test(str) ? + cache[str] = cache[str] || + tmpl(document.getElementById(str).innerHTML) : + + // Generate a reusable function that will serve as a template + // generator (and which will be cached). + new Function("obj", + "var p=[],print=function(){p.push.apply(p,arguments);};" + + + // Introduce the data as local variables using with(){} + "with(obj){p.push('" + + + // Convert the template into pure JavaScript + str + .replace(/[\r\t\n]/g, " ") + .split("<%").join("\t") + .replace(/((^|%>)[^\t]*)'/g, "$1\r") + .replace(/\t=(.*?)%>/g, "',$1,'") + .split("\t").join("');") + .split("%>").join("p.push('") + .split("\r").join("\\'") + + "');}return p.join('');"); + + // Provide some basic currying to the user + return data ? fn( data ) : fn; + }; +} + + diff --git a/admin/view/javascript/shopunity/charts_canvas/chart.min.js b/admin/view/javascript/shopunity/charts_canvas/chart.min.js new file mode 100755 index 0000000..ab63588 --- /dev/null +++ b/admin/view/javascript/shopunity/charts_canvas/chart.min.js @@ -0,0 +1,39 @@ +var Chart=function(s){function v(a,c,b){a=A((a-c.graphMin)/(c.steps*c.stepValue),1,0);return b*c.steps*a}function x(a,c,b,e){function h(){g+=f;var k=a.animation?A(d(g),null,0):1;e.clearRect(0,0,q,u);a.scaleOverlay?(b(k),c()):(c(),b(k));if(1>=g)D(h);else if("function"==typeof a.onAnimationComplete)a.onAnimationComplete()}var f=a.animation?1/A(a.animationSteps,Number.MAX_VALUE,1):1,d=B[a.animationEasing],g=a.animation?0:1;"function"!==typeof c&&(c=function(){});D(h)}function C(a,c,b,e,h,f){var d;a= +Math.floor(Math.log(e-h)/Math.LN10);h=Math.floor(h/(1*Math.pow(10,a)))*Math.pow(10,a);e=Math.ceil(e/(1*Math.pow(10,a)))*Math.pow(10,a)-h;a=Math.pow(10,a);for(d=Math.round(e/a);dc;)a=dc?c:!isNaN(parseFloat(b))&& +isFinite(b)&&a)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return c? +b(c):b}var r=this,B={linear:function(a){return a},easeInQuad:function(a){return a*a},easeOutQuad:function(a){return-1*a*(a-2)},easeInOutQuad:function(a){return 1>(a/=0.5)?0.5*a*a:-0.5*(--a*(a-2)-1)},easeInCubic:function(a){return a*a*a},easeOutCubic:function(a){return 1*((a=a/1-1)*a*a+1)},easeInOutCubic:function(a){return 1>(a/=0.5)?0.5*a*a*a:0.5*((a-=2)*a*a+2)},easeInQuart:function(a){return a*a*a*a},easeOutQuart:function(a){return-1*((a=a/1-1)*a*a*a-1)},easeInOutQuart:function(a){return 1>(a/=0.5)? +0.5*a*a*a*a:-0.5*((a-=2)*a*a*a-2)},easeInQuint:function(a){return 1*(a/=1)*a*a*a*a},easeOutQuint:function(a){return 1*((a=a/1-1)*a*a*a*a+1)},easeInOutQuint:function(a){return 1>(a/=0.5)?0.5*a*a*a*a*a:0.5*((a-=2)*a*a*a*a+2)},easeInSine:function(a){return-1*Math.cos(a/1*(Math.PI/2))+1},easeOutSine:function(a){return 1*Math.sin(a/1*(Math.PI/2))},easeInOutSine:function(a){return-0.5*(Math.cos(Math.PI*a/1)-1)},easeInExpo:function(a){return 0==a?1:1*Math.pow(2,10*(a/1-1))},easeOutExpo:function(a){return 1== +a?1:1*(-Math.pow(2,-10*a/1)+1)},easeInOutExpo:function(a){return 0==a?0:1==a?1:1>(a/=0.5)?0.5*Math.pow(2,10*(a-1)):0.5*(-Math.pow(2,-10*--a)+2)},easeInCirc:function(a){return 1<=a?a:-1*(Math.sqrt(1-(a/=1)*a)-1)},easeOutCirc:function(a){return 1*Math.sqrt(1-(a=a/1-1)*a)},easeInOutCirc:function(a){return 1>(a/=0.5)?-0.5*(Math.sqrt(1-a*a)-1):0.5*(Math.sqrt(1-(a-=2)*a)+1)},easeInElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);ea?-0.5*e*Math.pow(2,10* +(a-=1))*Math.sin((1*a-c)*2*Math.PI/b):0.5*e*Math.pow(2,-10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInBack:function(a){return 1*(a/=1)*a*(2.70158*a-1.70158)},easeOutBack:function(a){return 1*((a=a/1-1)*a*(2.70158*a+1.70158)+1)},easeInOutBack:function(a){var c=1.70158;return 1>(a/=0.5)?0.5*a*a*(((c*=1.525)+1)*a-c):0.5*((a-=2)*a*(((c*=1.525)+1)*a+c)+2)},easeInBounce:function(a){return 1-B.easeOutBounce(1-a)},easeOutBounce:function(a){return(a/=1)<1/2.75?1*7.5625*a*a:a<2/2.75?1*(7.5625*(a-=1.5/2.75)* +a+0.75):a<2.5/2.75?1*(7.5625*(a-=2.25/2.75)*a+0.9375):1*(7.5625*(a-=2.625/2.75)*a+0.984375)},easeInOutBounce:function(a){return 0.5>a?0.5*B.easeInBounce(2*a):0.5*B.easeOutBounce(2*a-1)+0.5}},q=s.canvas.width,u=s.canvas.height;window.devicePixelRatio&&(s.canvas.style.width=q+"px",s.canvas.style.height=u+"px",s.canvas.height=u*window.devicePixelRatio,s.canvas.width=q*window.devicePixelRatio,s.scale(window.devicePixelRatio,window.devicePixelRatio));this.PolarArea=function(a,c){r.PolarArea.defaults={scaleOverlay:!0, +scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce", +animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.PolarArea.defaults,c):r.PolarArea.defaults;return new G(a,b,s)};this.Radar=function(a,c){r.Radar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!1,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)", +scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,angleShowLineOut:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:12,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Radar.defaults,c):r.Radar.defaults;return new H(a,b,s)};this.Pie=function(a, +c){r.Pie.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.Pie.defaults,c):r.Pie.defaults;return new I(a,b,s)};this.Doughnut=function(a,c){r.Doughnut.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1, +onAnimationComplete:null};var b=c?y(r.Doughnut.defaults,c):r.Doughnut.defaults;return new J(a,b,s)};this.Line=function(a,c){r.Line.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,bezierCurve:!0, +pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:2,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Line.defaults,c):r.Line.defaults;return new K(a,b,s)};this.Bar=function(a,c){r.Bar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'", +scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Bar.defaults,c):r.Bar.defaults;return new L(a,b,s)};var G=function(a,c,b){var e,h,f,d,g,k,j,l,m;g=Math.min.apply(Math,[q,u])/2;g-=Math.max.apply(Math,[0.5*c.scaleFontSize,0.5*c.scaleLineWidth]); +d=2*c.scaleFontSize;c.scaleShowLabelBackdrop&&(d+=2*c.scaleBackdropPaddingY,g-=1.5*c.scaleBackdropPaddingY);l=g;d=d?d:5;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;fe&&(e=a[f].value),a[f].valuel&&(l=h);g-=Math.max.apply(Math,[l,1.5*(c.pointLabelFontSize/2)]);g-=c.pointLabelFontSize;l=g=A(g,null,0);d=d?d:5;e=Number.MIN_VALUE; +h=Number.MAX_VALUE;for(f=0;fe&&(e=a.datasets[f].data[m]),a.datasets[f].data[m]Math.PI?"right":"left";b.textBaseline="middle";b.fillText(a.labels[d],f,-h)}b.restore()},function(d){var e=2*Math.PI/a.datasets[0].data.length;b.save();b.translate(q/2,u/2);for(var g=0;gt?e:t;q/a.labels.lengthe&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]d?h:d;d+=10}r=q-d-t;m=Math.floor(r/(a.labels.length-1));n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0t?e:t;q/a.labels.lengthe&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]< +h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;for(e=0;ed?h:d;d+=10}r=q-d-t;m= +Math.floor(r/a.labels.length);s=(m-2*c.scaleGridLineWidth-2*c.barValueSpacing-(c.barDatasetSpacing*a.datasets.length-1)-(c.barStrokeWidth/2*a.datasets.length-1))/a.datasets.length;n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0= x for v in + // a[i:hi] for the right side. + function bisectLeft(a, x, lo, hi) { + while (lo < hi) { + var mid = lo + hi >>> 1; + if (f(a[mid]) < x) lo = mid + 1; + else hi = mid; + } + return lo; + } + + // Similar to bisectLeft, but returns an insertion point which comes after (to + // the right of) any existing entries of x in a. + // + // The returned insertion point i partitions the array into two halves so that + // all v <= x for v in a[lo:i] for the left side and all v > x for v in + // a[i:hi] for the right side. + function bisectRight(a, x, lo, hi) { + while (lo < hi) { + var mid = lo + hi >>> 1; + if (x < f(a[mid])) hi = mid; + else lo = mid + 1; + } + return lo; + } + + bisectRight.right = bisectRight; + bisectRight.left = bisectLeft; + return bisectRight; +} +var heap = crossfilter.heap = heap_by(crossfilter_identity); + +heap.by = heap_by; + +function heap_by(f) { + + // Builds a binary heap within the specified array a[lo:hi]. The heap has the + // property such that the parent a[lo+i] is always less than or equal to its + // two children: a[lo+2*i+1] and a[lo+2*i+2]. + function heap(a, lo, hi) { + var n = hi - lo, + i = (n >>> 1) + 1; + while (--i > 0) sift(a, i, n, lo); + return a; + } + + // Sorts the specified array a[lo:hi] in descending order, assuming it is + // already a heap. + function sort(a, lo, hi) { + var n = hi - lo, + t; + while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo); + return a; + } + + // Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous + // slice of array a[lo:lo+n]. This method can also be used to update the heap + // incrementally, without incurring the full cost of reconstructing the heap. + function sift(a, i, n, lo) { + var d = a[--lo + i], + x = f(d), + child; + while ((child = i << 1) <= n) { + if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++; + if (x <= f(a[lo + child])) break; + a[lo + i] = a[lo + child]; + i = child; + } + a[lo + i] = d; + } + + heap.sort = sort; + return heap; +} +var heapselect = crossfilter.heapselect = heapselect_by(crossfilter_identity); + +heapselect.by = heapselect_by; + +function heapselect_by(f) { + var heap = heap_by(f); + + // Returns a new array containing the top k elements in the array a[lo:hi]. + // The returned array is not sorted, but maintains the heap property. If k is + // greater than hi - lo, then fewer than k elements will be returned. The + // order of elements in a is unchanged by this operation. + function heapselect(a, lo, hi, k) { + var queue = new Array(k = Math.min(hi - lo, k)), + min, + i, + x, + d; + + for (i = 0; i < k; ++i) queue[i] = a[lo++]; + heap(queue, 0, k); + + if (lo < hi) { + min = f(queue[0]); + do { + if (x = f(d = a[lo]) > min) { + queue[0] = d; + min = f(heap(queue, 0, k)[0]); + } + } while (++lo < hi); + } + + return queue; + } + + return heapselect; +} +var insertionsort = crossfilter.insertionsort = insertionsort_by(crossfilter_identity); + +insertionsort.by = insertionsort_by; + +function insertionsort_by(f) { + + function insertionsort(a, lo, hi) { + for (var i = lo + 1; i < hi; ++i) { + for (var j = i, t = a[i], x = f(t); j > lo && f(a[j - 1]) > x; --j) { + a[j] = a[j - 1]; + } + a[j] = t; + } + return a; + } + + return insertionsort; +} +// Algorithm designed by Vladimir Yaroslavskiy. +// Implementation based on the Dart project; see lib/dart/LICENSE for details. + +var quicksort = crossfilter.quicksort = quicksort_by(crossfilter_identity); + +quicksort.by = quicksort_by; + +function quicksort_by(f) { + var insertionsort = insertionsort_by(f); + + function sort(a, lo, hi) { + return (hi - lo < quicksort_sizeThreshold + ? insertionsort + : quicksort)(a, lo, hi); + } + + function quicksort(a, lo, hi) { + // Compute the two pivots by looking at 5 elements. + var sixth = (hi - lo) / 6 | 0, + i1 = lo + sixth, + i5 = hi - 1 - sixth, + i3 = lo + hi - 1 >> 1, // The midpoint. + i2 = i3 - sixth, + i4 = i3 + sixth; + + var e1 = a[i1], x1 = f(e1), + e2 = a[i2], x2 = f(e2), + e3 = a[i3], x3 = f(e3), + e4 = a[i4], x4 = f(e4), + e5 = a[i5], x5 = f(e5); + + var t; + + // Sort the selected 5 elements using a sorting network. + if (x1 > x2) t = e1, e1 = e2, e2 = t, t = x1, x1 = x2, x2 = t; + if (x4 > x5) t = e4, e4 = e5, e5 = t, t = x4, x4 = x5, x5 = t; + if (x1 > x3) t = e1, e1 = e3, e3 = t, t = x1, x1 = x3, x3 = t; + if (x2 > x3) t = e2, e2 = e3, e3 = t, t = x2, x2 = x3, x3 = t; + if (x1 > x4) t = e1, e1 = e4, e4 = t, t = x1, x1 = x4, x4 = t; + if (x3 > x4) t = e3, e3 = e4, e4 = t, t = x3, x3 = x4, x4 = t; + if (x2 > x5) t = e2, e2 = e5, e5 = t, t = x2, x2 = x5, x5 = t; + if (x2 > x3) t = e2, e2 = e3, e3 = t, t = x2, x2 = x3, x3 = t; + if (x4 > x5) t = e4, e4 = e5, e5 = t, t = x4, x4 = x5, x5 = t; + + var pivot1 = e2, pivotValue1 = x2, + pivot2 = e4, pivotValue2 = x4; + + // e2 and e4 have been saved in the pivot variables. They will be written + // back, once the partitioning is finished. + a[i1] = e1; + a[i2] = a[lo]; + a[i3] = e3; + a[i4] = a[hi - 1]; + a[i5] = e5; + + var less = lo + 1, // First element in the middle partition. + great = hi - 2; // Last element in the middle partition. + + // Note that for value comparison, <, <=, >= and > coerce to a primitive via + // Object.prototype.valueOf; == and === do not, so in order to be consistent + // with natural order (such as for Date objects), we must do two compares. + var pivotsEqual = pivotValue1 <= pivotValue2 && pivotValue1 >= pivotValue2; + if (pivotsEqual) { + + // Degenerated case where the partitioning becomes a dutch national flag + // problem. + // + // [ | < pivot | == pivot | unpartitioned | > pivot | ] + // ^ ^ ^ ^ ^ + // left less k great right + // + // a[left] and a[right] are undefined and are filled after the + // partitioning. + // + // Invariants: + // 1) for x in ]left, less[ : x < pivot. + // 2) for x in [less, k[ : x == pivot. + // 3) for x in ]great, right[ : x > pivot. + for (var k = less; k <= great; ++k) { + var ek = a[k], xk = f(ek); + if (xk < pivotValue1) { + if (k !== less) { + a[k] = a[less]; + a[less] = ek; + } + ++less; + } else if (xk > pivotValue1) { + + // Find the first element <= pivot in the range [k - 1, great] and + // put [:ek:] there. We know that such an element must exist: + // When k == less, then el3 (which is equal to pivot) lies in the + // interval. Otherwise a[k - 1] == pivot and the search stops at k-1. + // Note that in the latter case invariant 2 will be violated for a + // short amount of time. The invariant will be restored when the + // pivots are put into their final positions. + while (true) { + var greatValue = f(a[great]); + if (greatValue > pivotValue1) { + great--; + // This is the only location in the while-loop where a new + // iteration is started. + continue; + } else if (greatValue < pivotValue1) { + // Triple exchange. + a[k] = a[less]; + a[less++] = a[great]; + a[great--] = ek; + break; + } else { + a[k] = a[great]; + a[great--] = ek; + // Note: if great < k then we will exit the outer loop and fix + // invariant 2 (which we just violated). + break; + } + } + } + } + } else { + + // We partition the list into three parts: + // 1. < pivot1 + // 2. >= pivot1 && <= pivot2 + // 3. > pivot2 + // + // During the loop we have: + // [ | < pivot1 | >= pivot1 && <= pivot2 | unpartitioned | > pivot2 | ] + // ^ ^ ^ ^ ^ + // left less k great right + // + // a[left] and a[right] are undefined and are filled after the + // partitioning. + // + // Invariants: + // 1. for x in ]left, less[ : x < pivot1 + // 2. for x in [less, k[ : pivot1 <= x && x <= pivot2 + // 3. for x in ]great, right[ : x > pivot2 + for (var k = less; k <= great; k++) { + var ek = a[k], xk = f(ek); + if (xk < pivotValue1) { + if (k !== less) { + a[k] = a[less]; + a[less] = ek; + } + ++less; + } else { + if (xk > pivotValue2) { + while (true) { + var greatValue = f(a[great]); + if (greatValue > pivotValue2) { + great--; + if (great < k) break; + // This is the only location inside the loop where a new + // iteration is started. + continue; + } else { + // a[great] <= pivot2. + if (greatValue < pivotValue1) { + // Triple exchange. + a[k] = a[less]; + a[less++] = a[great]; + a[great--] = ek; + } else { + // a[great] >= pivot1. + a[k] = a[great]; + a[great--] = ek; + } + break; + } + } + } + } + } + } + + // Move pivots into their final positions. + // We shrunk the list from both sides (a[left] and a[right] have + // meaningless values in them) and now we move elements from the first + // and third partition into these locations so that we can store the + // pivots. + a[lo] = a[less - 1]; + a[less - 1] = pivot1; + a[hi - 1] = a[great + 1]; + a[great + 1] = pivot2; + + // The list is now partitioned into three partitions: + // [ < pivot1 | >= pivot1 && <= pivot2 | > pivot2 ] + // ^ ^ ^ ^ + // left less great right + + // Recursive descent. (Don't include the pivot values.) + sort(a, lo, less - 1); + sort(a, great + 2, hi); + + if (pivotsEqual) { + // All elements in the second partition are equal to the pivot. No + // need to sort them. + return a; + } + + // In theory it should be enough to call _doSort recursively on the second + // partition. + // The Android source however removes the pivot elements from the recursive + // call if the second partition is too large (more than 2/3 of the list). + if (less < i1 && great > i5) { + var lessValue, greatValue; + while ((lessValue = f(a[less])) <= pivotValue1 && lessValue >= pivotValue1) ++less; + while ((greatValue = f(a[great])) <= pivotValue2 && greatValue >= pivotValue2) --great; + + // Copy paste of the previous 3-way partitioning with adaptions. + // + // We partition the list into three parts: + // 1. == pivot1 + // 2. > pivot1 && < pivot2 + // 3. == pivot2 + // + // During the loop we have: + // [ == pivot1 | > pivot1 && < pivot2 | unpartitioned | == pivot2 ] + // ^ ^ ^ + // less k great + // + // Invariants: + // 1. for x in [ *, less[ : x == pivot1 + // 2. for x in [less, k[ : pivot1 < x && x < pivot2 + // 3. for x in ]great, * ] : x == pivot2 + for (var k = less; k <= great; k++) { + var ek = a[k], xk = f(ek); + if (xk <= pivotValue1 && xk >= pivotValue1) { + if (k !== less) { + a[k] = a[less]; + a[less] = ek; + } + less++; + } else { + if (xk <= pivotValue2 && xk >= pivotValue2) { + while (true) { + var greatValue = f(a[great]); + if (greatValue <= pivotValue2 && greatValue >= pivotValue2) { + great--; + if (great < k) break; + // This is the only location inside the loop where a new + // iteration is started. + continue; + } else { + // a[great] < pivot2. + if (greatValue < pivotValue1) { + // Triple exchange. + a[k] = a[less]; + a[less++] = a[great]; + a[great--] = ek; + } else { + // a[great] == pivot1. + a[k] = a[great]; + a[great--] = ek; + } + break; + } + } + } + } + } + } + + // The second partition has now been cleared of pivot elements and looks + // as follows: + // [ * | > pivot1 && < pivot2 | * ] + // ^ ^ + // less great + // Sort the second partition using recursive descent. + + // The second partition looks as follows: + // [ * | >= pivot1 && <= pivot2 | * ] + // ^ ^ + // less great + // Simply sort it by recursive descent. + + return sort(a, less, great + 1); + } + + return sort; +} + +var quicksort_sizeThreshold = 32; +var crossfilter_array8 = crossfilter_arrayUntyped, + crossfilter_array16 = crossfilter_arrayUntyped, + crossfilter_array32 = crossfilter_arrayUntyped, + crossfilter_arrayLengthen = crossfilter_identity, + crossfilter_arrayWiden = crossfilter_identity; + +if (typeof Uint8Array !== "undefined") { + crossfilter_array8 = function(n) { return new Uint8Array(n); }; + crossfilter_array16 = function(n) { return new Uint16Array(n); }; + crossfilter_array32 = function(n) { return new Uint32Array(n); }; + + crossfilter_arrayLengthen = function(array, length) { + if (array.length >= length) return array; + var copy = new array.constructor(length); + copy.set(array); + return copy; + }; + + crossfilter_arrayWiden = function(array, width) { + var copy; + switch (width) { + case 16: copy = crossfilter_array16(array.length); break; + case 32: copy = crossfilter_array32(array.length); break; + default: throw new Error("invalid array width!"); + } + copy.set(array); + return copy; + }; +} + +function crossfilter_arrayUntyped(n) { + return new Array(n); +} +function crossfilter_filterExact(bisect, value) { + return function(values) { + var n = values.length; + return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)]; + }; +} + +function crossfilter_filterRange(bisect, range) { + var min = range[0], + max = range[1]; + return function(values) { + var n = values.length; + return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)]; + }; +} + +function crossfilter_filterAll(values) { + return [0, values.length]; +} +function crossfilter_null() { + return null; +} +function crossfilter_zero() { + return 0; +} +function crossfilter_reduceIncrement(p) { + return p + 1; +} + +function crossfilter_reduceDecrement(p) { + return p - 1; +} + +function crossfilter_reduceAdd(f) { + return function(p, v) { + return p + +f(v); + }; +} + +function crossfilter_reduceSubtract(f) { + return function(p, v) { + return p - f(v); + }; +} +exports.crossfilter = crossfilter; + +function crossfilter() { + var crossfilter = { + add: add, + remove: removeData, + dimension: dimension, + groupAll: groupAll, + size: size + }; + + var data = [], // the records + n = 0, // the number of records; data.length + m = 0, // a bit mask representing which dimensions are in use + M = 8, // number of dimensions that can fit in `filters` + filters = crossfilter_array8(0), // M bits per record; 1 is filtered out + filterListeners = [], // when the filters change + dataListeners = [], // when data is added + removeDataListeners = []; // when data is removed + + // Adds the specified new records to this crossfilter. + function add(newData) { + var n0 = n, + n1 = newData.length; + + // If there's actually new data to add… + // Merge the new data into the existing data. + // Lengthen the filter bitset to handle the new records. + // Notify listeners (dimensions and groups) that new data is available. + if (n1) { + data = data.concat(newData); + filters = crossfilter_arrayLengthen(filters, n += n1); + dataListeners.forEach(function(l) { l(newData, n0, n1); }); + } + + return crossfilter; + } + + // Removes all records that match the current filters. + function removeData() { + var newIndex = crossfilter_index(n, n), + removed = []; + for (var i = 0, j = 0; i < n; ++i) { + if (filters[i]) newIndex[i] = j++; + else removed.push(i); + } + + // Remove all matching records from groups. + filterListeners.forEach(function(l) { l(0, [], removed); }); + + // Update indexes. + removeDataListeners.forEach(function(l) { l(newIndex); }); + + // Remove old filters and data by overwriting. + for (var i = 0, j = 0, k; i < n; ++i) { + if (k = filters[i]) { + if (i !== j) filters[j] = k, data[j] = data[i]; + ++j; + } + } + data.length = j; + while (n > j) filters[--n] = 0; + } + + // Adds a new dimension with the specified value accessor function. + function dimension(value) { + var dimension = { + filter: filter, + filterExact: filterExact, + filterRange: filterRange, + filterFunction: filterFunction, + filterAll: filterAll, + top: top, + bottom: bottom, + group: group, + groupAll: groupAll, + dispose: dispose, + remove: dispose // for backwards-compatibility + }; + + var one = ~m & -~m, // lowest unset bit as mask, e.g., 00001000 + zero = ~one, // inverted one, e.g., 11110111 + values, // sorted, cached array + index, // value rank ↦ object id + newValues, // temporary array storing newly-added values + newIndex, // temporary array storing newly-added index + sort = quicksort_by(function(i) { return newValues[i]; }), + refilter = crossfilter_filterAll, // for recomputing filter + refilterFunction, // the custom filter function in use + indexListeners = [], // when data is added + dimensionGroups = [], + lo0 = 0, + hi0 = 0; + + // Updating a dimension is a two-stage process. First, we must update the + // associated filters for the newly-added records. Once all dimensions have + // updated their filters, the groups are notified to update. + dataListeners.unshift(preAdd); + dataListeners.push(postAdd); + + removeDataListeners.push(removeData); + + // Incorporate any existing data into this dimension, and make sure that the + // filter bitset is wide enough to handle the new dimension. + m |= one; + if (M >= 32 ? !one : m & (1 << M) - 1) { + filters = crossfilter_arrayWiden(filters, M <<= 1); + } + preAdd(data, 0, n); + postAdd(data, 0, n); + + // Incorporates the specified new records into this dimension. + // This function is responsible for updating filters, values, and index. + function preAdd(newData, n0, n1) { + + // Permute new values into natural order using a sorted index. + newValues = newData.map(value); + newIndex = sort(crossfilter_range(n1), 0, n1); + newValues = permute(newValues, newIndex); + + // Bisect newValues to determine which new records are selected. + var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1], i; + if (refilterFunction) { + for (i = 0; i < n1; ++i) { + if (!refilterFunction(newValues[i], i)) filters[newIndex[i] + n0] |= one; + } + } else { + for (i = 0; i < lo1; ++i) filters[newIndex[i] + n0] |= one; + for (i = hi1; i < n1; ++i) filters[newIndex[i] + n0] |= one; + } + + // If this dimension previously had no data, then we don't need to do the + // more expensive merge operation; use the new values and index as-is. + if (!n0) { + values = newValues; + index = newIndex; + lo0 = lo1; + hi0 = hi1; + return; + } + + var oldValues = values, + oldIndex = index, + i0 = 0, + i1 = 0; + + // Otherwise, create new arrays into which to merge new and old. + values = new Array(n); + index = crossfilter_index(n, n); + + // Merge the old and new sorted values, and old and new index. + for (i = 0; i0 < n0 && i1 < n1; ++i) { + if (oldValues[i0] < newValues[i1]) { + values[i] = oldValues[i0]; + index[i] = oldIndex[i0++]; + } else { + values[i] = newValues[i1]; + index[i] = newIndex[i1++] + n0; + } + } + + // Add any remaining old values. + for (; i0 < n0; ++i0, ++i) { + values[i] = oldValues[i0]; + index[i] = oldIndex[i0]; + } + + // Add any remaining new values. + for (; i1 < n1; ++i1, ++i) { + values[i] = newValues[i1]; + index[i] = newIndex[i1] + n0; + } + + // Bisect again to recompute lo0 and hi0. + bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1]; + } + + // When all filters have updated, notify index listeners of the new values. + function postAdd(newData, n0, n1) { + indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); }); + newValues = newIndex = null; + } + + function removeData(reIndex) { + for (var i = 0, j = 0, k; i < n; ++i) { + if (filters[k = index[i]]) { + if (i !== j) values[j] = values[i]; + index[j] = reIndex[k]; + ++j; + } + } + values.length = j; + while (j < n) index[j++] = 0; + + // Bisect again to recompute lo0 and hi0. + var bounds = refilter(values); + lo0 = bounds[0], hi0 = bounds[1]; + } + + // Updates the selected values based on the specified bounds [lo, hi]. + // This implementation is used by all the public filter methods. + function filterIndexBounds(bounds) { + var lo1 = bounds[0], + hi1 = bounds[1]; + + if (refilterFunction) { + refilterFunction = null; + filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; }); + lo0 = lo1; + hi0 = hi1; + return dimension; + } + + var i, + j, + k, + added = [], + removed = []; + + // Fast incremental update based on previous lo index. + if (lo1 < lo0) { + for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) { + filters[k = index[i]] ^= one; + added.push(k); + } + } else if (lo1 > lo0) { + for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) { + filters[k = index[i]] ^= one; + removed.push(k); + } + } + + // Fast incremental update based on previous hi index. + if (hi1 > hi0) { + for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) { + filters[k = index[i]] ^= one; + added.push(k); + } + } else if (hi1 < hi0) { + for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) { + filters[k = index[i]] ^= one; + removed.push(k); + } + } + + lo0 = lo1; + hi0 = hi1; + filterListeners.forEach(function(l) { l(one, added, removed); }); + return dimension; + } + + // Filters this dimension using the specified range, value, or null. + // If the range is null, this is equivalent to filterAll. + // If the range is an array, this is equivalent to filterRange. + // Otherwise, this is equivalent to filterExact. + function filter(range) { + return range == null + ? filterAll() : Array.isArray(range) + ? filterRange(range) : typeof range === "function" + ? filterFunction(range) + : filterExact(range); + } + + // Filters this dimension to select the exact value. + function filterExact(value) { + return filterIndexBounds((refilter = crossfilter_filterExact(bisect, value))(values)); + } + + // Filters this dimension to select the specified range [lo, hi]. + // The lower bound is inclusive, and the upper bound is exclusive. + function filterRange(range) { + return filterIndexBounds((refilter = crossfilter_filterRange(bisect, range))(values)); + } + + // Clears any filters on this dimension. + function filterAll() { + return filterIndexBounds((refilter = crossfilter_filterAll)(values)); + } + + // Filters this dimension using an arbitrary function. + function filterFunction(f) { + refilter = crossfilter_filterAll; + + filterIndexFunction(refilterFunction = f); + + lo0 = 0; + hi0 = n; + + return dimension; + } + + function filterIndexFunction(f) { + var i, + k, + x, + added = [], + removed = []; + + for (i = 0; i < n; ++i) { + if (!(filters[k = index[i]] & one) ^ (x = f(values[i], i))) { + if (x) filters[k] &= zero, added.push(k); + else filters[k] |= one, removed.push(k); + } + } + filterListeners.forEach(function(l) { l(one, added, removed); }); + } + + // Returns the top K selected records based on this dimension's order. + // Note: observes this dimension's filter, unlike group and groupAll. + function top(k) { + var array = [], + i = hi0, + j; + + while (--i >= lo0 && k > 0) { + if (!filters[j = index[i]]) { + array.push(data[j]); + --k; + } + } + + return array; + } + + // Returns the bottom K selected records based on this dimension's order. + // Note: observes this dimension's filter, unlike group and groupAll. + function bottom(k) { + var array = [], + i = lo0, + j; + + while (i < hi0 && k > 0) { + if (!filters[j = index[i]]) { + array.push(data[j]); + --k; + } + i++; + } + + return array; + } + + // Adds a new group to this dimension, using the specified key function. + function group(key) { + var group = { + top: top, + all: all, + reduce: reduce, + reduceCount: reduceCount, + reduceSum: reduceSum, + order: order, + orderNatural: orderNatural, + size: size, + dispose: dispose, + remove: dispose // for backwards-compatibility + }; + + // Ensure that this group will be removed when the dimension is removed. + dimensionGroups.push(group); + + var groups, // array of {key, value} + groupIndex, // object id ↦ group id + groupWidth = 8, + groupCapacity = crossfilter_capacity(groupWidth), + k = 0, // cardinality + select, + heap, + reduceAdd, + reduceRemove, + reduceInitial, + update = crossfilter_null, + reset = crossfilter_null, + resetNeeded = true; + + if (arguments.length < 1) key = crossfilter_identity; + + // The group listens to the crossfilter for when any dimension changes, so + // that it can update the associated reduce values. It must also listen to + // the parent dimension for when data is added, and compute new keys. + filterListeners.push(update); + indexListeners.push(add); + removeDataListeners.push(removeData); + + // Incorporate any existing data into the grouping. + add(values, index, 0, n); + + // Incorporates the specified new values into this group. + // This function is responsible for updating groups and groupIndex. + function add(newValues, newIndex, n0, n1) { + var oldGroups = groups, + reIndex = crossfilter_index(k, groupCapacity), + add = reduceAdd, + initial = reduceInitial, + k0 = k, // old cardinality + i0 = 0, // index of old group + i1 = 0, // index of new record + j, // object id + g0, // old group + x0, // old key + x1, // new key + g, // group to add + x; // key of group to add + + // If a reset is needed, we don't need to update the reduce values. + if (resetNeeded) add = initial = crossfilter_null; + + // Reset the new groups (k is a lower bound). + // Also, make sure that groupIndex exists and is long enough. + groups = new Array(k), k = 0; + groupIndex = k0 > 1 ? crossfilter_arrayLengthen(groupIndex, n) : crossfilter_index(n, groupCapacity); + + // Get the first old key (x0 of g0), if it exists. + if (k0) x0 = (g0 = oldGroups[0]).key; + + // Find the first new key (x1), skipping NaN keys. + while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1; + + // While new keys remain… + while (i1 < n1) { + + // Determine the lesser of the two current keys; new and old. + // If there are no old keys remaining, then always add the new key. + if (g0 && x0 <= x1) { + g = g0, x = x0; + + // Record the new index of the old group. + reIndex[i0] = k; + + // Retrieve the next old key. + if (g0 = oldGroups[++i0]) x0 = g0.key; + } else { + g = {key: x1, value: initial()}, x = x1; + } + + // Add the lesser group. + groups[k] = g; + + // Add any selected records belonging to the added group, while + // advancing the new key and populating the associated group index. + while (!(x1 > x)) { + groupIndex[j = newIndex[i1] + n0] = k; + if (!(filters[j] & zero)) g.value = add(g.value, data[j]); + if (++i1 >= n1) break; + x1 = key(newValues[i1]); + } + + groupIncrement(); + } + + // Add any remaining old groups that were greater than all new keys. + // No incremental reduce is needed; these groups have no new records. + // Also record the new index of the old group. + while (i0 < k0) { + groups[reIndex[i0] = k] = oldGroups[i0++]; + groupIncrement(); + } + + // If we added any new groups before any old groups, + // update the group index of all the old records. + if (k > i0) for (i0 = 0; i0 < n0; ++i0) { + groupIndex[i0] = reIndex[groupIndex[i0]]; + } + + // Modify the update and reset behavior based on the cardinality. + // If the cardinality is less than or equal to one, then the groupIndex + // is not needed. If the cardinality is zero, then there are no records + // and therefore no groups to update or reset. Note that we also must + // change the registered listener to point to the new method. + j = filterListeners.indexOf(update); + if (k > 1) { + update = updateMany; + reset = resetMany; + } else { + if (k === 1) { + update = updateOne; + reset = resetOne; + } else { + update = crossfilter_null; + reset = crossfilter_null; + } + groupIndex = null; + } + filterListeners[j] = update; + + // Count the number of added groups, + // and widen the group index as needed. + function groupIncrement() { + if (++k === groupCapacity) { + reIndex = crossfilter_arrayWiden(reIndex, groupWidth <<= 1); + groupIndex = crossfilter_arrayWiden(groupIndex, groupWidth); + groupCapacity = crossfilter_capacity(groupWidth); + } + } + } + + function removeData() { + if (k > 1) { + var oldK = k, + oldGroups = groups, + seenGroups = crossfilter_index(oldK, oldK); + + // Filter out non-matches by copying matching group index entries to + // the beginning of the array. + for (var i = 0, j = 0; i < n; ++i) { + if (filters[i]) { + seenGroups[groupIndex[j] = groupIndex[i]] = 1; + ++j; + } + } + + // Reassemble groups including only those groups that were referred + // to by matching group index entries. Note the new group index in + // seenGroups. + groups = [], k = 0; + for (i = 0; i < oldK; ++i) { + if (seenGroups[i]) { + seenGroups[i] = k++; + groups.push(oldGroups[i]); + } + } + + if (k > 1) { + // Reindex the group index using seenGroups to find the new index. + for (var i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]]; + } else { + groupIndex = null; + } + filterListeners[filterListeners.indexOf(update)] = k > 1 + ? (reset = resetMany, update = updateMany) + : k === 1 ? (reset = resetOne, update = updateOne) + : reset = update = crossfilter_null; + } else if (k === 1) { + for (var i = 0; i < n; ++i) if (filters[i]) return; + groups = [], k = 0; + filterListeners[filterListeners.indexOf(update)] = + update = reset = crossfilter_null; + } + } + + // Reduces the specified selected or deselected records. + // This function is only used when the cardinality is greater than 1. + function updateMany(filterOne, added, removed) { + if (filterOne === one || resetNeeded) return; + + var i, + k, + n, + g; + + // Add the added values. + for (i = 0, n = added.length; i < n; ++i) { + if (!(filters[k = added[i]] & zero)) { + g = groups[groupIndex[k]]; + g.value = reduceAdd(g.value, data[k]); + } + } + + // Remove the removed values. + for (i = 0, n = removed.length; i < n; ++i) { + if ((filters[k = removed[i]] & zero) === filterOne) { + g = groups[groupIndex[k]]; + g.value = reduceRemove(g.value, data[k]); + } + } + } + + // Reduces the specified selected or deselected records. + // This function is only used when the cardinality is 1. + function updateOne(filterOne, added, removed) { + if (filterOne === one || resetNeeded) return; + + var i, + k, + n, + g = groups[0]; + + // Add the added values. + for (i = 0, n = added.length; i < n; ++i) { + if (!(filters[k = added[i]] & zero)) { + g.value = reduceAdd(g.value, data[k]); + } + } + + // Remove the removed values. + for (i = 0, n = removed.length; i < n; ++i) { + if ((filters[k = removed[i]] & zero) === filterOne) { + g.value = reduceRemove(g.value, data[k]); + } + } + } + + // Recomputes the group reduce values from scratch. + // This function is only used when the cardinality is greater than 1. + function resetMany() { + var i, + g; + + // Reset all group values. + for (i = 0; i < k; ++i) { + groups[i].value = reduceInitial(); + } + + // Add any selected records. + for (i = 0; i < n; ++i) { + if (!(filters[i] & zero)) { + g = groups[groupIndex[i]]; + g.value = reduceAdd(g.value, data[i]); + } + } + } + + // Recomputes the group reduce values from scratch. + // This function is only used when the cardinality is 1. + function resetOne() { + var i, + g = groups[0]; + + // Reset the singleton group values. + g.value = reduceInitial(); + + // Add any selected records. + for (i = 0; i < n; ++i) { + if (!(filters[i] & zero)) { + g.value = reduceAdd(g.value, data[i]); + } + } + } + + // Returns the array of group values, in the dimension's natural order. + function all() { + if (resetNeeded) reset(), resetNeeded = false; + return groups; + } + + // Returns a new array containing the top K group values, in reduce order. + function top(k) { + var top = select(all(), 0, groups.length, k); + return heap.sort(top, 0, top.length); + } + + // Sets the reduce behavior for this group to use the specified functions. + // This method lazily recomputes the reduce values, waiting until needed. + function reduce(add, remove, initial) { + reduceAdd = add; + reduceRemove = remove; + reduceInitial = initial; + resetNeeded = true; + return group; + } + + // A convenience method for reducing by count. + function reduceCount() { + return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero); + } + + // A convenience method for reducing by sum(value). + function reduceSum(value) { + return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero); + } + + // Sets the reduce order, using the specified accessor. + function order(value) { + select = heapselect_by(valueOf); + heap = heap_by(valueOf); + function valueOf(d) { return value(d.value); } + return group; + } + + // A convenience method for natural ordering by reduce value. + function orderNatural() { + return order(crossfilter_identity); + } + + // Returns the cardinality of this group, irrespective of any filters. + function size() { + return k; + } + + // Removes this group and associated event listeners. + function dispose() { + var i = filterListeners.indexOf(update); + if (i >= 0) filterListeners.splice(i, 1); + i = indexListeners.indexOf(add); + if (i >= 0) indexListeners.splice(i, 1); + i = removeDataListeners.indexOf(removeData); + if (i >= 0) removeDataListeners.splice(i, 1); + return group; + } + + return reduceCount().orderNatural(); + } + + // A convenience function for generating a singleton group. + function groupAll() { + var g = group(crossfilter_null), all = g.all; + delete g.all; + delete g.top; + delete g.order; + delete g.orderNatural; + delete g.size; + g.value = function() { return all()[0].value; }; + return g; + } + + // Removes this dimension and associated groups and event listeners. + function dispose() { + dimensionGroups.forEach(function(group) { group.dispose(); }); + var i = dataListeners.indexOf(preAdd); + if (i >= 0) dataListeners.splice(i, 1); + i = dataListeners.indexOf(postAdd); + if (i >= 0) dataListeners.splice(i, 1); + i = removeDataListeners.indexOf(removeData); + if (i >= 0) removeDataListeners.splice(i, 1); + for (i = 0; i < n; ++i) filters[i] &= zero; + m &= zero; + return dimension; + } + + return dimension; + } + + // A convenience method for groupAll on a dummy dimension. + // This implementation can be optimized since it always has cardinality 1. + function groupAll() { + var group = { + reduce: reduce, + reduceCount: reduceCount, + reduceSum: reduceSum, + value: value, + dispose: dispose, + remove: dispose // for backwards-compatibility + }; + + var reduceValue, + reduceAdd, + reduceRemove, + reduceInitial, + resetNeeded = true; + + // The group listens to the crossfilter for when any dimension changes, so + // that it can update the reduce value. It must also listen to the parent + // dimension for when data is added. + filterListeners.push(update); + dataListeners.push(add); + + // For consistency; actually a no-op since resetNeeded is true. + add(data, 0, n); + + // Incorporates the specified new values into this group. + function add(newData, n0) { + var i; + + if (resetNeeded) return; + + // Add the added values. + for (i = n0; i < n; ++i) { + if (!filters[i]) { + reduceValue = reduceAdd(reduceValue, data[i]); + } + } + } + + // Reduces the specified selected or deselected records. + function update(filterOne, added, removed) { + var i, + k, + n; + + if (resetNeeded) return; + + // Add the added values. + for (i = 0, n = added.length; i < n; ++i) { + if (!filters[k = added[i]]) { + reduceValue = reduceAdd(reduceValue, data[k]); + } + } + + // Remove the removed values. + for (i = 0, n = removed.length; i < n; ++i) { + if (filters[k = removed[i]] === filterOne) { + reduceValue = reduceRemove(reduceValue, data[k]); + } + } + } + + // Recomputes the group reduce value from scratch. + function reset() { + var i; + + reduceValue = reduceInitial(); + + for (i = 0; i < n; ++i) { + if (!filters[i]) { + reduceValue = reduceAdd(reduceValue, data[i]); + } + } + } + + // Sets the reduce behavior for this group to use the specified functions. + // This method lazily recomputes the reduce value, waiting until needed. + function reduce(add, remove, initial) { + reduceAdd = add; + reduceRemove = remove; + reduceInitial = initial; + resetNeeded = true; + return group; + } + + // A convenience method for reducing by count. + function reduceCount() { + return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero); + } + + // A convenience method for reducing by sum(value). + function reduceSum(value) { + return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero); + } + + // Returns the computed reduce value. + function value() { + if (resetNeeded) reset(), resetNeeded = false; + return reduceValue; + } + + // Removes this group and associated event listeners. + function dispose() { + var i = filterListeners.indexOf(update); + if (i >= 0) filterListeners.splice(i); + i = dataListeners.indexOf(add); + if (i >= 0) dataListeners.splice(i); + return group; + } + + return reduceCount(); + } + + // Returns the number of records in this crossfilter, irrespective of any filters. + function size() { + return n; + } + + return arguments.length + ? add(arguments[0]) + : crossfilter; +} + +// Returns an array of size n, big enough to store ids up to m. +function crossfilter_index(n, m) { + return (m < 0x101 + ? crossfilter_array8 : m < 0x10001 + ? crossfilter_array16 + : crossfilter_array32)(n); +} + +// Constructs a new array of size n, with sequential values from 0 to n - 1. +function crossfilter_range(n) { + var range = crossfilter_index(n, n); + for (var i = -1; ++i < n;) range[i] = i; + return range; +} + +function crossfilter_capacity(w) { + return w === 8 + ? 0x100 : w === 16 + ? 0x10000 + : 0x100000000; +} +})(this); diff --git a/admin/view/javascript/shopunity/charts_svg/crossfilter.min.js b/admin/view/javascript/shopunity/charts_svg/crossfilter.min.js new file mode 100755 index 0000000..b9c9880 --- /dev/null +++ b/admin/view/javascript/shopunity/charts_svg/crossfilter.min.js @@ -0,0 +1 @@ +!function(r){function n(r){return r}function t(r,n){for(var t=0,e=n.length,u=Array(e);e>t;++t)u[t]=r[n[t]];return u}function e(r){function n(n,t,e,u){for(;u>e;){var f=e+u>>>1;r(n[f])e;){var f=e+u>>>1;t>>1)+1;--f>0;)e(r,f,u,n);return r}function t(r,n,t){for(var u,f=t-n;--f>0;)u=r[n],r[n]=r[n+f],r[n+f]=u,e(r,1,f,n);return r}function e(n,t,e,u){for(var f,o=n[--u+t],i=r(o);(f=t<<1)<=e&&(e>f&&r(n[u+f])>r(n[u+f+1])&&f++,!(i<=r(n[u+f])));)n[u+t]=n[u+f],t=f;n[u+t]=o}return n.sort=t,n}function f(r){function n(n,e,u,f){var o,i,a,c,l=Array(f=Math.min(u-e,f));for(i=0;f>i;++i)l[i]=n[e++];if(t(l,0,f),u>e){o=r(l[0]);do(a=r(c=n[e])>o)&&(l[0]=c,o=r(t(l,0,f)[0]));while(++eu;++u){for(var f=u,o=n[u],i=r(o);f>t&&r(n[f-1])>i;--f)n[f]=n[f-1];n[f]=o}return n}return n}function i(r){function n(r,n,u){return(U>u-n?e:t)(r,n,u)}function t(t,e,u){var f,o=0|(u-e)/6,i=e+o,a=u-1-o,c=e+u-1>>1,l=c-o,v=c+o,s=t[i],h=r(s),p=t[l],d=r(p),g=t[c],y=r(g),m=t[v],b=r(m),x=t[a],A=r(x);h>d&&(f=s,s=p,p=f,f=h,h=d,d=f),b>A&&(f=m,m=x,x=f,f=b,b=A,A=f),h>y&&(f=s,s=g,g=f,f=h,h=y,y=f),d>y&&(f=p,p=g,g=f,f=d,d=y,y=f),h>b&&(f=s,s=m,m=f,f=h,h=b,b=f),y>b&&(f=g,g=m,m=f,f=y,y=b,b=f),d>A&&(f=p,p=x,x=f,f=d,d=A,A=f),d>y&&(f=p,p=g,g=f,f=d,d=y,y=f),b>A&&(f=m,m=x,x=f,f=b,b=A,A=f);var k=p,O=d,E=m,w=b;t[i]=s,t[l]=t[e],t[c]=g,t[v]=t[u-1],t[a]=x;var M=e+1,U=u-2,z=w>=O&&O>=w;if(z)for(var N=M;U>=N;++N){var C=t[N],S=r(C);if(O>S)N!==M&&(t[N]=t[M],t[M]=C),++M;else if(S>O)for(;;){var q=r(t[U]);{if(!(q>O)){if(O>q){t[N]=t[M],t[M++]=t[U],t[U--]=C;break}t[N]=t[U],t[U--]=C;break}U--}}}else for(var N=M;U>=N;N++){var C=t[N],S=r(C);if(O>S)N!==M&&(t[N]=t[M],t[M]=C),++M;else if(S>w)for(;;){var q=r(t[U]);{if(!(q>w)){O>q?(t[N]=t[M],t[M++]=t[U],t[U--]=C):(t[N]=t[U],t[U--]=C);break}if(U--,N>U)break}}}if(t[e]=t[M-1],t[M-1]=k,t[u-1]=t[U+1],t[U+1]=E,n(t,e,M-1),n(t,U+2,u),z)return t;if(i>M&&U>a){for(var F,q;(F=r(t[M]))<=O&&F>=O;)++M;for(;(q=r(t[U]))<=w&&q>=w;)--U;for(var N=M;U>=N;N++){var C=t[N],S=r(C);if(O>=S&&S>=O)N!==M&&(t[N]=t[M],t[M]=C),M++;else if(w>=S&&S>=w)for(;;){var q=r(t[U]);{if(!(w>=q&&q>=w)){O>q?(t[N]=t[M],t[M++]=t[U],t[U--]=C):(t[N]=t[U],t[U--]=C);break}if(U--,N>U)break}}}}return n(t,M,U+1)}var e=o(r);return n}function a(r){return Array(r)}function c(r,n){return function(t){var e=t.length;return[r.left(t,n,0,e),r.right(t,n,0,e)]}}function l(r,n){var t=n[0],e=n[1];return function(n){var u=n.length;return[r.left(n,t,0,u),r.left(n,e,0,u)]}}function v(r){return[0,r.length]}function s(){return null}function h(){return 0}function p(r){return r+1}function d(r){return r-1}function g(r){return function(n,t){return n+ +r(t)}}function y(r){return function(n,t){return n-r(t)}}function m(){function r(r){var n=w,t=r.length;return t&&(E=E.concat(r),N=S(N,w+=t),F.forEach(function(e){e(r,n,t)})),O}function e(){for(var r=b(w,w),n=[],t=0,e=0;w>t;++t)N[t]?r[t]=e++:n.push(t);C.forEach(function(r){r(0,[],n)}),R.forEach(function(n){n(r)});for(var u,t=0,e=0;w>t;++t)(u=N[t])&&(t!==e&&(N[e]=u,E[e]=E[t]),++e);for(E.length=e;w>e;)N[--w]=0}function o(r){function e(n,e,u){T=n.map(r),V=$(x(u),0,u),T=t(T,V);var f,o=_(T),i=o[0],a=o[1];if(W)for(f=0;u>f;++f)W(T[f],f)||(N[V[f]+e]|=Y);else{for(f=0;i>f;++f)N[V[f]+e]|=Y;for(f=a;u>f;++f)N[V[f]+e]|=Y}if(!e)return P=T,Q=V,tn=i,en=a,void 0;var c=P,l=Q,v=0,s=0;for(P=Array(w),Q=b(w,w),f=0;e>v&&u>s;++f)c[v]v;++v,++f)P[f]=c[v],Q[f]=l[v];for(;u>s;++s,++f)P[f]=T[s],Q[f]=V[s]+e;o=_(P),tn=o[0],en=o[1]}function o(r,n,t){rn.forEach(function(r){r(T,V,n,t)}),T=V=null}function a(r){for(var n,t=0,e=0;w>t;++t)N[n=Q[t]]&&(t!==e&&(P[e]=P[t]),Q[e]=r[n],++e);for(P.length=e;w>e;)Q[e++]=0;var u=_(P);tn=u[0],en=u[1]}function m(r){var n=r[0],t=r[1];if(W)return W=null,G(function(r,e){return e>=n&&t>e}),tn=n,en=t,X;var e,u,f,o=[],i=[];if(tn>n)for(e=n,u=Math.min(tn,t);u>e;++e)N[f=Q[e]]^=Y,o.push(f);else if(n>tn)for(e=tn,u=Math.min(n,en);u>e;++e)N[f=Q[e]]^=Y,i.push(f);if(t>en)for(e=Math.max(n,en),u=t;u>e;++e)N[f=Q[e]]^=Y,o.push(f);else if(en>t)for(e=Math.max(tn,t),u=en;u>e;++e)N[f=Q[e]]^=Y,i.push(f);return tn=n,en=t,C.forEach(function(r){r(Y,o,i)}),X}function O(r){return null==r?B():Array.isArray(r)?j(r):"function"==typeof r?D(r):z(r)}function z(r){return m((_=c(k,r))(P))}function j(r){return m((_=l(k,r))(P))}function B(){return m((_=v)(P))}function D(r){return _=v,G(W=r),tn=0,en=w,X}function G(r){var n,t,e,u=[],f=[];for(n=0;w>n;++n)!(N[t=Q[n]]&Y)^(e=r(P[n],n))&&(e?(N[t]&=Z,u.push(t)):(N[t]|=Y,f.push(t)));C.forEach(function(r){r(Y,u,f)})}function H(r){for(var n,t=[],e=en;--e>=tn&&r>0;)N[n=Q[e]]||(t.push(E[n]),--r);return t}function I(r){for(var n,t=[],e=tn;en>e&&r>0;)N[n=Q[e]]||(t.push(E[n]),--r),e++;return t}function J(r){function t(n,t,e,u){function f(){++T===L&&(m=q(m,K<<=1),B=q(B,K),L=A(K))}var l,v,h,p,d,g,y=j,m=b(T,L),x=H,k=J,O=T,M=0,U=0;for(X&&(x=k=s),j=Array(T),T=0,B=O>1?S(B,w):b(w,L),O&&(h=(v=y[0]).key);u>U&&!((p=r(n[U]))>=p);)++U;for(;u>U;){for(v&&p>=h?(d=v,g=h,m[M]=T,(v=y[++M])&&(h=v.key)):(d={key:p,value:k()},g=p),j[T]=d;!(p>g||(B[l=t[U]+e]=T,N[l]&Z||(d.value=x(d.value,E[l])),++U>=u));)p=r(n[U]);f()}for(;O>M;)j[m[M]=T]=y[M++],f();if(T>M)for(M=0;e>M;++M)B[M]=m[B[M]];l=C.indexOf(V),T>1?(V=o,W=a):(1===T?(V=i,W=c):(V=s,W=s),B=null),C[l]=V}function e(){if(T>1){for(var r=T,n=j,t=b(r,r),e=0,u=0;w>e;++e)N[e]&&(t[B[u]=B[e]]=1,++u);for(j=[],T=0,e=0;r>e;++e)t[e]&&(t[e]=T++,j.push(n[e]));if(T>1)for(var e=0;u>e;++e)B[e]=t[B[e]];else B=null;C[C.indexOf(V)]=T>1?(W=a,V=o):1===T?(W=c,V=i):W=V=s}else if(1===T){for(var e=0;w>e;++e)if(N[e])return;j=[],T=0,C[C.indexOf(V)]=V=W=s}}function o(r,n,t){if(r!==Y&&!X){var e,u,f,o;for(e=0,f=n.length;f>e;++e)N[u=n[e]]&Z||(o=j[B[u]],o.value=H(o.value,E[u]));for(e=0,f=t.length;f>e;++e)(N[u=t[e]]&Z)===r&&(o=j[B[u]],o.value=I(o.value,E[u]))}}function i(r,n,t){if(r!==Y&&!X){var e,u,f,o=j[0];for(e=0,f=n.length;f>e;++e)N[u=n[e]]&Z||(o.value=H(o.value,E[u]));for(e=0,f=t.length;f>e;++e)(N[u=t[e]]&Z)===r&&(o.value=I(o.value,E[u]))}}function a(){var r,n;for(r=0;T>r;++r)j[r].value=J();for(r=0;w>r;++r)N[r]&Z||(n=j[B[r]],n.value=H(n.value,E[r]))}function c(){var r,n=j[0];for(n.value=J(),r=0;w>r;++r)N[r]&Z||(n.value=H(n.value,E[r]))}function l(){return X&&(W(),X=!1),j}function v(r){var n=D(l(),0,j.length,r);return G.sort(n,0,n.length)}function m(r,n,t){return H=r,I=n,J=t,X=!0,F}function x(){return m(p,d,h)}function k(r){return m(g(r),y(r),h)}function O(r){function n(n){return r(n.value)}return D=f(n),G=u(n),F}function M(){return O(n)}function U(){return T}function z(){var r=C.indexOf(V);return r>=0&&C.splice(r,1),r=rn.indexOf(t),r>=0&&rn.splice(r,1),r=R.indexOf(e),r>=0&&R.splice(r,1),F}var F={top:v,all:l,reduce:m,reduceCount:x,reduceSum:k,order:O,orderNatural:M,size:U,dispose:z,remove:z};nn.push(F);var j,B,D,G,H,I,J,K=8,L=A(K),T=0,V=s,W=s,X=!0;return arguments.length<1&&(r=n),C.push(V),rn.push(t),R.push(e),t(P,Q,0,w),x().orderNatural()}function K(){var r=J(s),n=r.all;return delete r.all,delete r.top,delete r.order,delete r.orderNatural,delete r.size,r.value=function(){return n()[0].value},r}function L(){nn.forEach(function(r){r.dispose()});var r=F.indexOf(e);for(r>=0&&F.splice(r,1),r=F.indexOf(o),r>=0&&F.splice(r,1),r=R.indexOf(a),r>=0&&R.splice(r,1),r=0;w>r;++r)N[r]&=Z;return M&=Z,X}var P,Q,T,V,W,X={filter:O,filterExact:z,filterRange:j,filterFunction:D,filterAll:B,top:H,bottom:I,group:J,groupAll:K,dispose:L,remove:L},Y=~M&-~M,Z=~Y,$=i(function(r){return T[r]}),_=v,rn=[],nn=[],tn=0,en=0;return F.unshift(e),F.push(o),R.push(a),M|=Y,(U>=32?!Y:M&(1<t;++t)N[t]||(a=c(a,E[t]))}function n(r,n,t){var e,u,f;if(!m){for(e=0,f=n.length;f>e;++e)N[u=n[e]]||(a=c(a,E[u]));for(e=0,f=t.length;f>e;++e)N[u=t[e]]===r&&(a=l(a,E[u]))}}function t(){var r;for(a=v(),r=0;w>r;++r)N[r]||(a=c(a,E[r]))}function e(r,n,t){return c=r,l=n,v=t,m=!0,s}function u(){return e(p,d,h)}function f(r){return e(g(r),y(r),h)}function o(){return m&&(t(),m=!1),a}function i(){var t=C.indexOf(n);return t>=0&&C.splice(t),t=F.indexOf(r),t>=0&&F.splice(t),s}var a,c,l,v,s={reduce:e,reduceCount:u,reduceSum:f,value:o,dispose:i,remove:i},m=!0;return C.push(n),F.push(r),r(E,0,w),u()}function m(){return w}var O={add:r,remove:e,dimension:o,groupAll:a,size:m},E=[],w=0,M=0,U=8,N=z(0),C=[],F=[],R=[];return arguments.length?r(arguments[0]):O}function b(r,n){return(257>n?z:65537>n?N:C)(r)}function x(r){for(var n=b(r,r),t=-1;++t=n)return r;var t=new r.constructor(n);return t.set(r),t},q=function(r,n){var t;switch(n){case 16:t=N(r.length);break;case 32:t=C(r.length);break;default:throw Error("invalid array width!")}return t.set(r),t}),r.crossfilter=m}(this); \ No newline at end of file diff --git a/admin/view/javascript/shopunity/charts_svg/d3.js b/admin/view/javascript/shopunity/charts_svg/d3.js new file mode 100755 index 0000000..79eab31 --- /dev/null +++ b/admin/view/javascript/shopunity/charts_svg/d3.js @@ -0,0 +1,9274 @@ +d3 = function() { + var d3 = { + version: "3.3.9" + }; + if (!Date.now) Date.now = function() { + return +new Date(); + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = document, d3_documentElement = d3_document.documentElement, d3_window = window; + try { + d3_array(d3_documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array = new Array(i); + while (i--) array[i] = list[i]; + return array; + }; + } + try { + d3_document.createElement("div").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = d3_window.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = d3_window.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name, value) { + d3_element_setAttribute.call(this, name, value + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value) { + d3_element_setAttributeNS.call(this, space, local, value + ""); + }; + d3_style_prototype.setProperty = function(name, value, priority) { + d3_style_setProperty.call(this, name, value + "", priority); + }; + } + d3.ascending = function(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + }; + d3.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d3.min = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined; + while (++i < n) if ((b = array[i]) != null && a > b) a = b; + } else { + while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined; + while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b; + } + return a; + }; + d3.max = function(array, f) { + var i = -1, n = array.length, a, b; + if (arguments.length === 1) { + while (++i < n && !((a = array[i]) != null && a <= a)) a = undefined; + while (++i < n) if ((b = array[i]) != null && b > a) a = b; + } else { + while (++i < n && !((a = f.call(array, array[i], i)) != null && a <= a)) a = undefined; + while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b; + } + return a; + }; + d3.extent = function(array, f) { + var i = -1, n = array.length, a, b, c; + if (arguments.length === 1) { + while (++i < n && !((a = c = array[i]) != null && a <= a)) a = c = undefined; + while (++i < n) if ((b = array[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n && !((a = c = f.call(array, array[i], i)) != null && a <= a)) a = undefined; + while (++i < n) if ((b = f.call(array, array[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [ a, c ]; + }; + d3.sum = function(array, f) { + var s = 0, n = array.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (!isNaN(a = +array[i])) s += a; + } else { + while (++i < n) if (!isNaN(a = +f.call(array, array[i], i))) s += a; + } + return s; + }; + function d3_number(x) { + return x != null && !isNaN(x); + } + d3.mean = function(array, f) { + var n = array.length, a, m = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) if (d3_number(a = array[i])) m += (a - m) / ++j; + } else { + while (++i < n) if (d3_number(a = f.call(array, array[i], i))) m += (a - m) / ++j; + } + return j ? m : undefined; + }; + d3.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d3.median = function(array, f) { + if (arguments.length > 1) array = array.map(f); + array = array.filter(d3_number); + return array.length ? d3.quantile(array.sort(d3.ascending), .5) : undefined; + }; + d3.bisector = function(f) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (f.call(a, a[mid], mid) < x) lo = mid + 1; else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (x < f.call(a, a[mid], mid)) hi = mid; else lo = mid + 1; + } + return lo; + } + }; + }; + var d3_bisector = d3.bisector(function(d) { + return d; + }); + d3.bisectLeft = d3_bisector.left; + d3.bisect = d3.bisectRight = d3_bisector.right; + d3.shuffle = function(array) { + var m = array.length, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array[m], array[m] = array[i], array[i] = t; + } + return array; + }; + d3.permute = function(array, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array[indexes[i]]; + return permutes; + }; + d3.pairs = function(array) { + var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ]; + return pairs; + }; + d3.zip = function() { + if (!(n = arguments.length)) return []; + for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) { + for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) { + zip[j] = arguments[j][i]; + } + } + return zips; + }; + function d3_zipLength(d) { + return d.length; + } + d3.transpose = function(matrix) { + return d3.zip.apply(d3, matrix); + }; + d3.keys = function(map) { + var keys = []; + for (var key in map) keys.push(key); + return keys; + }; + d3.values = function(map) { + var values = []; + for (var key in map) values.push(map[key]); + return values; + }; + d3.entries = function(map) { + var entries = []; + for (var key in map) entries.push({ + key: key, + value: map[key] + }); + return entries; + }; + d3.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array = arrays[n]; + m = array.length; + while (--m >= 0) { + merged[--j] = array[m]; + } + } + return merged; + }; + var abs = Math.abs; + d3.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } + } + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + try { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); + } + } catch (e) { + ctor.prototype = properties; + } + } + d3.map = function(object) { + var map = new d3_Map(); + if (object instanceof d3_Map) object.forEach(function(key, value) { + map.set(key, value); + }); else for (var key in object) map.set(key, object[key]); + return map; + }; + function d3_Map() {} + d3_class(d3_Map, { + has: function(key) { + return d3_map_prefix + key in this; + }, + get: function(key) { + return this[d3_map_prefix + key]; + }, + set: function(key, value) { + return this[d3_map_prefix + key] = value; + }, + remove: function(key) { + key = d3_map_prefix + key; + return key in this && delete this[key]; + }, + keys: function() { + var keys = []; + this.forEach(function(key) { + keys.push(key); + }); + return keys; + }, + values: function() { + var values = []; + this.forEach(function(key, value) { + values.push(value); + }); + return values; + }, + entries: function() { + var entries = []; + this.forEach(function(key, value) { + entries.push({ + key: key, + value: value + }); + }); + return entries; + }, + forEach: function(f) { + for (var key in this) { + if (key.charCodeAt(0) === d3_map_prefixCode) { + f.call(this, key.substring(1), this[key]); + } + } + } + }); + var d3_map_prefix = "\x00", d3_map_prefixCode = d3_map_prefix.charCodeAt(0); + d3.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map(mapType, array, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array; + var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object = array[i]))) { + values.push(object); + } else { + valuesByKey.set(keyValue, [ object ]); + } + } + if (mapType) { + object = mapType(); + setter = function(keyValue, values) { + object.set(keyValue, map(mapType, values, depth)); + }; + } else { + object = {}; + setter = function(keyValue, values) { + object[keyValue] = map(mapType, values, depth); + }; + } + valuesByKey.forEach(setter); + return object; + } + function entries(map, depth) { + if (depth >= keys.length) return map; + var array = [], sortKey = sortKeys[depth++]; + map.forEach(function(key, keyMap) { + array.push({ + key: key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array; + } + nest.map = function(array, mapType) { + return map(mapType, array, 0); + }; + nest.entries = function(array) { + return entries(map(d3.map, array, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d3.set = function(array) { + var set = new d3_Set(); + if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]); + return set; + }; + function d3_Set() {} + d3_class(d3_Set, { + has: function(value) { + return d3_map_prefix + value in this; + }, + add: function(value) { + this[d3_map_prefix + value] = true; + return value; + }, + remove: function(value) { + value = d3_map_prefix + value; + return value in this && delete this[value]; + }, + values: function() { + var values = []; + this.forEach(function(value) { + values.push(value); + }); + return values; + }, + forEach: function(f) { + for (var value in this) { + if (value.charCodeAt(0) === d3_map_prefixCode) { + f.call(this, value.substring(1)); + } + } + } + }); + d3.behavior = {}; + d3.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value = method.apply(source, arguments); + return value === source ? target : value; + }; + } + function d3_vendorSymbol(object, name) { + if (name in object) return name; + name = name.charAt(0).toUpperCase() + name.substring(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name; + if (prefixName in object) return prefixName; + } + } + var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ]; + function d3_noop() {} + d3.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() {} + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name = ""; + if (i >= 0) { + name = type.substring(i + 1); + type = type.substring(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners = [], listenerByName = new d3_Map(); + function event() { + var z = listeners, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name, listener) { + var l = listenerByName.get(name), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1)); + listenerByName.remove(name); + } + if (listener) listeners.push(listenerByName.set(name, { + on: listener + })); + return dispatch; + }; + return event; + } + d3.event = null; + function d3_eventPreventDefault() { + d3.event.preventDefault(); + } + function d3_eventSource() { + var e = d3.event, s; + while (s = e.sourceEvent) e = s; + return e; + } + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d3.event; + e1.target = target; + d3.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d3.event = e0; + } + }; + }; + return dispatch; + } + d3.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object, prototype) { + object.__proto__ = prototype; + } : function(object, prototype) { + for (var property in prototype) object[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; + } + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatcher = d3_documentElement[d3_vendorSymbol(d3_documentElement, "matchesSelector")], d3_selectMatches = function(n, s) { + return d3_selectMatcher.call(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = function(s, n) { + return Sizzle.uniqueSort(Sizzle(s, n)); + }; + d3_selectMatches = Sizzle.matchesSelector; + } + d3.selection = function() { + return d3_selectionRoot; + }; + var d3_selectionPrototype = d3.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; + } + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; + } + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: "http://www.w3.org/1999/xhtml", + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d3.ns = { + prefix: d3_nsPrefix, + qualify: function(name) { + var i = name.indexOf(":"), prefix = name; + if (i >= 0) { + prefix = name.substring(0, i); + name = name.substring(i + 1); + } + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name + } : name; + } + }; + d3_selectionPrototype.attr = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(); + name = d3.ns.qualify(name); + return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name); + } + for (value in name) this.each(d3_selection_attr(value, name[value])); + return this; + } + return this.each(d3_selection_attr(name, value)); + }; + function d3_selection_attr(name, value) { + name = d3.ns.qualify(name); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrConstant() { + this.setAttribute(name, value); + } + function attrConstantNS() { + this.setAttributeNS(name.space, name.local, value); + } + function attrFunction() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttribute(name); else this.setAttribute(name, x); + } + function attrFunctionNS() { + var x = value.apply(this, arguments); + if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x); + } + return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant; + } + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); + } + d3_selectionPrototype.classed = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") { + var node = this.node(), n = (name = name.trim().split(/^|\s+/g)).length, i = -1; + if (value = node.classList) { + while (++i < n) if (!value.contains(name[i])) return false; + } else { + value = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false; + } + return true; + } + for (value in name) this.each(d3_selection_classed(value, name[value])); + return this; + } + return this.each(d3_selection_classed(name, value)); + }; + function d3_selection_classedRe(name) { + return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g"); + } + function d3_selection_classed(name, value) { + name = name.trim().split(/\s+/).map(d3_selection_classedName); + var n = name.length; + function classedConstant() { + var i = -1; + while (++i < n) name[i](this, value); + } + function classedFunction() { + var i = -1, x = value.apply(this, arguments); + while (++i < n) name[i](this, x); + } + return typeof value === "function" ? classedFunction : classedConstant; + } + function d3_selection_classedName(name) { + var re = d3_selection_classedRe(name); + return function(node, value) { + if (c = node.classList) return value ? c.add(name) : c.remove(name); + var c = node.getAttribute("class") || ""; + if (value) { + re.lastIndex = 0; + if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re, " "))); + } + }; + } + d3_selectionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.each(d3_selection_style(priority, name[priority], value)); + return this; + } + if (n < 2) return d3_window.getComputedStyle(this.node(), null).getPropertyValue(name); + priority = ""; + } + return this.each(d3_selection_style(name, value, priority)); + }; + function d3_selection_style(name, value, priority) { + function styleNull() { + this.style.removeProperty(name); + } + function styleConstant() { + this.style.setProperty(name, value, priority); + } + function styleFunction() { + var x = value.apply(this, arguments); + if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority); + } + return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant; + } + d3_selectionPrototype.property = function(name, value) { + if (arguments.length < 2) { + if (typeof name === "string") return this.node()[name]; + for (value in name) this.each(d3_selection_property(value, name[value])); + return this; + } + return this.each(d3_selection_property(name, value)); + }; + function d3_selection_property(name, value) { + function propertyNull() { + delete this[name]; + } + function propertyConstant() { + this[name] = value; + } + function propertyFunction() { + var x = value.apply(this, arguments); + if (x == null) delete this[name]; else this[name] = x; + } + return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant; + } + d3_selectionPrototype.text = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value) { + return arguments.length ? this.each(typeof value === "function" ? function() { + var v = value.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name) { + name = d3_selection_creator(name); + return this.select(function() { + return this.appendChild(name.apply(this, arguments)); + }); + }; + function d3_selection_creator(name) { + return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? function() { + return this.ownerDocument.createElementNS(name.space, name.local); + } : function() { + return this.ownerDocument.createElementNS(this.namespaceURI, name); + }; + } + d3_selectionPrototype.insert = function(name, before) { + name = d3_selection_creator(name); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(function() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); + }); + }; + d3_selectionPrototype.data = function(value, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value[i] = node.__data__; + } + } + return value; + } + function bind(group, groupData) { + var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), dataByKeyValue = new d3_Map(), keyValues = [], keyValue; + for (i = -1; ++i < n; ) { + keyValue = key.call(node = group[i], node.__data__, i); + if (nodeByKeyValue.has(keyValue)) { + exitNodes[i] = node; + } else { + nodeByKeyValue.set(keyValue, node); + } + keyValues.push(keyValue); + } + for (i = -1; ++i < m; ) { + keyValue = key.call(groupData, nodeData = groupData[i], i); + if (node = nodeByKeyValue.get(keyValue)) { + updateNodes[i] = node; + node.__data__ = nodeData; + } else if (!dataByKeyValue.has(keyValue)) { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + dataByKeyValue.set(keyValue, nodeData); + nodeByKeyValue.remove(keyValue); + } + for (i = -1; ++i < n; ) { + if (nodeByKeyValue.has(keyValues[i])) { + exitNodes[i] = group[i]; + } + } + } else { + for (i = -1; ++i < n0; ) { + node = group[i]; + nodeData = groupData[i]; + if (node) { + node.__data__ = nodeData; + updateNodes[i] = node; + } else { + enterNodes[i] = d3_selection_dataNode(nodeData); + } + } + for (;i < m; ++i) { + enterNodes[i] = d3_selection_dataNode(groupData[i]); + } + for (;i < n; ++i) { + exitNodes[i] = group[i]; + } + } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode; + enter.push(enterNodes); + update.push(updateNodes); + exit.push(exitNodes); + } + var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]); + if (typeof value === "function") { + while (++i < n) { + bind(group = this[i], value.call(group, group.parentNode.__data__, i)); + } + } else { + while (++i < n) { + bind(group = this[i], value); + } + } + update.enter = function() { + return enter; + }; + update.exit = function() { + return exit; + }; + return update; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; + } + d3_selectionPrototype.datum = function(value) { + return arguments.length ? this.property("__data__", value) : this.property("__data__"); + }; + d3_selectionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i)) { + subgroup.push(node); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } + } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3.ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; + } + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } + } + return groups; + } + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + this.each(function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; + } + var d3_selection_enterPrototype = []; + d3.selection.enter = d3_selection_enter; + d3.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; + } + d3_selectionPrototype.transition = function() { + var id = d3_transitionInheritId || ++d3_transitionId, subgroups = [], subgroup, node, transition = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, id, transition); + subgroup.push(node); + } + } + return d3_transition(subgroups, id); + }; + d3_selectionPrototype.interrupt = function() { + return this.each(d3_selection_interrupt); + }; + function d3_selection_interrupt() { + var lock = this.__transition__; + if (lock) ++lock.active; + } + d3.select = function(node) { + var group = [ typeof node === "string" ? d3_select(node, d3_document) : node ]; + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + d3.selectAll = function(nodes) { + var group = d3_array(typeof nodes === "string" ? d3_selectAll(nodes, d3_document) : nodes); + group.parentNode = d3_documentElement; + return d3_selection([ group ]); + }; + var d3_selectionRoot = d3.select(d3_documentElement); + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.substring(0, i); + var filter = d3_selection_onFilters.get(type); + if (filter) type = filter, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match; + for (var name in this) { + if (match = name.match(re)) { + var l = this[name]; + this.removeEventListener(match[1], l, l.$); + delete this[name]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; + } + var d3_selection_onFilters = d3.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d3.event; + d3.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d3.event = o; + } + }; + } + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; + } + var d3_event_dragSelect = "onselectstart" in d3_document ? null : d3_vendorSymbol(d3_documentElement.style, "userSelect"), d3_event_dragId = 0; + function d3_event_dragSuppress() { + var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault); + if (d3_event_dragSelect) { + var style = d3_documentElement.style, select = style[d3_event_dragSelect]; + style[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name, null); + if (d3_event_dragSelect) style[d3_event_dragSelect] = select; + if (suppressClick) { + function off() { + w.on(click, null); + } + w.on(click, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; + } + d3.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = /WebKit/.test(d3_window.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0 && (d3_window.scrollX || d3_window.scrollY)) { + svg = d3.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, + point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [ point.x, point.y ]; + } + var rect = container.getBoundingClientRect(); + return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ]; + } + d3.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + d3.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, "mousemove", "mouseup"), touchstart = dragstart(touchid, touchposition, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function touchid() { + return d3.event.changedTouches[0].identifier; + } + function touchposition(parent, id) { + return d3.touches(parent).filter(function(p) { + return p.identifier === id; + })[0]; + } + function dragstart(id, position, move, end) { + return function() { + var target = this, parent = target.parentNode, event_ = event.of(target, arguments), eventTarget = d3.event.target, eventId = id(), drag = eventId == null ? "drag" : "drag-" + eventId, origin_ = position(parent, eventId), dragged = 0, offset, w = d3.select(d3_window).on(move + "." + drag, moved).on(end + "." + drag, ended), dragRestore = d3_event_dragSuppress(); + if (origin) { + offset = origin.apply(target, arguments); + offset = [ offset.x - origin_[0], offset.y - origin_[1] ]; + } else { + offset = [ 0, 0 ]; + } + event_({ + type: "dragstart" + }); + function moved() { + var p = position(parent, eventId), dx = p[0] - origin_[0], dy = p[1] - origin_[1]; + dragged |= dx | dy; + origin_ = p; + event_({ + type: "drag", + x: p[0] + offset[0], + y: p[1] + offset[1], + dx: dx, + dy: dy + }); + } + function ended() { + w.on(move + "." + drag, null).on(end + "." + drag, null); + dragRestore(dragged && d3.event.target === eventTarget); + event_({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d3.rebind(drag, event, "on"); + }; + var Ï€ = Math.PI, Ï„ = 2 * Ï€, halfÏ€ = Ï€ / 2, ε = 1e-6, ε2 = ε * ε, d3_radians = Ï€ / 180, d3_degrees = 180 / Ï€; + function d3_sgn(x) { + return x > 0 ? 1 : x < 0 ? -1 : 0; + } + function d3_acos(x) { + return x > 1 ? 0 : x < -1 ? Ï€ : Math.acos(x); + } + function d3_asin(x) { + return x > 1 ? halfÏ€ : x < -1 ? -halfÏ€ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + function d3_haversin(x) { + return (x = Math.sin(x / 2)) * x; + } + var Ï = Math.SQRT2, Ï2 = 2, Ï4 = 4; + d3.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2]; + var dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + Ï4 * d2) / (2 * w0 * Ï2 * d1), b1 = (w1 * w1 - w0 * w0 - Ï4 * d2) / (2 * w1 * Ï2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1), dr = r1 - r0, S = (dr || Math.log(w1 / w0)) / Ï; + function interpolate(t) { + var s = t * S; + if (dr) { + var coshr0 = d3_cosh(r0), u = w0 / (Ï2 * d1) * (coshr0 * d3_tanh(Ï * s + r0) - d3_sinh(r0)); + return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(Ï * s + r0) ]; + } + return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(Ï * s) ]; + } + interpolate.duration = S * 1e3; + return interpolate; + }; + d3.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + function zoom(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on(mousemove, mousewheelreset).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), view1 = view; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.zoom", function() { + view = this.__chart__ || { + x: 0, + y: 0, + k: 1 + }; + zoomstarted(event_); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = dx / 2, cy = dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]); + return function(t) { + var l = i(t), k = dx / l[2]; + this.__chart__ = view = { + x: cx - l[0] * k, + y: cy - l[1] * k, + k: k + }; + zoomed(event_); + }; + }).each("end.zoom", function() { + zoomended(event_); + }); + } else { + this.__chart__ = view; + zoomstarted(event_); + zoomed(event_); + zoomended(event_); + } + }); + }; + zoom.translate = function(_) { + if (!arguments.length) return [ view.x, view.y ]; + view = { + x: +_[0], + y: +_[1], + k: view.k + }; + rescale(); + return zoom; + }; + zoom.scale = function(_) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: +_ + }; + rescale(); + return zoom; + }; + zoom.scaleExtent = function(_) { + if (!arguments.length) return scaleExtent; + scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ]; + return zoom; + }; + zoom.center = function(_) { + if (!arguments.length) return center; + center = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.size = function(_) { + if (!arguments.length) return size; + size = _ && [ +_[0], +_[1] ]; + return zoom; + }; + zoom.x = function(z) { + if (!arguments.length) return x1; + x1 = z; + x0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + zoom.y = function(z) { + if (!arguments.length) return y1; + y1 = z; + y0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom; + }; + function location(p) { + return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ]; + } + function point(l) { + return [ l[0] * view.k + view.x, l[1] * view.k + view.y ]; + } + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(event) { + event({ + type: "zoomstart" + }); + } + function zoomed(event) { + rescale(); + event({ + type: "zoom", + scale: view.k, + translate: [ view.x, view.y ] + }); + } + function zoomended(event) { + event({ + type: "zoomend" + }); + } + function mousedowned() { + var target = this, event_ = event.of(target, arguments), eventTarget = d3.event.target, dragged = 0, w = d3.select(d3_window).on(mousemove, moved).on(mouseup, ended), l = location(d3.mouse(target)), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(target); + zoomstarted(event_); + function moved() { + dragged = 1; + translateTo(d3.mouse(target), l); + zoomed(event_); + } + function ended() { + w.on(mousemove, d3_window === target ? mousewheelreset : null).on(mouseup, null); + dragRestore(dragged && d3.event.target === eventTarget); + zoomended(event_); + } + } + function touchstarted() { + var target = this, event_ = event.of(target, arguments), locations0 = {}, distance0 = 0, scale0, eventId = d3.event.changedTouches[0].identifier, touchmove = "touchmove.zoom-" + eventId, touchend = "touchend.zoom-" + eventId, w = d3.select(d3_window).on(touchmove, moved).on(touchend, ended), t = d3.select(target).on(mousedown, null).on(touchstart, started), dragRestore = d3_event_dragSuppress(); + d3_selection_interrupt.call(target); + started(); + zoomstarted(event_); + function relocate() { + var touches = d3.touches(target); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; + } + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0], l = locations0[p.identifier]; + scaleTo(view.k * 2); + translateTo(p, l); + d3_eventPreventDefault(); + zoomed(event_); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d3.touches(target), p0, l0, p1, l1; + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ]; + l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(event_); + } + function ended() { + if (d3.event.touches.length) { + var changed = d3.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + w.on(touchmove, null).on(touchend, null); + t.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(event_); + } + } + function mousewheeled() { + var event_ = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), + zoomstarted(event_); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(event_); + }, 50); + d3_eventPreventDefault(); + var point = center || d3.mouse(this); + if (!translate0) translate0 = location(point); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k); + translateTo(point, translate0); + zoomed(event_); + } + function mousewheelreset() { + translate0 = null; + } + function dblclicked() { + var event_ = event.of(this, arguments), p = d3.mouse(this), l = location(p), k = Math.log(view.k) / Math.LN2; + zoomstarted(event_); + scaleTo(Math.pow(2, d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1)); + translateTo(p, l); + zoomed(event_); + zoomended(event_); + } + return d3.rebind(zoom, event, "on"); + }; + var d3_behavior_zoomInfinity = [ 0, Infinity ]; + var d3_behavior_zoomDelta, d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d3.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d3.event.detail; + }, "MozMousePixelScroll"); + function d3_Color() {} + d3_Color.prototype.toString = function() { + return this.rgb() + ""; + }; + d3.hsl = function(h, s, l) { + return arguments.length === 1 ? h instanceof d3_Hsl ? d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : d3_hsl(+h, +s, +l); + }; + function d3_hsl(h, s, l) { + return new d3_Hsl(h, s, l); + } + function d3_Hsl(h, s, l) { + this.h = h; + this.s = s; + this.l = l; + } + var d3_hslPrototype = d3_Hsl.prototype = new d3_Color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= .5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h) { + if (h > 360) h -= 360; else if (h < 0) h += 360; + if (h < 60) return m1 + (m2 - m1) * h / 60; + if (h < 180) return m2; + if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60; + return m1; + } + function vv(h) { + return Math.round(v(h) * 255); + } + return d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + } + d3.hcl = function(h, c, l) { + return arguments.length === 1 ? h instanceof d3_Hcl ? d3_hcl(h.h, h.c, h.l) : h instanceof d3_Lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : d3_hcl(+h, +c, +l); + }; + function d3_hcl(h, c, l) { + return new d3_Hcl(h, c, l); + } + function d3_Hcl(h, c, l) { + this.h = h; + this.c = c; + this.l = l; + } + var d3_hclPrototype = d3_Hcl.prototype = new d3_Color(); + d3_hclPrototype.brighter = function(k) { + return d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.darker = function(k) { + return d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.rgb = function() { + return d3_hcl_lab(this.h, this.c, this.l).rgb(); + }; + function d3_hcl_lab(h, c, l) { + if (isNaN(h)) h = 0; + if (isNaN(c)) c = 0; + return d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + } + d3.lab = function(l, a, b) { + return arguments.length === 1 ? l instanceof d3_Lab ? d3_lab(l.l, l.a, l.b) : l instanceof d3_Hcl ? d3_hcl_lab(l.l, l.c, l.h) : d3_rgb_lab((l = d3.rgb(l)).r, l.g, l.b) : d3_lab(+l, +a, +b); + }; + function d3_lab(l, a, b) { + return new d3_Lab(l, a, b); + } + function d3_Lab(l, a, b) { + this.l = l; + this.a = a; + this.b = b; + } + var d3_lab_K = 18; + var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; + var d3_labPrototype = d3_Lab.prototype = new d3_Color(); + d3_labPrototype.brighter = function(k) { + return d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.darker = function(k) { + return d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.rgb = function() { + return d3_lab_rgb(this.l, this.a, this.b); + }; + function d3_lab_rgb(l, a, b) { + var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; + x = d3_lab_xyz(x) * d3_lab_X; + y = d3_lab_xyz(y) * d3_lab_Y; + z = d3_lab_xyz(z) * d3_lab_Z; + return d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z)); + } + function d3_lab_hcl(l, a, b) { + return l > 0 ? d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : d3_hcl(NaN, NaN, l); + } + function d3_lab_xyz(x) { + return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + } + function d3_xyz_lab(x) { + return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + } + function d3_xyz_rgb(r) { + return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055)); + } + d3.rgb = function(r, g, b) { + return arguments.length === 1 ? r instanceof d3_Rgb ? d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : d3_rgb(~~r, ~~g, ~~b); + }; + function d3_rgbNumber(value) { + return d3_rgb(value >> 16, value >> 8 & 255, value & 255); + } + function d3_rgbString(value) { + return d3_rgbNumber(value) + ""; + } + function d3_rgb(r, g, b) { + return new d3_Rgb(r, g, b); + } + function d3_Rgb(r, g, b) { + this.r = r; + this.g = g; + this.b = b; + } + var d3_rgbPrototype = d3_Rgb.prototype = new d3_Color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return d3_rgb(Math.min(255, ~~(r / k)), Math.min(255, ~~(g / k)), Math.min(255, ~~(b / k))); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(.7, arguments.length ? k : 1); + return d3_rgb(~~(k * this.r), ~~(k * this.g), ~~(k * this.b)); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format, rgb, hsl) { + var r = 0, g = 0, b = 0, m1, m2, name; + m1 = /([a-z]+)\((.*)\)/i.exec(format); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": + { + return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } + + case "rgb": + { + return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + } + } + } + if (name = d3_rgb_names.get(format)) return rgb(name.r, name.g, name.b); + if (format != null && format.charAt(0) === "#") { + if (format.length === 4) { + r = format.charAt(1); + r += r; + g = format.charAt(2); + g += g; + b = format.charAt(3); + b += b; + } else if (format.length === 7) { + r = format.substring(1, 3); + g = format.substring(3, 5); + b = format.substring(5, 7); + } + r = parseInt(r, 16); + g = parseInt(g, 16); + b = parseInt(b, 16); + } + return rgb(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < .5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4; + h *= 60; + } else { + h = NaN; + s = l > 0 && l < 1 ? 0 : h; + } + return d3_hsl(h, s, l); + } + function d3_rgb_lab(r, g, b) { + r = d3_rgb_xyz(r); + g = d3_rgb_xyz(g); + b = d3_rgb_xyz(b); + var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z); + return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); + } + function d3_rgb_xyz(r) { + return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4); + } + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d3.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value) { + d3_rgb_names.set(key, d3_rgbNumber(value)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d3.functor = d3_functor; + function d3_identity(d) { + return d; + } + d3.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, + mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (d3_window.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && request.responseText || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; + } + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); + } + } + request.onprogress = function(event) { + var o = d3.event; + d3.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d3.event = o; + } + }; + xhr.header = function(name, value) { + name = (name + "").toLowerCase(); + if (arguments.length < 2) return headers[name]; + if (value == null) delete headers[name]; else headers[name] = value + ""; + return xhr; + }; + xhr.mimeType = function(value) { + if (!arguments.length) return mimeType; + mimeType = value == null ? null : value + ""; + return xhr; + }; + xhr.responseType = function(value) { + if (!arguments.length) return responseType; + responseType = value; + return xhr; + }; + xhr.response = function(value) { + response = value; + return xhr; + }; + [ "get", "post" ].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback) { + if (arguments.length === 2 && typeof data === "function") callback = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback != null) xhr.on("error", callback).on("load", function(request) { + callback(null, request); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d3.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + d3.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3.xhr(url, mimeType, callback); + xhr.row = function(_) { + return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row; + }; + return xhr.row(row); + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = new Function("d", "return {" + row.map(function(name, i) { + return JSON.stringify(name) + ": d[" + i + "]"; + }).join(",") + "}"); + o = f ? function(row, i) { + return f(a(row), i); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.substring(j + 1, i).replace(/""/g, '"'); + } + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.substring(j, I - k); + } + return text.substring(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); + } + if (f && !(a = f(a, n++))) continue; + rows.push(a); + } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue).join(delimiter); + } + function formatValue(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d3.csv = d3.dsv(",", "text/csv"); + d3.tsv = d3.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_active, d3_timer_frame = d3_window[d3_vendorSymbol(d3_window, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d3.timer = function(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + f: false, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + }; + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); + } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d3.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(); + d3_timer_active = d3_timer_queueHead; + while (d3_timer_active) { + if (now >= d3_timer_active.t) d3_timer_active.f = d3_timer_active.c(now - d3_timer_active.t); + d3_timer_active = d3_timer_active.n; + } + return now; + } + function d3_timer_sweep() { + var t0, t1 = d3_timer_queueHead, time = Infinity; + while (t1) { + if (t1.f) { + t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n; + } else { + if (t1.t < time) time = t1.t; + t1 = (t0 = t1).n; + } + } + d3_timer_queueTail = t0; + return time; + } + var d3_format_decimalPoint = ".", d3_format_thousandsSeparator = ",", d3_format_grouping = [ 3, 3 ], d3_format_currencySymbol = "$"; + var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix); + d3.formatPrefix = function(value, precision) { + var i = 0; + if (value) { + if (value < 0) value *= -1; + if (precision) value = d3.round(value, d3_format_precision(value, precision)); + i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); + i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3)); + } + return d3_formatPrefixes[8 + i / 3]; + }; + function d3_formatPrefix(d, i) { + var k = Math.pow(10, abs(8 - i) * 3); + return { + scale: i > 8 ? function(d) { + return d / k; + } : function(d) { + return d * k; + }, + symbol: d + }; + } + d3.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + d3.format = function(specifier) { + var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, suffix = "", integer = false; + if (precision) precision = +precision.substring(1); + if (zfill || fill === "0" && align === "=") { + zfill = fill = "0"; + align = "="; + if (comma) width -= Math.floor((width - 1) / 4); + } + switch (type) { + case "n": + comma = true; + type = "g"; + break; + + case "%": + scale = 100; + suffix = "%"; + type = "f"; + break; + + case "p": + scale = 100; + suffix = "%"; + type = "r"; + break; + + case "b": + case "o": + case "x": + case "X": + if (symbol === "#") symbol = "0" + type.toLowerCase(); + + case "c": + case "d": + integer = true; + precision = 0; + break; + + case "s": + scale = -1; + type = "r"; + break; + } + if (symbol === "#") symbol = ""; else if (symbol === "$") symbol = d3_format_currencySymbol; + if (type == "r" && !precision) type = "g"; + if (precision != null) { + if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision)); + } + type = d3_format_types.get(type) || d3_format_typeDefault; + var zcomma = zfill && comma; + return function(value) { + if (integer && value % 1) return ""; + var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign; + if (scale < 0) { + var prefix = d3.formatPrefix(value, precision); + value = prefix.scale(value); + suffix = prefix.symbol; + } else { + value *= scale; + } + value = type(value, precision); + var i = value.lastIndexOf("."), before = i < 0 ? value : value.substring(0, i), after = i < 0 ? "" : d3_format_decimalPoint + value.substring(i + 1); + if (!zfill && comma) before = d3_format_group(before); + var length = symbol.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : ""; + if (zcomma) before = d3_format_group(padding + before); + negative += symbol; + value = before + after; + return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + suffix; + }; + }; + var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; + var d3_format_types = d3.map({ + b: function(x) { + return x.toString(2); + }, + c: function(x) { + return String.fromCharCode(x); + }, + o: function(x) { + return x.toString(8); + }, + x: function(x) { + return x.toString(16); + }, + X: function(x) { + return x.toString(16).toUpperCase(); + }, + g: function(x, p) { + return x.toPrecision(p); + }, + e: function(x, p) { + return x.toExponential(p); + }, + f: function(x, p) { + return x.toFixed(p); + }, + r: function(x, p) { + return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p)))); + } + }); + function d3_format_precision(x, p) { + return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1); + } + function d3_format_typeDefault(x) { + return x + ""; + } + var d3_format_group = d3_identity; + if (d3_format_grouping) { + var d3_format_groupingLength = d3_format_grouping.length; + d3_format_group = function(value) { + var i = value.length, t = [], j = 0, g = d3_format_grouping[0]; + while (i > 0 && g > 0) { + t.push(value.substring(i -= g, i + g)); + g = d3_format_grouping[j = (j + 1) % d3_format_groupingLength]; + } + return t.reverse().join(d3_format_thousandsSeparator); + }; + } + d3.geo = {}; + function d3_adder() {} + d3_adder.prototype = { + s: 0, + t: 0, + add: function(y) { + d3_adderSum(y, this.t, d3_adderTemp); + d3_adderSum(d3_adderTemp.s, this.s, this); + if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t; + }, + reset: function() { + this.s = this.t = 0; + }, + valueOf: function() { + return this.s; + } + }; + var d3_adderTemp = new d3_adder(); + function d3_adderSum(a, b, o) { + var x = o.s = a + b, bv = x - a, av = x - bv; + o.t = a - av + (b - bv); + } + d3.geo.stream = function(object, listener) { + if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) { + d3_geo_streamObjectType[object.type](object, listener); + } else { + d3_geo_streamGeometry(object, listener); + } + }; + function d3_geo_streamGeometry(geometry, listener) { + if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) { + d3_geo_streamGeometryType[geometry.type](geometry, listener); + } + } + var d3_geo_streamObjectType = { + Feature: function(feature, listener) { + d3_geo_streamGeometry(feature.geometry, listener); + }, + FeatureCollection: function(object, listener) { + var features = object.features, i = -1, n = features.length; + while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener); + } + }; + var d3_geo_streamGeometryType = { + Sphere: function(object, listener) { + listener.sphere(); + }, + Point: function(object, listener) { + object = object.coordinates; + listener.point(object[0], object[1], object[2]); + }, + MultiPoint: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]); + }, + LineString: function(object, listener) { + d3_geo_streamLine(object.coordinates, listener, 0); + }, + MultiLineString: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0); + }, + Polygon: function(object, listener) { + d3_geo_streamPolygon(object.coordinates, listener); + }, + MultiPolygon: function(object, listener) { + var coordinates = object.coordinates, i = -1, n = coordinates.length; + while (++i < n) d3_geo_streamPolygon(coordinates[i], listener); + }, + GeometryCollection: function(object, listener) { + var geometries = object.geometries, i = -1, n = geometries.length; + while (++i < n) d3_geo_streamGeometry(geometries[i], listener); + } + }; + function d3_geo_streamLine(coordinates, listener, closed) { + var i = -1, n = coordinates.length - closed, coordinate; + listener.lineStart(); + while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]); + listener.lineEnd(); + } + function d3_geo_streamPolygon(coordinates, listener) { + var i = -1, n = coordinates.length; + listener.polygonStart(); + while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1); + listener.polygonEnd(); + } + d3.geo.area = function(object) { + d3_geo_areaSum = 0; + d3.geo.stream(object, d3_geo_area); + return d3_geo_areaSum; + }; + var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder(); + var d3_geo_area = { + sphere: function() { + d3_geo_areaSum += 4 * Ï€; + }, + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_areaRingSum.reset(); + d3_geo_area.lineStart = d3_geo_areaRingStart; + }, + polygonEnd: function() { + var area = 2 * d3_geo_areaRingSum; + d3_geo_areaSum += area < 0 ? 4 * Ï€ + area : area; + d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop; + } + }; + function d3_geo_areaRingStart() { + var λ00, φ00, λ0, cosφ0, sinφ0; + d3_geo_area.point = function(λ, φ) { + d3_geo_area.point = nextPoint; + λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + Ï€ / 4), + sinφ0 = Math.sin(φ); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + φ = φ * d3_radians / 2 + Ï€ / 4; + var dλ = λ - λ0, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(dλ), v = k * Math.sin(dλ); + d3_geo_areaRingSum.add(Math.atan2(v, u)); + λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ; + } + d3_geo_area.lineEnd = function() { + nextPoint(λ00, φ00); + }; + } + function d3_geo_cartesian(spherical) { + var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ); + return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ]; + } + function d3_geo_cartesianDot(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + } + function d3_geo_cartesianCross(a, b) { + return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; + } + function d3_geo_cartesianAdd(a, b) { + a[0] += b[0]; + a[1] += b[1]; + a[2] += b[2]; + } + function d3_geo_cartesianScale(vector, k) { + return [ vector[0] * k, vector[1] * k, vector[2] * k ]; + } + function d3_geo_cartesianNormalize(d) { + var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); + d[0] /= l; + d[1] /= l; + d[2] /= l; + } + function d3_geo_spherical(cartesian) { + return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ]; + } + function d3_geo_sphericalEqual(a, b) { + return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε; + } + d3.geo.bounds = function() { + var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range; + var bound = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + bound.point = ringPoint; + bound.lineStart = ringStart; + bound.lineEnd = ringEnd; + dλSum = 0; + d3_geo_area.polygonStart(); + }, + polygonEnd: function() { + d3_geo_area.polygonEnd(); + bound.point = point; + bound.lineStart = lineStart; + bound.lineEnd = lineEnd; + if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90; + range[0] = λ0, range[1] = λ1; + } + }; + function point(λ, φ) { + ranges.push(range = [ λ0 = λ, λ1 = λ ]); + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + function linePoint(λ, φ) { + var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]); + if (p0) { + var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal); + d3_geo_cartesianNormalize(inflection); + inflection = d3_geo_spherical(inflection); + var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180; + if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = inflection[1] * d3_degrees; + if (φi > φ1) φ1 = φi; + } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) { + var φi = -inflection[1] * d3_degrees; + if (φi < φ0) φ0 = φi; + } else { + if (φ < φ0) φ0 = φ; + if (φ > φ1) φ1 = φ; + } + if (antimeridian) { + if (λ < λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } else { + if (λ1 >= λ0) { + if (λ < λ0) λ0 = λ; + if (λ > λ1) λ1 = λ; + } else { + if (λ > λ_) { + if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ; + } else { + if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ; + } + } + } + } else { + point(λ, φ); + } + p0 = p, λ_ = λ; + } + function lineStart() { + bound.point = linePoint; + } + function lineEnd() { + range[0] = λ0, range[1] = λ1; + bound.point = point; + p0 = null; + } + function ringPoint(λ, φ) { + if (p0) { + var dλ = λ - λ_; + dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ; + } else λ__ = λ, φ__ = φ; + d3_geo_area.point(λ, φ); + linePoint(λ, φ); + } + function ringStart() { + d3_geo_area.lineStart(); + } + function ringEnd() { + ringPoint(λ__, φ__); + d3_geo_area.lineEnd(); + if (abs(dλSum) > ε) λ0 = -(λ1 = 180); + range[0] = λ0, range[1] = λ1; + p0 = null; + } + function angle(λ0, λ1) { + return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1; + } + function compareRanges(a, b) { + return a[0] - b[0]; + } + function withinRange(x, range) { + return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x; + } + return function(feature) { + φ1 = λ1 = -(λ0 = φ0 = Infinity); + ranges = []; + d3.geo.stream(feature, bound); + var n = ranges.length; + if (n) { + ranges.sort(compareRanges); + for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) { + b = ranges[i]; + if (withinRange(b[0], a) || withinRange(b[1], a)) { + if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1]; + if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0]; + } else { + merged.push(a = b); + } + } + var best = -Infinity, dλ; + for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) { + b = merged[i]; + if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1]; + } + } + ranges = range = null; + return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ]; + }; + }(); + d3.geo.centroid = function(object) { + d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, d3_geo_centroid); + var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z; + if (m < ε2) { + x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1; + if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0; + m = x * x + y * y + z * z; + if (m < ε2) return [ NaN, NaN ]; + } + return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ]; + }; + var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2; + var d3_geo_centroid = { + sphere: d3_noop, + point: d3_geo_centroidPoint, + lineStart: d3_geo_centroidLineStart, + lineEnd: d3_geo_centroidLineEnd, + polygonStart: function() { + d3_geo_centroid.lineStart = d3_geo_centroidRingStart; + }, + polygonEnd: function() { + d3_geo_centroid.lineStart = d3_geo_centroidLineStart; + } + }; + function d3_geo_centroidPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ)); + } + function d3_geo_centroidPointXYZ(x, y, z) { + ++d3_geo_centroidW0; + d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0; + d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0; + d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0; + } + function d3_geo_centroidLineStart() { + var x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroid.point = nextPoint; + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_geo_centroidLineEnd() { + d3_geo_centroid.point = d3_geo_centroidPoint; + } + function d3_geo_centroidRingStart() { + var λ00, φ00, x0, y0, z0; + d3_geo_centroid.point = function(λ, φ) { + λ00 = λ, φ00 = φ; + d3_geo_centroid.point = nextPoint; + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians); + x0 = cosφ * Math.cos(λ); + y0 = cosφ * Math.sin(λ); + z0 = Math.sin(φ); + d3_geo_centroidPointXYZ(x0, y0, z0); + }; + d3_geo_centroid.lineEnd = function() { + nextPoint(λ00, φ00); + d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd; + d3_geo_centroid.point = d3_geo_centroidPoint; + }; + function nextPoint(λ, φ) { + λ *= d3_radians; + var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u); + d3_geo_centroidX2 += v * cx; + d3_geo_centroidY2 += v * cy; + d3_geo_centroidZ2 += v * cz; + d3_geo_centroidW1 += w; + d3_geo_centroidX1 += w * (x0 + (x0 = x)); + d3_geo_centroidY1 += w * (y0 + (y0 = y)); + d3_geo_centroidZ1 += w * (z0 + (z0 = z)); + d3_geo_centroidPointXYZ(x0, y0, z0); + } + } + function d3_true() { + return true; + } + function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) { + var subject = [], clip = []; + segments.forEach(function(segment) { + if ((n = segment.length - 1) <= 0) return; + var n, p0 = segment[0], p1 = segment[n]; + if (d3_geo_sphericalEqual(p0, p1)) { + listener.lineStart(); + for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]); + listener.lineEnd(); + return; + } + var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false); + a.o = b; + subject.push(a); + clip.push(b); + a = new d3_geo_clipPolygonIntersection(p1, segment, null, false); + b = new d3_geo_clipPolygonIntersection(p1, null, a, true); + a.o = b; + subject.push(a); + clip.push(b); + }); + clip.sort(compare); + d3_geo_clipPolygonLinkCircular(subject); + d3_geo_clipPolygonLinkCircular(clip); + if (!subject.length) return; + for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) { + clip[i].e = entry = !entry; + } + var start = subject[0], points, point; + while (1) { + var current = start, isSubject = true; + while (current.v) if ((current = current.n) === start) return; + points = current.z; + listener.lineStart(); + do { + current.v = current.o.v = true; + if (current.e) { + if (isSubject) { + for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.n.x, 1, listener); + } + current = current.n; + } else { + if (isSubject) { + points = current.p.z; + for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]); + } else { + interpolate(current.x, current.p.x, -1, listener); + } + current = current.p; + } + current = current.o; + points = current.z; + isSubject = !isSubject; + } while (!current.v); + listener.lineEnd(); + } + } + function d3_geo_clipPolygonLinkCircular(array) { + if (!(n = array.length)) return; + var n, i = 0, a = array[0], b; + while (++i < n) { + a.n = b = array[i]; + b.p = a; + a = b; + } + a.n = b = array[0]; + b.p = a; + } + function d3_geo_clipPolygonIntersection(point, points, other, entry) { + this.x = point; + this.z = points; + this.o = other; + this.e = entry; + this.v = false; + this.n = this.p = null; + } + function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) { + return function(rotate, listener) { + var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]); + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + clip.point = pointRing; + clip.lineStart = ringStart; + clip.lineEnd = ringEnd; + segments = []; + polygon = []; + listener.polygonStart(); + }, + polygonEnd: function() { + clip.point = point; + clip.lineStart = lineStart; + clip.lineEnd = lineEnd; + segments = d3.merge(segments); + var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon); + if (segments.length) { + d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener); + } else if (clipStartInside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + listener.polygonEnd(); + segments = polygon = null; + }, + sphere: function() { + listener.polygonStart(); + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + listener.polygonEnd(); + } + }; + function point(λ, φ) { + var point = rotate(λ, φ); + if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ); + } + function pointLine(λ, φ) { + var point = rotate(λ, φ); + line.point(point[0], point[1]); + } + function lineStart() { + clip.point = pointLine; + line.lineStart(); + } + function lineEnd() { + clip.point = point; + line.lineEnd(); + } + var segments; + var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygon, ring; + function pointRing(λ, φ) { + ring.push([ λ, φ ]); + var point = rotate(λ, φ); + ringListener.point(point[0], point[1]); + } + function ringStart() { + ringListener.lineStart(); + ring = []; + } + function ringEnd() { + pointRing(ring[0][0], ring[0][1]); + ringListener.lineEnd(); + var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length; + ring.pop(); + polygon.push(ring); + ring = null; + if (!n) return; + if (clean & 1) { + segment = ringSegments[0]; + var n = segment.length - 1, i = -1, point; + listener.lineStart(); + while (++i < n) listener.point((point = segment[i])[0], point[1]); + listener.lineEnd(); + return; + } + if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); + segments.push(ringSegments.filter(d3_geo_clipSegmentLength1)); + } + return clip; + }; + } + function d3_geo_clipSegmentLength1(segment) { + return segment.length > 1; + } + function d3_geo_clipBufferListener() { + var lines = [], line; + return { + lineStart: function() { + lines.push(line = []); + }, + point: function(λ, φ) { + line.push([ λ, φ ]); + }, + lineEnd: d3_noop, + buffer: function() { + var buffer = lines; + lines = []; + line = null; + return buffer; + }, + rejoin: function() { + if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); + } + }; + } + function d3_geo_clipSort(a, b) { + return ((a = a.x)[0] < 0 ? a[1] - halfÏ€ - ε : halfÏ€ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfÏ€ - ε : halfÏ€ - b[1]); + } + function d3_geo_pointInPolygon(point, polygon) { + var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0; + d3_geo_areaRingSum.reset(); + for (var i = 0, n = polygon.length; i < n; ++i) { + var ring = polygon[i], m = ring.length; + if (!m) continue; + var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + Ï€ / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1; + while (true) { + if (j === m) j = 0; + point = ring[j]; + var λ = point[0], φ = point[1] / 2 + Ï€ / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, antimeridian = abs(dλ) > Ï€, k = sinφ0 * sinφ; + d3_geo_areaRingSum.add(Math.atan2(k * Math.sin(dλ), cosφ0 * cosφ + k * Math.cos(dλ))); + polarAngle += antimeridian ? dλ + (dλ >= 0 ? Ï„ : -Ï„) : dλ; + if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) { + var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point)); + d3_geo_cartesianNormalize(arc); + var intersection = d3_geo_cartesianCross(meridianNormal, arc); + d3_geo_cartesianNormalize(intersection); + var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]); + if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) { + winding += antimeridian ^ dλ >= 0 ? 1 : -1; + } + } + if (!j++) break; + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point; + } + } + return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < 0) ^ winding & 1; + } + var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -Ï€, -Ï€ / 2 ]); + function d3_geo_clipAntimeridianLine(listener) { + var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean; + return { + lineStart: function() { + listener.lineStart(); + clean = 1; + }, + point: function(λ1, φ1) { + var sλ1 = λ1 > 0 ? Ï€ : -Ï€, dλ = abs(λ1 - λ0); + if (abs(dλ - Ï€) < ε) { + listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfÏ€ : -halfÏ€); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + listener.point(λ1, φ0); + clean = 0; + } else if (sλ0 !== sλ1 && dλ >= Ï€) { + if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε; + if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε; + φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1); + listener.point(sλ0, φ0); + listener.lineEnd(); + listener.lineStart(); + listener.point(sλ1, φ0); + clean = 0; + } + listener.point(λ0 = λ1, φ0 = φ1); + sλ0 = sλ1; + }, + lineEnd: function() { + listener.lineEnd(); + λ0 = φ0 = NaN; + }, + clean: function() { + return 2 - clean; + } + }; + } + function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) { + var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1); + return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2; + } + function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) { + var φ; + if (from == null) { + φ = direction * halfÏ€; + listener.point(-Ï€, φ); + listener.point(0, φ); + listener.point(Ï€, φ); + listener.point(Ï€, 0); + listener.point(Ï€, -φ); + listener.point(0, -φ); + listener.point(-Ï€, -φ); + listener.point(-Ï€, 0); + listener.point(-Ï€, φ); + } else if (abs(from[0] - to[0]) > ε) { + var s = from[0] < to[0] ? Ï€ : -Ï€; + φ = direction * s / 2; + listener.point(-s, φ); + listener.point(0, φ); + listener.point(s, φ); + } else { + listener.point(to[0], to[1]); + } + } + function d3_geo_clipCircle(radius) { + var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians); + return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -Ï€, radius - Ï€ ]); + function visible(λ, φ) { + return Math.cos(λ) * Math.cos(φ) > cr; + } + function clipLine(listener) { + var point0, c0, v0, v00, clean; + return { + lineStart: function() { + v00 = v0 = false; + clean = 1; + }, + point: function(λ, φ) { + var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? Ï€ : -Ï€), φ) : 0; + if (!point0 && (v00 = v0 = v)) listener.lineStart(); + if (v !== v0) { + point2 = intersect(point0, point1); + if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) { + point1[0] += ε; + point1[1] += ε; + v = visible(point1[0], point1[1]); + } + } + if (v !== v0) { + clean = 0; + if (v) { + listener.lineStart(); + point2 = intersect(point1, point0); + listener.point(point2[0], point2[1]); + } else { + point2 = intersect(point0, point1); + listener.point(point2[0], point2[1]); + listener.lineEnd(); + } + point0 = point2; + } else if (notHemisphere && point0 && smallRadius ^ v) { + var t; + if (!(c & c0) && (t = intersect(point1, point0, true))) { + clean = 0; + if (smallRadius) { + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + } else { + listener.point(t[1][0], t[1][1]); + listener.lineEnd(); + listener.lineStart(); + listener.point(t[0][0], t[0][1]); + } + } + } + if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) { + listener.point(point1[0], point1[1]); + } + point0 = point1, v0 = v, c0 = c; + }, + lineEnd: function() { + if (v0) listener.lineEnd(); + point0 = null; + }, + clean: function() { + return clean | (v00 && v0) << 1; + } + }; + } + function intersect(a, b, two) { + var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b); + var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2; + if (!determinant) return !two && a; + var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2); + d3_geo_cartesianAdd(A, B); + var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1); + if (t2 < 0) return; + var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu); + d3_geo_cartesianAdd(q, A); + q = d3_geo_spherical(q); + if (!two) return q; + var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z; + if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z; + var δλ = λ1 - λ0, polar = abs(δλ - Ï€) < ε, meridian = polar || δλ < ε; + if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z; + if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > Ï€ ^ (λ0 <= q[0] && q[0] <= λ1)) { + var q1 = d3_geo_cartesianScale(u, (-w + t) / uu); + d3_geo_cartesianAdd(q1, A); + return [ q, d3_geo_spherical(q1) ]; + } + } + function code(λ, φ) { + var r = smallRadius ? radius : Ï€ - radius, code = 0; + if (λ < -r) code |= 1; else if (λ > r) code |= 2; + if (φ < -r) code |= 4; else if (φ > r) code |= 8; + return code; + } + } + function d3_geom_clipLine(x0, y0, x1, y1) { + return function(line) { + var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; + r = x0 - ax; + if (!dx && r > 0) return; + r /= dx; + if (dx < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dx > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dx > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } else if (dy > 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t1) return; + if (r > t0) t0 = r; + } else if (dy > 0) { + if (r < t0) return; + if (r < t1) t1 = r; + } + if (t0 > 0) line.a = { + x: ax + t0 * dx, + y: ay + t0 * dy + }; + if (t1 < 1) line.b = { + x: ax + t1 * dx, + y: ay + t1 * dy + }; + return line; + }; + } + var d3_geo_clipExtentMAX = 1e9; + d3.geo.clipExtent = function() { + var x0, y0, x1, y1, stream, clip, clipExtent = { + stream: function(output) { + if (stream) stream.valid = false; + stream = clip(output); + stream.valid = true; + return stream; + }, + extent: function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]); + if (stream) stream.valid = false, stream = null; + return clipExtent; + } + }; + return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]); + }; + function d3_geo_clipExtent(x0, y0, x1, y1) { + return function(listener) { + var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring; + var clip = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + listener = bufferListener; + segments = []; + polygon = []; + clean = true; + }, + polygonEnd: function() { + listener = listener_; + segments = d3.merge(segments); + var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length; + if (inside || visible) { + listener.polygonStart(); + if (inside) { + listener.lineStart(); + interpolate(null, null, 1, listener); + listener.lineEnd(); + } + if (visible) { + d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener); + } + listener.polygonEnd(); + } + segments = polygon = ring = null; + } + }; + function insidePolygon(p) { + var wn = 0, n = polygon.length, y = p[1]; + for (var i = 0; i < n; ++i) { + for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) { + b = v[j]; + if (a[1] <= y) { + if (b[1] > y && isLeft(a, b, p) > 0) ++wn; + } else { + if (b[1] <= y && isLeft(a, b, p) < 0) --wn; + } + a = b; + } + } + return wn !== 0; + } + function isLeft(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]); + } + function interpolate(from, to, direction, listener) { + var a = 0, a1 = 0; + if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) { + do { + listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); + } while ((a = (a + direction + 4) % 4) !== a1); + } else { + listener.point(to[0], to[1]); + } + } + function pointVisible(x, y) { + return x0 <= x && x <= x1 && y0 <= y && y <= y1; + } + function point(x, y) { + if (pointVisible(x, y)) listener.point(x, y); + } + var x__, y__, v__, x_, y_, v_, first, clean; + function lineStart() { + clip.point = linePoint; + if (polygon) polygon.push(ring = []); + first = true; + v_ = false; + x_ = y_ = NaN; + } + function lineEnd() { + if (segments) { + linePoint(x__, y__); + if (v__ && v_) bufferListener.rejoin(); + segments.push(bufferListener.buffer()); + } + clip.point = point; + if (v_) listener.lineEnd(); + } + function linePoint(x, y) { + x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x)); + y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y)); + var v = pointVisible(x, y); + if (polygon) ring.push([ x, y ]); + if (first) { + x__ = x, y__ = y, v__ = v; + first = false; + if (v) { + listener.lineStart(); + listener.point(x, y); + } + } else { + if (v && v_) listener.point(x, y); else { + var l = { + a: { + x: x_, + y: y_ + }, + b: { + x: x, + y: y + } + }; + if (clipLine(l)) { + if (!v_) { + listener.lineStart(); + listener.point(l.a.x, l.a.y); + } + listener.point(l.b.x, l.b.y); + if (!v) listener.lineEnd(); + clean = false; + } else if (v) { + listener.lineStart(); + listener.point(x, y); + clean = false; + } + } + } + x_ = x, y_ = y, v_ = v; + } + return clip; + }; + function corner(p, direction) { + return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; + } + function compare(a, b) { + return comparePoints(a.x, b.x); + } + function comparePoints(a, b) { + var ca = corner(a, 1), cb = corner(b, 1); + return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; + } + } + function d3_geo_compose(a, b) { + function compose(x, y) { + return x = a(x, y), b(x[0], x[1]); + } + if (a.invert && b.invert) compose.invert = function(x, y) { + return x = b.invert(x, y), x && a.invert(x[0], x[1]); + }; + return compose; + } + function d3_geo_conic(projectAt) { + var φ0 = 0, φ1 = Ï€ / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1); + p.parallels = function(_) { + if (!arguments.length) return [ φ0 / Ï€ * 180, φ1 / Ï€ * 180 ]; + return m(φ0 = _[0] * Ï€ / 180, φ1 = _[1] * Ï€ / 180); + }; + return p; + } + function d3_geo_conicEqualArea(φ0, φ1) { + var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), Ï0 = Math.sqrt(C) / n; + function forward(λ, φ) { + var Ï = Math.sqrt(C - 2 * n * Math.sin(φ)) / n; + return [ Ï * Math.sin(λ *= n), Ï0 - Ï * Math.cos(λ) ]; + } + forward.invert = function(x, y) { + var Ï0_y = Ï0 - y; + return [ Math.atan2(x, Ï0_y) / n, d3_asin((C - (x * x + Ï0_y * Ï0_y) * n * n) / (2 * n)) ]; + }; + return forward; + } + (d3.geo.conicEqualArea = function() { + return d3_geo_conic(d3_geo_conicEqualArea); + }).raw = d3_geo_conicEqualArea; + d3.geo.albers = function() { + return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070); + }; + d3.geo.albersUsa = function() { + var lower48 = d3.geo.albers(); + var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]); + var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]); + var point, pointStream = { + point: function(x, y) { + point = [ x, y ]; + } + }, lower48Point, alaskaPoint, hawaiiPoint; + function albersUsa(coordinates) { + var x = coordinates[0], y = coordinates[1]; + point = null; + (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y); + return point; + } + albersUsa.invert = function(coordinates) { + var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; + return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates); + }; + albersUsa.stream = function(stream) { + var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream); + return { + point: function(x, y) { + lower48Stream.point(x, y); + alaskaStream.point(x, y); + hawaiiStream.point(x, y); + }, + sphere: function() { + lower48Stream.sphere(); + alaskaStream.sphere(); + hawaiiStream.sphere(); + }, + lineStart: function() { + lower48Stream.lineStart(); + alaskaStream.lineStart(); + hawaiiStream.lineStart(); + }, + lineEnd: function() { + lower48Stream.lineEnd(); + alaskaStream.lineEnd(); + hawaiiStream.lineEnd(); + }, + polygonStart: function() { + lower48Stream.polygonStart(); + alaskaStream.polygonStart(); + hawaiiStream.polygonStart(); + }, + polygonEnd: function() { + lower48Stream.polygonEnd(); + alaskaStream.polygonEnd(); + hawaiiStream.polygonEnd(); + } + }; + }; + albersUsa.precision = function(_) { + if (!arguments.length) return lower48.precision(); + lower48.precision(_); + alaska.precision(_); + hawaii.precision(_); + return albersUsa; + }; + albersUsa.scale = function(_) { + if (!arguments.length) return lower48.scale(); + lower48.scale(_); + alaska.scale(_ * .35); + hawaii.scale(_); + return albersUsa.translate(lower48.translate()); + }; + albersUsa.translate = function(_) { + if (!arguments.length) return lower48.translate(); + var k = lower48.scale(), x = +_[0], y = +_[1]; + lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point; + alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point; + return albersUsa; + }; + return albersUsa.scale(1070); + }; + var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = { + point: d3_noop, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: function() { + d3_geo_pathAreaPolygon = 0; + d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart; + }, + polygonEnd: function() { + d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop; + d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2); + } + }; + function d3_geo_pathAreaRingStart() { + var x00, y00, x0, y0; + d3_geo_pathArea.point = function(x, y) { + d3_geo_pathArea.point = nextPoint; + x00 = x0 = x, y00 = y0 = y; + }; + function nextPoint(x, y) { + d3_geo_pathAreaPolygon += y0 * x - x0 * y; + x0 = x, y0 = y; + } + d3_geo_pathArea.lineEnd = function() { + nextPoint(x00, y00); + }; + } + var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1; + var d3_geo_pathBounds = { + point: d3_geo_pathBoundsPoint, + lineStart: d3_noop, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_pathBoundsPoint(x, y) { + if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x; + if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x; + if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y; + if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y; + } + function d3_geo_pathBuffer() { + var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = []; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointCircle = d3_geo_pathBufferCircle(_); + return stream; + }, + result: function() { + if (buffer.length) { + var result = buffer.join(""); + buffer = []; + return result; + } + } + }; + function point(x, y) { + buffer.push("M", x, ",", y, pointCircle); + } + function pointLineStart(x, y) { + buffer.push("M", x, ",", y); + stream.point = pointLine; + } + function pointLine(x, y) { + buffer.push("L", x, ",", y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + buffer.push("Z"); + } + return stream; + } + function d3_geo_pathBufferCircle(radius) { + return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; + } + var d3_geo_pathCentroid = { + point: d3_geo_pathCentroidPoint, + lineStart: d3_geo_pathCentroidLineStart, + lineEnd: d3_geo_pathCentroidLineEnd, + polygonStart: function() { + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart; + }, + polygonEnd: function() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart; + d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd; + } + }; + function d3_geo_pathCentroidPoint(x, y) { + d3_geo_centroidX0 += x; + d3_geo_centroidY0 += y; + ++d3_geo_centroidZ0; + } + function d3_geo_pathCentroidLineStart() { + var x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + } + function d3_geo_pathCentroidLineEnd() { + d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint; + } + function d3_geo_pathCentroidRingStart() { + var x00, y00, x0, y0; + d3_geo_pathCentroid.point = function(x, y) { + d3_geo_pathCentroid.point = nextPoint; + d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y); + }; + function nextPoint(x, y) { + var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy); + d3_geo_centroidX1 += z * (x0 + x) / 2; + d3_geo_centroidY1 += z * (y0 + y) / 2; + d3_geo_centroidZ1 += z; + z = y0 * x - x0 * y; + d3_geo_centroidX2 += z * (x0 + x); + d3_geo_centroidY2 += z * (y0 + y); + d3_geo_centroidZ2 += z * 3; + d3_geo_pathCentroidPoint(x0 = x, y0 = y); + } + d3_geo_pathCentroid.lineEnd = function() { + nextPoint(x00, y00); + }; + } + function d3_geo_pathContext(context) { + var pointRadius = 4.5; + var stream = { + point: point, + lineStart: function() { + stream.point = pointLineStart; + }, + lineEnd: lineEnd, + polygonStart: function() { + stream.lineEnd = lineEndPolygon; + }, + polygonEnd: function() { + stream.lineEnd = lineEnd; + stream.point = point; + }, + pointRadius: function(_) { + pointRadius = _; + return stream; + }, + result: d3_noop + }; + function point(x, y) { + context.moveTo(x, y); + context.arc(x, y, pointRadius, 0, Ï„); + } + function pointLineStart(x, y) { + context.moveTo(x, y); + stream.point = pointLine; + } + function pointLine(x, y) { + context.lineTo(x, y); + } + function lineEnd() { + stream.point = point; + } + function lineEndPolygon() { + context.closePath(); + } + return stream; + } + function d3_geo_resample(project) { + var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16; + function resample(stream) { + return (maxDepth ? resampleRecursive : resampleNone)(stream); + } + function resampleNone(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + }); + } + function resampleRecursive(stream) { + var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0; + var resample = { + point: point, + lineStart: lineStart, + lineEnd: lineEnd, + polygonStart: function() { + stream.polygonStart(); + resample.lineStart = ringStart; + }, + polygonEnd: function() { + stream.polygonEnd(); + resample.lineStart = lineStart; + } + }; + function point(x, y) { + x = project(x, y); + stream.point(x[0], x[1]); + } + function lineStart() { + x0 = NaN; + resample.point = linePoint; + stream.lineStart(); + } + function linePoint(λ, φ) { + var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ); + resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); + stream.point(x0, y0); + } + function lineEnd() { + resample.point = point; + stream.lineEnd(); + } + function ringStart() { + lineStart(); + resample.point = ringPoint; + resample.lineEnd = ringEnd; + } + function ringPoint(λ, φ) { + linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; + resample.point = linePoint; + } + function ringEnd() { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream); + resample.lineEnd = lineEnd; + lineEnd(); + } + return resample; + } + function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) { + var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; + if (d2 > 4 * δ2 && depth--) { + var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; + if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { + resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream); + stream.point(x2, y2); + resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream); + } + } + } + resample.precision = function(_) { + if (!arguments.length) return Math.sqrt(δ2); + maxDepth = (δ2 = _ * _) > 0 && 16; + return resample; + }; + return resample; + } + d3.geo.path = function() { + var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream; + function path(object) { + if (object) { + if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); + if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream); + d3.geo.stream(object, cacheStream); + } + return contextStream.result(); + } + path.area = function(object) { + d3_geo_pathAreaSum = 0; + d3.geo.stream(object, projectStream(d3_geo_pathArea)); + return d3_geo_pathAreaSum; + }; + path.centroid = function(object) { + d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0; + d3.geo.stream(object, projectStream(d3_geo_pathCentroid)); + return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ]; + }; + path.bounds = function(object) { + d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity); + d3.geo.stream(object, projectStream(d3_geo_pathBounds)); + return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ]; + }; + path.projection = function(_) { + if (!arguments.length) return projection; + projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity; + return reset(); + }; + path.context = function(_) { + if (!arguments.length) return context; + contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_); + if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); + return reset(); + }; + path.pointRadius = function(_) { + if (!arguments.length) return pointRadius; + pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); + return path; + }; + function reset() { + cacheStream = null; + return path; + } + return path.projection(d3.geo.albersUsa()).context(null); + }; + function d3_geo_pathProjectStream(project) { + var resample = d3_geo_resample(function(x, y) { + return project([ x * d3_degrees, y * d3_degrees ]); + }); + return function(stream) { + return d3_geo_projectionRadians(resample(stream)); + }; + } + d3.geo.transform = function(methods) { + return { + stream: function(stream) { + var transform = new d3_geo_transform(stream); + for (var k in methods) transform[k] = methods[k]; + return transform; + } + }; + }; + function d3_geo_transform(stream) { + this.stream = stream; + } + d3_geo_transform.prototype = { + point: function(x, y) { + this.stream.point(x, y); + }, + sphere: function() { + this.stream.sphere(); + }, + lineStart: function() { + this.stream.lineStart(); + }, + lineEnd: function() { + this.stream.lineEnd(); + }, + polygonStart: function() { + this.stream.polygonStart(); + }, + polygonEnd: function() { + this.stream.polygonEnd(); + } + }; + function d3_geo_transformPoint(stream, point) { + return { + point: point, + sphere: function() { + stream.sphere(); + }, + lineStart: function() { + stream.lineStart(); + }, + lineEnd: function() { + stream.lineEnd(); + }, + polygonStart: function() { + stream.polygonStart(); + }, + polygonEnd: function() { + stream.polygonEnd(); + } + }; + } + d3.geo.projection = d3_geo_projection; + d3.geo.projectionMutator = d3_geo_projectionMutator; + function d3_geo_projection(project) { + return d3_geo_projectionMutator(function() { + return project; + })(); + } + function d3_geo_projectionMutator(projectAt) { + var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) { + x = project(x, y); + return [ x[0] * k + δx, δy - x[1] * k ]; + }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream; + function projection(point) { + point = projectRotate(point[0] * d3_radians, point[1] * d3_radians); + return [ point[0] * k + δx, δy - point[1] * k ]; + } + function invert(point) { + point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k); + return point && [ point[0] * d3_degrees, point[1] * d3_degrees ]; + } + projection.stream = function(output) { + if (stream) stream.valid = false; + stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output)))); + stream.valid = true; + return stream; + }; + projection.clipAngle = function(_) { + if (!arguments.length) return clipAngle; + preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians); + return invalidate(); + }; + projection.clipExtent = function(_) { + if (!arguments.length) return clipExtent; + clipExtent = _; + postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity; + return invalidate(); + }; + projection.scale = function(_) { + if (!arguments.length) return k; + k = +_; + return reset(); + }; + projection.translate = function(_) { + if (!arguments.length) return [ x, y ]; + x = +_[0]; + y = +_[1]; + return reset(); + }; + projection.center = function(_) { + if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ]; + λ = _[0] % 360 * d3_radians; + φ = _[1] % 360 * d3_radians; + return reset(); + }; + projection.rotate = function(_) { + if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ]; + δλ = _[0] % 360 * d3_radians; + δφ = _[1] % 360 * d3_radians; + δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0; + return reset(); + }; + d3.rebind(projection, projectResample, "precision"); + function reset() { + projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project); + var center = project(λ, φ); + δx = x - center[0] * k; + δy = y + center[1] * k; + return invalidate(); + } + function invalidate() { + if (stream) stream.valid = false, stream = null; + return projection; + } + return function() { + project = projectAt.apply(this, arguments); + projection.invert = project.invert && invert; + return reset(); + }; + } + function d3_geo_projectionRadians(stream) { + return d3_geo_transformPoint(stream, function(x, y) { + stream.point(x * d3_radians, y * d3_radians); + }); + } + function d3_geo_equirectangular(λ, φ) { + return [ λ, φ ]; + } + (d3.geo.equirectangular = function() { + return d3_geo_projection(d3_geo_equirectangular); + }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular; + d3.geo.rotation = function(rotate) { + rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0); + function forward(coordinates) { + coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + } + forward.invert = function(coordinates) { + coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians); + return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates; + }; + return forward; + }; + function d3_geo_identityRotation(λ, φ) { + return [ λ > Ï€ ? λ - Ï„ : λ < -Ï€ ? λ + Ï„ : λ, φ ]; + } + d3_geo_identityRotation.invert = d3_geo_equirectangular; + function d3_geo_rotation(δλ, δφ, δγ) { + return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation; + } + function d3_geo_forwardRotationλ(δλ) { + return function(λ, φ) { + return λ += δλ, [ λ > Ï€ ? λ - Ï„ : λ < -Ï€ ? λ + Ï„ : λ, φ ]; + }; + } + function d3_geo_rotationλ(δλ) { + var rotation = d3_geo_forwardRotationλ(δλ); + rotation.invert = d3_geo_forwardRotationλ(-δλ); + return rotation; + } + function d3_geo_rotationφγ(δφ, δγ) { + var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ); + function rotation(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ; + return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ]; + } + rotation.invert = function(λ, φ) { + var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ; + return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ]; + }; + return rotation; + } + d3.geo.circle = function() { + var origin = [ 0, 0 ], angle, precision = 6, interpolate; + function circle() { + var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = []; + interpolate(null, null, 1, { + point: function(x, y) { + ring.push(x = rotate(x, y)); + x[0] *= d3_degrees, x[1] *= d3_degrees; + } + }); + return { + type: "Polygon", + coordinates: [ ring ] + }; + } + circle.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return circle; + }; + circle.angle = function(x) { + if (!arguments.length) return angle; + interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians); + return circle; + }; + circle.precision = function(_) { + if (!arguments.length) return precision; + interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians); + return circle; + }; + return circle.angle(90); + }; + function d3_geo_circleInterpolate(radius, precision) { + var cr = Math.cos(radius), sr = Math.sin(radius); + return function(from, to, direction, listener) { + var step = direction * precision; + if (from != null) { + from = d3_geo_circleAngle(cr, from); + to = d3_geo_circleAngle(cr, to); + if (direction > 0 ? from < to : from > to) from += direction * Ï„; + } else { + from = radius + direction * Ï„; + to = radius - .5 * step; + } + for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) { + listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]); + } + }; + } + function d3_geo_circleAngle(cr, point) { + var a = d3_geo_cartesian(point); + a[0] -= cr; + d3_geo_cartesianNormalize(a); + var angle = d3_acos(-a[1]); + return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI); + } + d3.geo.distance = function(a, b) { + var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t; + return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ); + }; + d3.geo.graticule = function() { + var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; + function graticule() { + return { + type: "MultiLineString", + coordinates: lines() + }; + } + function lines() { + return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) { + return abs(x % DX) > ε; + }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) { + return abs(y % DY) > ε; + }).map(y)); + } + graticule.lines = function() { + return lines().map(function(coordinates) { + return { + type: "LineString", + coordinates: coordinates + }; + }); + }; + graticule.outline = function() { + return { + type: "Polygon", + coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] + }; + }; + graticule.extent = function(_) { + if (!arguments.length) return graticule.minorExtent(); + return graticule.majorExtent(_).minorExtent(_); + }; + graticule.majorExtent = function(_) { + if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ]; + X0 = +_[0][0], X1 = +_[1][0]; + Y0 = +_[0][1], Y1 = +_[1][1]; + if (X0 > X1) _ = X0, X0 = X1, X1 = _; + if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; + return graticule.precision(precision); + }; + graticule.minorExtent = function(_) { + if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ]; + x0 = +_[0][0], x1 = +_[1][0]; + y0 = +_[0][1], y1 = +_[1][1]; + if (x0 > x1) _ = x0, x0 = x1, x1 = _; + if (y0 > y1) _ = y0, y0 = y1, y1 = _; + return graticule.precision(precision); + }; + graticule.step = function(_) { + if (!arguments.length) return graticule.minorStep(); + return graticule.majorStep(_).minorStep(_); + }; + graticule.majorStep = function(_) { + if (!arguments.length) return [ DX, DY ]; + DX = +_[0], DY = +_[1]; + return graticule; + }; + graticule.minorStep = function(_) { + if (!arguments.length) return [ dx, dy ]; + dx = +_[0], dy = +_[1]; + return graticule; + }; + graticule.precision = function(_) { + if (!arguments.length) return precision; + precision = +_; + x = d3_geo_graticuleX(y0, y1, 90); + y = d3_geo_graticuleY(x0, x1, precision); + X = d3_geo_graticuleX(Y0, Y1, 90); + Y = d3_geo_graticuleY(X0, X1, precision); + return graticule; + }; + return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]); + }; + function d3_geo_graticuleX(y0, y1, dy) { + var y = d3.range(y0, y1 - ε, dy).concat(y1); + return function(x) { + return y.map(function(y) { + return [ x, y ]; + }); + }; + } + function d3_geo_graticuleY(x0, x1, dx) { + var x = d3.range(x0, x1 - ε, dx).concat(x1); + return function(y) { + return x.map(function(x) { + return [ x, y ]; + }); + }; + } + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d3.geo.greatArc = function() { + var source = d3_source, source_, target = d3_target, target_; + function greatArc() { + return { + type: "LineString", + coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ] + }; + } + greatArc.distance = function() { + return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments)); + }; + greatArc.source = function(_) { + if (!arguments.length) return source; + source = _, source_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.target = function(_) { + if (!arguments.length) return target; + target = _, target_ = typeof _ === "function" ? null : _; + return greatArc; + }; + greatArc.precision = function() { + return arguments.length ? greatArc : 0; + }; + return greatArc; + }; + d3.geo.interpolate = function(source, target) { + return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians); + }; + function d3_geo_interpolate(x0, y0, x1, y1) { + var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d); + var interpolate = d ? function(t) { + var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1; + return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ]; + } : function() { + return [ x0 * d3_degrees, y0 * d3_degrees ]; + }; + interpolate.distance = d; + return interpolate; + } + d3.geo.length = function(object) { + d3_geo_lengthSum = 0; + d3.geo.stream(object, d3_geo_length); + return d3_geo_lengthSum; + }; + var d3_geo_lengthSum; + var d3_geo_length = { + sphere: d3_noop, + point: d3_noop, + lineStart: d3_geo_lengthLineStart, + lineEnd: d3_noop, + polygonStart: d3_noop, + polygonEnd: d3_noop + }; + function d3_geo_lengthLineStart() { + var λ0, sinφ0, cosφ0; + d3_geo_length.point = function(λ, φ) { + λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ); + d3_geo_length.point = nextPoint; + }; + d3_geo_length.lineEnd = function() { + d3_geo_length.point = d3_geo_length.lineEnd = d3_noop; + }; + function nextPoint(λ, φ) { + var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t); + d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ); + λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ; + } + } + function d3_geo_azimuthal(scale, angle) { + function azimuthal(λ, φ) { + var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ); + return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ]; + } + azimuthal.invert = function(x, y) { + var Ï = Math.sqrt(x * x + y * y), c = angle(Ï), sinc = Math.sin(c), cosc = Math.cos(c); + return [ Math.atan2(x * sinc, Ï * cosc), Math.asin(Ï && y * sinc / Ï) ]; + }; + return azimuthal; + } + var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) { + return Math.sqrt(2 / (1 + cosλcosφ)); + }, function(Ï) { + return 2 * Math.asin(Ï / 2); + }); + (d3.geo.azimuthalEqualArea = function() { + return d3_geo_projection(d3_geo_azimuthalEqualArea); + }).raw = d3_geo_azimuthalEqualArea; + var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) { + var c = Math.acos(cosλcosφ); + return c && c / Math.sin(c); + }, d3_identity); + (d3.geo.azimuthalEquidistant = function() { + return d3_geo_projection(d3_geo_azimuthalEquidistant); + }).raw = d3_geo_azimuthalEquidistant; + function d3_geo_conicConformal(φ0, φ1) { + var cosφ0 = Math.cos(φ0), t = function(φ) { + return Math.tan(Ï€ / 4 + φ / 2); + }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n; + if (!n) return d3_geo_mercator; + function forward(λ, φ) { + var Ï = abs(abs(φ) - halfÏ€) < ε ? 0 : F / Math.pow(t(φ), n); + return [ Ï * Math.sin(n * λ), F - Ï * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var Ï0_y = F - y, Ï = d3_sgn(n) * Math.sqrt(x * x + Ï0_y * Ï0_y); + return [ Math.atan2(x, Ï0_y) / n, 2 * Math.atan(Math.pow(F / Ï, 1 / n)) - halfÏ€ ]; + }; + return forward; + } + (d3.geo.conicConformal = function() { + return d3_geo_conic(d3_geo_conicConformal); + }).raw = d3_geo_conicConformal; + function d3_geo_conicEquidistant(φ0, φ1) { + var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0; + if (abs(n) < ε) return d3_geo_equirectangular; + function forward(λ, φ) { + var Ï = G - φ; + return [ Ï * Math.sin(n * λ), G - Ï * Math.cos(n * λ) ]; + } + forward.invert = function(x, y) { + var Ï0_y = G - y; + return [ Math.atan2(x, Ï0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + Ï0_y * Ï0_y) ]; + }; + return forward; + } + (d3.geo.conicEquidistant = function() { + return d3_geo_conic(d3_geo_conicEquidistant); + }).raw = d3_geo_conicEquidistant; + var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / cosλcosφ; + }, Math.atan); + (d3.geo.gnomonic = function() { + return d3_geo_projection(d3_geo_gnomonic); + }).raw = d3_geo_gnomonic; + function d3_geo_mercator(λ, φ) { + return [ λ, Math.log(Math.tan(Ï€ / 4 + φ / 2)) ]; + } + d3_geo_mercator.invert = function(x, y) { + return [ x, 2 * Math.atan(Math.exp(y)) - halfÏ€ ]; + }; + function d3_geo_mercatorProjection(project) { + var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; + m.scale = function() { + var v = scale.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.translate = function() { + var v = translate.apply(m, arguments); + return v === m ? clipAuto ? m.clipExtent(null) : m : v; + }; + m.clipExtent = function(_) { + var v = clipExtent.apply(m, arguments); + if (v === m) { + if (clipAuto = _ == null) { + var k = Ï€ * scale(), t = translate(); + clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]); + } + } else if (clipAuto) { + v = null; + } + return v; + }; + return m.clipExtent(null); + } + (d3.geo.mercator = function() { + return d3_geo_mercatorProjection(d3_geo_mercator); + }).raw = d3_geo_mercator; + var d3_geo_orthographic = d3_geo_azimuthal(function() { + return 1; + }, Math.asin); + (d3.geo.orthographic = function() { + return d3_geo_projection(d3_geo_orthographic); + }).raw = d3_geo_orthographic; + var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) { + return 1 / (1 + cosλcosφ); + }, function(Ï) { + return 2 * Math.atan(Ï); + }); + (d3.geo.stereographic = function() { + return d3_geo_projection(d3_geo_stereographic); + }).raw = d3_geo_stereographic; + function d3_geo_transverseMercator(λ, φ) { + var B = Math.cos(φ) * Math.sin(λ); + return [ Math.log((1 + B) / (1 - B)) / 2, Math.atan2(Math.tan(φ), Math.cos(λ)) ]; + } + d3_geo_transverseMercator.invert = function(x, y) { + return [ Math.atan2(d3_sinh(x), Math.cos(y)), d3_asin(Math.sin(y) / d3_cosh(x)) ]; + }; + (d3.geo.transverseMercator = function() { + return d3_geo_mercatorProjection(d3_geo_transverseMercator); + }).raw = d3_geo_transverseMercator; + d3.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d3.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx = d3_functor(x), fy = d3_functor(y), n = data.length, vertices, plen = n - 1, points = [], stack = [], d, i, j, h = 0, x1, y1, x2, y2, u, v, a, sp; + if (fx === d3_geom_pointX && y === d3_geom_pointY) vertices = data; else for (i = 0, + vertices = []; i < n; ++i) { + vertices.push([ +fx.call(this, d = data[i], i), +fy.call(this, d, i) ]); + } + for (i = 1; i < n; ++i) { + if (vertices[i][1] < vertices[h][1] || vertices[i][1] == vertices[h][1] && vertices[i][0] < vertices[h][0]) h = i; + } + for (i = 0; i < n; ++i) { + if (i === h) continue; + y1 = vertices[i][1] - vertices[h][1]; + x1 = vertices[i][0] - vertices[h][0]; + points.push({ + angle: Math.atan2(y1, x1), + index: i + }); + } + points.sort(function(a, b) { + return a.angle - b.angle; + }); + a = points[0].angle; + v = points[0].index; + u = 0; + for (i = 1; i < plen; ++i) { + j = points[i].index; + if (a == points[i].angle) { + x1 = vertices[v][0] - vertices[h][0]; + y1 = vertices[v][1] - vertices[h][1]; + x2 = vertices[j][0] - vertices[h][0]; + y2 = vertices[j][1] - vertices[h][1]; + if (x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2) { + points[i].index = -1; + continue; + } else { + points[u].index = -1; + } + } + a = points[i].angle; + u = i; + v = j; + } + stack.push(h); + for (i = 0, j = 0; i < 2; ++j) { + if (points[j].index > -1) { + stack.push(points[j].index); + i++; + } + } + sp = stack.length; + for (;j < plen; ++j) { + if (points[j].index < 0) continue; + while (!d3_geom_hullCCW(stack[sp - 2], stack[sp - 1], points[j].index, vertices)) { + --sp; + } + stack[sp++] = points[j].index; + } + var poly = []; + for (i = sp - 1; i >= 0; --i) poly.push(data[stack[i]]); + return poly; + } + hull.x = function(_) { + return arguments.length ? (x = _, hull) : x; + }; + hull.y = function(_) { + return arguments.length ? (y = _, hull) : y; + }; + return hull; + }; + function d3_geom_hullCCW(i1, i2, i3, v) { + var t, a, b, c, d, e, f; + t = v[i1]; + a = t[0]; + b = t[1]; + t = v[i2]; + c = t[0]; + d = t[1]; + t = v[i3]; + e = t[0]; + f = t[1]; + return (f - b) * (c - a) - (d - b) * (e - a) > 0; + } + d3.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; + }; + var d3_geom_polygonPrototype = d3.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area = 0; + while (++i < n) { + a = b; + b = this[i]; + area += a[1] * b[0] - a[0] * b[1]; + } + return area * .5; + }; + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [ x * k, y * k ]; + }; + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + } + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [ x1 + ua * x21, y1 + ua * y21 ]; + } + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); + } + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; + } + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; + } + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); + } + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x: x, + y: y + }, previous = beach.P, next = beach.N, disappearing = [ beach ]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -ε) { + lArc = node.P; + rArc = node; + } else if (dxr > -ε) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiLeftBreakPoint(arc, directrix) { + var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; + } + function d3_geom_voronoiRightBreakPoint(arc, directrix) { + var rArc = arc.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc.site; + return site.y === directrix ? site.x : Infinity; + } + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; + } + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent) { + var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs(x2 - x0) < ε ? y2 : y1 + } : abs(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs(x2 - x1) < ε ? y2 : y0 + } : abs(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; + } + } + } + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc) { + var lArc = arc.P, rArc = arc.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -ε2) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; else { + before = node; + break; + } + } + } + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; + } + function d3_geom_voronoiDetachCircle(arc) { + var circle = arc.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc.circle = null; + } + } + function d3_geom_voronoiClipEdges(extent) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } + } + function d3_geom_voronoiConnectEdge(edge, extent) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx < x0 || fx >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: fx, + y: y1 + }; + } else { + if (!va) va = { + x: fx, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: fx, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; + } + } else { + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } + } + } + edge.a = va; + edge.b = vb; + return true; + } + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; + } + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; + } + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; + } + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; + } + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); + } + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + } + parent = after.U; + } + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; + } + } else { + red = node.C; + node = next; + } + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; + } + } + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; + } + }; + function d3_geom_voronoiRedBlackRotateLeft(tree, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; + } + function d3_geom_voronoiRedBlackRotateRight(tree, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; else parent.R = q; + } else { + tree._ = q; + } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; + } + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; + } + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); + } else { + break; + } + } + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; + } + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; + } + d3.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [ s.x, s.y ]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : []; + polygon.point = data[i]; + }); + return polygons; + } + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i: i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); + }; + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + e0 = e1; + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([ data[i], data[s0.i], data[s1.i] ]); + } + } + }); + return triangles; + }; + voronoi.x = function(_) { + return arguments.length ? (fx = d3_functor(x = _), voronoi) : x; + }; + voronoi.y = function(_) { + return arguments.length ? (fy = d3_functor(y = _), voronoi) : y; + }; + voronoi.clipExtent = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _ == null ? d3_geom_voronoiClipExtent : _; + return voronoi; + }; + voronoi.size = function(_) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); + } + d3.geom.delaunay = function(vertices) { + return d3.geom.voronoi().triangles(vertices); + }; + d3.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; + } + return quadtree(points); + } + function quadtree(data) { + var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } else for (i = 0; i < n; ++i) { + var x_ = +fx(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } + } + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy; + function insert(n, d, x, y, x1, y1, x2, y2) { + if (isNaN(x) || isNaN(y)) return; + if (n.leaf) { + var nx = n.x, ny = n.y; + if (nx != null) { + if (abs(nx - x) + abs(ny - y) < .01) { + insertChild(n, d, x, y, x1, y1, x2, y2); + } else { + var nPoint = n.point; + n.x = n.y = n.point = null; + insertChild(n, nPoint, nx, ny, x1, y1, x2, y2); + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } else { + n.x = x, n.y = y, n.point = d; + } + } else { + insertChild(n, d, x, y, x1, y1, x2, y2); + } + } + function insertChild(n, d, x, y, x1, y1, x2, y2) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, right = x >= sx, bottom = y >= sy, i = (bottom << 1) + right; + n.leaf = false; + n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode()); + if (right) x1 = sx; else x2 = sx; + if (bottom) y1 = sy; else y2 = sy; + insert(n, d, x, y, x1, y1, x2, y2); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d) { + insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_); + }; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); + } + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; + } + quadtree.x = function(_) { + return arguments.length ? (x = _, quadtree) : x; + }; + quadtree.y = function(_) { + return arguments.length ? (y = _, quadtree) : y; + }; + quadtree.extent = function(_) { + if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], + y2 = +_[1][1]; + return quadtree; + }; + quadtree.size = function(_) { + if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ]; + if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + d3.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d3.rgb(a); + b = d3.rgb(b); + var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t)); + }; + } + d3.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } + } + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } + } + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d3.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + b -= a = +a; + return function(t) { + return a + b * t; + }; + } + d3.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var m, i, j, s0 = 0, s1 = 0, s = [], q = [], n, o; + a = a + "", b = b + ""; + d3_interpolate_number.lastIndex = 0; + for (i = 0; m = d3_interpolate_number.exec(b); ++i) { + if (m.index) s.push(b.substring(s0, s1 = m.index)); + q.push({ + i: s.length, + x: m[0] + }); + s.push(null); + s0 = d3_interpolate_number.lastIndex; + } + if (s0 < b.length) s.push(b.substring(s0)); + for (i = 0, n = q.length; (m = d3_interpolate_number.exec(a)) && i < n; ++i) { + o = q[i]; + if (o.x == m[0]) { + if (o.i) { + if (s[o.i + 1] == null) { + s[o.i - 1] += o.x; + s.splice(o.i, 1); + for (j = i + 1; j < n; ++j) q[j].i--; + } else { + s[o.i - 1] += o.x + s[o.i + 1]; + s.splice(o.i, 2); + for (j = i + 1; j < n; ++j) q[j].i -= 2; + } + } else { + if (s[o.i + 1] == null) { + s[o.i] = o.x; + } else { + s[o.i] = o.x + s[o.i + 1]; + s.splice(o.i + 1, 1); + for (j = i + 1; j < n; ++j) q[j].i--; + } + } + q.splice(i, 1); + n--; + i--; + } else { + o.x = d3_interpolateNumber(parseFloat(m[0]), parseFloat(o.x)); + } + } + while (i < n) { + o = q.pop(); + if (s[o.i + 1] == null) { + s[o.i] = o.x; + } else { + s[o.i] = o.x + s[o.i + 1]; + s.splice(o.i + 1, 1); + } + n--; + } + if (s.length === 1) { + return s[0] == null ? (o = q[0].x, function(t) { + return o(t) + ""; + }) : function() { + return b; + }; + } + return function(t) { + for (i = 0; i < n; ++i) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + var d3_interpolate_number = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; + d3.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d3.interpolators.length, f; + while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ; + return f; + } + d3.interpolators = [ function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b) || /^(#|rgb\(|hsl\()/.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_Color ? d3_interpolateRgb : t === "object" ? Array.isArray(b) ? d3_interpolateArray : d3_interpolateObject : d3_interpolateNumber)(a, b); + } ]; + d3.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (;i < na; ++i) c[i] = a[i]; + for (;i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; + } + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d3.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d3.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d3.ease = function(name) { + var i = name.indexOf("-"), t = i >= 0 ? name.substring(0, i) : name, m = i >= 0 ? name.substring(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; + } + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; + } + function d3_ease_reflect(f) { + return function(t) { + return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; + } + function d3_ease_quad(t) { + return t * t; + } + function d3_ease_cubic(t) { + return t * t * t; + } + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t2 = t * t, t3 = t2 * t; + return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); + } + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; + } + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfÏ€); + } + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); + } + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); + } + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = .45; + if (arguments.length) s = p / Ï„ * Math.asin(1 / a); else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * Ï„ / p); + }; + } + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; + } + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375; + } + d3.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d3.hcl(a); + b = d3.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; + } + d3.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d3.hsl(a); + b = d3.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; + } + d3.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d3.lab(a); + b = d3.lab(b); + var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + ""; + }; + } + d3.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); + }; + } + d3.transform = function(string) { + var g = d3_document.createElementNS(d3.ns.prefix.svg, "g"); + return (d3.transform = function(string) { + if (string != null) { + g.setAttribute("transform", string); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string); + }; + function d3_transform(m) { + var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; + } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [ m.e, m.f ]; + this.scale = [ kx, ky ]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; + } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; + }; + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; + } + return k; + } + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; + } + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 + }; + d3.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransform(a, b) { + var s = [], q = [], n, A = d3.transform(a), B = d3.transform(b), ta = A.translate, tb = B.translate, ra = A.rotate, rb = B.rotate, wa = A.skew, wb = B.skew, ka = A.scale, kb = B.scale; + if (ta[0] != tb[0] || ta[1] != tb[1]) { + s.push("translate(", null, ",", null, ")"); + q.push({ + i: 1, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: 3, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } else { + s.push(""); + } + if (ra != rb) { + if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(s.pop() + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(s.pop() + "rotate(" + rb + ")"); + } + if (wa != wb) { + q.push({ + i: s.push(s.pop() + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(s.pop() + "skewX(" + wb + ")"); + } + if (ka[0] != kb[0] || ka[1] != kb[1]) { + n = s.push(s.pop() + "scale(", null, ",", null, ")"); + q.push({ + i: n - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: n - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] != 1 || kb[1] != 1) { + s.push(s.pop() + "scale(" + kb + ")"); + } + n = q.length; + return function(t) { + var i = -1, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + function d3_uninterpolateNumber(a, b) { + b = b - (a = +a) ? 1 / (b - a) : 0; + return function(x) { + return (x - a) * b; + }; + } + function d3_uninterpolateClamp(a, b) { + b = b - (a = +a) ? 1 / (b - a) : 0; + return function(x) { + return Math.max(0, Math.min(1, (x - a) * b)); + }; + } + d3.layout = {}; + d3.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; + } + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; + } + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; + } + d3.layout.chord = function() { + var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d3.range(n)); + k += x; + } + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i) { + d.sort(function(a, b) { + return sortSubgroups(matrix[i][a], matrix[i][b]); + }); + }); + } + k = (Ï„ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; + } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: (x - x0) / k + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source: source, + target: target + }); + } + } + } + if (sortChords) resort(); + } + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); + } + chord.matrix = function(x) { + if (!arguments.length) return matrix; + n = (matrix = x) && matrix.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d3.layout.force = function() { + var force = {}, event = d3.dispatch("start", "tick", "end"), size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, gravity = .1, theta = .8, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad, x1, _, x2) { + if (quad.point !== node) { + var dx = quad.cx - node.x, dy = quad.cy - node.y, dn = 1 / Math.sqrt(dx * dx + dy * dy); + if ((x2 - x1) * dn < theta) { + var k = quad.charge * dn * dn; + node.px -= dx * k; + node.py -= dy * k; + return true; + } + if (quad.point && isFinite(dn)) { + var k = quad.pointCharge * dn * dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad.charge; + }; + } + force.tick = function() { + if ((alpha *= .99) < .005) { + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight / (t.weight + s.weight)); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); + } + } + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; + } + } + event.tick({ + type: "tick", + alpha: alpha + }); + }; + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; + }; + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return theta; + theta = +x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) alpha = x; else alpha = 0; + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + d3.timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o = links[j]; + neighbors[o.source.index].push(o.target); + neighbors[o.target.index].push(o.source); + } + } + var candidates = neighbors[i], j = -1, m = candidates.length, x; + while (++j < m) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size; + } + return force.resume(); + }; + force.resume = function() { + return force.alpha(.1); + }; + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d3.event.x, d.py = d3.event.y; + force.resume(); + } + return d3.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; + } + function d3_layout_forceDragend(d) { + d.fixed &= ~6; + } + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; + } + function d3_layout_forceMouseout(d) { + d.fixed &= ~4; + } + function d3_layout_forceAccumulate(quad, alpha, charges) { + var cx = 0, cy = 0; + quad.charge = 0; + if (!quad.leaf) { + var nodes = quad.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; + } + } + if (quad.point) { + if (!quad.leaf) { + quad.point.x += Math.random() - .5; + quad.point.y += Math.random() - .5; + } + var k = alpha * charges[quad.point.index]; + quad.charge += quad.pointCharge = k; + cx += k * quad.point.x; + cy += k * quad.point.y; + } + quad.cx = cx / quad.charge; + quad.cy = cy / quad.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1; + d3.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue; + function recurse(node, depth, nodes) { + var childs = children.call(hierarchy, node, depth); + node.depth = depth; + nodes.push(node); + if (childs && (n = childs.length)) { + var i = -1, n, c = node.children = new Array(n), v = 0, j = depth + 1, d; + while (++i < n) { + d = c[i] = recurse(childs[i], j, nodes); + d.parent = node; + v += d.value; + } + if (sort) c.sort(sort); + if (value) node.value = v; + } else { + delete node.children; + if (value) { + node.value = +value.call(hierarchy, node, depth) || 0; + } + } + return node; + } + function revalue(node, depth) { + var children = node.children, v = 0; + if (children && (n = children.length)) { + var i = -1, n, j = depth + 1; + while (++i < n) v += revalue(children[i], j); + } else if (value) { + v = +value.call(hierarchy, node, depth) || 0; + } + if (value) node.value = v; + return v; + } + function hierarchy(d) { + var nodes = []; + recurse(d, 0, nodes); + return nodes; + } + hierarchy.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy; + }; + hierarchy.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy; + }; + hierarchy.value = function(x) { + if (!arguments.length) return value; + value = x; + return hierarchy; + }; + hierarchy.revalue = function(root) { + revalue(root, 0); + return root; + }; + return hierarchy; + }; + function d3_layout_hierarchyRebind(object, hierarchy) { + d3.rebind(object, hierarchy, "sort", "children", "value"); + object.nodes = object; + object.links = d3_layout_hierarchyLinks; + return object; + } + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d3.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d3.layout.partition = function() { + var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; + } + } + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); + } + return 1 + d; + } + function partition(d, i) { + var nodes = hierarchy.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition; + }; + return d3_layout_hierarchyRebind(partition, hierarchy); + }; + d3.layout.pie = function() { + var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = Ï„; + function pie(data) { + var values = data.map(function(d, i) { + return +value.call(pie, d, i); + }); + var a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle); + var k = ((typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a) / d3.sum(values); + var index = d3.range(data.length); + if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + var arcs = []; + index.forEach(function(i) { + var d; + arcs[i] = { + data: data[i], + value: d = values[i], + startAngle: a, + endAngle: a += d * k + }; + }); + return arcs; + } + pie.value = function(x) { + if (!arguments.length) return value; + value = x; + return pie; + }; + pie.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return pie; + }; + pie.startAngle = function(x) { + if (!arguments.length) return startAngle; + startAngle = x; + return pie; + }; + pie.endAngle = function(x) { + if (!arguments.length) return endAngle; + endAngle = x; + return pie; + }; + return pie; + }; + var d3_layout_pieSortByValue = {}; + d3.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index) { + var series = data.map(function(d, i) { + return values.call(stack, d, i); + }); + var points = series.map(function(d) { + return d.map(function(v, i) { + return [ x.call(stack, v, i), y.call(stack, v, i) ]; + }); + }); + var orders = order.call(stack, points, index); + series = d3.permute(series, orders); + points = d3.permute(points, orders); + var offsets = offset.call(stack, points, index); + var n = series.length, m = series[0].length, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } + } + return data; + } + stack.values = function(x) { + if (!arguments.length) return values; + values = x; + return stack; + }; + stack.order = function(x) { + if (!arguments.length) return order; + order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x) { + if (!arguments.length) return offset; + offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d3.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } + } + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d3.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d3.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); + } + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; + } + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; + } + s2 += s3 * data[i][j][1]; + } + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; + } + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k; + } + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d3.range(data.length); + } + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; + } + function d3_layout_stackMaxIndex(array) { + var i = 1, j = 0, v = array[0][1], k, n = array.length; + for (;i < n; ++i) { + if ((k = array[i][1]) > v) { + j = i; + v = k; + } + } + return j; + } + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); + } + function d3_layout_stackSum(p, d) { + return p + d[1]; + } + d3.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d3.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); + } + } + } + return bins; + } + histogram.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram; + }; + histogram.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram; + }; + histogram.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram; + }; + histogram.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram; + }; + return histogram; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); + } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [ d3.min(values), d3.max(values) ]; + } + d3.layout.tree = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function tree(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0]; + function firstWalk(node, previousSibling) { + var children = node.children, layout = node._tree; + if (children && (n = children.length)) { + var n, firstChild = children[0], previousChild, ancestor = firstChild, child, i = -1; + while (++i < n) { + child = children[i]; + firstWalk(child, previousChild); + ancestor = apportion(child, previousChild, ancestor); + previousChild = child; + } + d3_layout_treeShift(node); + var midpoint = .5 * (firstChild._tree.prelim + child._tree.prelim); + if (previousSibling) { + layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling); + layout.mod = layout.prelim - midpoint; + } else { + layout.prelim = midpoint; + } + } else { + if (previousSibling) { + layout.prelim = previousSibling._tree.prelim + separation(node, previousSibling); + } + } + } + function secondWalk(node, x) { + node.x = node._tree.prelim + x; + var children = node.children; + if (children && (n = children.length)) { + var i = -1, n; + x += node._tree.mod; + while (++i < n) { + secondWalk(children[i], x); + } + } + } + function apportion(node, previousSibling, ancestor) { + if (previousSibling) { + var vip = node, vop = node, vim = previousSibling, vom = node.parent.children[0], sip = vip._tree.mod, sop = vop._tree.mod, sim = vim._tree.mod, som = vom._tree.mod, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop._tree.ancestor = node; + shift = vim._tree.prelim + sim - vip._tree.prelim - sip + separation(vim, vip); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, node, ancestor), node, shift); + sip += shift; + sop += shift; + } + sim += vim._tree.mod; + sip += vip._tree.mod; + som += vom._tree.mod; + sop += vop._tree.mod; + } + if (vim && !d3_layout_treeRight(vop)) { + vop._tree.thread = vim; + vop._tree.mod += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom._tree.thread = vip; + vom._tree.mod += sip - som; + ancestor = node; + } + } + return ancestor; + } + d3_layout_treeVisitAfter(root, function(node, previousSibling) { + node._tree = { + ancestor: node, + prelim: 0, + mod: 0, + change: 0, + shift: 0, + number: previousSibling ? previousSibling._tree.number + 1 : 0 + }; + }); + firstWalk(root); + secondWalk(root, -root._tree.prelim); + var left = d3_layout_treeSearch(root, d3_layout_treeLeftmost), right = d3_layout_treeSearch(root, d3_layout_treeRightmost), deep = d3_layout_treeSearch(root, d3_layout_treeDeepest), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2, y1 = deep.depth || 1; + d3_layout_treeVisitAfter(root, nodeSize ? function(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; + delete node._tree; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = node.depth / y1 * size[1]; + delete node._tree; + }); + return nodes; + } + tree.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree; + }; + tree.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return tree; + }; + tree.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return tree; + }; + return d3_layout_hierarchyRebind(tree, hierarchy); + }; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; + } + function d3_layout_treeLeft(node) { + var children = node.children; + return children && children.length ? children[0] : node._tree.thread; + } + function d3_layout_treeRight(node) { + var children = node.children, n; + return children && (n = children.length) ? children[n - 1] : node._tree.thread; + } + function d3_layout_treeSearch(node, compare) { + var children = node.children; + if (children && (n = children.length)) { + var child, n, i = -1; + while (++i < n) { + if (compare(child = d3_layout_treeSearch(children[i], compare), node) > 0) { + node = child; + } + } + } + return node; + } + function d3_layout_treeRightmost(a, b) { + return a.x - b.x; + } + function d3_layout_treeLeftmost(a, b) { + return b.x - a.x; + } + function d3_layout_treeDeepest(a, b) { + return a.depth - b.depth; + } + function d3_layout_treeVisitAfter(node, callback) { + function visit(node, previousSibling) { + var children = node.children; + if (children && (n = children.length)) { + var child, previousChild = null, i = -1, n; + while (++i < n) { + child = children[i]; + visit(child, previousChild); + previousChild = child; + } + } + callback(node, previousSibling); + } + visit(node, null); + } + function d3_layout_treeShift(node) { + var shift = 0, change = 0, children = node.children, i = children.length, child; + while (--i >= 0) { + child = children[i]._tree; + child.prelim += shift; + child.mod += shift; + shift += child.shift + (change += child.change); + } + } + function d3_layout_treeMove(ancestor, node, shift) { + ancestor = ancestor._tree; + node = node._tree; + var change = shift / (node.number - ancestor.number); + ancestor.change += change; + node.change -= change; + node.shift += shift; + node.prelim += shift; + node.mod += shift; + } + function d3_layout_treeAncestor(vim, node, ancestor) { + return vim._tree.ancestor.parent == node.parent ? vim._tree.ancestor : ancestor; + } + d3.layout.pack = function() { + var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius; + function pack(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; + }; + root.x = root.y = 0; + d3_layout_treeVisitAfter(root, function(d) { + d.r = +r(d.value); + }); + d3_layout_treeVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_treeVisitAfter(root, function(d) { + d.r += dr; + }); + d3_layout_treeVisitAfter(root, d3_layout_packSiblings); + d3_layout_treeVisitAfter(root, function(d) { + d.r -= dr; + }); + } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; + } + pack.size = function(_) { + if (!arguments.length) return size; + size = _; + return pack; + }; + pack.radius = function(_) { + if (!arguments.length) return radius; + radius = _ == null || typeof _ === "function" ? _ : +_; + return pack; + }; + pack.padding = function(_) { + if (!arguments.length) return padding; + padding = +_; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy); + }; + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return .999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node) { + xMin = Math.min(node.x - node.r, xMin); + xMax = Math.max(node.x + node.r, xMax); + yMin = Math.min(node.y - node.r, yMin); + yMax = Math.max(node.y + node.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } + } + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; + } + } + } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } + } + } + } + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); + } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); + } + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; + } + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); + } + } + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d3.layout.cluster = function() { + var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false; + function cluster(d, i) { + var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_treeVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_treeVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; + } + cluster.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster; + }; + cluster.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster; + }; + cluster.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster; + }; + return d3_layout_hierarchyRebind(cluster, hierarchy); + }; + function d3_layout_clusterY(children) { + return 1 + d3.max(children, function(child) { + return child.y; + }); + } + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d3.layout.treemap = function() { + var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5)); + function scale(children, k) { + var i = -1, n = children.length, child, area; + while (++i < n) { + area = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area) || area <= 0 ? 0 : area; + } + } + function squarify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score = worst(row, u)) <= best) { + remaining.pop(); + best = score; + } else { + row.area -= row.pop().area; + position(row, u, rect, false); + u = Math.min(rect.dx, rect.dy); + row.length = row.area = 0; + best = Infinity; + } + } + if (row.length) { + position(row, u, rect, true); + row.length = row.area = 0; + } + children.forEach(squarify); + } + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect = pad(node), remaining = children.slice(), child, row = []; + scale(remaining, rect.dx * rect.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); + } + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; + } + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + } + function position(row, u, rect, flush) { + var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o; + if (u == rect.dx) { + if (flush || v > rect.dy) v = rect.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0); + } + o.z = true; + o.dx += rect.x + rect.dx - x; + rect.y += v; + rect.dy -= v; + } else { + if (flush || v > rect.dx) v = rect.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0); + } + o.z = false; + o.dy += rect.y + rect.dy - y; + rect.x += v; + rect.dx -= v; + } + } + function treemap(d) { + var nodes = stickies || hierarchy(d), root = nodes[0]; + root.x = 0; + root.y = 0; + root.dx = size[0]; + root.dy = size[1]; + if (stickies) hierarchy.revalue(root); + scale([ root ], root.dx * root.dy / root.value); + (stickies ? stickify : squarify)(root); + if (sticky) stickies = nodes; + return nodes; + } + treemap.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap; + }; + treemap.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], + padConstant) : padConstant; + return treemap; + }; + treemap.round = function(x) { + if (!arguments.length) return round != Number; + round = x ? Math.round : Number; + return treemap; + }; + treemap.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap; + }; + treemap.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap; + }; + treemap.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap; + }; + return d3_layout_hierarchyRebind(treemap, hierarchy); + }; + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy + }; + } + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } + return { + x: x, + y: y, + dx: dx, + dy: dy + }; + } + d3.random = { + normal: function(µ, σ) { + var n = arguments.length; + if (n < 2) σ = 1; + if (n < 1) µ = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r); + }; + }, + logNormal: function() { + var random = d3.random.normal.apply(d3, arguments); + return function() { + return Math.exp(random()); + }; + }, + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s / m; + }; + } + }; + d3.scale = {}; + function d3_scaleExtent(domain) { + var start = domain[0], stop = domain[domain.length - 1]; + return start < stop ? [ start, stop ] : [ stop, start ]; + } + function d3_scaleRange(scale) { + return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); + } + function d3_scale_bilinear(domain, range, uninterpolate, interpolate) { + var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain, nice) { + var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain[i0] = nice.floor(x0); + domain[i1] = nice.ceil(x1); + return domain; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; + }, + ceil: function(x) { + return Math.ceil(x / step) * step; + } + } : d3_scale_niceIdentity; + } + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain, range, uninterpolate, interpolate) { + var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1; + if (domain[k] < domain[0]) { + domain = domain.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain[j - 1], domain[j])); + i.push(interpolate(range[j - 1], range[j])); + } + return function(x) { + var j = d3.bisect(domain, x, 1, k) - 1; + return i[j](u[j](x)); + }; + } + d3.scale.linear = function() { + return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false); + }; + function d3_scale_linear(domain, range, interpolate, clamp) { + var output, input; + function rescale() { + var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear(domain, range, uninterpolate, interpolate); + input = linear(range, domain, uninterpolate, d3_interpolate); + return scale; + } + function scale(x) { + return output(x); + } + scale.invert = function(y) { + return input(y); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.map(Number); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.rangeRound = function(x) { + return scale.range(x).interpolate(d3_interpolateRound); + }; + scale.clamp = function(x) { + if (!arguments.length) return clamp; + clamp = x; + return rescale(); + }; + scale.interpolate = function(x) { + if (!arguments.length) return interpolate; + interpolate = x; + return rescale(); + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + d3_scale_linearNice(domain, m); + return rescale(); + }; + scale.copy = function() { + return d3_scale_linear(domain, range, interpolate, clamp); + }; + return rescale(); + } + function d3_scale_linearRebind(scale, linear) { + return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp"); + } + function d3_scale_linearNice(domain, m) { + return d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2])); + } + function d3_scale_linearTickRange(domain, m) { + if (m == null) m = 10; + var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2; + extent[0] = Math.ceil(extent[0] / step) * step; + extent[1] = Math.floor(extent[1] / step) * step + step * .5; + extent[2] = step; + return extent; + } + function d3_scale_linearTicks(domain, m) { + return d3.range.apply(d3, d3_scale_linearTickRange(domain, m)); + } + function d3_scale_linearTickFormat(domain, m, format) { + var range = d3_scale_linearTickRange(domain, m); + return d3.format(format ? format.replace(d3_format_re, function(a, b, c, d, e, f, g, h, i, j) { + return [ b, c, d, e, f, g, h, i || "." + d3_scale_linearFormatPrecision(j, range), j ].join(""); + }) : ",." + d3_scale_linearPrecision(range[2]) + "f"); + } + var d3_scale_linearFormatSignificant = { + s: 1, + g: 1, + p: 1, + r: 1, + e: 1 + }; + function d3_scale_linearPrecision(value) { + return -Math.floor(Math.log(value) / Math.LN10 + .01); + } + function d3_scale_linearFormatPrecision(type, range) { + var p = d3_scale_linearPrecision(range[2]); + return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(Math.abs(range[0]), Math.abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2; + } + d3.scale.log = function() { + return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]); + }; + function d3_scale_log(linear, base, positive, domain) { + function log(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); + } + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale(x) { + return linear(log(x)); + } + scale.invert = function(x) { + return pow(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + positive = x[0] >= 0; + linear.domain((domain = x.map(Number)).map(log)); + return scale; + }; + scale.base = function(_) { + if (!arguments.length) return base; + base = +_; + linear.domain(domain.map(log)); + return scale; + }; + scale.nice = function() { + var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative); + linear.domain(niced); + domain = niced.map(pow); + return scale; + }; + scale.ticks = function() { + var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k); + ticks.push(pow(i)); + } else { + ticks.push(pow(i)); + for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k); + } + for (i = 0; ticks[i] < u; i++) {} + for (j = ticks.length; ticks[j - 1] > v; j--) {} + ticks = ticks.slice(i, j); + } + return ticks; + }; + scale.tickFormat = function(n, format) { + if (!arguments.length) return d3_scale_logFormat; + if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format); + var k = Math.max(.1, n / scale.ticks().length), f = positive ? (e = 1e-12, Math.ceil) : (e = -1e-12, + Math.floor), e; + return function(d) { + return d / pow(f(log(d) + e)) <= k ? format(d) : ""; + }; + }; + scale.copy = function() { + return d3_scale_log(linear.copy(), base, positive, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); + } + }; + d3.scale.pow = function() { + return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]); + }; + function d3_scale_pow(linear, exponent, domain) { + var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent); + function scale(x) { + return linear(powp(x)); + } + scale.invert = function(x) { + return powb(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return domain; + linear.domain((domain = x.map(Number)).map(powp)); + return scale; + }; + scale.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + scale.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + scale.nice = function(m) { + return scale.domain(d3_scale_linearNice(domain, m)); + }; + scale.exponent = function(x) { + if (!arguments.length) return exponent; + powp = d3_scale_powPow(exponent = x); + powb = d3_scale_powPow(1 / exponent); + linear.domain(domain.map(powp)); + return scale; + }; + scale.copy = function() { + return d3_scale_pow(linear.copy(), exponent, domain); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; + } + d3.scale.sqrt = function() { + return d3.scale.pow().exponent(.5); + }; + d3.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [ [] ] + }); + }; + function d3_scale_ordinal(domain, ranger) { + var index, range, rangeBand; + function scale(x) { + return range[((index.get(x) || ranger.t === "range" && index.set(x, domain.push(x))) - 1) % range.length]; + } + function steps(start, step) { + return d3.range(domain.length).map(function(i) { + return start + step * i; + }); + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = []; + index = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi)); + return scale[ranger.t].apply(scale, ranger.a); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments + }; + return scale; + }; + scale.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = (stop - start) / (Math.max(1, domain.length - 1) + padding); + range = steps(domain.length < 2 ? (start + stop) / 2 : start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale; + }; + scale.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale; + }; + scale.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding)), error = stop - start - (domain.length - padding) * step; + range = steps(start + Math.round(error / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale; + }; + scale.rangeBand = function() { + return rangeBand; + }; + scale.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); + }; + scale.copy = function() { + return d3_scale_ordinal(domain, ranger); + }; + return scale.domain(domain); + } + d3.scale.category10 = function() { + return d3.scale.ordinal().range(d3_category10); + }; + d3.scale.category20 = function() { + return d3.scale.ordinal().range(d3_category20); + }; + d3.scale.category20b = function() { + return d3.scale.ordinal().range(d3_category20b); + }; + d3.scale.category20c = function() { + return d3.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString); + var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString); + var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString); + var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString); + d3.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q); + return scale; + } + function scale(x) { + if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)]; + } + scale.domain = function(x) { + if (!arguments.length) return domain; + domain = x.filter(function(d) { + return !isNaN(d); + }).sort(d3.ascending); + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.quantiles = function() { + return thresholds; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ]; + }; + scale.copy = function() { + return d3_scale_quantile(domain, range); + }; + return rescale(); + } + d3.scale.quantize = function() { + return d3_scale_quantize(0, 1, [ 0, 1 ]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale; + } + scale.domain = function(x) { + if (!arguments.length) return [ x0, x1 ]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); + }; + scale.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [ y, y + 1 / kx ]; + }; + scale.copy = function() { + return d3_scale_quantize(x0, x1, range); + }; + return rescale(); + } + d3.scale.threshold = function() { + return d3_scale_threshold([ .5 ], [ 0, 1 ]); + }; + function d3_scale_threshold(domain, range) { + function scale(x) { + if (x <= x) return range[d3.bisect(domain, x)]; + } + scale.domain = function(_) { + if (!arguments.length) return domain; + domain = _; + return scale; + }; + scale.range = function(_) { + if (!arguments.length) return range; + range = _; + return scale; + }; + scale.invertExtent = function(y) { + y = range.indexOf(y); + return [ domain[y - 1], domain[y] ]; + }; + scale.copy = function() { + return d3_scale_threshold(domain, range); + }; + return scale; + } + d3.scale.identity = function() { + return d3_scale_identity([ 0, 1 ]); + }; + function d3_scale_identity(domain) { + function identity(x) { + return +x; + } + identity.invert = identity; + identity.domain = identity.range = function(x) { + if (!arguments.length) return domain; + domain = x.map(identity); + return identity; + }; + identity.ticks = function(m) { + return d3_scale_linearTicks(domain, m); + }; + identity.tickFormat = function(m, format) { + return d3_scale_linearTickFormat(domain, m, format); + }; + identity.copy = function() { + return d3_scale_identity(domain); + }; + return identity; + } + d3.svg = {}; + d3.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function arc() { + var r0 = innerRadius.apply(this, arguments), r1 = outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) + d3_svg_arcOffset, a1 = endAngle.apply(this, arguments) + d3_svg_arcOffset, da = (a1 < a0 && (da = a0, + a0 = a1, a1 = da), a1 - a0), df = da < Ï€ ? "0" : "1", c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1); + return da >= d3_svg_arcMax ? r0 ? "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "M0," + r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + -r0 + "A" + r0 + "," + r0 + " 0 1,0 0," + r0 + "Z" : "M0," + r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + -r1 + "A" + r1 + "," + r1 + " 0 1,1 0," + r1 + "Z" : r0 ? "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L" + r0 * c1 + "," + r0 * s1 + "A" + r0 + "," + r0 + " 0 " + df + ",0 " + r0 * c0 + "," + r0 * s0 + "Z" : "M" + r1 * c0 + "," + r1 * s0 + "A" + r1 + "," + r1 + " 0 " + df + ",1 " + r1 * c1 + "," + r1 * s1 + "L0,0" + "Z"; + } + arc.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc; + }; + arc.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc; + }; + arc.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc; + }; + arc.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc; + }; + arc.centroid = function() { + var r = (innerRadius.apply(this, arguments) + outerRadius.apply(this, arguments)) / 2, a = (startAngle.apply(this, arguments) + endAngle.apply(this, arguments)) / 2 + d3_svg_arcOffset; + return [ Math.cos(a) * r, Math.sin(a) * r ]; + }; + return arc; + }; + var d3_svg_arcOffset = -halfÏ€, d3_svg_arcMax = Ï„ - ε; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; + } + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; + } + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7; + function line(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y); + function segment() { + segments.push("M", interpolate(projection(points), tension)); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]); + } else if (points.length) { + segment(); + points = []; + } + } + if (points.length) segment(); + return segments.length ? segments.join("") : null; + } + line.x = function(_) { + if (!arguments.length) return x; + x = _; + return line; + }; + line.y = function(_) { + if (!arguments.length) return y; + y = _; + return line; + }; + line.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return line; + }; + line.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + return line; + }; + line.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return line; + }; + return line; + } + d3.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d3.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value) { + value.key = key; + value.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.join("L"); + } + function d3_svg_lineLinearClosed(points) { + return d3_svg_lineLinear(points) + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, points.length - 1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), + points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); + } + var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1; + if (quad) { + path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; + } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } + } + if (quad) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ]; + while (++i < 3) { + pi = points[i]; + px.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px.push(pi[0]); + py.push(pi[1]); + } + path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ]; + --i; + while (++i < m) { + pi = points[i % n]; + px.shift(); + px.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); + } + } + return d3_svg_lineBasis(points); + } + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); + } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs(d) < ε) { + m[i] = m[i + 1] = 0; + } else { + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; + } + } + } + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([ s || 0, m[i] * s || 0 ]); + } + return tangents; + } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d3.svg.line.radial = function() { + var line = d3_svg_line(d3_svg_lineRadial); + line.radius = line.x, delete line.x; + line.angle = line.y, delete line.y; + return line; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] + d3_svg_arcOffset; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); + } + return points; + } + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7; + function area(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment() { + segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); + } + while (++i < n) { + if (defined.call(this, d = data[i], i)) { + points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]); + points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]); + } else if (points0.length) { + segment(); + points0 = []; + points1 = []; + } + } + if (points0.length) segment(); + return segments.length ? segments.join("") : null; + } + area.x = function(_) { + if (!arguments.length) return x1; + x0 = x1 = _; + return area; + }; + area.x0 = function(_) { + if (!arguments.length) return x0; + x0 = _; + return area; + }; + area.x1 = function(_) { + if (!arguments.length) return x1; + x1 = _; + return area; + }; + area.y = function(_) { + if (!arguments.length) return y1; + y0 = y1 = _; + return area; + }; + area.y0 = function(_) { + if (!arguments.length) return y0; + y0 = _; + return area; + }; + area.y1 = function(_) { + if (!arguments.length) return y1; + y1 = _; + return area; + }; + area.defined = function(_) { + if (!arguments.length) return defined; + defined = _; + return area; + }; + area.interpolate = function(_) { + if (!arguments.length) return interpolateKey; + if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key; + interpolateReverse = interpolate.reverse || interpolate; + L = interpolate.closed ? "M" : "L"; + return area; + }; + area.tension = function(_) { + if (!arguments.length) return tension; + tension = _; + return area; + }; + return area; + } + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d3.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d3.svg.area.radial = function() { + var area = d3_svg_area(d3_svg_lineRadial); + area.radius = area.x, delete area.x; + area.innerRadius = area.x0, delete area.x0; + area.outerRadius = area.x1, delete area.x1; + area.angle = area.y, delete area.y; + area.startAngle = area.y0, delete area.y0; + area.endAngle = area.y1, delete area.y1; + return area; + }; + d3.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self, f, d, i) { + var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) + d3_svg_arcOffset, a1 = endAngle.call(self, subgroup, i) + d3_svg_arcOffset; + return { + r: r, + a0: a0, + a1: a1, + p0: [ r * Math.cos(a0), r * Math.sin(a0) ], + p1: [ r * Math.cos(a1), r * Math.sin(a1) ] + }; + } + function equals(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > Ï€) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; + } + d3.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3 ]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [ d.x, d.y ]; + } + d3.svg.diagonal.radial = function() { + var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] + d3_svg_arcOffset; + return [ r * Math.cos(a), r * Math.sin(a) ]; + }; + } + d3.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; + } + function d3_svg_symbolType() { + return "circle"; + } + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / Ï€); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d3.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; + }, + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d3.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + function d3_transition(groups, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.id = id; + return groups; + } + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d3.transition = function(selection) { + return arguments.length ? d3_transitionInheritId ? selection.transition() : selection : d3_selectionRoot.transition(); + }; + d3.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, id, node.__transition__[id]); + subgroup.push(subnode); + } else { + subgroup.push(null); + } + } + } + return d3_transition(subgroups, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, subgroups = [], subgroup, subnodes, node, subnode, transition; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition = node.__transition__[id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, id, transition); + subgroup.push(subnode); + } + } + } + } + return d3_transition(subgroups, id); + }; + d3_transitionPrototype.filter = function(filter) { + var subgroups = [], subgroup, group, node; + if (typeof filter !== "function") filter = d3_selection_filter(filter); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter.call(node, node.__data__, i)) { + subgroup.push(node); + } + } + } + return d3_transition(subgroups, this.id); + }; + d3_transitionPrototype.tween = function(name, tween) { + var id = this.id; + if (arguments.length < 2) return this.node().__transition__[id].tween.get(name); + return d3_selection_each(this, tween == null ? function(node) { + node.__transition__[id].tween.remove(name); + } : function(node) { + node.__transition__[id].tween.set(name, tween); + }); + }; + function d3_transition_tween(groups, name, value, tween) { + var id = groups.id; + return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) { + node.__transition__[id].tween.set(name, tween(value.call(node, node.__data__, i, j))); + } : (value = tween(value), function(node) { + node.__transition__[id].tween.set(name, value); + })); + } + d3_transitionPrototype.attr = function(nameNS, value) { + if (arguments.length < 2) { + for (value in nameNS) this.attr(value, nameNS[value]); + return this; + } + var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name); + } + function attrNullNS() { + this.removeAttributeNS(name.space, name.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttribute(name, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name.space, name.local), i; + return a !== b && (i = interpolate(a, b), function(t) { + this.setAttributeNS(name.space, name.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name = d3.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name)); + return f && function(t) { + this.setAttribute(name, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local)); + return f && function(t) { + this.setAttributeNS(name.space, name.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name, value, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name !== "string") { + if (n < 2) value = ""; + for (priority in name) this.style(priority, name[priority], value); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window.getComputedStyle(this, null).getPropertyValue(name), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name, value, styleString); + }; + d3_transitionPrototype.styleTween = function(name, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window.getComputedStyle(this, null).getPropertyValue(name)); + return f && function(t) { + this.style.setProperty(name, f(t), priority); + }; + } + return this.tween("style." + name, styleTween); + }; + d3_transitionPrototype.text = function(value) { + return d3_transition_tween(this, "text", value, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; + } + d3_transitionPrototype.remove = function() { + return this.each("end.transition", function() { + var p; + if (this.__transition__.count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value) { + var id = this.id; + if (arguments.length < 1) return this.node().__transition__[id].ease; + if (typeof value !== "function") value = d3.ease.apply(d3, arguments); + return d3_selection_each(this, function(node) { + node.__transition__[id].ease = value; + }); + }; + d3_transitionPrototype.delay = function(value) { + var id = this.id; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node.__transition__[id].delay = +value.call(node, node.__data__, i, j); + } : (value = +value, function(node) { + node.__transition__[id].delay = value; + })); + }; + d3_transitionPrototype.duration = function(value) { + var id = this.id; + return d3_selection_each(this, typeof value === "function" ? function(node, i, j) { + node.__transition__[id].duration = Math.max(1, value.call(node, node.__data__, i, j)); + } : (value = Math.max(1, value), function(node) { + node.__transition__[id].duration = value; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node.__transition__[id]; + type.call(node, node.__data__, i, j); + }); + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } else { + d3_selection_each(this, function(node) { + var transition = node.__transition__[id]; + (transition.event || (transition.event = d3.dispatch("start", "end"))).on(type, listener); + }); + } + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, subgroups = [], subgroup, group, node, transition; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition = Object.create(node.__transition__[id0]); + transition.delay += transition.duration; + d3_transitionNode(node, i, id1, transition); + } + subgroup.push(node); + } + } + return d3_transition(subgroups, id1); + }; + function d3_transitionNode(node, i, id, inherit) { + var lock = node.__transition__ || (node.__transition__ = { + active: 0, + count: 0 + }), transition = lock[id]; + if (!transition) { + var time = inherit.time; + transition = lock[id] = { + tween: new d3_Map(), + time: time, + ease: inherit.ease, + delay: inherit.delay, + duration: inherit.duration + }; + ++lock.count; + d3.timer(function(elapsed) { + var d = node.__data__, ease = transition.ease, delay = transition.delay, duration = transition.duration, timer = d3_timer_active, tweened = []; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + function start(elapsed) { + if (lock.active > id) return stop(); + lock.active = id; + transition.event && transition.event.start.call(node, d, i); + transition.tween.forEach(function(key, value) { + if (value = value.call(node, d, i)) { + tweened.push(value); + } + }); + d3.timer(function() { + timer.c = tick(elapsed || 1) ? d3_true : tick; + return 1; + }, 0, time); + } + function tick(elapsed) { + if (lock.active !== id) return stop(); + var t = elapsed / duration, e = ease(t), n = tweened.length; + while (n > 0) { + tweened[--n].call(node, e); + } + if (t >= 1) { + transition.event && transition.event.end.call(node, d, i); + return stop(); + } + } + function stop() { + if (--lock.count) delete lock[id]; else delete node.__transition__; + return 1; + } + }, 0, time); + } + } + d3.svg.axis = function() { + var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g = d3.select(this); + var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy(); + var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform; + var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), + d3.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"); + switch (orient) { + case "bottom": + { + tickTransform = d3_svg_axisX; + lineEnter.attr("y2", innerTickSize); + textEnter.attr("y", Math.max(innerTickSize, 0) + tickPadding); + lineUpdate.attr("x2", 0).attr("y2", innerTickSize); + textUpdate.attr("x", 0).attr("y", Math.max(innerTickSize, 0) + tickPadding); + text.attr("dy", ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize); + break; + } + + case "top": + { + tickTransform = d3_svg_axisX; + lineEnter.attr("y2", -innerTickSize); + textEnter.attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); + lineUpdate.attr("x2", 0).attr("y2", -innerTickSize); + textUpdate.attr("x", 0).attr("y", -(Math.max(innerTickSize, 0) + tickPadding)); + text.attr("dy", "0em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize); + break; + } + + case "left": + { + tickTransform = d3_svg_axisY; + lineEnter.attr("x2", -innerTickSize); + textEnter.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)); + lineUpdate.attr("x2", -innerTickSize).attr("y2", 0); + textUpdate.attr("x", -(Math.max(innerTickSize, 0) + tickPadding)).attr("y", 0); + text.attr("dy", ".32em").style("text-anchor", "end"); + pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize); + break; + } + + case "right": + { + tickTransform = d3_svg_axisY; + lineEnter.attr("x2", innerTickSize); + textEnter.attr("x", Math.max(innerTickSize, 0) + tickPadding); + lineUpdate.attr("x2", innerTickSize).attr("y2", 0); + textUpdate.attr("x", Math.max(innerTickSize, 0) + tickPadding).attr("y", 0); + text.attr("dy", ".32em").style("text-anchor", "start"); + pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize); + break; + } + } + if (scale1.rangeBand) { + var dx = scale1.rangeBand() / 2, x = function(d) { + return scale1(d) + dx; + }; + tickEnter.call(tickTransform, x); + tickUpdate.call(tickTransform, x); + } else { + tickEnter.call(tickTransform, scale0); + tickUpdate.call(tickTransform, scale1); + tickExit.call(tickTransform, scale1); + } + }); + } + axis.scale = function(x) { + if (!arguments.length) return scale; + scale = x; + return axis; + }; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; + }; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = arguments; + return axis; + }; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; + }; + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; + }; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; + }; + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 + }; + function d3_svg_axisX(selection, x) { + selection.attr("transform", function(d) { + return "translate(" + x(d) + ",0)"; + }); + } + function d3_svg_axisY(selection, y) { + selection.attr("transform", function(d) { + return "translate(0," + y(d) + ")"; + }); + } + d3.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background = g.selectAll(".background").data([ 0 ]); + background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize = g.selectAll(".resize").data(resizes, d3_identity); + resize.exit().remove(); + resize.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize.style("display", brush.empty() ? "none" : null); + var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); + } + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d3.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(), center, origin = d3.mouse(target), offset; + var w = d3.select(d3_window).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d3.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); + } else { + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d3.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d3.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d3.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); + } + } + function keyup() { + if (d3.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d3.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d3.event.altKey) { + if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale, i) { + var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; + } else { + max = position; + } + } + if (extent[0] != min || extent[1] != max) { + if (i) yExtentDomain = null; else xExtentDomain = null; + extent[0] = min; + extent[1] = max; + return true; + } + } + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d3.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); + } + } + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z; + return brush; + }; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } + } + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } + } + return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ]; + } + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [ x0, x1 ]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ]; + } + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [ y0, y1 ]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ]; + } + return brush; + }; + brush.clear = function() { + if (!brush.empty()) { + xExtent = [ 0, 0 ], yExtent = [ 0, 0 ]; + xExtentDomain = yExtentDomain = null; + } + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + }; + return d3.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ]; + var d3_time = d3.time = {}, d3_date = Date, d3_time_daySymbols = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]; + function d3_date_utc() { + this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]); + } + d3_date_utc.prototype = { + getDate: function() { + return this._.getUTCDate(); + }, + getDay: function() { + return this._.getUTCDay(); + }, + getFullYear: function() { + return this._.getUTCFullYear(); + }, + getHours: function() { + return this._.getUTCHours(); + }, + getMilliseconds: function() { + return this._.getUTCMilliseconds(); + }, + getMinutes: function() { + return this._.getUTCMinutes(); + }, + getMonth: function() { + return this._.getUTCMonth(); + }, + getSeconds: function() { + return this._.getUTCSeconds(); + }, + getTime: function() { + return this._.getTime(); + }, + getTimezoneOffset: function() { + return 0; + }, + valueOf: function() { + return this._.valueOf(); + }, + setDate: function() { + d3_time_prototype.setUTCDate.apply(this._, arguments); + }, + setDay: function() { + d3_time_prototype.setUTCDay.apply(this._, arguments); + }, + setFullYear: function() { + d3_time_prototype.setUTCFullYear.apply(this._, arguments); + }, + setHours: function() { + d3_time_prototype.setUTCHours.apply(this._, arguments); + }, + setMilliseconds: function() { + d3_time_prototype.setUTCMilliseconds.apply(this._, arguments); + }, + setMinutes: function() { + d3_time_prototype.setUTCMinutes.apply(this._, arguments); + }, + setMonth: function() { + d3_time_prototype.setUTCMonth.apply(this._, arguments); + }, + setSeconds: function() { + d3_time_prototype.setUTCSeconds.apply(this._, arguments); + }, + setTime: function() { + d3_time_prototype.setTime.apply(this._, arguments); + } + }; + var d3_time_prototype = Date.prototype; + var d3_time_formatDateTime = "%a %b %e %X %Y", d3_time_formatDate = "%m/%d/%Y", d3_time_formatTime = "%H:%M:%S"; + var d3_time_days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], d3_time_dayAbbreviations = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], d3_time_months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], d3_time_monthAbbreviations = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; + function d3_time_interval(local, step, number) { + function round(date) { + var d0 = local(date), d1 = offset(d0, 1); + return date - d0 < d1 - date ? d0 : d1; + } + function ceil(date) { + step(date = local(new d3_date(date - 1)), 1); + return date; + } + function offset(date, k) { + step(date = new d3_date(+date), k); + return date; + } + function range(t0, t1, dt) { + var time = ceil(t0), times = []; + if (dt > 1) { + while (time < t1) { + if (!(number(time) % dt)) times.push(new Date(+time)); + step(time, 1); + } + } else { + while (time < t1) times.push(new Date(+time)), step(time, 1); + } + return times; + } + function range_utc(t0, t1, dt) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = t0; + return range(utc, t1, dt); + } finally { + d3_date = Date; + } + } + local.floor = local; + local.round = round; + local.ceil = ceil; + local.offset = offset; + local.range = range; + var utc = local.utc = d3_time_interval_utc(local); + utc.floor = utc; + utc.round = d3_time_interval_utc(round); + utc.ceil = d3_time_interval_utc(ceil); + utc.offset = d3_time_interval_utc(offset); + utc.range = range_utc; + return local; + } + function d3_time_interval_utc(method) { + return function(date, k) { + try { + d3_date = d3_date_utc; + var utc = new d3_date_utc(); + utc._ = date; + return method(utc, k)._; + } finally { + d3_date = Date; + } + }; + } + d3_time.year = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setMonth(0, 1); + return date; + }, function(date, offset) { + date.setFullYear(date.getFullYear() + offset); + }, function(date) { + return date.getFullYear(); + }); + d3_time.years = d3_time.year.range; + d3_time.years.utc = d3_time.year.utc.range; + d3_time.day = d3_time_interval(function(date) { + var day = new d3_date(2e3, 0); + day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + return day; + }, function(date, offset) { + date.setDate(date.getDate() + offset); + }, function(date) { + return date.getDate() - 1; + }); + d3_time.days = d3_time.day.range; + d3_time.days.utc = d3_time.day.utc.range; + d3_time.dayOfYear = function(date) { + var year = d3_time.year(date); + return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5); + }; + d3_time_daySymbols.forEach(function(day, i) { + day = day.toLowerCase(); + i = 7 - i; + var interval = d3_time[day] = d3_time_interval(function(date) { + (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); + return date; + }, function(date, offset) { + date.setDate(date.getDate() + Math.floor(offset) * 7); + }, function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); + }); + d3_time[day + "s"] = interval.range; + d3_time[day + "s"].utc = interval.utc.range; + d3_time[day + "OfYear"] = function(date) { + var day = d3_time.year(date).getDay(); + return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7); + }; + }); + d3_time.week = d3_time.sunday; + d3_time.weeks = d3_time.sunday.range; + d3_time.weeks.utc = d3_time.sunday.utc.range; + d3_time.weekOfYear = d3_time.sundayOfYear; + d3_time.format = d3_time_format; + function d3_time_format(template) { + var n = template.length; + function format(date) { + var string = [], i = -1, j = 0, c, p, f; + while (++i < n) { + if (template.charCodeAt(i) === 37) { + string.push(template.substring(j, i)); + if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i); + if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p); + string.push(c); + j = i + 1; + } + } + string.push(template.substring(j, i)); + return string.join(""); + } + format.parse = function(string) { + var d = { + y: 1900, + m: 0, + d: 1, + H: 0, + M: 0, + S: 0, + L: 0, + Z: null + }, i = d3_time_parse(d, template, string, 0); + if (i != string.length) return null; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)(); + if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("w" in d && ("W" in d || "U" in d)) { + date.setFullYear(d.y, 0, 1); + date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7); + } else date.setFullYear(d.y, d.m, d.d); + date.setHours(d.H + Math.floor(d.Z / 100), d.M + d.Z % 100, d.S, d.L); + return localZ ? date._ : date; + }; + format.toString = function() { + return template; + }; + return format; + } + function d3_time_parse(date, template, string, j) { + var c, p, t, i = 0, n = template.length, m = string.length; + while (i < n) { + if (j >= m) return -1; + c = template.charCodeAt(i++); + if (c === 37) { + t = template.charAt(i++); + p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t]; + if (!p || (j = p(date, string, j)) < 0) return -1; + } else if (c != string.charCodeAt(j++)) { + return -1; + } + } + return j; + } + function d3_time_formatRe(names) { + return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i"); + } + function d3_time_formatLookup(names) { + var map = new d3_Map(), i = -1, n = names.length; + while (++i < n) map.set(names[i].toLowerCase(), i); + return map; + } + function d3_time_formatPad(value, fill, width) { + var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; + return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); + } + var d3_time_dayRe = d3_time_formatRe(d3_time_days), d3_time_dayLookup = d3_time_formatLookup(d3_time_days), d3_time_dayAbbrevRe = d3_time_formatRe(d3_time_dayAbbreviations), d3_time_dayAbbrevLookup = d3_time_formatLookup(d3_time_dayAbbreviations), d3_time_monthRe = d3_time_formatRe(d3_time_months), d3_time_monthLookup = d3_time_formatLookup(d3_time_months), d3_time_monthAbbrevRe = d3_time_formatRe(d3_time_monthAbbreviations), d3_time_monthAbbrevLookup = d3_time_formatLookup(d3_time_monthAbbreviations), d3_time_percentRe = /^%/; + var d3_time_formatPads = { + "-": "", + _: " ", + "0": "0" + }; + var d3_time_formats = { + a: function(d) { + return d3_time_dayAbbreviations[d.getDay()]; + }, + A: function(d) { + return d3_time_days[d.getDay()]; + }, + b: function(d) { + return d3_time_monthAbbreviations[d.getMonth()]; + }, + B: function(d) { + return d3_time_months[d.getMonth()]; + }, + c: d3_time_format(d3_time_formatDateTime), + d: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + e: function(d, p) { + return d3_time_formatPad(d.getDate(), p, 2); + }, + H: function(d, p) { + return d3_time_formatPad(d.getHours(), p, 2); + }, + I: function(d, p) { + return d3_time_formatPad(d.getHours() % 12 || 12, p, 2); + }, + j: function(d, p) { + return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3); + }, + L: function(d, p) { + return d3_time_formatPad(d.getMilliseconds(), p, 3); + }, + m: function(d, p) { + return d3_time_formatPad(d.getMonth() + 1, p, 2); + }, + M: function(d, p) { + return d3_time_formatPad(d.getMinutes(), p, 2); + }, + p: function(d) { + return d.getHours() >= 12 ? "PM" : "AM"; + }, + S: function(d, p) { + return d3_time_formatPad(d.getSeconds(), p, 2); + }, + U: function(d, p) { + return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2); + }, + w: function(d) { + return d.getDay(); + }, + W: function(d, p) { + return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2); + }, + x: d3_time_format(d3_time_formatDate), + X: d3_time_format(d3_time_formatTime), + y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 100, p, 2); + }, + Y: function(d, p) { + return d3_time_formatPad(d.getFullYear() % 1e4, p, 4); + }, + Z: d3_time_zone, + "%": function() { + return "%"; + } + }; + var d3_time_parsers = { + a: d3_time_parseWeekdayAbbrev, + A: d3_time_parseWeekday, + b: d3_time_parseMonthAbbrev, + B: d3_time_parseMonth, + c: d3_time_parseLocaleFull, + d: d3_time_parseDay, + e: d3_time_parseDay, + H: d3_time_parseHour24, + I: d3_time_parseHour24, + j: d3_time_parseDayOfYear, + L: d3_time_parseMilliseconds, + m: d3_time_parseMonthNumber, + M: d3_time_parseMinutes, + p: d3_time_parseAmPm, + S: d3_time_parseSeconds, + U: d3_time_parseWeekNumberSunday, + w: d3_time_parseWeekdayNumber, + W: d3_time_parseWeekNumberMonday, + x: d3_time_parseLocaleDate, + X: d3_time_parseLocaleTime, + y: d3_time_parseYear, + Y: d3_time_parseFullYear, + Z: d3_time_parseZone, + "%": d3_time_parseLiteralPercent + }; + function d3_time_parseWeekdayAbbrev(date, string, i) { + d3_time_dayAbbrevRe.lastIndex = 0; + var n = d3_time_dayAbbrevRe.exec(string.substring(i)); + return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekday(date, string, i) { + d3_time_dayRe.lastIndex = 0; + var n = d3_time_dayRe.exec(string.substring(i)); + return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseWeekdayNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 1)); + return n ? (date.w = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberSunday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i)); + return n ? (date.U = +n[0], i + n[0].length) : -1; + } + function d3_time_parseWeekNumberMonday(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i)); + return n ? (date.W = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMonthAbbrev(date, string, i) { + d3_time_monthAbbrevRe.lastIndex = 0; + var n = d3_time_monthAbbrevRe.exec(string.substring(i)); + return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseMonth(date, string, i) { + d3_time_monthRe.lastIndex = 0; + var n = d3_time_monthRe.exec(string.substring(i)); + return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1; + } + function d3_time_parseLocaleFull(date, string, i) { + return d3_time_parse(date, d3_time_formats.c.toString(), string, i); + } + function d3_time_parseLocaleDate(date, string, i) { + return d3_time_parse(date, d3_time_formats.x.toString(), string, i); + } + function d3_time_parseLocaleTime(date, string, i) { + return d3_time_parse(date, d3_time_formats.X.toString(), string, i); + } + function d3_time_parseFullYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 4)); + return n ? (date.y = +n[0], i + n[0].length) : -1; + } + function d3_time_parseYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1; + } + function d3_time_parseZone(date, string, i) { + return /^[+-]\d{4}$/.test(string = string.substring(i, i + 5)) ? (date.Z = +string, + i + 5) : -1; + } + function d3_time_expandYear(d) { + return d + (d > 68 ? 1900 : 2e3); + } + function d3_time_parseMonthNumber(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.m = n[0] - 1, i + n[0].length) : -1; + } + function d3_time_parseDay(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.d = +n[0], i + n[0].length) : -1; + } + function d3_time_parseDayOfYear(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 3)); + return n ? (date.j = +n[0], i + n[0].length) : -1; + } + function d3_time_parseHour24(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.H = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMinutes(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.M = +n[0], i + n[0].length) : -1; + } + function d3_time_parseSeconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 2)); + return n ? (date.S = +n[0], i + n[0].length) : -1; + } + function d3_time_parseMilliseconds(date, string, i) { + d3_time_numberRe.lastIndex = 0; + var n = d3_time_numberRe.exec(string.substring(i, i + 3)); + return n ? (date.L = +n[0], i + n[0].length) : -1; + } + var d3_time_numberRe = /^\s*\d+/; + function d3_time_parseAmPm(date, string, i) { + var n = d3_time_amPmLookup.get(string.substring(i, i += 2).toLowerCase()); + return n == null ? -1 : (date.p = n, i); + } + var d3_time_amPmLookup = d3.map({ + am: 0, + pm: 1 + }); + function d3_time_zone(d) { + var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = ~~(abs(z) / 60), zm = abs(z) % 60; + return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2); + } + function d3_time_parseLiteralPercent(date, string, i) { + d3_time_percentRe.lastIndex = 0; + var n = d3_time_percentRe.exec(string.substring(i, i + 1)); + return n ? i + n[0].length : -1; + } + d3_time_format.utc = d3_time_formatUtc; + function d3_time_formatUtc(template) { + var local = d3_time_format(template); + function format(date) { + try { + d3_date = d3_date_utc; + var utc = new d3_date(); + utc._ = date; + return local(utc); + } finally { + d3_date = Date; + } + } + format.parse = function(string) { + try { + d3_date = d3_date_utc; + var date = local.parse(string); + return date && date._; + } finally { + d3_date = Date; + } + }; + format.toString = local.toString; + return format; + } + var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ"); + d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso; + function d3_time_formatIsoNative(date) { + return date.toISOString(); + } + d3_time_formatIsoNative.parse = function(string) { + var date = new Date(string); + return isNaN(date) ? null : date; + }; + d3_time_formatIsoNative.toString = d3_time_formatIso.toString; + d3_time.second = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 1e3) * 1e3); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 1e3); + }, function(date) { + return date.getSeconds(); + }); + d3_time.seconds = d3_time.second.range; + d3_time.seconds.utc = d3_time.second.utc.range; + d3_time.minute = d3_time_interval(function(date) { + return new d3_date(Math.floor(date / 6e4) * 6e4); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 6e4); + }, function(date) { + return date.getMinutes(); + }); + d3_time.minutes = d3_time.minute.range; + d3_time.minutes.utc = d3_time.minute.utc.range; + d3_time.hour = d3_time_interval(function(date) { + var timezone = date.getTimezoneOffset() / 60; + return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5); + }, function(date, offset) { + date.setTime(date.getTime() + Math.floor(offset) * 36e5); + }, function(date) { + return date.getHours(); + }); + d3_time.hours = d3_time.hour.range; + d3_time.hours.utc = d3_time.hour.utc.range; + d3_time.month = d3_time_interval(function(date) { + date = d3_time.day(date); + date.setDate(1); + return date; + }, function(date, offset) { + date.setMonth(date.getMonth() + offset); + }, function(date) { + return date.getMonth(); + }); + d3_time.months = d3_time.month.range; + d3_time.months.utc = d3_time.month.utc.range; + function d3_time_scale(linear, methods, format) { + function scale(x) { + return linear(x); + } + scale.invert = function(x) { + return d3_time_scaleDate(linear.invert(x)); + }; + scale.domain = function(x) { + if (!arguments.length) return linear.domain().map(d3_time_scaleDate); + linear.domain(x); + return scale; + }; + function tickMethod(extent, count) { + var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target); + return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) { + return d / 31536e6; + }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i]; + } + scale.nice = function(interval, skip) { + var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval); + if (method) interval = method[0], skip = method[1]; + function skipped(date) { + return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length; + } + return scale.domain(d3_scale_nice(domain, skip > 1 ? { + floor: function(date) { + while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1); + return date; + }, + ceil: function(date) { + while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1); + return date; + } + } : interval)); + }; + scale.ticks = function(interval, skip) { + var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ { + range: interval + }, skip ]; + if (method) interval = method[0], skip = method[1]; + return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip); + }; + scale.tickFormat = function() { + return format; + }; + scale.copy = function() { + return d3_time_scale(linear.copy(), methods, format); + }; + return d3_scale_linearRebind(scale, linear); + } + function d3_time_scaleDate(t) { + return new Date(t); + } + function d3_time_scaleFormat(formats) { + return function(date) { + var i = formats.length - 1, f = formats[i]; + while (!f[1](date)) f = formats[--i]; + return f[0](date); + }; + } + var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ]; + var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ]; + var d3_time_scaleLocalFormats = [ [ d3_time_format("%Y"), d3_true ], [ d3_time_format("%B"), function(d) { + return d.getMonth(); + } ], [ d3_time_format("%b %d"), function(d) { + return d.getDate() != 1; + } ], [ d3_time_format("%a %d"), function(d) { + return d.getDay() && d.getDate() != 1; + } ], [ d3_time_format("%I %p"), function(d) { + return d.getHours(); + } ], [ d3_time_format("%I:%M"), function(d) { + return d.getMinutes(); + } ], [ d3_time_format(":%S"), function(d) { + return d.getSeconds(); + } ], [ d3_time_format(".%L"), function(d) { + return d.getMilliseconds(); + } ] ]; + var d3_time_scaleLocalFormat = d3_time_scaleFormat(d3_time_scaleLocalFormats); + d3_time_scaleLocalMethods.year = d3_time.year; + d3_time.scale = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat); + }; + var d3_time_scaleMilliseconds = { + range: function(start, stop, step) { + return d3.range(+start, +stop, step).map(d3_time_scaleDate); + } + }; + var d3_time_scaleUTCMethods = d3_time_scaleLocalMethods.map(function(m) { + return [ m[0].utc, m[1] ]; + }); + var d3_time_scaleUTCFormats = [ [ d3_time_formatUtc("%Y"), d3_true ], [ d3_time_formatUtc("%B"), function(d) { + return d.getUTCMonth(); + } ], [ d3_time_formatUtc("%b %d"), function(d) { + return d.getUTCDate() != 1; + } ], [ d3_time_formatUtc("%a %d"), function(d) { + return d.getUTCDay() && d.getUTCDate() != 1; + } ], [ d3_time_formatUtc("%I %p"), function(d) { + return d.getUTCHours(); + } ], [ d3_time_formatUtc("%I:%M"), function(d) { + return d.getUTCMinutes(); + } ], [ d3_time_formatUtc(":%S"), function(d) { + return d.getUTCSeconds(); + } ], [ d3_time_formatUtc(".%L"), function(d) { + return d.getUTCMilliseconds(); + } ] ]; + var d3_time_scaleUTCFormat = d3_time_scaleFormat(d3_time_scaleUTCFormats); + d3_time_scaleUTCMethods.year = d3_time.year.utc; + d3_time.scale.utc = function() { + return d3_time_scale(d3.scale.linear(), d3_time_scaleUTCMethods, d3_time_scaleUTCFormat); + }; + d3.text = d3_xhrType(function(request) { + return request.responseText; + }); + d3.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); + } + d3.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); + } + d3.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + return d3; +}(); \ No newline at end of file diff --git a/admin/view/javascript/shopunity/charts_svg/d3.min.js b/admin/view/javascript/shopunity/charts_svg/d3.min.js new file mode 100755 index 0000000..b8bffdc --- /dev/null +++ b/admin/view/javascript/shopunity/charts_svg/d3.min.js @@ -0,0 +1,5 @@ +d3=function(){function n(n){return null!=n&&!isNaN(n)}function t(n){return n.length}function e(n){for(var t=1;n*t%1;)t*=10;return t}function r(n,t){try{for(var e in t)Object.defineProperty(n.prototype,e,{value:t[e],enumerable:!1})}catch(r){n.prototype=t}}function u(){}function i(){}function o(n,t,e){return function(){var r=e.apply(t,arguments);return r===t?n:r}}function a(n,t){if(t in n)return t;t=t.charAt(0).toUpperCase()+t.substring(1);for(var e=0,r=la.length;r>e;++e){var u=la[e]+t;if(u in n)return u}}function c(){}function s(){}function l(n){function t(){for(var t,r=e,u=-1,i=r.length;++ue;e++)for(var u,i=n[e],o=0,a=i.length;a>o;o++)(u=i[o])&&t(u,o,e);return n}function N(n){return ha(n,xa),n}function L(n){var t,e;return function(r,u,i){var o,a=n[i].update,c=a.length;for(i!=e&&(e=i,t=0),u>=t&&(t=u+1);!(o=a[t])&&++t0&&(n=n.substring(0,a));var l=_a.get(n);return l&&(n=l,s=R),a?t?u:r:t?c:i}function z(n,t){return function(e){var r=$o.event;$o.event=e,t[0]=this.__data__;try{n.apply(this,t)}finally{$o.event=r}}}function R(n,t){var e=z(n,t);return function(n){var t=this,r=n.relatedTarget;r&&(r===t||8&r.compareDocumentPosition(t))||e.call(t,n)}}function D(){var n=".dragsuppress-"+ ++wa,t="click"+n,e=$o.select(Ko).on("touchmove"+n,f).on("dragstart"+n,f).on("selectstart"+n,f);if(ba){var r=Go.style,u=r[ba];r[ba]="none"}return function(i){function o(){e.on(t,null)}e.on(n,null),ba&&(r[ba]=u),i&&(e.on(t,function(){f(),o()},!0),setTimeout(o,0))}}function P(n,t){t.changedTouches&&(t=t.changedTouches[0]);var e=n.ownerSVGElement||n;if(e.createSVGPoint){var r=e.createSVGPoint();if(0>Sa&&(Ko.scrollX||Ko.scrollY)){e=$o.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var u=e[0][0].getScreenCTM();Sa=!(u.f||u.e),e.remove()}return Sa?(r.x=t.pageX,r.y=t.pageY):(r.x=t.clientX,r.y=t.clientY),r=r.matrixTransform(n.getScreenCTM().inverse()),[r.x,r.y]}var i=n.getBoundingClientRect();return[t.clientX-i.left-n.clientLeft,t.clientY-i.top-n.clientTop]}function U(n){return n>0?1:0>n?-1:0}function j(n){return n>1?0:-1>n?ka:Math.acos(n)}function H(n){return n>1?Aa:-1>n?-Aa:Math.asin(n)}function F(n){return((n=Math.exp(n))-1/n)/2}function O(n){return((n=Math.exp(n))+1/n)/2}function Y(n){return((n=Math.exp(2*n))-1)/(n+1)}function I(n){return(n=Math.sin(n/2))*n}function Z(){}function V(n,t,e){return new X(n,t,e)}function X(n,t,e){this.h=n,this.s=t,this.l=e}function $(n,t,e){function r(n){return n>360?n-=360:0>n&&(n+=360),60>n?i+(o-i)*n/60:180>n?o:240>n?i+(o-i)*(240-n)/60:i}function u(n){return Math.round(255*r(n))}var i,o;return n=isNaN(n)?0:(n%=360)<0?n+360:n,t=isNaN(t)?0:0>t?0:t>1?1:t,e=0>e?0:e>1?1:e,o=.5>=e?e*(1+t):e+t-e*t,i=2*e-o,ot(u(n+120),u(n),u(n-120))}function B(n,t,e){return new W(n,t,e)}function W(n,t,e){this.h=n,this.c=t,this.l=e}function J(n,t,e){return isNaN(n)&&(n=0),isNaN(t)&&(t=0),G(e,Math.cos(n*=La)*t,Math.sin(n)*t)}function G(n,t,e){return new K(n,t,e)}function K(n,t,e){this.l=n,this.a=t,this.b=e}function Q(n,t,e){var r=(n+16)/116,u=r+t/500,i=r-e/200;return u=tt(u)*Oa,r=tt(r)*Ya,i=tt(i)*Ia,ot(rt(3.2404542*u-1.5371385*r-.4985314*i),rt(-.969266*u+1.8760108*r+.041556*i),rt(.0556434*u-.2040259*r+1.0572252*i))}function nt(n,t,e){return n>0?B(Math.atan2(e,t)*Ta,Math.sqrt(t*t+e*e),n):B(0/0,0/0,n)}function tt(n){return n>.206893034?n*n*n:(n-4/29)/7.787037}function et(n){return n>.008856?Math.pow(n,1/3):7.787037*n+4/29}function rt(n){return Math.round(255*(.00304>=n?12.92*n:1.055*Math.pow(n,1/2.4)-.055))}function ut(n){return ot(n>>16,255&n>>8,255&n)}function it(n){return ut(n)+""}function ot(n,t,e){return new at(n,t,e)}function at(n,t,e){this.r=n,this.g=t,this.b=e}function ct(n){return 16>n?"0"+Math.max(0,n).toString(16):Math.min(255,n).toString(16)}function st(n,t,e){var r,u,i,o=0,a=0,c=0;if(r=/([a-z]+)\((.*)\)/i.exec(n))switch(u=r[2].split(","),r[1]){case"hsl":return e(parseFloat(u[0]),parseFloat(u[1])/100,parseFloat(u[2])/100);case"rgb":return t(gt(u[0]),gt(u[1]),gt(u[2]))}return(i=Xa.get(n))?t(i.r,i.g,i.b):(null!=n&&"#"===n.charAt(0)&&(4===n.length?(o=n.charAt(1),o+=o,a=n.charAt(2),a+=a,c=n.charAt(3),c+=c):7===n.length&&(o=n.substring(1,3),a=n.substring(3,5),c=n.substring(5,7)),o=parseInt(o,16),a=parseInt(a,16),c=parseInt(c,16)),t(o,a,c))}function lt(n,t,e){var r,u,i=Math.min(n/=255,t/=255,e/=255),o=Math.max(n,t,e),a=o-i,c=(o+i)/2;return a?(u=.5>c?a/(o+i):a/(2-o-i),r=n==o?(t-e)/a+(e>t?6:0):t==o?(e-n)/a+2:(n-t)/a+4,r*=60):(r=0/0,u=c>0&&1>c?0:r),V(r,u,c)}function ft(n,t,e){n=ht(n),t=ht(t),e=ht(e);var r=et((.4124564*n+.3575761*t+.1804375*e)/Oa),u=et((.2126729*n+.7151522*t+.072175*e)/Ya),i=et((.0193339*n+.119192*t+.9503041*e)/Ia);return G(116*u-16,500*(r-u),200*(u-i))}function ht(n){return(n/=255)<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function gt(n){var t=parseFloat(n);return"%"===n.charAt(n.length-1)?Math.round(2.55*t):t}function pt(n){return"function"==typeof n?n:function(){return n}}function vt(n){return n}function dt(n){return function(t,e,r){return 2===arguments.length&&"function"==typeof e&&(r=e,e=null),mt(t,e,n,r)}}function mt(n,t,e,r){function u(){var n,t=c.status;if(!t&&c.responseText||t>=200&&300>t||304===t){try{n=e.call(i,c)}catch(r){return o.error.call(i,r),void 0}o.load.call(i,n)}else o.error.call(i,c)}var i={},o=$o.dispatch("beforesend","progress","load","error"),a={},c=new XMLHttpRequest,s=null;return!Ko.XDomainRequest||"withCredentials"in c||!/^(http(s)?:)?\/\//.test(n)||(c=new XDomainRequest),"onload"in c?c.onload=c.onerror=u:c.onreadystatechange=function(){c.readyState>3&&u()},c.onprogress=function(n){var t=$o.event;$o.event=n;try{o.progress.call(i,c)}finally{$o.event=t}},i.header=function(n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)},i.mimeType=function(n){return arguments.length?(t=null==n?null:n+"",i):t},i.responseType=function(n){return arguments.length?(s=n,i):s},i.response=function(n){return e=n,i},["get","post"].forEach(function(n){i[n]=function(){return i.send.apply(i,[n].concat(Wo(arguments)))}}),i.send=function(e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var l in a)c.setRequestHeader(l,a[l]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=s&&(c.responseType=s),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i},i.abort=function(){return c.abort(),i},$o.rebind(i,o,"on"),null==r?i:i.get(yt(r))}function yt(n){return 1===n.length?function(t,e){n(null==t?e:null)}:n}function xt(){var n=Mt(),t=_t()-n;t>24?(isFinite(t)&&(clearTimeout(Ja),Ja=setTimeout(xt,t)),Wa=0):(Wa=1,Ka(xt))}function Mt(){var n=Date.now();for(Ga=$a;Ga;)n>=Ga.t&&(Ga.f=Ga.c(n-Ga.t)),Ga=Ga.n;return n}function _t(){for(var n,t=$a,e=1/0;t;)t.f?t=n?n.n=t.n:$a=t.n:(t.t8?function(n){return n/e}:function(n){return n*e},symbol:n}}function wt(n,t){return t-(n?Math.ceil(Math.log(n)/Math.LN10):1)}function St(n){return n+""}function kt(){}function Et(n,t,e){var r=e.s=n+t,u=r-n,i=r-u;e.t=n-i+(t-u)}function At(n,t){n&&lc.hasOwnProperty(n.type)&&lc[n.type](n,t)}function Ct(n,t,e){var r,u=-1,i=n.length-e;for(t.lineStart();++ua;++a)u.point((e=n[a])[0],e[1]);return u.lineEnd(),void 0}var c=new $t(e,n,null,!0),s=new $t(e,null,c,!1);c.o=s,i.push(c),o.push(s),c=new $t(r,n,null,!1),s=new $t(r,null,c,!0),c.o=s,i.push(c),o.push(s)}}),o.sort(t),Xt(i),Xt(o),i.length){for(var a=0,c=e,s=o.length;s>a;++a)o[a].e=c=!c;for(var l,f,h=i[0];;){for(var g=h,p=!0;g.v;)if((g=g.n)===h)return;l=g.z,u.lineStart();do{if(g.v=g.o.v=!0,g.e){if(p)for(var a=0,s=l.length;s>a;++a)u.point((f=l[a])[0],f[1]);else r(g.x,g.n.x,1,u);g=g.n}else{if(p){l=g.p.z;for(var a=l.length-1;a>=0;--a)u.point((f=l[a])[0],f[1])}else r(g.x,g.p.x,-1,u);g=g.p}g=g.o,l=g.z,p=!p}while(!g.v);u.lineEnd()}}}function Xt(n){if(t=n.length){for(var t,e,r=0,u=n[0];++r1&&2&t&&e.push(e.pop().concat(e.shift())),g.push(e.filter(Wt))}}var g,p,v,d=t(i),m=u.invert(r[0],r[1]),y={point:o,lineStart:c,lineEnd:s,polygonStart:function(){y.point=l,y.lineStart=f,y.lineEnd=h,g=[],p=[],i.polygonStart()},polygonEnd:function(){y.point=o,y.lineStart=c,y.lineEnd=s,g=$o.merge(g);var n=Kt(m,p);g.length?Vt(g,Gt,n,e,i):n&&(i.lineStart(),e(null,null,1,i),i.lineEnd()),i.polygonEnd(),g=p=null},sphere:function(){i.polygonStart(),i.lineStart(),e(null,null,1,i),i.lineEnd(),i.polygonEnd()}},x=Jt(),M=t(x);return y}}function Wt(n){return n.length>1}function Jt(){var n,t=[];return{lineStart:function(){t.push(n=[])},point:function(t,e){n.push([t,e])},lineEnd:c,buffer:function(){var e=t;return t=[],n=null,e},rejoin:function(){t.length>1&&t.push(t.pop().concat(t.shift()))}}}function Gt(n,t){return((n=n.x)[0]<0?n[1]-Aa-Ca:Aa-n[1])-((t=t.x)[0]<0?t[1]-Aa-Ca:Aa-t[1])}function Kt(n,t){var e=n[0],r=n[1],u=[Math.sin(e),-Math.cos(e),0],i=0,o=0;hc.reset();for(var a=0,c=t.length;c>a;++a){var s=t[a],l=s.length;if(l)for(var f=s[0],h=f[0],g=f[1]/2+ka/4,p=Math.sin(g),v=Math.cos(g),d=1;;){d===l&&(d=0),n=s[d];var m=n[0],y=n[1]/2+ka/4,x=Math.sin(y),M=Math.cos(y),_=m-h,b=aa(_)>ka,w=p*x;if(hc.add(Math.atan2(w*Math.sin(_),v*M+w*Math.cos(_))),i+=b?_+(_>=0?Ea:-Ea):_,b^h>=e^m>=e){var S=zt(Tt(f),Tt(n));Pt(S);var k=zt(u,S);Pt(k);var E=(b^_>=0?-1:1)*H(k[2]);(r>E||r===E&&(S[0]||S[1]))&&(o+=b^_>=0?1:-1)}if(!d++)break;h=m,p=x,v=M,f=n}}return(-Ca>i||Ca>i&&0>hc)^1&o}function Qt(n){var t,e=0/0,r=0/0,u=0/0;return{lineStart:function(){n.lineStart(),t=1},point:function(i,o){var a=i>0?ka:-ka,c=aa(i-e);aa(c-ka)0?Aa:-Aa),n.point(u,r),n.lineEnd(),n.lineStart(),n.point(a,r),n.point(i,r),t=0):u!==a&&c>=ka&&(aa(e-u)Ca?Math.atan((Math.sin(t)*(i=Math.cos(r))*Math.sin(e)-Math.sin(r)*(u=Math.cos(t))*Math.sin(n))/(u*i*o)):(t+r)/2}function te(n,t,e,r){var u;if(null==n)u=e*Aa,r.point(-ka,u),r.point(0,u),r.point(ka,u),r.point(ka,0),r.point(ka,-u),r.point(0,-u),r.point(-ka,-u),r.point(-ka,0),r.point(-ka,u);else if(aa(n[0]-t[0])>Ca){var i=n[0]i}function e(n){var e,i,c,s,l;return{lineStart:function(){s=c=!1,l=1},point:function(f,h){var g,p=[f,h],v=t(f,h),d=o?v?0:u(f,h):v?u(f+(0>f?ka:-ka),h):0;if(!e&&(s=c=v)&&n.lineStart(),v!==c&&(g=r(e,p),(jt(e,g)||jt(p,g))&&(p[0]+=Ca,p[1]+=Ca,v=t(p[0],p[1]))),v!==c)l=0,v?(n.lineStart(),g=r(p,e),n.point(g[0],g[1])):(g=r(e,p),n.point(g[0],g[1]),n.lineEnd()),e=g;else if(a&&e&&o^v){var m;d&i||!(m=r(p,e,!0))||(l=0,o?(n.lineStart(),n.point(m[0][0],m[0][1]),n.point(m[1][0],m[1][1]),n.lineEnd()):(n.point(m[1][0],m[1][1]),n.lineEnd(),n.lineStart(),n.point(m[0][0],m[0][1])))}!v||e&&jt(e,p)||n.point(p[0],p[1]),e=p,c=v,i=d},lineEnd:function(){c&&n.lineEnd(),e=null},clean:function(){return l|(s&&c)<<1}}}function r(n,t,e){var r=Tt(n),u=Tt(t),o=[1,0,0],a=zt(r,u),c=qt(a,a),s=a[0],l=c-s*s;if(!l)return!e&&n;var f=i*c/l,h=-i*s/l,g=zt(o,a),p=Dt(o,f),v=Dt(a,h);Rt(p,v);var d=g,m=qt(p,d),y=qt(d,d),x=m*m-y*(qt(p,p)-1);if(!(0>x)){var M=Math.sqrt(x),_=Dt(d,(-m-M)/y);if(Rt(_,p),_=Ut(_),!e)return _;var b,w=n[0],S=t[0],k=n[1],E=t[1];w>S&&(b=w,w=S,S=b);var A=S-w,C=aa(A-ka)A;if(!C&&k>E&&(b=k,k=E,E=b),N?C?k+E>0^_[1]<(aa(_[0]-w)ka^(w<=_[0]&&_[0]<=S)){var L=Dt(d,(-m+M)/y);return Rt(L,p),[_,Ut(L)]}}}function u(t,e){var r=o?n:ka-n,u=0;return-r>t?u|=1:t>r&&(u|=2),-r>e?u|=4:e>r&&(u|=8),u}var i=Math.cos(n),o=i>0,a=aa(i)>Ca,c=Le(n,6*La);return Bt(t,e,c,o?[0,-n]:[-ka,n-ka])}function re(n,t,e,r){return function(u){var i,o=u.a,a=u.b,c=o.x,s=o.y,l=a.x,f=a.y,h=0,g=1,p=l-c,v=f-s;if(i=n-c,p||!(i>0)){if(i/=p,0>p){if(h>i)return;g>i&&(g=i)}else if(p>0){if(i>g)return;i>h&&(h=i)}if(i=e-c,p||!(0>i)){if(i/=p,0>p){if(i>g)return;i>h&&(h=i)}else if(p>0){if(h>i)return;g>i&&(g=i)}if(i=t-s,v||!(i>0)){if(i/=v,0>v){if(h>i)return;g>i&&(g=i)}else if(v>0){if(i>g)return;i>h&&(h=i)}if(i=r-s,v||!(0>i)){if(i/=v,0>v){if(i>g)return;i>h&&(h=i)}else if(v>0){if(h>i)return;g>i&&(g=i)}return h>0&&(u.a={x:c+h*p,y:s+h*v}),1>g&&(u.b={x:c+g*p,y:s+g*v}),u}}}}}}function ue(n,t,e,r){function u(r,u){return aa(r[0]-n)0?0:3:aa(r[0]-e)0?2:1:aa(r[1]-t)0?1:0:u>0?3:2}function i(n,t){return o(n.x,t.x)}function o(n,t){var e=u(n,1),r=u(t,1);return e!==r?e-r:0===e?t[1]-n[1]:1===e?n[0]-t[0]:2===e?n[1]-t[1]:t[0]-n[0]}return function(a){function c(n){for(var t=0,e=m.length,r=n[1],u=0;e>u;++u)for(var i,o=1,a=m[u],c=a.length,l=a[0];c>o;++o)i=a[o],l[1]<=r?i[1]>r&&s(l,i,n)>0&&++t:i[1]<=r&&s(l,i,n)<0&&--t,l=i;return 0!==t}function s(n,t,e){return(t[0]-n[0])*(e[1]-n[1])-(e[0]-n[0])*(t[1]-n[1])}function l(i,a,c,s){var l=0,f=0;if(null==i||(l=u(i,c))!==(f=u(a,c))||o(i,a)<0^c>0){do s.point(0===l||3===l?n:e,l>1?r:t);while((l=(l+c+4)%4)!==f)}else s.point(a[0],a[1])}function f(u,i){return u>=n&&e>=u&&i>=t&&r>=i}function h(n,t){f(n,t)&&a.point(n,t)}function g(){L.point=v,m&&m.push(y=[]),k=!0,S=!1,b=w=0/0}function p(){d&&(v(x,M),_&&S&&C.rejoin(),d.push(C.buffer())),L.point=h,S&&a.lineEnd()}function v(n,t){n=Math.max(-Ac,Math.min(Ac,n)),t=Math.max(-Ac,Math.min(Ac,t));var e=f(n,t);if(m&&y.push([n,t]),k)x=n,M=t,_=e,k=!1,e&&(a.lineStart(),a.point(n,t));else if(e&&S)a.point(n,t);else{var r={a:{x:b,y:w},b:{x:n,y:t}};N(r)?(S||(a.lineStart(),a.point(r.a.x,r.a.y)),a.point(r.b.x,r.b.y),e||a.lineEnd(),E=!1):e&&(a.lineStart(),a.point(n,t),E=!1)}b=n,w=t,S=e}var d,m,y,x,M,_,b,w,S,k,E,A=a,C=Jt(),N=re(n,t,e,r),L={point:h,lineStart:g,lineEnd:p,polygonStart:function(){a=C,d=[],m=[],E=!0},polygonEnd:function(){a=A,d=$o.merge(d);var t=c([n,r]),e=E&&t,u=d.length;(e||u)&&(a.polygonStart(),e&&(a.lineStart(),l(null,null,1,a),a.lineEnd()),u&&Vt(d,i,t,l,a),a.polygonEnd()),d=m=y=null}};return L}}function ie(n,t){function e(e,r){return e=n(e,r),t(e[0],e[1])}return n.invert&&t.invert&&(e.invert=function(e,r){return e=t.invert(e,r),e&&n.invert(e[0],e[1])}),e}function oe(n){var t=0,e=ka/3,r=be(n),u=r(t,e);return u.parallels=function(n){return arguments.length?r(t=n[0]*ka/180,e=n[1]*ka/180):[180*(t/ka),180*(e/ka)]},u}function ae(n,t){function e(n,t){var e=Math.sqrt(i-2*u*Math.sin(t))/u;return[e*Math.sin(n*=u),o-e*Math.cos(n)]}var r=Math.sin(n),u=(r+Math.sin(t))/2,i=1+r*(2*u-r),o=Math.sqrt(i)/u;return e.invert=function(n,t){var e=o-t;return[Math.atan2(n,e)/u,H((i-(n*n+e*e)*u*u)/(2*u))]},e}function ce(){function n(n,t){Nc+=u*n-r*t,r=n,u=t}var t,e,r,u;Rc.point=function(i,o){Rc.point=n,t=r=i,e=u=o},Rc.lineEnd=function(){n(t,e)}}function se(n,t){Lc>n&&(Lc=n),n>qc&&(qc=n),Tc>t&&(Tc=t),t>zc&&(zc=t)}function le(){function n(n,t){o.push("M",n,",",t,i)}function t(n,t){o.push("M",n,",",t),a.point=e}function e(n,t){o.push("L",n,",",t)}function r(){a.point=n}function u(){o.push("Z")}var i=fe(4.5),o=[],a={point:n,lineStart:function(){a.point=t},lineEnd:r,polygonStart:function(){a.lineEnd=u},polygonEnd:function(){a.lineEnd=r,a.point=n},pointRadius:function(n){return i=fe(n),a},result:function(){if(o.length){var n=o.join("");return o=[],n}}};return a}function fe(n){return"m0,"+n+"a"+n+","+n+" 0 1,1 0,"+-2*n+"a"+n+","+n+" 0 1,1 0,"+2*n+"z"}function he(n,t){dc+=n,mc+=t,++yc}function ge(){function n(n,r){var u=n-t,i=r-e,o=Math.sqrt(u*u+i*i);xc+=o*(t+n)/2,Mc+=o*(e+r)/2,_c+=o,he(t=n,e=r)}var t,e;Pc.point=function(r,u){Pc.point=n,he(t=r,e=u)}}function pe(){Pc.point=he}function ve(){function n(n,t){var e=n-r,i=t-u,o=Math.sqrt(e*e+i*i);xc+=o*(r+n)/2,Mc+=o*(u+t)/2,_c+=o,o=u*n-r*t,bc+=o*(r+n),wc+=o*(u+t),Sc+=3*o,he(r=n,u=t)}var t,e,r,u;Pc.point=function(i,o){Pc.point=n,he(t=r=i,e=u=o)},Pc.lineEnd=function(){n(t,e)}}function de(n){function t(t,e){n.moveTo(t,e),n.arc(t,e,o,0,Ea)}function e(t,e){n.moveTo(t,e),a.point=r}function r(t,e){n.lineTo(t,e)}function u(){a.point=t}function i(){n.closePath()}var o=4.5,a={point:t,lineStart:function(){a.point=e},lineEnd:u,polygonStart:function(){a.lineEnd=i},polygonEnd:function(){a.lineEnd=u,a.point=t},pointRadius:function(n){return o=n,a},result:c};return a}function me(n){function t(n){return(a?r:e)(n)}function e(t){return Me(t,function(e,r){e=n(e,r),t.point(e[0],e[1])})}function r(t){function e(e,r){e=n(e,r),t.point(e[0],e[1])}function r(){x=0/0,S.point=i,t.lineStart()}function i(e,r){var i=Tt([e,r]),o=n(e,r);u(x,M,y,_,b,w,x=o[0],M=o[1],y=e,_=i[0],b=i[1],w=i[2],a,t),t.point(x,M)}function o(){S.point=e,t.lineEnd()}function c(){r(),S.point=s,S.lineEnd=l}function s(n,t){i(f=n,h=t),g=x,p=M,v=_,d=b,m=w,S.point=i}function l(){u(x,M,y,_,b,w,g,p,f,v,d,m,a,t),S.lineEnd=o,o()}var f,h,g,p,v,d,m,y,x,M,_,b,w,S={point:e,lineStart:r,lineEnd:o,polygonStart:function(){t.polygonStart(),S.lineStart=c},polygonEnd:function(){t.polygonEnd(),S.lineStart=r}};return S}function u(t,e,r,a,c,s,l,f,h,g,p,v,d,m){var y=l-t,x=f-e,M=y*y+x*x;if(M>4*i&&d--){var _=a+g,b=c+p,w=s+v,S=Math.sqrt(_*_+b*b+w*w),k=Math.asin(w/=S),E=aa(aa(w)-1)i||aa((y*L+x*T)/M-.5)>.3||o>a*g+c*p+s*v)&&(u(t,e,r,a,c,s,C,N,E,_/=S,b/=S,w,d,m),m.point(C,N),u(C,N,E,_,b,w,l,f,h,g,p,v,d,m))}}var i=.5,o=Math.cos(30*La),a=16;return t.precision=function(n){return arguments.length?(a=(i=n*n)>0&&16,t):Math.sqrt(i)},t}function ye(n){var t=me(function(t,e){return n([t*Ta,e*Ta])});return function(n){return we(t(n))}}function xe(n){this.stream=n}function Me(n,t){return{point:t,sphere:function(){n.sphere()},lineStart:function(){n.lineStart()},lineEnd:function(){n.lineEnd()},polygonStart:function(){n.polygonStart()},polygonEnd:function(){n.polygonEnd()}}}function _e(n){return be(function(){return n})()}function be(n){function t(n){return n=a(n[0]*La,n[1]*La),[n[0]*h+c,s-n[1]*h]}function e(n){return n=a.invert((n[0]-c)/h,(s-n[1])/h),n&&[n[0]*Ta,n[1]*Ta]}function r(){a=ie(o=Ee(m,y,x),i);var n=i(v,d);return c=g-n[0]*h,s=p+n[1]*h,u()}function u(){return l&&(l.valid=!1,l=null),t}var i,o,a,c,s,l,f=me(function(n,t){return n=i(n,t),[n[0]*h+c,s-n[1]*h]}),h=150,g=480,p=250,v=0,d=0,m=0,y=0,x=0,M=Ec,_=vt,b=null,w=null;return t.stream=function(n){return l&&(l.valid=!1),l=we(M(o,f(_(n)))),l.valid=!0,l},t.clipAngle=function(n){return arguments.length?(M=null==n?(b=n,Ec):ee((b=+n)*La),u()):b},t.clipExtent=function(n){return arguments.length?(w=n,_=n?ue(n[0][0],n[0][1],n[1][0],n[1][1]):vt,u()):w},t.scale=function(n){return arguments.length?(h=+n,r()):h},t.translate=function(n){return arguments.length?(g=+n[0],p=+n[1],r()):[g,p]},t.center=function(n){return arguments.length?(v=n[0]%360*La,d=n[1]%360*La,r()):[v*Ta,d*Ta]},t.rotate=function(n){return arguments.length?(m=n[0]%360*La,y=n[1]%360*La,x=n.length>2?n[2]%360*La:0,r()):[m*Ta,y*Ta,x*Ta]},$o.rebind(t,f,"precision"),function(){return i=n.apply(this,arguments),t.invert=i.invert&&e,r()}}function we(n){return Me(n,function(t,e){n.point(t*La,e*La)})}function Se(n,t){return[n,t]}function ke(n,t){return[n>ka?n-Ea:-ka>n?n+Ea:n,t]}function Ee(n,t,e){return n?t||e?ie(Ce(n),Ne(t,e)):Ce(n):t||e?Ne(t,e):ke}function Ae(n){return function(t,e){return t+=n,[t>ka?t-Ea:-ka>t?t+Ea:t,e]}}function Ce(n){var t=Ae(n);return t.invert=Ae(-n),t}function Ne(n,t){function e(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,s=Math.sin(t),l=s*r+a*u;return[Math.atan2(c*i-l*o,a*r-s*u),H(l*i+c*o)]}var r=Math.cos(n),u=Math.sin(n),i=Math.cos(t),o=Math.sin(t);return e.invert=function(n,t){var e=Math.cos(t),a=Math.cos(n)*e,c=Math.sin(n)*e,s=Math.sin(t),l=s*i-c*o;return[Math.atan2(c*i+s*o,a*r+l*u),H(l*r-a*u)]},e}function Le(n,t){var e=Math.cos(n),r=Math.sin(n);return function(u,i,o,a){var c=o*t;null!=u?(u=Te(e,u),i=Te(e,i),(o>0?i>u:u>i)&&(u+=o*Ea)):(u=n+o*Ea,i=n-.5*c);for(var s,l=u;o>0?l>i:i>l;l-=c)a.point((s=Ut([e,-r*Math.cos(l),-r*Math.sin(l)]))[0],s[1])}}function Te(n,t){var e=Tt(t);e[0]-=n,Pt(e);var r=j(-e[1]);return((-e[2]<0?-r:r)+2*Math.PI-Ca)%(2*Math.PI)}function qe(n,t,e){var r=$o.range(n,t-Ca,e).concat(t);return function(n){return r.map(function(t){return[n,t]})}}function ze(n,t,e){var r=$o.range(n,t-Ca,e).concat(t);return function(n){return r.map(function(t){return[t,n]})}}function Re(n){return n.source}function De(n){return n.target}function Pe(n,t,e,r){var u=Math.cos(t),i=Math.sin(t),o=Math.cos(r),a=Math.sin(r),c=u*Math.cos(n),s=u*Math.sin(n),l=o*Math.cos(e),f=o*Math.sin(e),h=2*Math.asin(Math.sqrt(I(r-t)+u*o*I(e-n))),g=1/Math.sin(h),p=h?function(n){var t=Math.sin(n*=h)*g,e=Math.sin(h-n)*g,r=e*c+t*l,u=e*s+t*f,o=e*i+t*a;return[Math.atan2(u,r)*Ta,Math.atan2(o,Math.sqrt(r*r+u*u))*Ta]}:function(){return[n*Ta,t*Ta]};return p.distance=h,p}function Ue(){function n(n,u){var i=Math.sin(u*=La),o=Math.cos(u),a=aa((n*=La)-t),c=Math.cos(a);Uc+=Math.atan2(Math.sqrt((a=o*Math.sin(a))*a+(a=r*i-e*o*c)*a),e*i+r*o*c),t=n,e=i,r=o}var t,e,r;jc.point=function(u,i){t=u*La,e=Math.sin(i*=La),r=Math.cos(i),jc.point=n},jc.lineEnd=function(){jc.point=jc.lineEnd=c}}function je(n,t){function e(t,e){var r=Math.cos(t),u=Math.cos(e),i=n(r*u);return[i*u*Math.sin(t),i*Math.sin(e)]}return e.invert=function(n,e){var r=Math.sqrt(n*n+e*e),u=t(r),i=Math.sin(u),o=Math.cos(u);return[Math.atan2(n*i,r*o),Math.asin(r&&e*i/r)]},e}function He(n,t){function e(n,t){var e=aa(aa(t)-Aa)0}function $e(n,t,e){return(e[0]-t[0])*(n[1]-t[1])<(e[1]-t[1])*(n[0]-t[0])}function Be(n,t,e,r){var u=n[0],i=e[0],o=t[0]-u,a=r[0]-i,c=n[1],s=e[1],l=t[1]-c,f=r[1]-s,h=(a*(c-s)-f*(u-i))/(f*o-a*l);return[u+h*o,c+h*l]}function We(n){var t=n[0],e=n[n.length-1];return!(t[0]-e[0]||t[1]-e[1])}function Je(){mr(this),this.edge=this.site=this.circle=null}function Ge(n){var t=Jc.pop()||new Je;return t.site=n,t}function Ke(n){cr(n),$c.remove(n),Jc.push(n),mr(n)}function Qe(n){var t=n.circle,e=t.x,r=t.cy,u={x:e,y:r},i=n.P,o=n.N,a=[n];Ke(n);for(var c=i;c.circle&&aa(e-c.circle.x)l;++l)s=a[l],c=a[l-1],pr(s.edge,c.site,s.site,u);c=a[0],s=a[f-1],s.edge=hr(c.site,s.site,null,u),ar(c),ar(s)}function nr(n){for(var t,e,r,u,i=n.x,o=n.y,a=$c._;a;)if(r=tr(a,o)-i,r>Ca)a=a.L;else{if(u=i-er(a,o),!(u>Ca)){r>-Ca?(t=a.P,e=a):u>-Ca?(t=a,e=a.N):t=e=a;break}if(!a.R){t=a;break}a=a.R}var c=Ge(n);if($c.insert(t,c),t||e){if(t===e)return cr(t),e=Ge(t.site),$c.insert(c,e),c.edge=e.edge=hr(t.site,c.site),ar(t),ar(e),void 0;if(!e)return c.edge=hr(t.site,c.site),void 0;cr(t),cr(e);var s=t.site,l=s.x,f=s.y,h=n.x-l,g=n.y-f,p=e.site,v=p.x-l,d=p.y-f,m=2*(h*d-g*v),y=h*h+g*g,x=v*v+d*d,M={x:(d*y-g*x)/m+l,y:(h*x-v*y)/m+f};pr(e.edge,s,p,M),c.edge=hr(s,n,null,M),e.edge=hr(n,p,null,M),ar(t),ar(e)}}function tr(n,t){var e=n.site,r=e.x,u=e.y,i=u-t;if(!i)return r;var o=n.P;if(!o)return-1/0;e=o.site;var a=e.x,c=e.y,s=c-t;if(!s)return a;var l=a-r,f=1/i-1/s,h=l/s;return f?(-h+Math.sqrt(h*h-2*f*(l*l/(-2*s)-c+s/2+u-i/2)))/f+r:(r+a)/2}function er(n,t){var e=n.N;if(e)return tr(e,t);var r=n.site;return r.y===t?r.x:1/0}function rr(n){this.site=n,this.edges=[]}function ur(n){for(var t,e,r,u,i,o,a,c,s,l,f=n[0][0],h=n[1][0],g=n[0][1],p=n[1][1],v=Xc,d=v.length;d--;)if(i=v[d],i&&i.prepare())for(a=i.edges,c=a.length,o=0;c>o;)l=a[o].end(),r=l.x,u=l.y,s=a[++o%c].start(),t=s.x,e=s.y,(aa(r-t)>Ca||aa(u-e)>Ca)&&(a.splice(o,0,new vr(gr(i.site,l,aa(r-f)Ca?{x:f,y:aa(t-f)Ca?{x:aa(e-p)Ca?{x:h,y:aa(t-h)Ca?{x:aa(e-g)=-Na)){var g=c*c+s*s,p=l*l+f*f,v=(f*g-s*p)/h,d=(c*p-l*g)/h,f=d+a,m=Gc.pop()||new or;m.arc=n,m.site=u,m.x=v+o,m.y=f+Math.sqrt(v*v+d*d),m.cy=f,n.circle=m;for(var y=null,x=Wc._;x;)if(m.yd||d>=a)return;if(h>p){if(i){if(i.y>=s)return}else i={x:d,y:c};e={x:d,y:s}}else{if(i){if(i.yr||r>1)if(h>p){if(i){if(i.y>=s)return}else i={x:(c-u)/r,y:c};e={x:(s-u)/r,y:s}}else{if(i){if(i.yg){if(i){if(i.x>=a)return}else i={x:o,y:r*o+u};e={x:a,y:r*a+u}}else{if(i){if(i.xr;++r)if(o=l[r],o.x==e[0]){if(o.i)if(null==s[o.i+1])for(s[o.i-1]+=o.x,s.splice(o.i,1),u=r+1;i>u;++u)l[u].i--;else for(s[o.i-1]+=o.x+s[o.i+1],s.splice(o.i,2),u=r+1;i>u;++u)l[u].i-=2;else if(null==s[o.i+1])s[o.i]=o.x;else for(s[o.i]=o.x+s[o.i+1],s.splice(o.i+1,1),u=r+1;i>u;++u)l[u].i--;l.splice(r,1),i--,r--}else o.x=Lr(parseFloat(e[0]),parseFloat(o.x));for(;i>r;)o=l.pop(),null==s[o.i+1]?s[o.i]=o.x:(s[o.i]=o.x+s[o.i+1],s.splice(o.i+1,1)),i--;return 1===s.length?null==s[0]?(o=l[0].x,function(n){return o(n)+""}):function(){return t}:function(n){for(r=0;i>r;++r)s[(o=l[r]).i]=o.x(n);return s.join("")}}function qr(n,t){for(var e,r=$o.interpolators.length;--r>=0&&!(e=$o.interpolators[r](n,t)););return e}function zr(n,t){var e,r=[],u=[],i=n.length,o=t.length,a=Math.min(n.length,t.length);for(e=0;a>e;++e)r.push(qr(n[e],t[e]));for(;i>e;++e)u[e]=n[e];for(;o>e;++e)u[e]=t[e];return function(n){for(e=0;a>e;++e)u[e]=r[e](n);return u}}function Rr(n){return function(t){return 0>=t?0:t>=1?1:n(t)}}function Dr(n){return function(t){return 1-n(1-t)}}function Pr(n){return function(t){return.5*(.5>t?n(2*t):2-n(2-2*t))}}function Ur(n){return n*n}function jr(n){return n*n*n}function Hr(n){if(0>=n)return 0;if(n>=1)return 1;var t=n*n,e=t*n;return 4*(.5>n?e:3*(n-t)+e-.75)}function Fr(n){return function(t){return Math.pow(t,n)}}function Or(n){return 1-Math.cos(n*Aa)}function Yr(n){return Math.pow(2,10*(n-1))}function Ir(n){return 1-Math.sqrt(1-n*n)}function Zr(n,t){var e;return arguments.length<2&&(t=.45),arguments.length?e=t/Ea*Math.asin(1/n):(n=1,e=t/4),function(r){return 1+n*Math.pow(2,-10*r)*Math.sin((r-e)*Ea/t)}}function Vr(n){return n||(n=1.70158),function(t){return t*t*((n+1)*t-n)}}function Xr(n){return 1/2.75>n?7.5625*n*n:2/2.75>n?7.5625*(n-=1.5/2.75)*n+.75:2.5/2.75>n?7.5625*(n-=2.25/2.75)*n+.9375:7.5625*(n-=2.625/2.75)*n+.984375}function $r(n,t){n=$o.hcl(n),t=$o.hcl(t);var e=n.h,r=n.c,u=n.l,i=t.h-e,o=t.c-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.c:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return J(e+i*n,r+o*n,u+a*n)+""}}function Br(n,t){n=$o.hsl(n),t=$o.hsl(t);var e=n.h,r=n.s,u=n.l,i=t.h-e,o=t.s-r,a=t.l-u;return isNaN(o)&&(o=0,r=isNaN(r)?t.s:r),isNaN(i)?(i=0,e=isNaN(e)?t.h:e):i>180?i-=360:-180>i&&(i+=360),function(n){return $(e+i*n,r+o*n,u+a*n)+""}}function Wr(n,t){n=$o.lab(n),t=$o.lab(t);var e=n.l,r=n.a,u=n.b,i=t.l-e,o=t.a-r,a=t.b-u;return function(n){return Q(e+i*n,r+o*n,u+a*n)+""}}function Jr(n,t){return t-=n,function(e){return Math.round(n+t*e)}}function Gr(n){var t=[n.a,n.b],e=[n.c,n.d],r=Qr(t),u=Kr(t,e),i=Qr(nu(e,t,-u))||0;t[0]*e[1]180?l+=360:l-s>180&&(s+=360),u.push({i:r.push(r.pop()+"rotate(",null,")")-2,x:Lr(s,l)})):l&&r.push(r.pop()+"rotate("+l+")"),f!=h?u.push({i:r.push(r.pop()+"skewX(",null,")")-2,x:Lr(f,h)}):h&&r.push(r.pop()+"skewX("+h+")"),g[0]!=p[0]||g[1]!=p[1]?(e=r.push(r.pop()+"scale(",null,",",null,")"),u.push({i:e-4,x:Lr(g[0],p[0])},{i:e-2,x:Lr(g[1],p[1])})):(1!=p[0]||1!=p[1])&&r.push(r.pop()+"scale("+p+")"),e=u.length,function(n){for(var t,i=-1;++ie;++e)(t=n[e][1])>u&&(r=e,u=t);return r}function wu(n){return n.reduce(Su,0)}function Su(n,t){return n+t[1]}function ku(n,t){return Eu(n,Math.ceil(Math.log(t.length)/Math.LN2+1))}function Eu(n,t){for(var e=-1,r=+n[0],u=(n[1]-r)/t,i=[];++e<=t;)i[e]=u*e+r;return i}function Au(n){return[$o.min(n),$o.max(n)]}function Cu(n,t){return n.parent==t.parent?1:2}function Nu(n){var t=n.children;return t&&t.length?t[0]:n._tree.thread}function Lu(n){var t,e=n.children;return e&&(t=e.length)?e[t-1]:n._tree.thread}function Tu(n,t){var e=n.children;if(e&&(u=e.length))for(var r,u,i=-1;++i0&&(n=r);return n}function qu(n,t){return n.x-t.x}function zu(n,t){return t.x-n.x}function Ru(n,t){return n.depth-t.depth}function Du(n,t){function e(n,r){var u=n.children;if(u&&(o=u.length))for(var i,o,a=null,c=-1;++c=0;)t=u[i]._tree,t.prelim+=e,t.mod+=e,e+=t.shift+(r+=t.change)}function Uu(n,t,e){n=n._tree,t=t._tree;var r=e/(t.number-n.number);n.change+=r,t.change-=r,t.shift+=e,t.prelim+=e,t.mod+=e}function ju(n,t,e){return n._tree.ancestor.parent==t.parent?n._tree.ancestor:e}function Hu(n,t){return n.value-t.value}function Fu(n,t){var e=n._pack_next;n._pack_next=t,t._pack_prev=n,t._pack_next=e,e._pack_prev=t}function Ou(n,t){n._pack_next=t,t._pack_prev=n}function Yu(n,t){var e=t.x-n.x,r=t.y-n.y,u=n.r+t.r;return.999*u*u>e*e+r*r}function Iu(n){function t(n){l=Math.min(n.x-n.r,l),f=Math.max(n.x+n.r,f),h=Math.min(n.y-n.r,h),g=Math.max(n.y+n.r,g)}if((e=n.children)&&(s=e.length)){var e,r,u,i,o,a,c,s,l=1/0,f=-1/0,h=1/0,g=-1/0;if(e.forEach(Zu),r=e[0],r.x=-r.r,r.y=0,t(r),s>1&&(u=e[1],u.x=u.r,u.y=0,t(u),s>2))for(i=e[2],$u(r,u,i),t(i),Fu(r,i),r._pack_prev=i,Fu(i,u),u=r._pack_next,o=3;s>o;o++){$u(r,u,i=e[o]);var p=0,v=1,d=1;for(a=u._pack_next;a!==u;a=a._pack_next,v++)if(Yu(a,i)){p=1;break}if(1==p)for(c=r._pack_prev;c!==a._pack_prev&&!Yu(c,i);c=c._pack_prev,d++);p?(d>v||v==d&&u.ro;o++)i=e[o],i.x-=m,i.y-=y,x=Math.max(x,i.r+Math.sqrt(i.x*i.x+i.y*i.y));n.r=x,e.forEach(Vu)}}function Zu(n){n._pack_next=n._pack_prev=n}function Vu(n){delete n._pack_next,delete n._pack_prev}function Xu(n,t,e,r){var u=n.children;if(n.x=t+=r*n.x,n.y=e+=r*n.y,n.r*=r,u)for(var i=-1,o=u.length;++iu&&(e+=u/2,u=0),0>i&&(r+=i/2,i=0),{x:e,y:r,dx:u,dy:i}}function ni(n){var t=n[0],e=n[n.length-1];return e>t?[t,e]:[e,t]}function ti(n){return n.rangeExtent?n.rangeExtent():ni(n.range())}function ei(n,t,e,r){var u=e(n[0],n[1]),i=r(t[0],t[1]);return function(n){return i(u(n))}}function ri(n,t){var e,r=0,u=n.length-1,i=n[r],o=n[u];return i>o&&(e=r,r=u,u=e,e=i,i=o,o=e),n[r]=t.floor(i),n[u]=t.ceil(o),n}function ui(n){return n?{floor:function(t){return Math.floor(t/n)*n},ceil:function(t){return Math.ceil(t/n)*n}}:ss}function ii(n,t,e,r){var u=[],i=[],o=0,a=Math.min(n.length,t.length)-1;for(n[a]2?ii:ei,c=r?ru:eu;return o=u(n,t,c,e),a=u(t,n,c,qr),i}function i(n){return o(n)}var o,a;return i.invert=function(n){return a(n)},i.domain=function(t){return arguments.length?(n=t.map(Number),u()):n},i.range=function(n){return arguments.length?(t=n,u()):t},i.rangeRound=function(n){return i.range(n).interpolate(Jr)},i.clamp=function(n){return arguments.length?(r=n,u()):r},i.interpolate=function(n){return arguments.length?(e=n,u()):e},i.ticks=function(t){return li(n,t)},i.tickFormat=function(t,e){return fi(n,t,e)},i.nice=function(t){return ci(n,t),u()},i.copy=function(){return oi(n,t,e,r)},u()}function ai(n,t){return $o.rebind(n,t,"range","rangeRound","interpolate","clamp")}function ci(n,t){return ri(n,ui(si(n,t)[2]))}function si(n,t){null==t&&(t=10);var e=ni(n),r=e[1]-e[0],u=Math.pow(10,Math.floor(Math.log(r/t)/Math.LN10)),i=t/r*u;return.15>=i?u*=10:.35>=i?u*=5:.75>=i&&(u*=2),e[0]=Math.ceil(e[0]/u)*u,e[1]=Math.floor(e[1]/u)*u+.5*u,e[2]=u,e}function li(n,t){return $o.range.apply($o,si(n,t))}function fi(n,t,e){var r=si(n,t);return $o.format(e?e.replace(uc,function(n,t,e,u,i,o,a,c,s,l){return[t,e,u,i,o,a,c,s||"."+gi(l,r),l].join("")}):",."+hi(r[2])+"f")}function hi(n){return-Math.floor(Math.log(n)/Math.LN10+.01)}function gi(n,t){var e=hi(t[2]);return n in ls?Math.abs(e-hi(Math.max(Math.abs(t[0]),Math.abs(t[1]))))+ +("e"!==n):e-2*("%"===n)}function pi(n,t,e,r){function u(n){return(e?Math.log(0>n?0:n):-Math.log(n>0?0:-n))/Math.log(t)}function i(n){return e?Math.pow(t,n):-Math.pow(t,-n)}function o(t){return n(u(t))}return o.invert=function(t){return i(n.invert(t))},o.domain=function(t){return arguments.length?(e=t[0]>=0,n.domain((r=t.map(Number)).map(u)),o):r},o.base=function(e){return arguments.length?(t=+e,n.domain(r.map(u)),o):t},o.nice=function(){var t=ri(r.map(u),e?Math:hs);return n.domain(t),r=t.map(i),o},o.ticks=function(){var n=ni(r),o=[],a=n[0],c=n[1],s=Math.floor(u(a)),l=Math.ceil(u(c)),f=t%1?2:t;if(isFinite(l-s)){if(e){for(;l>s;s++)for(var h=1;f>h;h++)o.push(i(s)*h);o.push(i(s))}else for(o.push(i(s));s++0;h--)o.push(i(s)*h);for(s=0;o[s]c;l--);o=o.slice(s,l)}return o},o.tickFormat=function(n,t){if(!arguments.length)return fs;arguments.length<2?t=fs:"function"!=typeof t&&(t=$o.format(t));var r,a=Math.max(.1,n/o.ticks().length),c=e?(r=1e-12,Math.ceil):(r=-1e-12,Math.floor);return function(n){return n/i(c(u(n)+r))<=a?t(n):""}},o.copy=function(){return pi(n.copy(),t,e,r)},ai(o,n)}function vi(n,t,e){function r(t){return n(u(t))}var u=di(t),i=di(1/t);return r.invert=function(t){return i(n.invert(t))},r.domain=function(t){return arguments.length?(n.domain((e=t.map(Number)).map(u)),r):e},r.ticks=function(n){return li(e,n)},r.tickFormat=function(n,t){return fi(e,n,t)},r.nice=function(n){return r.domain(ci(e,n))},r.exponent=function(o){return arguments.length?(u=di(t=o),i=di(1/t),n.domain(e.map(u)),r):t},r.copy=function(){return vi(n.copy(),t,e)},ai(r,n)}function di(n){return function(t){return 0>t?-Math.pow(-t,n):Math.pow(t,n)}}function mi(n,t){function e(e){return o[((i.get(e)||"range"===t.t&&i.set(e,n.push(e)))-1)%o.length]}function r(t,e){return $o.range(n.length).map(function(n){return t+e*n})}var i,o,a;return e.domain=function(r){if(!arguments.length)return n;n=[],i=new u;for(var o,a=-1,c=r.length;++ae?[0/0,0/0]:[e>0?u[e-1]:n[0],et?0/0:t/i+n,[t,t+1/i]},r.copy=function(){return xi(n,t,e)},u()}function Mi(n,t){function e(e){return e>=e?t[$o.bisect(n,e)]:void 0}return e.domain=function(t){return arguments.length?(n=t,e):n},e.range=function(n){return arguments.length?(t=n,e):t},e.invertExtent=function(e){return e=t.indexOf(e),[n[e-1],n[e]]},e.copy=function(){return Mi(n,t)},e}function _i(n){function t(n){return+n}return t.invert=t,t.domain=t.range=function(e){return arguments.length?(n=e.map(t),t):n},t.ticks=function(t){return li(n,t)},t.tickFormat=function(t,e){return fi(n,t,e)},t.copy=function(){return _i(n)},t}function bi(n){return n.innerRadius}function wi(n){return n.outerRadius}function Si(n){return n.startAngle}function ki(n){return n.endAngle}function Ei(n){function t(t){function o(){s.push("M",i(n(l),a))}for(var c,s=[],l=[],f=-1,h=t.length,g=pt(e),p=pt(r);++f1&&u.push("H",r[0]),u.join("")}function Li(n){for(var t=0,e=n.length,r=n[0],u=[r[0],",",r[1]];++t1){a=t[1],i=n[c],c++,r+="C"+(u[0]+o[0])+","+(u[1]+o[1])+","+(i[0]-a[0])+","+(i[1]-a[1])+","+i[0]+","+i[1];for(var s=2;s9&&(u=3*t/Math.sqrt(u),o[a]=u*e,o[a+1]=u*r));for(a=-1;++a<=c;)u=(n[Math.min(c,a+1)][0]-n[Math.max(0,a-1)][0])/(6*(1+o[a]*o[a])),i.push([u||0,o[a]*u||0]);return i}function Xi(n){return n.length<3?Ai(n):n[0]+Di(n,Vi(n))}function $i(n){for(var t,e,r,u=-1,i=n.length;++ue?s():(i.active=e,o.event&&o.event.start.call(n,l,t),o.tween.forEach(function(e,r){(r=r.call(n,l,t))&&v.push(r)}),$o.timer(function(){return p.c=c(r||1)?Zt:c,1},0,a),void 0)}function c(r){if(i.active!==e)return s();for(var u=r/g,a=f(u),c=v.length;c>0;)v[--c].call(n,a);return u>=1?(o.event&&o.event.end.call(n,l,t),s()):void 0}function s(){return--i.count?delete i[e]:delete n.__transition__,1}var l=n.__data__,f=o.ease,h=o.delay,g=o.duration,p=Ga,v=[];return p.t=h+a,r>=h?u(r-h):(p.c=u,void 0)},0,a)}}function io(n,t){n.attr("transform",function(n){return"translate("+t(n)+",0)"})}function oo(n,t){n.attr("transform",function(n){return"translate(0,"+t(n)+")"})}function ao(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function co(n,t,e){function r(t){var e=n(t),r=i(e,1);return r-t>t-e?e:r}function u(e){return t(e=n(new Ds(e-1)),1),e}function i(n,e){return t(n=new Ds(+n),e),n}function o(n,r,i){var o=u(n),a=[];if(i>1)for(;r>o;)e(o)%i||a.push(new Date(+o)),t(o,1);else for(;r>o;)a.push(new Date(+o)),t(o,1);return a}function a(n,t,e){try{Ds=ao;var r=new ao;return r._=n,o(r,t,e)}finally{Ds=Date}}n.floor=n,n.round=r,n.ceil=u,n.offset=i,n.range=o;var c=n.utc=so(n);return c.floor=c,c.round=so(r),c.ceil=so(u),c.offset=so(i),c.range=a,n}function so(n){return function(t,e){try{Ds=ao;var r=new ao;return r._=t,n(r,e)._}finally{Ds=Date}}}function lo(n){function t(t){for(var r,u,i,o=[],a=-1,c=0;++aa;){if(r>=s)return-1;if(u=t.charCodeAt(a++),37===u){if(o=t.charAt(a++),i=el[o in nl?t.charAt(a++):o],!i||(r=i(n,e,r))<0)return-1}else if(u!=e.charCodeAt(r++))return-1}return r}function ho(n){return new RegExp("^(?:"+n.map($o.requote).join("|")+")","i")}function go(n){for(var t=new u,e=-1,r=n.length;++en?"-":"",u=(r?-n:n)+"",i=u.length;return r+(e>i?new Array(e-i+1).join(t)+u:u)}function vo(n,t,e){$s.lastIndex=0;var r=$s.exec(t.substring(e));return r?(n.w=Bs.get(r[0].toLowerCase()),e+r[0].length):-1}function mo(n,t,e){Vs.lastIndex=0;var r=Vs.exec(t.substring(e));return r?(n.w=Xs.get(r[0].toLowerCase()),e+r[0].length):-1}function yo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+1));return r?(n.w=+r[0],e+r[0].length):-1}function xo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e));return r?(n.U=+r[0],e+r[0].length):-1}function Mo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e));return r?(n.W=+r[0],e+r[0].length):-1}function _o(n,t,e){Gs.lastIndex=0;var r=Gs.exec(t.substring(e));return r?(n.m=Ks.get(r[0].toLowerCase()),e+r[0].length):-1}function bo(n,t,e){Ws.lastIndex=0;var r=Ws.exec(t.substring(e));return r?(n.m=Js.get(r[0].toLowerCase()),e+r[0].length):-1}function wo(n,t,e){return fo(n,tl.c.toString(),t,e)}function So(n,t,e){return fo(n,tl.x.toString(),t,e)}function ko(n,t,e){return fo(n,tl.X.toString(),t,e)}function Eo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+4));return r?(n.y=+r[0],e+r[0].length):-1}function Ao(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+2));return r?(n.y=No(+r[0]),e+r[0].length):-1}function Co(n,t,e){return/^[+-]\d{4}$/.test(t=t.substring(e,e+5))?(n.Z=+t,e+5):-1}function No(n){return n+(n>68?1900:2e3)}function Lo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+2));return r?(n.m=r[0]-1,e+r[0].length):-1}function To(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+2));return r?(n.d=+r[0],e+r[0].length):-1}function qo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+3));return r?(n.j=+r[0],e+r[0].length):-1}function zo(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+2));return r?(n.H=+r[0],e+r[0].length):-1}function Ro(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+2));return r?(n.M=+r[0],e+r[0].length):-1}function Do(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+2));return r?(n.S=+r[0],e+r[0].length):-1}function Po(n,t,e){rl.lastIndex=0;var r=rl.exec(t.substring(e,e+3));return r?(n.L=+r[0],e+r[0].length):-1}function Uo(n,t,e){var r=ul.get(t.substring(e,e+=2).toLowerCase());return null==r?-1:(n.p=r,e)}function jo(n){var t=n.getTimezoneOffset(),e=t>0?"-":"+",r=~~(aa(t)/60),u=aa(t)%60;return e+po(r,"0",2)+po(u,"0",2)}function Ho(n,t,e){Qs.lastIndex=0;var r=Qs.exec(t.substring(e,e+1));return r?e+r[0].length:-1}function Fo(n){function t(n){try{Ds=ao;var t=new Ds;return t._=n,e(t)}finally{Ds=Date}}var e=lo(n);return t.parse=function(n){try{Ds=ao;var t=e.parse(n);return t&&t._}finally{Ds=Date}},t.toString=e.toString,t}function Oo(n){return n.toISOString()}function Yo(n,t,e){function r(t){return n(t)}function u(n,e){var r=n[1]-n[0],u=r/e,i=$o.bisect(ol,u);return i==ol.length?[t.year,si(n.map(function(n){return n/31536e6}),e)[2]]:i?t[u/ol[i-1]1?{floor:function(t){for(;e(t=n.floor(t));)t=Io(t-1);return t},ceil:function(t){for(;e(t=n.ceil(t));)t=Io(+t+1);return t}}:n))},r.ticks=function(n,t){var e=ni(r.domain()),i=null==n?u(e,10):"number"==typeof n?u(e,n):!n.range&&[{range:n},t];return i&&(n=i[0],t=i[1]),n.range(e[0],Io(+e[1]+1),1>t?1:t)},r.tickFormat=function(){return e},r.copy=function(){return Yo(n.copy(),t,e)},ai(r,n)}function Io(n){return new Date(n)}function Zo(n){return function(t){for(var e=n.length-1,r=n[e];!r[1](t);)r=n[--e];return r[0](t)}}function Vo(n){return JSON.parse(n.responseText)}function Xo(n){var t=Jo.createRange();return t.selectNode(Jo.body),t.createContextualFragment(n.responseText)}var $o={version:"3.3.9"};Date.now||(Date.now=function(){return+new Date});var Bo=[].slice,Wo=function(n){return Bo.call(n)},Jo=document,Go=Jo.documentElement,Ko=window;try{Wo(Go.childNodes)[0].nodeType}catch(Qo){Wo=function(n){for(var t=n.length,e=new Array(t);t--;)e[t]=n[t];return e}}try{Jo.createElement("div").style.setProperty("opacity",0,"")}catch(na){var ta=Ko.Element.prototype,ea=ta.setAttribute,ra=ta.setAttributeNS,ua=Ko.CSSStyleDeclaration.prototype,ia=ua.setProperty;ta.setAttribute=function(n,t){ea.call(this,n,t+"")},ta.setAttributeNS=function(n,t,e){ra.call(this,n,t,e+"")},ua.setProperty=function(n,t,e){ia.call(this,n,t+"",e)}}$o.ascending=function(n,t){return t>n?-1:n>t?1:n>=t?0:0/0},$o.descending=function(n,t){return n>t?-1:t>n?1:t>=n?0:0/0},$o.min=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u=e);)e=void 0;for(;++ur&&(e=r)}else{for(;++u=e);)e=void 0;for(;++ur&&(e=r)}return e},$o.max=function(n,t){var e,r,u=-1,i=n.length;if(1===arguments.length){for(;++u=e);)e=void 0;for(;++ue&&(e=r)}else{for(;++u=e);)e=void 0;for(;++ue&&(e=r)}return e},$o.extent=function(n,t){var e,r,u,i=-1,o=n.length;if(1===arguments.length){for(;++i=e);)e=u=void 0;for(;++ir&&(e=r),r>u&&(u=r))}else{for(;++i=e);)e=void 0;for(;++ir&&(e=r),r>u&&(u=r))}return[e,u]},$o.sum=function(n,t){var e,r=0,u=n.length,i=-1;if(1===arguments.length)for(;++i1&&(t=t.map(e)),t=t.filter(n),t.length?$o.quantile(t.sort($o.ascending),.5):void 0},$o.bisector=function(n){return{left:function(t,e,r,u){for(arguments.length<3&&(r=0),arguments.length<4&&(u=t.length);u>r;){var i=r+u>>>1;n.call(t,t[i],i)r;){var i=r+u>>>1;er?0:r);r>e;)i[e]=[t=u,u=n[++e]];return i},$o.zip=function(){if(!(u=arguments.length))return[];for(var n=-1,e=$o.min(arguments,t),r=new Array(e);++n=0;)for(r=n[u],t=r.length;--t>=0;)e[--o]=r[t];return e};var aa=Math.abs;$o.range=function(n,t,r){if(arguments.length<3&&(r=1,arguments.length<2&&(t=n,n=0)),1/0===(t-n)/r)throw new Error("infinite range");var u,i=[],o=e(aa(r)),a=-1;if(n*=o,t*=o,r*=o,0>r)for(;(u=n+r*++a)>t;)i.push(u/o);else for(;(u=n+r*++a)=o.length)return r?r.call(i,a):e?a.sort(e):a;for(var s,l,f,h,g=-1,p=a.length,v=o[c++],d=new u;++g=o.length)return n;var r=[],u=a[e++];return n.forEach(function(n,u){r.push({key:n,values:t(u,e)})}),u?r.sort(function(n,t){return u(n.key,t.key)}):r}var e,r,i={},o=[],a=[];return i.map=function(t,e){return n(e,t,0)},i.entries=function(e){return t(n($o.map,e,0),0)},i.key=function(n){return o.push(n),i},i.sortKeys=function(n){return a[o.length-1]=n,i},i.sortValues=function(n){return e=n,i},i.rollup=function(n){return r=n,i},i},$o.set=function(n){var t=new i;if(n)for(var e=0,r=n.length;r>e;++e)t.add(n[e]);return t},r(i,{has:function(n){return ca+n in this},add:function(n){return this[ca+n]=!0,n},remove:function(n){return n=ca+n,n in this&&delete this[n]},values:function(){var n=[];return this.forEach(function(t){n.push(t)}),n},forEach:function(n){for(var t in this)t.charCodeAt(0)===sa&&n.call(this,t.substring(1))}}),$o.behavior={},$o.rebind=function(n,t){for(var e,r=1,u=arguments.length;++r=0&&(r=n.substring(e+1),n=n.substring(0,e)),n)return arguments.length<2?this[n].on(r):this[n].on(r,t);if(2===arguments.length){if(null==t)for(n in this)this.hasOwnProperty(n)&&this[n].on(r,null);return this}},$o.event=null,$o.requote=function(n){return n.replace(fa,"\\$&")};var fa=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,ha={}.__proto__?function(n,t){n.__proto__=t}:function(n,t){for(var e in t)n[e]=t[e]},ga=function(n,t){return t.querySelector(n)},pa=function(n,t){return t.querySelectorAll(n)},va=Go[a(Go,"matchesSelector")],da=function(n,t){return va.call(n,t)};"function"==typeof Sizzle&&(ga=function(n,t){return Sizzle(n,t)[0]||null},pa=function(n,t){return Sizzle.uniqueSort(Sizzle(n,t))},da=Sizzle.matchesSelector),$o.selection=function(){return Ma};var ma=$o.selection.prototype=[];ma.select=function(n){var t,e,r,u,i=[];n=v(n);for(var o=-1,a=this.length;++o=0&&(e=n.substring(0,t),n=n.substring(t+1)),ya.hasOwnProperty(e)?{space:ya[e],local:n}:n}},ma.attr=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node();return n=$o.ns.qualify(n),n.local?e.getAttributeNS(n.space,n.local):e.getAttribute(n)}for(t in n)this.each(m(t,n[t]));return this}return this.each(m(n,t))},ma.classed=function(n,t){if(arguments.length<2){if("string"==typeof n){var e=this.node(),r=(n=n.trim().split(/^|\s+/g)).length,u=-1;if(t=e.classList){for(;++ur){if("string"!=typeof n){2>r&&(t="");for(e in n)this.each(b(e,n[e],t));return this}if(2>r)return Ko.getComputedStyle(this.node(),null).getPropertyValue(n);e=""}return this.each(b(n,t,e))},ma.property=function(n,t){if(arguments.length<2){if("string"==typeof n)return this.node()[n];for(t in n)this.each(w(t,n[t]));return this}return this.each(w(n,t))},ma.text=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.textContent=null==t?"":t}:null==n?function(){this.textContent=""}:function(){this.textContent=n}):this.node().textContent},ma.html=function(n){return arguments.length?this.each("function"==typeof n?function(){var t=n.apply(this,arguments);this.innerHTML=null==t?"":t}:null==n?function(){this.innerHTML=""}:function(){this.innerHTML=n}):this.node().innerHTML},ma.append=function(n){return n=S(n),this.select(function(){return this.appendChild(n.apply(this,arguments))})},ma.insert=function(n,t){return n=S(n),t=v(t),this.select(function(){return this.insertBefore(n.apply(this,arguments),t.apply(this,arguments)||null)})},ma.remove=function(){return this.each(function(){var n=this.parentNode;n&&n.removeChild(this)})},ma.data=function(n,t){function e(n,e){var r,i,o,a=n.length,f=e.length,h=Math.min(a,f),g=new Array(f),p=new Array(f),v=new Array(a);if(t){var d,m=new u,y=new u,x=[];for(r=-1;++rr;++r)p[r]=k(e[r]);for(;a>r;++r)v[r]=n[r]}p.update=g,p.parentNode=g.parentNode=v.parentNode=n.parentNode,c.push(p),s.push(g),l.push(v)}var r,i,o=-1,a=this.length;if(!arguments.length){for(n=new Array(a=(r=this[0]).length);++oi;i++){u.push(t=[]),t.parentNode=(e=this[i]).parentNode;for(var a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a)&&t.push(r)}return p(u)},ma.order=function(){for(var n=-1,t=this.length;++n=0;)(e=r[u])&&(i&&i!==e.nextSibling&&i.parentNode.insertBefore(e,i),i=e);return this},ma.sort=function(n){n=A.apply(this,arguments);for(var t=-1,e=this.length;++tn;n++)for(var e=this[n],r=0,u=e.length;u>r;r++){var i=e[r];if(i)return i}return null},ma.size=function(){var n=0;return this.each(function(){++n}),n};var xa=[];$o.selection.enter=N,$o.selection.enter.prototype=xa,xa.append=ma.append,xa.empty=ma.empty,xa.node=ma.node,xa.call=ma.call,xa.size=ma.size,xa.select=function(n){for(var t,e,r,u,i,o=[],a=-1,c=this.length;++ar){if("string"!=typeof n){2>r&&(t=!1);for(e in n)this.each(q(e,n[e],t));return this}if(2>r)return(r=this.node()["__on"+n])&&r._;e=!1}return this.each(q(n,t,e))};var _a=$o.map({mouseenter:"mouseover",mouseleave:"mouseout"});_a.forEach(function(n){"on"+n in Jo&&_a.remove(n)});var ba="onselectstart"in Jo?null:a(Go.style,"userSelect"),wa=0;$o.mouse=function(n){return P(n,h())};var Sa=/WebKit/.test(Ko.navigator.userAgent)?-1:0;$o.touches=function(n,t){return arguments.length<2&&(t=h().touches),t?Wo(t).map(function(t){var e=P(n,t);return e.identifier=t.identifier,e}):[]},$o.behavior.drag=function(){function n(){this.on("mousedown.drag",o).on("touchstart.drag",a)}function t(){return $o.event.changedTouches[0].identifier}function e(n,t){return $o.touches(n).filter(function(n){return n.identifier===t})[0]}function r(n,t,e,r){return function(){function o(){var n=t(l,g),e=n[0]-v[0],r=n[1]-v[1];d|=e|r,v=n,f({type:"drag",x:n[0]+c[0],y:n[1]+c[1],dx:e,dy:r})}function a(){m.on(e+"."+p,null).on(r+"."+p,null),y(d&&$o.event.target===h),f({type:"dragend"})}var c,s=this,l=s.parentNode,f=u.of(s,arguments),h=$o.event.target,g=n(),p=null==g?"drag":"drag-"+g,v=t(l,g),d=0,m=$o.select(Ko).on(e+"."+p,o).on(r+"."+p,a),y=D();i?(c=i.apply(s,arguments),c=[c.x-v[0],c.y-v[1]]):c=[0,0],f({type:"dragstart"})}}var u=g(n,"drag","dragstart","dragend"),i=null,o=r(c,$o.mouse,"mousemove","mouseup"),a=r(t,e,"touchmove","touchend");return n.origin=function(t){return arguments.length?(i=t,n):i},$o.rebind(n,u,"on")};var ka=Math.PI,Ea=2*ka,Aa=ka/2,Ca=1e-6,Na=Ca*Ca,La=ka/180,Ta=180/ka,qa=Math.SQRT2,za=2,Ra=4;$o.interpolateZoom=function(n,t){function e(n){var t=n*y;if(m){var e=O(v),o=i/(za*h)*(e*Y(qa*t+v)-F(v));return[r+o*s,u+o*l,i*e/O(qa*t+v)]}return[r+n*s,u+n*l,i*Math.exp(qa*t)]}var r=n[0],u=n[1],i=n[2],o=t[0],a=t[1],c=t[2],s=o-r,l=a-u,f=s*s+l*l,h=Math.sqrt(f),g=(c*c-i*i+Ra*f)/(2*i*za*h),p=(c*c-i*i-Ra*f)/(2*c*za*h),v=Math.log(Math.sqrt(g*g+1)-g),d=Math.log(Math.sqrt(p*p+1)-p),m=d-v,y=(m||Math.log(c/i))/qa;return e.duration=1e3*y,e},$o.behavior.zoom=function(){function n(n){n.on(A,s).on(Ua+".zoom",h).on(C,p).on("dblclick.zoom",v).on(L,l)}function t(n){return[(n[0]-S.x)/S.k,(n[1]-S.y)/S.k]}function e(n){return[n[0]*S.k+S.x,n[1]*S.k+S.y]}function r(n){S.k=Math.max(E[0],Math.min(E[1],n))}function u(n,t){t=e(t),S.x+=n[0]-t[0],S.y+=n[1]-t[1]}function i(){_&&_.domain(M.range().map(function(n){return(n-S.x)/S.k}).map(M.invert)),w&&w.domain(b.range().map(function(n){return(n-S.y)/S.k}).map(b.invert))}function o(n){n({type:"zoomstart"})}function a(n){i(),n({type:"zoom",scale:S.k,translate:[S.x,S.y]})}function c(n){n({type:"zoomend"})}function s(){function n(){l=1,u($o.mouse(r),h),a(i)}function e(){f.on(C,Ko===r?p:null).on(N,null),g(l&&$o.event.target===s),c(i)}var r=this,i=q.of(r,arguments),s=$o.event.target,l=0,f=$o.select(Ko).on(C,n).on(N,e),h=t($o.mouse(r)),g=D();T.call(r),o(i)}function l(){function n(){var n=$o.touches(p);return g=S.k,n.forEach(function(n){n.identifier in d&&(d[n.identifier]=t(n))}),n}function e(){for(var t=$o.event.changedTouches,e=0,i=t.length;i>e;++e)d[t[e].identifier]=null;var o=n(),c=Date.now();if(1===o.length){if(500>c-x){var s=o[0],l=d[s.identifier];r(2*S.k),u(s,l),f(),a(v)}x=c}else if(o.length>1){var s=o[0],h=o[1],g=s[0]-h[0],p=s[1]-h[1];m=g*g+p*p}}function i(){for(var n,t,e,i,o=$o.touches(p),c=0,s=o.length;s>c;++c,i=null)if(e=o[c],i=d[e.identifier]){if(t)break;n=e,t=i}if(i){var l=(l=e[0]-n[0])*l+(l=e[1]-n[1])*l,f=m&&Math.sqrt(l/m);n=[(n[0]+e[0])/2,(n[1]+e[1])/2],t=[(t[0]+i[0])/2,(t[1]+i[1])/2],r(f*g)}x=null,u(n,t),a(v)}function h(){if($o.event.touches.length){for(var t=$o.event.changedTouches,e=0,r=t.length;r>e;++e)delete d[t[e].identifier];for(var u in d)return void n()}b.on(M,null).on(_,null),w.on(A,s).on(L,l),k(),c(v)}var g,p=this,v=q.of(p,arguments),d={},m=0,y=$o.event.changedTouches[0].identifier,M="touchmove.zoom-"+y,_="touchend.zoom-"+y,b=$o.select(Ko).on(M,i).on(_,h),w=$o.select(p).on(A,null).on(L,e),k=D();T.call(p),e(),o(v)}function h(){var n=q.of(this,arguments);y?clearTimeout(y):(T.call(this),o(n)),y=setTimeout(function(){y=null,c(n)},50),f();var e=m||$o.mouse(this);d||(d=t(e)),r(Math.pow(2,.002*Da())*S.k),u(e,d),a(n)}function p(){d=null}function v(){var n=q.of(this,arguments),e=$o.mouse(this),i=t(e),s=Math.log(S.k)/Math.LN2;o(n),r(Math.pow(2,$o.event.shiftKey?Math.ceil(s)-1:Math.floor(s)+1)),u(e,i),a(n),c(n)}var d,m,y,x,M,_,b,w,S={x:0,y:0,k:1},k=[960,500],E=Pa,A="mousedown.zoom",C="mousemove.zoom",N="mouseup.zoom",L="touchstart.zoom",q=g(n,"zoomstart","zoom","zoomend");return n.event=function(n){n.each(function(){var n=q.of(this,arguments),t=S;Ss?$o.select(this).transition().each("start.zoom",function(){S=this.__chart__||{x:0,y:0,k:1},o(n)}).tween("zoom:zoom",function(){var e=k[0],r=k[1],u=e/2,i=r/2,o=$o.interpolateZoom([(u-S.x)/S.k,(i-S.y)/S.k,e/S.k],[(u-t.x)/t.k,(i-t.y)/t.k,e/t.k]);return function(t){var r=o(t),c=e/r[2];this.__chart__=S={x:u-r[0]*c,y:i-r[1]*c,k:c},a(n)}}).each("end.zoom",function(){c(n)}):(this.__chart__=S,o(n),a(n),c(n))})},n.translate=function(t){return arguments.length?(S={x:+t[0],y:+t[1],k:S.k},i(),n):[S.x,S.y]},n.scale=function(t){return arguments.length?(S={x:S.x,y:S.y,k:+t},i(),n):S.k},n.scaleExtent=function(t){return arguments.length?(E=null==t?Pa:[+t[0],+t[1]],n):E},n.center=function(t){return arguments.length?(m=t&&[+t[0],+t[1]],n):m},n.size=function(t){return arguments.length?(k=t&&[+t[0],+t[1]],n):k},n.x=function(t){return arguments.length?(_=t,M=t.copy(),S={x:0,y:0,k:1},n):_},n.y=function(t){return arguments.length?(w=t,b=t.copy(),S={x:0,y:0,k:1},n):w},$o.rebind(n,q,"on")};var Da,Pa=[0,1/0],Ua="onwheel"in Jo?(Da=function(){return-$o.event.deltaY*($o.event.deltaMode?120:1)},"wheel"):"onmousewheel"in Jo?(Da=function(){return $o.event.wheelDelta},"mousewheel"):(Da=function(){return-$o.event.detail},"MozMousePixelScroll");Z.prototype.toString=function(){return this.rgb()+""},$o.hsl=function(n,t,e){return 1===arguments.length?n instanceof X?V(n.h,n.s,n.l):st(""+n,lt,V):V(+n,+t,+e)};var ja=X.prototype=new Z;ja.brighter=function(n){return n=Math.pow(.7,arguments.length?n:1),V(this.h,this.s,this.l/n)},ja.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),V(this.h,this.s,n*this.l)},ja.rgb=function(){return $(this.h,this.s,this.l)},$o.hcl=function(n,t,e){return 1===arguments.length?n instanceof W?B(n.h,n.c,n.l):n instanceof K?nt(n.l,n.a,n.b):nt((n=ft((n=$o.rgb(n)).r,n.g,n.b)).l,n.a,n.b):B(+n,+t,+e)};var Ha=W.prototype=new Z;Ha.brighter=function(n){return B(this.h,this.c,Math.min(100,this.l+Fa*(arguments.length?n:1)))},Ha.darker=function(n){return B(this.h,this.c,Math.max(0,this.l-Fa*(arguments.length?n:1)))},Ha.rgb=function(){return J(this.h,this.c,this.l).rgb()},$o.lab=function(n,t,e){return 1===arguments.length?n instanceof K?G(n.l,n.a,n.b):n instanceof W?J(n.l,n.c,n.h):ft((n=$o.rgb(n)).r,n.g,n.b):G(+n,+t,+e)};var Fa=18,Oa=.95047,Ya=1,Ia=1.08883,Za=K.prototype=new Z;Za.brighter=function(n){return G(Math.min(100,this.l+Fa*(arguments.length?n:1)),this.a,this.b)},Za.darker=function(n){return G(Math.max(0,this.l-Fa*(arguments.length?n:1)),this.a,this.b)},Za.rgb=function(){return Q(this.l,this.a,this.b)},$o.rgb=function(n,t,e){return 1===arguments.length?n instanceof at?ot(n.r,n.g,n.b):st(""+n,ot,$):ot(~~n,~~t,~~e)};var Va=at.prototype=new Z;Va.brighter=function(n){n=Math.pow(.7,arguments.length?n:1);var t=this.r,e=this.g,r=this.b,u=30;return t||e||r?(t&&u>t&&(t=u),e&&u>e&&(e=u),r&&u>r&&(r=u),ot(Math.min(255,~~(t/n)),Math.min(255,~~(e/n)),Math.min(255,~~(r/n)))):ot(u,u,u)},Va.darker=function(n){return n=Math.pow(.7,arguments.length?n:1),ot(~~(n*this.r),~~(n*this.g),~~(n*this.b))},Va.hsl=function(){return lt(this.r,this.g,this.b)},Va.toString=function(){return"#"+ct(this.r)+ct(this.g)+ct(this.b)};var Xa=$o.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});Xa.forEach(function(n,t){Xa.set(n,ut(t))}),$o.functor=pt,$o.xhr=dt(vt),$o.dsv=function(n,t){function e(n,e,i){arguments.length<3&&(i=e,e=null);var o=$o.xhr(n,t,i);return o.row=function(n){return arguments.length?o.response(null==(e=n)?r:u(n)):e},o.row(e)}function r(n){return e.parse(n.responseText)}function u(n){return function(t){return e.parse(t.responseText,n)}}function o(t){return t.map(a).join(n)}function a(n){return c.test(n)?'"'+n.replace(/\"/g,'""')+'"':n}var c=new RegExp('["'+n+"\n]"),s=n.charCodeAt(0);return e.parse=function(n,t){var r;return e.parseRows(n,function(n,e){if(r)return r(n,e-1);var u=new Function("d","return {"+n.map(function(n,t){return JSON.stringify(n)+": d["+t+"]"}).join(",")+"}");r=t?function(n,e){return t(u(n),e)}:u})},e.parseRows=function(n,t){function e(){if(l>=c)return o;if(u)return u=!1,i;var t=l;if(34===n.charCodeAt(t)){for(var e=t;e++l;){var r=n.charCodeAt(l++),a=1;if(10===r)u=!0;else if(13===r)u=!0,10===n.charCodeAt(l)&&(++l,++a);else if(r!==s)continue;return n.substring(t,l-a)}return n.substring(t)}for(var r,u,i={},o={},a=[],c=n.length,l=0,f=0;(r=e())!==o;){for(var h=[];r!==i&&r!==o;)h.push(r),r=e();(!t||(h=t(h,f++)))&&a.push(h)}return a},e.format=function(t){if(Array.isArray(t[0]))return e.formatRows(t);var r=new i,u=[];return t.forEach(function(n){for(var t in n)r.has(t)||u.push(r.add(t))}),[u.map(a).join(n)].concat(t.map(function(t){return u.map(function(n){return a(t[n])}).join(n)})).join("\n")},e.formatRows=function(n){return n.map(o).join("\n")},e},$o.csv=$o.dsv(",","text/csv"),$o.tsv=$o.dsv(" ","text/tab-separated-values");var $a,Ba,Wa,Ja,Ga,Ka=Ko[a(Ko,"requestAnimationFrame")]||function(n){setTimeout(n,17)};$o.timer=function(n,t,e){var r=arguments.length;2>r&&(t=0),3>r&&(e=Date.now());var u=e+t,i={c:n,t:u,f:!1,n:null};Ba?Ba.n=i:$a=i,Ba=i,Wa||(Ja=clearTimeout(Ja),Wa=1,Ka(xt))},$o.timer.flush=function(){Mt(),_t()};var Qa=".",nc=",",tc=[3,3],ec="$",rc=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(bt);$o.formatPrefix=function(n,t){var e=0;return n&&(0>n&&(n*=-1),t&&(n=$o.round(n,wt(n,t))),e=1+Math.floor(1e-12+Math.log(n)/Math.LN10),e=Math.max(-24,Math.min(24,3*Math.floor((0>=e?e+1:e-1)/3)))),rc[8+e/3]},$o.round=function(n,t){return t?Math.round(n*(t=Math.pow(10,t)))/t:Math.round(n)},$o.format=function(n){var t=uc.exec(n),e=t[1]||" ",r=t[2]||">",u=t[3]||"",i=t[4]||"",o=t[5],a=+t[6],c=t[7],s=t[8],l=t[9],f=1,h="",g=!1;switch(s&&(s=+s.substring(1)),(o||"0"===e&&"="===r)&&(o=e="0",r="=",c&&(a-=Math.floor((a-1)/4))),l){case"n":c=!0,l="g";break;case"%":f=100,h="%",l="f";break;case"p":f=100,h="%",l="r";break;case"b":case"o":case"x":case"X":"#"===i&&(i="0"+l.toLowerCase());case"c":case"d":g=!0,s=0;break;case"s":f=-1,l="r"}"#"===i?i="":"$"===i&&(i=ec),"r"!=l||s||(l="g"),null!=s&&("g"==l?s=Math.max(1,Math.min(21,s)):("e"==l||"f"==l)&&(s=Math.max(0,Math.min(20,s)))),l=ic.get(l)||St;var p=o&&c;return function(n){if(g&&n%1)return"";var t=0>n||0===n&&0>1/n?(n=-n,"-"):u;if(0>f){var v=$o.formatPrefix(n,s);n=v.scale(n),h=v.symbol}else n*=f;n=l(n,s);var d=n.lastIndexOf("."),m=0>d?n:n.substring(0,d),y=0>d?"":Qa+n.substring(d+1);!o&&c&&(m=oc(m));var x=i.length+m.length+y.length+(p?0:t.length),M=a>x?new Array(x=a-x+1).join(e):"";return p&&(m=oc(M+m)),t+=i,n=m+y,("<"===r?t+n+M:">"===r?M+t+n:"^"===r?M.substring(0,x>>=1)+t+n+M.substring(x):t+(p?n:M+n))+h}};var uc=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,ic=$o.map({b:function(n){return n.toString(2)},c:function(n){return String.fromCharCode(n)},o:function(n){return n.toString(8)},x:function(n){return n.toString(16)},X:function(n){return n.toString(16).toUpperCase()},g:function(n,t){return n.toPrecision(t)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},r:function(n,t){return(n=$o.round(n,wt(n,t))).toFixed(Math.max(0,Math.min(20,wt(n*(1+1e-15),t))))}}),oc=vt;if(tc){var ac=tc.length;oc=function(n){for(var t=n.length,e=[],r=0,u=tc[0];t>0&&u>0;)e.push(n.substring(t-=u,t+u)),u=tc[r=(r+1)%ac];return e.reverse().join(nc)}}$o.geo={},kt.prototype={s:0,t:0,add:function(n){Et(n,this.t,cc),Et(cc.s,this.s,this),this.s?this.t+=cc.t:this.s=cc.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var cc=new kt;$o.geo.stream=function(n,t){n&&sc.hasOwnProperty(n.type)?sc[n.type](n,t):At(n,t)};var sc={Feature:function(n,t){At(n.geometry,t)},FeatureCollection:function(n,t){for(var e=n.features,r=-1,u=e.length;++rn?4*ka+n:n,gc.lineStart=gc.lineEnd=gc.point=c}};$o.geo.bounds=function(){function n(n,t){x.push(M=[l=n,h=n]),f>t&&(f=t),t>g&&(g=t)}function t(t,e){var r=Tt([t*La,e*La]);if(m){var u=zt(m,r),i=[u[1],-u[0],0],o=zt(i,u);Pt(o),o=Ut(o);var c=t-p,s=c>0?1:-1,v=o[0]*Ta*s,d=aa(c)>180;if(d^(v>s*p&&s*t>v)){var y=o[1]*Ta;y>g&&(g=y)}else if(v=(v+360)%360-180,d^(v>s*p&&s*t>v)){var y=-o[1]*Ta;f>y&&(f=y)}else f>e&&(f=e),e>g&&(g=e);d?p>t?a(l,t)>a(l,h)&&(h=t):a(t,h)>a(l,h)&&(l=t):h>=l?(l>t&&(l=t),t>h&&(h=t)):t>p?a(l,t)>a(l,h)&&(h=t):a(t,h)>a(l,h)&&(l=t)}else n(t,e);m=r,p=t}function e(){_.point=t}function r(){M[0]=l,M[1]=h,_.point=n,m=null}function u(n,e){if(m){var r=n-p;y+=aa(r)>180?r+(r>0?360:-360):r}else v=n,d=e;gc.point(n,e),t(n,e)}function i(){gc.lineStart()}function o(){u(v,d),gc.lineEnd(),aa(y)>Ca&&(l=-(h=180)),M[0]=l,M[1]=h,m=null}function a(n,t){return(t-=n)<0?t+360:t}function c(n,t){return n[0]-t[0]}function s(n,t){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nhc?(l=-(h=180),f=-(g=90)):y>Ca?g=90:-Ca>y&&(f=-90),M[0]=l,M[1]=h}};return function(n){g=h=-(l=f=1/0),x=[],$o.geo.stream(n,_);var t=x.length;if(t){x.sort(c);for(var e,r=1,u=x[0],i=[u];t>r;++r)e=x[r],s(e[0],u)||s(e[1],u)?(a(u[0],e[1])>a(u[0],u[1])&&(u[1]=e[1]),a(e[0],u[1])>a(u[0],u[1])&&(u[0]=e[0])):i.push(u=e);for(var o,e,p=-1/0,t=i.length-1,r=0,u=i[t];t>=r;u=e,++r)e=i[r],(o=a(u[1],e[0]))>p&&(p=o,l=e[0],h=u[1])}return x=M=null,1/0===l||1/0===f?[[0/0,0/0],[0/0,0/0]]:[[l,f],[h,g]]}}(),$o.geo.centroid=function(n){pc=vc=dc=mc=yc=xc=Mc=_c=bc=wc=Sc=0,$o.geo.stream(n,kc);var t=bc,e=wc,r=Sc,u=t*t+e*e+r*r;return Na>u&&(t=xc,e=Mc,r=_c,Ca>vc&&(t=dc,e=mc,r=yc),u=t*t+e*e+r*r,Na>u)?[0/0,0/0]:[Math.atan2(e,t)*Ta,H(r/Math.sqrt(u))*Ta]};var pc,vc,dc,mc,yc,xc,Mc,_c,bc,wc,Sc,kc={sphere:c,point:Ht,lineStart:Ot,lineEnd:Yt,polygonStart:function(){kc.lineStart=It},polygonEnd:function(){kc.lineStart=Ot}},Ec=Bt(Zt,Qt,te,[-ka,-ka/2]),Ac=1e9;$o.geo.clipExtent=function(){var n,t,e,r,u,i,o={stream:function(n){return u&&(u.valid=!1),u=i(n),u.valid=!0,u},extent:function(a){return arguments.length?(i=ue(n=+a[0][0],t=+a[0][1],e=+a[1][0],r=+a[1][1]),u&&(u.valid=!1,u=null),o):[[n,t],[e,r]]}};return o.extent([[0,0],[960,500]])},($o.geo.conicEqualArea=function(){return oe(ae)}).raw=ae,$o.geo.albers=function(){return $o.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},$o.geo.albersUsa=function(){function n(n){var i=n[0],o=n[1];return t=null,e(i,o),t||(r(i,o),t)||u(i,o),t}var t,e,r,u,i=$o.geo.albers(),o=$o.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),a=$o.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),c={point:function(n,e){t=[n,e]}};return n.invert=function(n){var t=i.scale(),e=i.translate(),r=(n[0]-e[0])/t,u=(n[1]-e[1])/t;return(u>=.12&&.234>u&&r>=-.425&&-.214>r?o:u>=.166&&.234>u&&r>=-.214&&-.115>r?a:i).invert(n)},n.stream=function(n){var t=i.stream(n),e=o.stream(n),r=a.stream(n);return{point:function(n,u){t.point(n,u),e.point(n,u),r.point(n,u)},sphere:function(){t.sphere(),e.sphere(),r.sphere()},lineStart:function(){t.lineStart(),e.lineStart(),r.lineStart()},lineEnd:function(){t.lineEnd(),e.lineEnd(),r.lineEnd()},polygonStart:function(){t.polygonStart(),e.polygonStart(),r.polygonStart()},polygonEnd:function(){t.polygonEnd(),e.polygonEnd(),r.polygonEnd()}}},n.precision=function(t){return arguments.length?(i.precision(t),o.precision(t),a.precision(t),n):i.precision()},n.scale=function(t){return arguments.length?(i.scale(t),o.scale(.35*t),a.scale(t),n.translate(i.translate())):i.scale()},n.translate=function(t){if(!arguments.length)return i.translate();var s=i.scale(),l=+t[0],f=+t[1];return e=i.translate(t).clipExtent([[l-.455*s,f-.238*s],[l+.455*s,f+.238*s]]).stream(c).point,r=o.translate([l-.307*s,f+.201*s]).clipExtent([[l-.425*s+Ca,f+.12*s+Ca],[l-.214*s-Ca,f+.234*s-Ca]]).stream(c).point,u=a.translate([l-.205*s,f+.212*s]).clipExtent([[l-.214*s+Ca,f+.166*s+Ca],[l-.115*s-Ca,f+.234*s-Ca]]).stream(c).point,n},n.scale(1070)};var Cc,Nc,Lc,Tc,qc,zc,Rc={point:c,lineStart:c,lineEnd:c,polygonStart:function(){Nc=0,Rc.lineStart=ce},polygonEnd:function(){Rc.lineStart=Rc.lineEnd=Rc.point=c,Cc+=aa(Nc/2)}},Dc={point:se,lineStart:c,lineEnd:c,polygonStart:c,polygonEnd:c},Pc={point:he,lineStart:ge,lineEnd:pe,polygonStart:function(){Pc.lineStart=ve},polygonEnd:function(){Pc.point=he,Pc.lineStart=ge,Pc.lineEnd=pe}};$o.geo.path=function(){function n(n){return n&&("function"==typeof a&&i.pointRadius(+a.apply(this,arguments)),o&&o.valid||(o=u(i)),$o.geo.stream(n,o)),i.result()}function t(){return o=null,n}var e,r,u,i,o,a=4.5;return n.area=function(n){return Cc=0,$o.geo.stream(n,u(Rc)),Cc},n.centroid=function(n){return dc=mc=yc=xc=Mc=_c=bc=wc=Sc=0,$o.geo.stream(n,u(Pc)),Sc?[bc/Sc,wc/Sc]:_c?[xc/_c,Mc/_c]:yc?[dc/yc,mc/yc]:[0/0,0/0]},n.bounds=function(n){return qc=zc=-(Lc=Tc=1/0),$o.geo.stream(n,u(Dc)),[[Lc,Tc],[qc,zc]]},n.projection=function(n){return arguments.length?(u=(e=n)?n.stream||ye(n):vt,t()):e},n.context=function(n){return arguments.length?(i=null==(r=n)?new le:new de(n),"function"!=typeof a&&i.pointRadius(a),t()):r},n.pointRadius=function(t){return arguments.length?(a="function"==typeof t?t:(i.pointRadius(+t),+t),n):a},n.projection($o.geo.albersUsa()).context(null)},$o.geo.transform=function(n){return{stream:function(t){var e=new xe(t);for(var r in n)e[r]=n[r];return e}}},xe.prototype={point:function(n,t){this.stream.point(n,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart() +},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}},$o.geo.projection=_e,$o.geo.projectionMutator=be,($o.geo.equirectangular=function(){return _e(Se)}).raw=Se.invert=Se,$o.geo.rotation=function(n){function t(t){return t=n(t[0]*La,t[1]*La),t[0]*=Ta,t[1]*=Ta,t}return n=Ee(n[0]%360*La,n[1]*La,n.length>2?n[2]*La:0),t.invert=function(t){return t=n.invert(t[0]*La,t[1]*La),t[0]*=Ta,t[1]*=Ta,t},t},ke.invert=Se,$o.geo.circle=function(){function n(){var n="function"==typeof r?r.apply(this,arguments):r,t=Ee(-n[0]*La,-n[1]*La,0).invert,u=[];return e(null,null,1,{point:function(n,e){u.push(n=t(n,e)),n[0]*=Ta,n[1]*=Ta}}),{type:"Polygon",coordinates:[u]}}var t,e,r=[0,0],u=6;return n.origin=function(t){return arguments.length?(r=t,n):r},n.angle=function(r){return arguments.length?(e=Le((t=+r)*La,u*La),n):t},n.precision=function(r){return arguments.length?(e=Le(t*La,(u=+r)*La),n):u},n.angle(90)},$o.geo.distance=function(n,t){var e,r=(t[0]-n[0])*La,u=n[1]*La,i=t[1]*La,o=Math.sin(r),a=Math.cos(r),c=Math.sin(u),s=Math.cos(u),l=Math.sin(i),f=Math.cos(i);return Math.atan2(Math.sqrt((e=f*o)*e+(e=s*l-c*f*a)*e),c*l+s*f*a)},$o.geo.graticule=function(){function n(){return{type:"MultiLineString",coordinates:t()}}function t(){return $o.range(Math.ceil(i/d)*d,u,d).map(h).concat($o.range(Math.ceil(s/m)*m,c,m).map(g)).concat($o.range(Math.ceil(r/p)*p,e,p).filter(function(n){return aa(n%d)>Ca}).map(l)).concat($o.range(Math.ceil(a/v)*v,o,v).filter(function(n){return aa(n%m)>Ca}).map(f))}var e,r,u,i,o,a,c,s,l,f,h,g,p=10,v=p,d=90,m=360,y=2.5;return n.lines=function(){return t().map(function(n){return{type:"LineString",coordinates:n}})},n.outline=function(){return{type:"Polygon",coordinates:[h(i).concat(g(c).slice(1),h(u).reverse().slice(1),g(s).reverse().slice(1))]}},n.extent=function(t){return arguments.length?n.majorExtent(t).minorExtent(t):n.minorExtent()},n.majorExtent=function(t){return arguments.length?(i=+t[0][0],u=+t[1][0],s=+t[0][1],c=+t[1][1],i>u&&(t=i,i=u,u=t),s>c&&(t=s,s=c,c=t),n.precision(y)):[[i,s],[u,c]]},n.minorExtent=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],a=+t[0][1],o=+t[1][1],r>e&&(t=r,r=e,e=t),a>o&&(t=a,a=o,o=t),n.precision(y)):[[r,a],[e,o]]},n.step=function(t){return arguments.length?n.majorStep(t).minorStep(t):n.minorStep()},n.majorStep=function(t){return arguments.length?(d=+t[0],m=+t[1],n):[d,m]},n.minorStep=function(t){return arguments.length?(p=+t[0],v=+t[1],n):[p,v]},n.precision=function(t){return arguments.length?(y=+t,l=qe(a,o,90),f=ze(r,e,y),h=qe(s,c,90),g=ze(i,u,y),n):y},n.majorExtent([[-180,-90+Ca],[180,90-Ca]]).minorExtent([[-180,-80-Ca],[180,80+Ca]])},$o.geo.greatArc=function(){function n(){return{type:"LineString",coordinates:[t||r.apply(this,arguments),e||u.apply(this,arguments)]}}var t,e,r=Re,u=De;return n.distance=function(){return $o.geo.distance(t||r.apply(this,arguments),e||u.apply(this,arguments))},n.source=function(e){return arguments.length?(r=e,t="function"==typeof e?null:e,n):r},n.target=function(t){return arguments.length?(u=t,e="function"==typeof t?null:t,n):u},n.precision=function(){return arguments.length?n:0},n},$o.geo.interpolate=function(n,t){return Pe(n[0]*La,n[1]*La,t[0]*La,t[1]*La)},$o.geo.length=function(n){return Uc=0,$o.geo.stream(n,jc),Uc};var Uc,jc={sphere:c,point:c,lineStart:Ue,lineEnd:c,polygonStart:c,polygonEnd:c},Hc=je(function(n){return Math.sqrt(2/(1+n))},function(n){return 2*Math.asin(n/2)});($o.geo.azimuthalEqualArea=function(){return _e(Hc)}).raw=Hc;var Fc=je(function(n){var t=Math.acos(n);return t&&t/Math.sin(t)},vt);($o.geo.azimuthalEquidistant=function(){return _e(Fc)}).raw=Fc,($o.geo.conicConformal=function(){return oe(He)}).raw=He,($o.geo.conicEquidistant=function(){return oe(Fe)}).raw=Fe;var Oc=je(function(n){return 1/n},Math.atan);($o.geo.gnomonic=function(){return _e(Oc)}).raw=Oc,Oe.invert=function(n,t){return[n,2*Math.atan(Math.exp(t))-Aa]},($o.geo.mercator=function(){return Ye(Oe)}).raw=Oe;var Yc=je(function(){return 1},Math.asin);($o.geo.orthographic=function(){return _e(Yc)}).raw=Yc;var Ic=je(function(n){return 1/(1+n)},function(n){return 2*Math.atan(n)});($o.geo.stereographic=function(){return _e(Ic)}).raw=Ic,Ie.invert=function(n,t){return[Math.atan2(F(n),Math.cos(t)),H(Math.sin(t)/O(n))]},($o.geo.transverseMercator=function(){return Ye(Ie)}).raw=Ie,$o.geom={},$o.geom.hull=function(n){function t(n){if(n.length<3)return[];var t,u,i,o,a,c,s,l,f,h,g,p,v=pt(e),d=pt(r),m=n.length,y=m-1,x=[],M=[],_=0;if(v===Ze&&r===Ve)t=n;else for(i=0,t=[];m>i;++i)t.push([+v.call(this,u=n[i],i),+d.call(this,u,i)]);for(i=1;m>i;++i)(t[i][1]i;++i)i!==_&&(c=t[i][1]-t[_][1],a=t[i][0]-t[_][0],x.push({angle:Math.atan2(c,a),index:i}));for(x.sort(function(n,t){return n.angle-t.angle}),g=x[0].angle,h=x[0].index,f=0,i=1;y>i;++i){if(o=x[i].index,g==x[i].angle){if(a=t[h][0]-t[_][0],c=t[h][1]-t[_][1],s=t[o][0]-t[_][0],l=t[o][1]-t[_][1],a*a+c*c>=s*s+l*l){x[i].index=-1;continue}x[f].index=-1}g=x[i].angle,f=i,h=o}for(M.push(_),i=0,o=0;2>i;++o)x[o].index>-1&&(M.push(x[o].index),i++);for(p=M.length;y>o;++o)if(!(x[o].index<0)){for(;!Xe(M[p-2],M[p-1],x[o].index,t);)--p;M[p++]=x[o].index}var b=[];for(i=p-1;i>=0;--i)b.push(n[M[i]]);return b}var e=Ze,r=Ve;return arguments.length?t(n):(t.x=function(n){return arguments.length?(e=n,t):e},t.y=function(n){return arguments.length?(r=n,t):r},t)},$o.geom.polygon=function(n){return ha(n,Zc),n};var Zc=$o.geom.polygon.prototype=[];Zc.area=function(){for(var n,t=-1,e=this.length,r=this[e-1],u=0;++t=r&&s.x<=i&&s.y>=u&&s.y<=o?[[r,o],[i,o],[i,u],[r,u]]:[];l.point=n[a]}),t}function e(n){return n.map(function(n,t){return{x:Math.round(i(n,t)/Ca)*Ca,y:Math.round(o(n,t)/Ca)*Ca,i:t}})}var r=Ze,u=Ve,i=r,o=u,a=Kc;return n?t(n):(t.links=function(n){return _r(e(n)).edges.filter(function(n){return n.l&&n.r}).map(function(t){return{source:n[t.l.i],target:n[t.r.i]}})},t.triangles=function(n){var t=[];return _r(e(n)).cells.forEach(function(e,r){for(var u,i,o=e.site,a=e.edges.sort(ir),c=-1,s=a.length,l=a[s-1].edge,f=l.l===o?l.r:l.l;++c=s,h=r>=l,g=(h<<1)+f;n.leaf=!1,n=n.nodes[g]||(n.nodes[g]=Er()),f?u=s:a=s,h?o=l:c=l,i(n,t,e,r,u,o,a,c)}var l,f,h,g,p,v,d,m,y,x=pt(a),M=pt(c);if(null!=t)v=t,d=e,m=r,y=u;else if(m=y=-(v=d=1/0),f=[],h=[],p=n.length,o)for(g=0;p>g;++g)l=n[g],l.xm&&(m=l.x),l.y>y&&(y=l.y),f.push(l.x),h.push(l.y);else for(g=0;p>g;++g){var _=+x(l=n[g],g),b=+M(l,g);v>_&&(v=_),d>b&&(d=b),_>m&&(m=_),b>y&&(y=b),f.push(_),h.push(b)}var w=m-v,S=y-d;w>S?y=d+w:m=v+S;var k=Er();if(k.add=function(n){i(k,n,+x(n,++g),+M(n,g),v,d,m,y)},k.visit=function(n){Ar(n,k,v,d,m,y)},g=-1,null==t){for(;++g=0?n.substring(0,t):n,r=t>=0?n.substring(t+1):"in";return e=ts.get(e)||ns,r=es.get(r)||vt,Rr(r(e.apply(null,Bo.call(arguments,1))))},$o.interpolateHcl=$r,$o.interpolateHsl=Br,$o.interpolateLab=Wr,$o.interpolateRound=Jr,$o.transform=function(n){var t=Jo.createElementNS($o.ns.prefix.svg,"g");return($o.transform=function(n){if(null!=n){t.setAttribute("transform",n);var e=t.transform.baseVal.consolidate()}return new Gr(e?e.matrix:rs)})(n)},Gr.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var rs={a:1,b:0,c:0,d:1,e:0,f:0};$o.interpolateTransform=tu,$o.layout={},$o.layout.bundle=function(){return function(n){for(var t=[],e=-1,r=n.length;++e(u-e)*a){var c=t.charge*a*a;return n.px-=i*c,n.py-=o*c,!0}if(t.point&&isFinite(a)){var c=t.pointCharge*a*a;n.px-=i*c,n.py-=o*c}}return!t.charge}}function t(n){n.px=$o.event.x,n.py=$o.event.y,a.resume()}var e,r,u,i,o,a={},c=$o.dispatch("start","tick","end"),s=[1,1],l=.9,f=us,h=is,g=-30,p=.1,v=.8,d=[],m=[];return a.tick=function(){if((r*=.99)<.005)return c.end({type:"end",alpha:r=0}),!0;var t,e,a,f,h,v,y,x,M,_=d.length,b=m.length;for(e=0;b>e;++e)a=m[e],f=a.source,h=a.target,x=h.x-f.x,M=h.y-f.y,(v=x*x+M*M)&&(v=r*i[e]*((v=Math.sqrt(v))-u[e])/v,x*=v,M*=v,h.x-=x*(y=f.weight/(h.weight+f.weight)),h.y-=M*y,f.x+=x*(y=1-y),f.y+=M*y);if((y=r*p)&&(x=s[0]/2,M=s[1]/2,e=-1,y))for(;++e<_;)a=d[e],a.x+=(x-a.x)*y,a.y+=(M-a.y)*y;if(g)for(fu(t=$o.geom.quadtree(d),r,o),e=-1;++e<_;)(a=d[e]).fixed||t.visit(n(a));for(e=-1;++e<_;)a=d[e],a.fixed?(a.x=a.px,a.y=a.py):(a.x-=(a.px-(a.px=a.x))*l,a.y-=(a.py-(a.py=a.y))*l);c.tick({type:"tick",alpha:r})},a.nodes=function(n){return arguments.length?(d=n,a):d},a.links=function(n){return arguments.length?(m=n,a):m},a.size=function(n){return arguments.length?(s=n,a):s},a.linkDistance=function(n){return arguments.length?(f="function"==typeof n?n:+n,a):f},a.distance=a.linkDistance,a.linkStrength=function(n){return arguments.length?(h="function"==typeof n?n:+n,a):h},a.friction=function(n){return arguments.length?(l=+n,a):l},a.charge=function(n){return arguments.length?(g="function"==typeof n?n:+n,a):g},a.gravity=function(n){return arguments.length?(p=+n,a):p},a.theta=function(n){return arguments.length?(v=+n,a):v},a.alpha=function(n){return arguments.length?(n=+n,r?r=n>0?n:0:n>0&&(c.start({type:"start",alpha:r=n}),$o.timer(a.tick)),a):r},a.start=function(){function n(n,r){if(!e){for(e=new Array(c),a=0;c>a;++a)e[a]=[];for(a=0;s>a;++a){var u=m[a];e[u.source.index].push(u.target),e[u.target.index].push(u.source)}}for(var i,o=e[t],a=-1,s=o.length;++at;++t)(r=d[t]).index=t,r.weight=0;for(t=0;l>t;++t)r=m[t],"number"==typeof r.source&&(r.source=d[r.source]),"number"==typeof r.target&&(r.target=d[r.target]),++r.source.weight,++r.target.weight;for(t=0;c>t;++t)r=d[t],isNaN(r.x)&&(r.x=n("x",p)),isNaN(r.y)&&(r.y=n("y",v)),isNaN(r.px)&&(r.px=r.x),isNaN(r.py)&&(r.py=r.y);if(u=[],"function"==typeof f)for(t=0;l>t;++t)u[t]=+f.call(this,m[t],t);else for(t=0;l>t;++t)u[t]=f;if(i=[],"function"==typeof h)for(t=0;l>t;++t)i[t]=+h.call(this,m[t],t);else for(t=0;l>t;++t)i[t]=h;if(o=[],"function"==typeof g)for(t=0;c>t;++t)o[t]=+g.call(this,d[t],t);else for(t=0;c>t;++t)o[t]=g;return a.resume()},a.resume=function(){return a.alpha(.1)},a.stop=function(){return a.alpha(0)},a.drag=function(){return e||(e=$o.behavior.drag().origin(vt).on("dragstart.force",au).on("drag.force",t).on("dragend.force",cu)),arguments.length?(this.on("mouseover.force",su).on("mouseout.force",lu).call(e),void 0):e},$o.rebind(a,c,"on")};var us=20,is=1;$o.layout.hierarchy=function(){function n(t,o,a){var c=u.call(e,t,o);if(t.depth=o,a.push(t),c&&(s=c.length)){for(var s,l,f=-1,h=t.children=new Array(s),g=0,p=o+1;++fg;++g)for(u.call(n,s[0][g],p=v[g],l[0][g][1]),h=1;d>h;++h)u.call(n,s[h][g],p+=l[h-1][g][1],l[h][g][1]);return a}var t=vt,e=Mu,r=_u,u=xu,i=mu,o=yu;return n.values=function(e){return arguments.length?(t=e,n):t},n.order=function(t){return arguments.length?(e="function"==typeof t?t:as.get(t)||Mu,n):e},n.offset=function(t){return arguments.length?(r="function"==typeof t?t:cs.get(t)||_u,n):r},n.x=function(t){return arguments.length?(i=t,n):i},n.y=function(t){return arguments.length?(o=t,n):o},n.out=function(t){return arguments.length?(u=t,n):u},n};var as=$o.map({"inside-out":function(n){var t,e,r=n.length,u=n.map(bu),i=n.map(wu),o=$o.range(r).sort(function(n,t){return u[n]-u[t]}),a=0,c=0,s=[],l=[];for(t=0;r>t;++t)e=o[t],c>a?(a+=i[e],s.push(e)):(c+=i[e],l.push(e));return l.reverse().concat(s)},reverse:function(n){return $o.range(n.length).reverse()},"default":Mu}),cs=$o.map({silhouette:function(n){var t,e,r,u=n.length,i=n[0].length,o=[],a=0,c=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];r>a&&(a=r),o.push(r)}for(e=0;i>e;++e)c[e]=(a-o[e])/2;return c},wiggle:function(n){var t,e,r,u,i,o,a,c,s,l=n.length,f=n[0],h=f.length,g=[];for(g[0]=c=s=0,e=1;h>e;++e){for(t=0,u=0;l>t;++t)u+=n[t][e][1];for(t=0,i=0,a=f[e][0]-f[e-1][0];l>t;++t){for(r=0,o=(n[t][e][1]-n[t][e-1][1])/(2*a);t>r;++r)o+=(n[r][e][1]-n[r][e-1][1])/a;i+=o*n[t][e][1]}g[e]=c-=u?i/u*a:0,s>c&&(s=c)}for(e=0;h>e;++e)g[e]-=s;return g},expand:function(n){var t,e,r,u=n.length,i=n[0].length,o=1/u,a=[];for(e=0;i>e;++e){for(t=0,r=0;u>t;t++)r+=n[t][e][1];if(r)for(t=0;u>t;t++)n[t][e][1]/=r;else for(t=0;u>t;t++)n[t][e][1]=o}for(e=0;i>e;++e)a[e]=0;return a},zero:_u});$o.layout.histogram=function(){function n(n,i){for(var o,a,c=[],s=n.map(e,this),l=r.call(this,s,i),f=u.call(this,l,s,i),i=-1,h=s.length,g=f.length-1,p=t?1:1/h;++i0)for(i=-1;++i=l[0]&&a<=l[1]&&(o=c[$o.bisect(f,a,1,g)-1],o.y+=p,o.push(n[i]));return c}var t=!0,e=Number,r=Au,u=ku;return n.value=function(t){return arguments.length?(e=t,n):e},n.range=function(t){return arguments.length?(r=pt(t),n):r},n.bins=function(t){return arguments.length?(u="number"==typeof t?function(n){return Eu(n,t)}:pt(t),n):u},n.frequency=function(e){return arguments.length?(t=!!e,n):t},n},$o.layout.tree=function(){function n(n,i){function o(n,t){var r=n.children,u=n._tree;if(r&&(i=r.length)){for(var i,a,s,l=r[0],f=l,h=-1;++h0&&(Uu(ju(a,n,r),n,u),s+=u,l+=u),f+=a._tree.mod,s+=i._tree.mod,h+=c._tree.mod,l+=o._tree.mod;a&&!Lu(o)&&(o._tree.thread=a,o._tree.mod+=f-l),i&&!Nu(c)&&(c._tree.thread=i,c._tree.mod+=s-h,r=n)}return r}var s=t.call(this,n,i),l=s[0];Du(l,function(n,t){n._tree={ancestor:n,prelim:0,mod:0,change:0,shift:0,number:t?t._tree.number+1:0}}),o(l),a(l,-l._tree.prelim);var f=Tu(l,zu),h=Tu(l,qu),g=Tu(l,Ru),p=f.x-e(f,h)/2,v=h.x+e(h,f)/2,d=g.depth||1;return Du(l,u?function(n){n.x*=r[0],n.y=n.depth*r[1],delete n._tree}:function(n){n.x=(n.x-p)/(v-p)*r[0],n.y=n.depth/d*r[1],delete n._tree}),s}var t=$o.layout.hierarchy().sort(null).value(null),e=Cu,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},hu(n,t)},$o.layout.pack=function(){function n(n,i){var o=e.call(this,n,i),a=o[0],c=u[0],s=u[1],l=null==t?Math.sqrt:"function"==typeof t?t:function(){return t};if(a.x=a.y=0,Du(a,function(n){n.r=+l(n.value)}),Du(a,Iu),r){var f=r*(t?1:Math.max(2*a.r/c,2*a.r/s))/2;Du(a,function(n){n.r+=f}),Du(a,Iu),Du(a,function(n){n.r-=f})}return Xu(a,c/2,s/2,t?1:1/Math.max(2*a.r/c,2*a.r/s)),o}var t,e=$o.layout.hierarchy().sort(Hu),r=0,u=[1,1];return n.size=function(t){return arguments.length?(u=t,n):u},n.radius=function(e){return arguments.length?(t=null==e||"function"==typeof e?e:+e,n):t},n.padding=function(t){return arguments.length?(r=+t,n):r},hu(n,e)},$o.layout.cluster=function(){function n(n,i){var o,a=t.call(this,n,i),c=a[0],s=0;Du(c,function(n){var t=n.children;t&&t.length?(n.x=Wu(t),n.y=Bu(t)):(n.x=o?s+=e(n,o):0,n.y=0,o=n)});var l=Ju(c),f=Gu(c),h=l.x-e(l,f)/2,g=f.x+e(f,l)/2;return Du(c,u?function(n){n.x=(n.x-c.x)*r[0],n.y=(c.y-n.y)*r[1]}:function(n){n.x=(n.x-h)/(g-h)*r[0],n.y=(1-(c.y?n.y/c.y:1))*r[1]}),a}var t=$o.layout.hierarchy().sort(null).value(null),e=Cu,r=[1,1],u=!1;return n.separation=function(t){return arguments.length?(e=t,n):e},n.size=function(t){return arguments.length?(u=null==(r=t),n):u?null:r},n.nodeSize=function(t){return arguments.length?(u=null!=(r=t),n):u?r:null},hu(n,t)},$o.layout.treemap=function(){function n(n,t){for(var e,r,u=-1,i=n.length;++ut?0:t),e.area=isNaN(r)||0>=r?0:r}function t(e){var i=e.children;if(i&&i.length){var o,a,c,s=f(e),l=[],h=i.slice(),p=1/0,v="slice"===g?s.dx:"dice"===g?s.dy:"slice-dice"===g?1&e.depth?s.dy:s.dx:Math.min(s.dx,s.dy);for(n(h,s.dx*s.dy/e.value),l.area=0;(c=h.length)>0;)l.push(o=h[c-1]),l.area+=o.area,"squarify"!==g||(a=r(l,v))<=p?(h.pop(),p=a):(l.area-=l.pop().area,u(l,v,s,!1),v=Math.min(s.dx,s.dy),l.length=l.area=0,p=1/0);l.length&&(u(l,v,s,!0),l.length=l.area=0),i.forEach(t)}}function e(t){var r=t.children;if(r&&r.length){var i,o=f(t),a=r.slice(),c=[];for(n(a,o.dx*o.dy/t.value),c.area=0;i=a.pop();)c.push(i),c.area+=i.area,null!=i.z&&(u(c,i.z?o.dx:o.dy,o,!a.length),c.length=c.area=0);r.forEach(e)}}function r(n,t){for(var e,r=n.area,u=0,i=1/0,o=-1,a=n.length;++oe&&(i=e),e>u&&(u=e));return r*=r,t*=t,r?Math.max(t*u*p/r,r/(t*i*p)):1/0}function u(n,t,e,r){var u,i=-1,o=n.length,a=e.x,s=e.y,l=t?c(n.area/t):0;if(t==e.dx){for((r||l>e.dy)&&(l=e.dy);++ie.dx)&&(l=e.dx);++ie&&(t=1),1>e&&(n=0),function(){var e,r,u;do e=2*Math.random()-1,r=2*Math.random()-1,u=e*e+r*r;while(!u||u>1);return n+t*e*Math.sqrt(-2*Math.log(u)/u)}},logNormal:function(){var n=$o.random.normal.apply($o,arguments);return function(){return Math.exp(n())}},irwinHall:function(n){return function(){for(var t=0,e=0;n>e;e++)t+=Math.random();return t/n}}},$o.scale={};var ss={floor:vt,ceil:vt};$o.scale.linear=function(){return oi([0,1],[0,1],qr,!1)};var ls={s:1,g:1,p:1,r:1,e:1};$o.scale.log=function(){return pi($o.scale.linear().domain([0,1]),10,!0,[1,10])};var fs=$o.format(".0e"),hs={floor:function(n){return-Math.ceil(-n)},ceil:function(n){return-Math.floor(-n)}};$o.scale.pow=function(){return vi($o.scale.linear(),1,[0,1])},$o.scale.sqrt=function(){return $o.scale.pow().exponent(.5)},$o.scale.ordinal=function(){return mi([],{t:"range",a:[[]]})},$o.scale.category10=function(){return $o.scale.ordinal().range(gs)},$o.scale.category20=function(){return $o.scale.ordinal().range(ps)},$o.scale.category20b=function(){return $o.scale.ordinal().range(vs)},$o.scale.category20c=function(){return $o.scale.ordinal().range(ds)};var gs=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(it),ps=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(it),vs=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(it),ds=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(it);$o.scale.quantile=function(){return yi([],[])},$o.scale.quantize=function(){return xi(0,1,[0,1])},$o.scale.threshold=function(){return Mi([.5],[0,1])},$o.scale.identity=function(){return _i([0,1])},$o.svg={},$o.svg.arc=function(){function n(){var n=t.apply(this,arguments),i=e.apply(this,arguments),o=r.apply(this,arguments)+ms,a=u.apply(this,arguments)+ms,c=(o>a&&(c=o,o=a,a=c),a-o),s=ka>c?"0":"1",l=Math.cos(o),f=Math.sin(o),h=Math.cos(a),g=Math.sin(a);return c>=ys?n?"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"M0,"+n+"A"+n+","+n+" 0 1,0 0,"+-n+"A"+n+","+n+" 0 1,0 0,"+n+"Z":"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"Z":n?"M"+i*l+","+i*f+"A"+i+","+i+" 0 "+s+",1 "+i*h+","+i*g+"L"+n*h+","+n*g+"A"+n+","+n+" 0 "+s+",0 "+n*l+","+n*f+"Z":"M"+i*l+","+i*f+"A"+i+","+i+" 0 "+s+",1 "+i*h+","+i*g+"L0,0"+"Z"}var t=bi,e=wi,r=Si,u=ki;return n.innerRadius=function(e){return arguments.length?(t=pt(e),n):t},n.outerRadius=function(t){return arguments.length?(e=pt(t),n):e},n.startAngle=function(t){return arguments.length?(r=pt(t),n):r},n.endAngle=function(t){return arguments.length?(u=pt(t),n):u},n.centroid=function(){var n=(t.apply(this,arguments)+e.apply(this,arguments))/2,i=(r.apply(this,arguments)+u.apply(this,arguments))/2+ms;return[Math.cos(i)*n,Math.sin(i)*n]},n};var ms=-Aa,ys=Ea-Ca;$o.svg.line=function(){return Ei(vt)};var xs=$o.map({linear:Ai,"linear-closed":Ci,step:Ni,"step-before":Li,"step-after":Ti,basis:Ui,"basis-open":ji,"basis-closed":Hi,bundle:Fi,cardinal:Ri,"cardinal-open":qi,"cardinal-closed":zi,monotone:Xi});xs.forEach(function(n,t){t.key=n,t.closed=/-closed$/.test(n)});var Ms=[0,2/3,1/3,0],_s=[0,1/3,2/3,0],bs=[0,1/6,2/3,1/6];$o.svg.line.radial=function(){var n=Ei($i);return n.radius=n.x,delete n.x,n.angle=n.y,delete n.y,n},Li.reverse=Ti,Ti.reverse=Li,$o.svg.area=function(){return Bi(vt)},$o.svg.area.radial=function(){var n=Bi($i);return n.radius=n.x,delete n.x,n.innerRadius=n.x0,delete n.x0,n.outerRadius=n.x1,delete n.x1,n.angle=n.y,delete n.y,n.startAngle=n.y0,delete n.y0,n.endAngle=n.y1,delete n.y1,n},$o.svg.chord=function(){function n(n,a){var c=t(this,i,n,a),s=t(this,o,n,a);return"M"+c.p0+r(c.r,c.p1,c.a1-c.a0)+(e(c,s)?u(c.r,c.p1,c.r,c.p0):u(c.r,c.p1,s.r,s.p0)+r(s.r,s.p1,s.a1-s.a0)+u(s.r,s.p1,c.r,c.p0))+"Z"}function t(n,t,e,r){var u=t.call(n,e,r),i=a.call(n,u,r),o=c.call(n,u,r)+ms,l=s.call(n,u,r)+ms;return{r:i,a0:o,a1:l,p0:[i*Math.cos(o),i*Math.sin(o)],p1:[i*Math.cos(l),i*Math.sin(l)]}}function e(n,t){return n.a0==t.a0&&n.a1==t.a1}function r(n,t,e){return"A"+n+","+n+" 0 "+ +(e>ka)+",1 "+t}function u(n,t,e,r){return"Q 0,0 "+r}var i=Re,o=De,a=Wi,c=Si,s=ki;return n.radius=function(t){return arguments.length?(a=pt(t),n):a},n.source=function(t){return arguments.length?(i=pt(t),n):i},n.target=function(t){return arguments.length?(o=pt(t),n):o},n.startAngle=function(t){return arguments.length?(c=pt(t),n):c},n.endAngle=function(t){return arguments.length?(s=pt(t),n):s},n},$o.svg.diagonal=function(){function n(n,u){var i=t.call(this,n,u),o=e.call(this,n,u),a=(i.y+o.y)/2,c=[i,{x:i.x,y:a},{x:o.x,y:a},o];return c=c.map(r),"M"+c[0]+"C"+c[1]+" "+c[2]+" "+c[3]}var t=Re,e=De,r=Ji;return n.source=function(e){return arguments.length?(t=pt(e),n):t},n.target=function(t){return arguments.length?(e=pt(t),n):e},n.projection=function(t){return arguments.length?(r=t,n):r},n},$o.svg.diagonal.radial=function(){var n=$o.svg.diagonal(),t=Ji,e=n.projection;return n.projection=function(n){return arguments.length?e(Gi(t=n)):t},n},$o.svg.symbol=function(){function n(n,r){return(ws.get(t.call(this,n,r))||no)(e.call(this,n,r))}var t=Qi,e=Ki;return n.type=function(e){return arguments.length?(t=pt(e),n):t},n.size=function(t){return arguments.length?(e=pt(t),n):e},n};var ws=$o.map({circle:no,cross:function(n){var t=Math.sqrt(n/5)/2;return"M"+-3*t+","+-t+"H"+-t+"V"+-3*t+"H"+t+"V"+-t+"H"+3*t+"V"+t+"H"+t+"V"+3*t+"H"+-t+"V"+t+"H"+-3*t+"Z"},diamond:function(n){var t=Math.sqrt(n/(2*As)),e=t*As;return"M0,"+-t+"L"+e+",0"+" 0,"+t+" "+-e+",0"+"Z"},square:function(n){var t=Math.sqrt(n)/2;return"M"+-t+","+-t+"L"+t+","+-t+" "+t+","+t+" "+-t+","+t+"Z"},"triangle-down":function(n){var t=Math.sqrt(n/Es),e=t*Es/2;return"M0,"+e+"L"+t+","+-e+" "+-t+","+-e+"Z"},"triangle-up":function(n){var t=Math.sqrt(n/Es),e=t*Es/2;return"M0,"+-e+"L"+t+","+e+" "+-t+","+e+"Z"}});$o.svg.symbolTypes=ws.keys();var Ss,ks,Es=Math.sqrt(3),As=Math.tan(30*La),Cs=[],Ns=0; +Cs.call=ma.call,Cs.empty=ma.empty,Cs.node=ma.node,Cs.size=ma.size,$o.transition=function(n){return arguments.length?Ss?n.transition():n:Ma.transition()},$o.transition.prototype=Cs,Cs.select=function(n){var t,e,r,u=this.id,i=[];n=v(n);for(var o=-1,a=this.length;++oi;i++){u.push(t=[]);for(var e=this[i],a=0,c=e.length;c>a;a++)(r=e[a])&&n.call(r,r.__data__,a)&&t.push(r)}return to(u,this.id)},Cs.tween=function(n,t){var e=this.id;return arguments.length<2?this.node().__transition__[e].tween.get(n):C(this,null==t?function(t){t.__transition__[e].tween.remove(n)}:function(r){r.__transition__[e].tween.set(n,t)})},Cs.attr=function(n,t){function e(){this.removeAttribute(a)}function r(){this.removeAttributeNS(a.space,a.local)}function u(n){return null==n?e:(n+="",function(){var t,e=this.getAttribute(a);return e!==n&&(t=o(e,n),function(n){this.setAttribute(a,t(n))})})}function i(n){return null==n?r:(n+="",function(){var t,e=this.getAttributeNS(a.space,a.local);return e!==n&&(t=o(e,n),function(n){this.setAttributeNS(a.space,a.local,t(n))})})}if(arguments.length<2){for(t in n)this.attr(t,n[t]);return this}var o="transform"==n?tu:qr,a=$o.ns.qualify(n);return eo(this,"attr."+n,t,a.local?i:u)},Cs.attrTween=function(n,t){function e(n,e){var r=t.call(this,n,e,this.getAttribute(u));return r&&function(n){this.setAttribute(u,r(n))}}function r(n,e){var r=t.call(this,n,e,this.getAttributeNS(u.space,u.local));return r&&function(n){this.setAttributeNS(u.space,u.local,r(n))}}var u=$o.ns.qualify(n);return this.tween("attr."+n,u.local?r:e)},Cs.style=function(n,t,e){function r(){this.style.removeProperty(n)}function u(t){return null==t?r:(t+="",function(){var r,u=Ko.getComputedStyle(this,null).getPropertyValue(n);return u!==t&&(r=qr(u,t),function(t){this.style.setProperty(n,r(t),e)})})}var i=arguments.length;if(3>i){if("string"!=typeof n){2>i&&(t="");for(e in n)this.style(e,n[e],t);return this}e=""}return eo(this,"style."+n,t,u)},Cs.styleTween=function(n,t,e){function r(r,u){var i=t.call(this,r,u,Ko.getComputedStyle(this,null).getPropertyValue(n));return i&&function(t){this.style.setProperty(n,i(t),e)}}return arguments.length<3&&(e=""),this.tween("style."+n,r)},Cs.text=function(n){return eo(this,"text",n,ro)},Cs.remove=function(){return this.each("end.transition",function(){var n;this.__transition__.count<2&&(n=this.parentNode)&&n.removeChild(this)})},Cs.ease=function(n){var t=this.id;return arguments.length<1?this.node().__transition__[t].ease:("function"!=typeof n&&(n=$o.ease.apply($o,arguments)),C(this,function(e){e.__transition__[t].ease=n}))},Cs.delay=function(n){var t=this.id;return C(this,"function"==typeof n?function(e,r,u){e.__transition__[t].delay=+n.call(e,e.__data__,r,u)}:(n=+n,function(e){e.__transition__[t].delay=n}))},Cs.duration=function(n){var t=this.id;return C(this,"function"==typeof n?function(e,r,u){e.__transition__[t].duration=Math.max(1,n.call(e,e.__data__,r,u))}:(n=Math.max(1,n),function(e){e.__transition__[t].duration=n}))},Cs.each=function(n,t){var e=this.id;if(arguments.length<2){var r=ks,u=Ss;Ss=e,C(this,function(t,r,u){ks=t.__transition__[e],n.call(t,t.__data__,r,u)}),ks=r,Ss=u}else C(this,function(r){var u=r.__transition__[e];(u.event||(u.event=$o.dispatch("start","end"))).on(n,t)});return this},Cs.transition=function(){for(var n,t,e,r,u=this.id,i=++Ns,o=[],a=0,c=this.length;c>a;a++){o.push(n=[]);for(var t=this[a],s=0,l=t.length;l>s;s++)(e=t[s])&&(r=Object.create(e.__transition__[u]),r.delay+=r.duration,uo(e,s,i,r)),n.push(e)}return to(o,i)},$o.svg.axis=function(){function n(n){n.each(function(){var n,s=$o.select(this),l=this.__chart__||e,f=this.__chart__=e.copy(),h=null==c?f.ticks?f.ticks.apply(f,a):f.domain():c,g=null==t?f.tickFormat?f.tickFormat.apply(f,a):vt:t,p=s.selectAll(".tick").data(h,f),v=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Ca),d=$o.transition(p.exit()).style("opacity",Ca).remove(),m=$o.transition(p).style("opacity",1),y=ti(f),x=s.selectAll(".domain").data([0]),M=(x.enter().append("path").attr("class","domain"),$o.transition(x));v.append("line"),v.append("text");var _=v.select("line"),b=m.select("line"),w=p.select("text").text(g),S=v.select("text"),k=m.select("text");switch(r){case"bottom":n=io,_.attr("y2",u),S.attr("y",Math.max(u,0)+o),b.attr("x2",0).attr("y2",u),k.attr("x",0).attr("y",Math.max(u,0)+o),w.attr("dy",".71em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+i+"V0H"+y[1]+"V"+i);break;case"top":n=io,_.attr("y2",-u),S.attr("y",-(Math.max(u,0)+o)),b.attr("x2",0).attr("y2",-u),k.attr("x",0).attr("y",-(Math.max(u,0)+o)),w.attr("dy","0em").style("text-anchor","middle"),M.attr("d","M"+y[0]+","+-i+"V0H"+y[1]+"V"+-i);break;case"left":n=oo,_.attr("x2",-u),S.attr("x",-(Math.max(u,0)+o)),b.attr("x2",-u).attr("y2",0),k.attr("x",-(Math.max(u,0)+o)).attr("y",0),w.attr("dy",".32em").style("text-anchor","end"),M.attr("d","M"+-i+","+y[0]+"H0V"+y[1]+"H"+-i);break;case"right":n=oo,_.attr("x2",u),S.attr("x",Math.max(u,0)+o),b.attr("x2",u).attr("y2",0),k.attr("x",Math.max(u,0)+o).attr("y",0),w.attr("dy",".32em").style("text-anchor","start"),M.attr("d","M"+i+","+y[0]+"H0V"+y[1]+"H"+i)}if(f.rangeBand){var E=f.rangeBand()/2,A=function(n){return f(n)+E};v.call(n,A),m.call(n,A)}else v.call(n,l),m.call(n,f),d.call(n,f)})}var t,e=$o.scale.linear(),r=Ls,u=6,i=6,o=3,a=[10],c=null;return n.scale=function(t){return arguments.length?(e=t,n):e},n.orient=function(t){return arguments.length?(r=t in Ts?t+"":Ls,n):r},n.ticks=function(){return arguments.length?(a=arguments,n):a},n.tickValues=function(t){return arguments.length?(c=t,n):c},n.tickFormat=function(e){return arguments.length?(t=e,n):t},n.tickSize=function(t){var e=arguments.length;return e?(u=+t,i=+arguments[e-1],n):u},n.innerTickSize=function(t){return arguments.length?(u=+t,n):u},n.outerTickSize=function(t){return arguments.length?(i=+t,n):i},n.tickPadding=function(t){return arguments.length?(o=+t,n):o},n.tickSubdivide=function(){return arguments.length&&n},n};var Ls="bottom",Ts={top:1,right:1,bottom:1,left:1};$o.svg.brush=function(){function n(i){i.each(function(){var i=$o.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",u).on("touchstart.brush",u),o=i.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),i.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var a=i.selectAll(".resize").data(d,vt);a.exit().remove(),a.enter().append("g").attr("class",function(n){return"resize "+n}).style("cursor",function(n){return qs[n]}).append("rect").attr("x",function(n){return/[ew]$/.test(n)?-3:null}).attr("y",function(n){return/^[ns]/.test(n)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),a.style("display",n.empty()?"none":null);var l,f=$o.transition(i),h=$o.transition(o);c&&(l=ti(c),h.attr("x",l[0]).attr("width",l[1]-l[0]),e(f)),s&&(l=ti(s),h.attr("y",l[0]).attr("height",l[1]-l[0]),r(f)),t(f)})}function t(n){n.selectAll(".resize").attr("transform",function(n){return"translate("+l[+/e$/.test(n)]+","+h[+/^s/.test(n)]+")"})}function e(n){n.select(".extent").attr("x",l[0]),n.selectAll(".extent,.n>rect,.s>rect").attr("width",l[1]-l[0])}function r(n){n.select(".extent").attr("y",h[0]),n.selectAll(".extent,.e>rect,.w>rect").attr("height",h[1]-h[0])}function u(){function u(){32==$o.event.keyCode&&(C||(x=null,L[0]-=l[1],L[1]-=h[1],C=2),f())}function g(){32==$o.event.keyCode&&2==C&&(L[0]+=l[1],L[1]+=h[1],C=0,f())}function d(){var n=$o.mouse(_),u=!1;M&&(n[0]+=M[0],n[1]+=M[1]),C||($o.event.altKey?(x||(x=[(l[0]+l[1])/2,(h[0]+h[1])/2]),L[0]=l[+(n[0]f?(u=r,r=f):u=f),g[0]!=r||g[1]!=u?(e?o=null:i=null,g[0]=r,g[1]=u,!0):void 0}function y(){d(),S.style("pointer-events","all").selectAll(".resize").style("display",n.empty()?"none":null),$o.select("body").style("cursor",null),T.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),N(),w({type:"brushend"})}var x,M,_=this,b=$o.select($o.event.target),w=a.of(_,arguments),S=$o.select(_),k=b.datum(),E=!/^(n|s)$/.test(k)&&c,A=!/^(e|w)$/.test(k)&&s,C=b.classed("extent"),N=D(),L=$o.mouse(_),T=$o.select(Ko).on("keydown.brush",u).on("keyup.brush",g);if($o.event.changedTouches?T.on("touchmove.brush",d).on("touchend.brush",y):T.on("mousemove.brush",d).on("mouseup.brush",y),S.interrupt().selectAll("*").interrupt(),C)L[0]=l[0]-L[0],L[1]=h[0]-L[1];else if(k){var q=+/w$/.test(k),z=+/^n/.test(k);M=[l[1-q]-L[0],h[1-z]-L[1]],L[0]=l[q],L[1]=h[z]}else $o.event.altKey&&(x=L.slice());S.style("pointer-events","none").selectAll(".resize").style("display",null),$o.select("body").style("cursor",b.style("cursor")),w({type:"brushstart"}),d()}var i,o,a=g(n,"brushstart","brush","brushend"),c=null,s=null,l=[0,0],h=[0,0],p=!0,v=!0,d=zs[0];return n.event=function(n){n.each(function(){var n=a.of(this,arguments),t={x:l,y:h,i:i,j:o},e=this.__chart__||t;this.__chart__=t,Ss?$o.select(this).transition().each("start.brush",function(){i=e.i,o=e.j,l=e.x,h=e.y,n({type:"brushstart"})}).tween("brush:brush",function(){var e=zr(l,t.x),r=zr(h,t.y);return i=o=null,function(u){l=t.x=e(u),h=t.y=r(u),n({type:"brush",mode:"resize"})}}).each("end.brush",function(){i=t.i,o=t.j,n({type:"brush",mode:"resize"}),n({type:"brushend"})}):(n({type:"brushstart"}),n({type:"brush",mode:"resize"}),n({type:"brushend"}))})},n.x=function(t){return arguments.length?(c=t,d=zs[!c<<1|!s],n):c},n.y=function(t){return arguments.length?(s=t,d=zs[!c<<1|!s],n):s},n.clamp=function(t){return arguments.length?(c&&s?(p=!!t[0],v=!!t[1]):c?p=!!t:s&&(v=!!t),n):c&&s?[p,v]:c?p:s?v:null},n.extent=function(t){var e,r,u,a,f;return arguments.length?(c&&(e=t[0],r=t[1],s&&(e=e[0],r=r[0]),i=[e,r],c.invert&&(e=c(e),r=c(r)),e>r&&(f=e,e=r,r=f),(e!=l[0]||r!=l[1])&&(l=[e,r])),s&&(u=t[0],a=t[1],c&&(u=u[1],a=a[1]),o=[u,a],s.invert&&(u=s(u),a=s(a)),u>a&&(f=u,u=a,a=f),(u!=h[0]||a!=h[1])&&(h=[u,a])),n):(c&&(i?(e=i[0],r=i[1]):(e=l[0],r=l[1],c.invert&&(e=c.invert(e),r=c.invert(r)),e>r&&(f=e,e=r,r=f))),s&&(o?(u=o[0],a=o[1]):(u=h[0],a=h[1],s.invert&&(u=s.invert(u),a=s.invert(a)),u>a&&(f=u,u=a,a=f))),c&&s?[[e,u],[r,a]]:c?[e,r]:s&&[u,a])},n.clear=function(){return n.empty()||(l=[0,0],h=[0,0],i=o=null),n},n.empty=function(){return!!c&&l[0]==l[1]||!!s&&h[0]==h[1]},$o.rebind(n,a,"on")};var qs={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},zs=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],Rs=$o.time={},Ds=Date,Ps=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];ao.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){Us.setUTCDate.apply(this._,arguments)},setDay:function(){Us.setUTCDay.apply(this._,arguments)},setFullYear:function(){Us.setUTCFullYear.apply(this._,arguments)},setHours:function(){Us.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){Us.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){Us.setUTCMinutes.apply(this._,arguments)},setMonth:function(){Us.setUTCMonth.apply(this._,arguments)},setSeconds:function(){Us.setUTCSeconds.apply(this._,arguments)},setTime:function(){Us.setTime.apply(this._,arguments)}};var Us=Date.prototype,js="%a %b %e %X %Y",Hs="%m/%d/%Y",Fs="%H:%M:%S",Os=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Ys=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Is=["January","February","March","April","May","June","July","August","September","October","November","December"],Zs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Rs.year=co(function(n){return n=Rs.day(n),n.setMonth(0,1),n},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n){return n.getFullYear()}),Rs.years=Rs.year.range,Rs.years.utc=Rs.year.utc.range,Rs.day=co(function(n){var t=new Ds(2e3,0);return t.setFullYear(n.getFullYear(),n.getMonth(),n.getDate()),t},function(n,t){n.setDate(n.getDate()+t)},function(n){return n.getDate()-1}),Rs.days=Rs.day.range,Rs.days.utc=Rs.day.utc.range,Rs.dayOfYear=function(n){var t=Rs.year(n);return Math.floor((n-t-6e4*(n.getTimezoneOffset()-t.getTimezoneOffset()))/864e5)},Ps.forEach(function(n,t){n=n.toLowerCase(),t=7-t;var e=Rs[n]=co(function(n){return(n=Rs.day(n)).setDate(n.getDate()-(n.getDay()+t)%7),n},function(n,t){n.setDate(n.getDate()+7*Math.floor(t))},function(n){var e=Rs.year(n).getDay();return Math.floor((Rs.dayOfYear(n)+(e+t)%7)/7)-(e!==t)});Rs[n+"s"]=e.range,Rs[n+"s"].utc=e.utc.range,Rs[n+"OfYear"]=function(n){var e=Rs.year(n).getDay();return Math.floor((Rs.dayOfYear(n)+(e+t)%7)/7)}}),Rs.week=Rs.sunday,Rs.weeks=Rs.sunday.range,Rs.weeks.utc=Rs.sunday.utc.range,Rs.weekOfYear=Rs.sundayOfYear,Rs.format=lo;var Vs=ho(Os),Xs=go(Os),$s=ho(Ys),Bs=go(Ys),Ws=ho(Is),Js=go(Is),Gs=ho(Zs),Ks=go(Zs),Qs=/^%/,nl={"-":"",_:" ",0:"0"},tl={a:function(n){return Ys[n.getDay()]},A:function(n){return Os[n.getDay()]},b:function(n){return Zs[n.getMonth()]},B:function(n){return Is[n.getMonth()]},c:lo(js),d:function(n,t){return po(n.getDate(),t,2)},e:function(n,t){return po(n.getDate(),t,2)},H:function(n,t){return po(n.getHours(),t,2)},I:function(n,t){return po(n.getHours()%12||12,t,2)},j:function(n,t){return po(1+Rs.dayOfYear(n),t,3)},L:function(n,t){return po(n.getMilliseconds(),t,3)},m:function(n,t){return po(n.getMonth()+1,t,2)},M:function(n,t){return po(n.getMinutes(),t,2)},p:function(n){return n.getHours()>=12?"PM":"AM"},S:function(n,t){return po(n.getSeconds(),t,2)},U:function(n,t){return po(Rs.sundayOfYear(n),t,2)},w:function(n){return n.getDay()},W:function(n,t){return po(Rs.mondayOfYear(n),t,2)},x:lo(Hs),X:lo(Fs),y:function(n,t){return po(n.getFullYear()%100,t,2)},Y:function(n,t){return po(n.getFullYear()%1e4,t,4)},Z:jo,"%":function(){return"%"}},el={a:vo,A:mo,b:_o,B:bo,c:wo,d:To,e:To,H:zo,I:zo,j:qo,L:Po,m:Lo,M:Ro,p:Uo,S:Do,U:xo,w:yo,W:Mo,x:So,X:ko,y:Ao,Y:Eo,Z:Co,"%":Ho},rl=/^\s*\d+/,ul=$o.map({am:0,pm:1});lo.utc=Fo;var il=Fo("%Y-%m-%dT%H:%M:%S.%LZ");lo.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?Oo:il,Oo.parse=function(n){var t=new Date(n);return isNaN(t)?null:t},Oo.toString=il.toString,Rs.second=co(function(n){return new Ds(1e3*Math.floor(n/1e3))},function(n,t){n.setTime(n.getTime()+1e3*Math.floor(t))},function(n){return n.getSeconds()}),Rs.seconds=Rs.second.range,Rs.seconds.utc=Rs.second.utc.range,Rs.minute=co(function(n){return new Ds(6e4*Math.floor(n/6e4))},function(n,t){n.setTime(n.getTime()+6e4*Math.floor(t))},function(n){return n.getMinutes()}),Rs.minutes=Rs.minute.range,Rs.minutes.utc=Rs.minute.utc.range,Rs.hour=co(function(n){var t=n.getTimezoneOffset()/60;return new Ds(36e5*(Math.floor(n/36e5-t)+t))},function(n,t){n.setTime(n.getTime()+36e5*Math.floor(t))},function(n){return n.getHours()}),Rs.hours=Rs.hour.range,Rs.hours.utc=Rs.hour.utc.range,Rs.month=co(function(n){return n=Rs.day(n),n.setDate(1),n},function(n,t){n.setMonth(n.getMonth()+t)},function(n){return n.getMonth()}),Rs.months=Rs.month.range,Rs.months.utc=Rs.month.utc.range;var ol=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],al=[[Rs.second,1],[Rs.second,5],[Rs.second,15],[Rs.second,30],[Rs.minute,1],[Rs.minute,5],[Rs.minute,15],[Rs.minute,30],[Rs.hour,1],[Rs.hour,3],[Rs.hour,6],[Rs.hour,12],[Rs.day,1],[Rs.day,2],[Rs.week,1],[Rs.month,1],[Rs.month,3],[Rs.year,1]],cl=[[lo("%Y"),Zt],[lo("%B"),function(n){return n.getMonth()}],[lo("%b %d"),function(n){return 1!=n.getDate()}],[lo("%a %d"),function(n){return n.getDay()&&1!=n.getDate()}],[lo("%I %p"),function(n){return n.getHours()}],[lo("%I:%M"),function(n){return n.getMinutes()}],[lo(":%S"),function(n){return n.getSeconds()}],[lo(".%L"),function(n){return n.getMilliseconds()}]],sl=Zo(cl);al.year=Rs.year,Rs.scale=function(){return Yo($o.scale.linear(),al,sl)};var ll={range:function(n,t,e){return $o.range(+n,+t,e).map(Io)}},fl=al.map(function(n){return[n[0].utc,n[1]]}),hl=[[Fo("%Y"),Zt],[Fo("%B"),function(n){return n.getUTCMonth()}],[Fo("%b %d"),function(n){return 1!=n.getUTCDate()}],[Fo("%a %d"),function(n){return n.getUTCDay()&&1!=n.getUTCDate()}],[Fo("%I %p"),function(n){return n.getUTCHours()}],[Fo("%I:%M"),function(n){return n.getUTCMinutes()}],[Fo(":%S"),function(n){return n.getUTCSeconds()}],[Fo(".%L"),function(n){return n.getUTCMilliseconds()}]],gl=Zo(hl);return fl.year=Rs.year.utc,Rs.scale.utc=function(){return Yo($o.scale.linear(),fl,gl)},$o.text=dt(function(n){return n.responseText}),$o.json=function(n,t){return mt(n,"application/json",Vo,t)},$o.html=function(n,t){return mt(n,"text/html",Xo,t)},$o.xml=dt(function(n){return n.responseXML}),$o}(); \ No newline at end of file diff --git a/admin/view/javascript/shopunity/charts_svg/dc.css b/admin/view/javascript/shopunity/charts_svg/dc.css new file mode 100755 index 0000000..935ed3a --- /dev/null +++ b/admin/view/javascript/shopunity/charts_svg/dc.css @@ -0,0 +1,308 @@ +div.dc-chart { + float: left; +} + +.dc-chart rect.bar { + stroke: none; + cursor: pointer; +} + +.dc-chart rect.bar:hover { + fill-opacity: .5; +} + +.dc-chart rect.stack1 { + stroke: none; + fill: red; +} + +.dc-chart rect.stack2 { + stroke: none; + fill: green; +} + +.dc-chart rect.deselected { + stroke: none; + fill: #ccc; +} + +.dc-chart .pie-slice { + fill: white; + font-size: 12px; + cursor: pointer; +} + +.dc-chart .pie-slice.external{ + fill: black; +} + +.dc-chart .pie-slice :hover { + fill-opacity: .8; +} + +.dc-chart .pie-slice.highlight { + fill-opacity: .8; +} + +.dc-chart .selected path { + stroke-width: 3; + stroke: #ccc; + fill-opacity: 1; +} + +.dc-chart .deselected path { + stroke: none; + fill-opacity: .5; + fill: #ccc; +} + +.dc-chart .axis path, .axis line { + fill: none; + stroke: #000; + shape-rendering: crispEdges; +} + +.dc-chart .axis text { + font: 10px sans-serif; +} + +.dc-chart .grid-line { + fill: none; + stroke: #ccc; + opacity: .5; + shape-rendering: crispEdges; +} + +.dc-chart .grid-line line { + fill: none; + stroke: #ccc; + opacity: .5; + shape-rendering: crispEdges; +} + +.dc-chart .brush rect.background { + z-index: -999; +} + +.dc-chart .brush rect.extent { + fill: steelblue; + fill-opacity: .125; +} + +.dc-chart .brush .resize path { + fill: #eee; + stroke: #666; +} + +.dc-chart path.line { + fill: none; + stroke-width: 1.5px; +} + +.dc-chart circle.dot { + stroke: none; +} + +.dc-chart g.dc-tooltip path { + fill: none; + stroke: grey; + stroke-opacity: .8; +} + +.dc-chart path.area { + fill-opacity: .3; + stroke: none; +} + +.dc-chart .node { + font-size: 0.7em; + cursor: pointer; +} + +.dc-chart .node :hover { + fill-opacity: .8; +} + +.dc-chart .selected circle { + stroke-width: 3; + stroke: #ccc; + fill-opacity: 1; +} + +.dc-chart .deselected circle { + stroke: none; + fill-opacity: .5; + fill: #ccc; +} + +.dc-chart .bubble { + stroke: none; + fill-opacity: 0.6; +} + +.dc-data-count { + float: right; + margin-top: 15px; + margin-right: 15px; +} + +.dc-data-count .filter-count { + color: #3182bd; + font-weight: bold; +} + +.dc-data-count .total-count { + color: #3182bd; + font-weight: bold; +} + +.dc-data-table { +} + +.dc-chart g.state { + cursor: pointer; +} + +.dc-chart g.state :hover { + fill-opacity: .8; +} + +.dc-chart g.state path { + stroke: white; +} + +.dc-chart g.selected path { +} + +.dc-chart g.deselected path { + fill: grey; +} + +.dc-chart g.selected text { +} + +.dc-chart g.deselected text { + display: none; +} + +.dc-chart g.county path { + stroke: white; + fill: none; +} + +.dc-chart g.debug rect { + fill: blue; + fill-opacity: .2; +} + +.dc-chart g.row rect { + fill-opacity: 0.8; + cursor: pointer; +} + +.dc-chart g.row rect:hover { + fill-opacity: 0.6; +} + +.dc-chart g.row text { + fill: white; + font-size: 12px; + cursor: pointer; +} + +.dc-legend { + font-size: 11px; +} + +.dc-legend-item { + cursor: pointer; +} + +.dc-chart g.axis text { + /* Makes it so the user can't accidentally click and select text that is meant as a label only */ + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10 */ + -o-user-select: none; + user-select: none; + pointer-events: none; +} + +.dc-chart path.highlight { + stroke-width: 3; + fill-opacity: 1; + stroke-opacity: 1; +} + +.dc-chart .highlight { + fill-opacity: 1; + stroke-opacity: 1; +} + +.dc-chart .fadeout { + fill-opacity: 0.2; + stroke-opacity: 0.2; +} + +.dc-chart path.dc-mbolmbol, g.dc-legend-item.fadeout { + fill-opacity: 0.5; + stroke-opacity: 0.5; +} + +.dc-hard .number-display { + float: none; +} + +.dc-chart .box text { + font: 10px sans-serif; + -webkit-user-select: none; /* Chrome/Safari */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* IE10 */ + -o-user-select: none; + user-select: none; + pointer-events: none; +} + +.dc-chart .box line, +.dc-chart .box circle { + fill: #fff; + stroke: #000; + stroke-width: 1.5px; +} + +.dc-chart .box rect { + stroke: #000; + stroke-width: 1.5px; +} + +.dc-chart .box .center { + stroke-dasharray: 3,3; +} + +.dc-chart .box .outlier { + fill: none; + stroke: #ccc; +} + +.dc-chart .box.deselected .box { + fill: #ccc; +} + +.dc-chart .box.deselected { + opacity: .5; +} + +.dc-chart .symbol{ + stroke: none; +} + +.dc-chart .heatmap .box-group.deselected rect { + stroke: none; + fill-opacity: .5; + fill: #ccc; +} + +.dc-chart .heatmap g.axis text { + pointer-events: all; + cursor: pointer; +} diff --git a/admin/view/javascript/shopunity/charts_svg/dc.js b/admin/view/javascript/shopunity/charts_svg/dc.js new file mode 100755 index 0000000..45b0531 --- /dev/null +++ b/admin/view/javascript/shopunity/charts_svg/dc.js @@ -0,0 +1,6805 @@ +/*! + * dc 2.0.0-dev + * http://nickqizhu.github.io/dc.js/ + * Copyright 2012 Nick Zhu and other contributors + * + * 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. + */ + +dc = (function(){ +'use strict'; + +/** +#### Version 2.0.0-dev + +The entire dc.js library is scoped under **dc** name space. It does not introduce anything else into the global +name space. + +* [Base Chart [abstract]](#base-chart) +* [Color Chart [abstract]](#color-chart) +* [Stackable Chart [abstract]](#stackable-chart) +* [Coordinate Grid Chart [abstract] < Color Chart < Base Chart](#coordinate-grid-chart) +* [Pie Chart [concrete] < Color Chart < Base Chart](#pie-chart) +* [Row Chart [concrete] < Color Chart < Base chart](#row-chart) +* [Bar Chart [concrete] < Stackable Chart < CoordinateGrid Chart](#bar-chart) +* [Line Chart [concrete] < Stackable Chart < CoordinateGrid Chart](#line-chart) +* [Composite Chart [concrete] < CoordinateGrid Chart](#composite-chart) +* [Abstract Bubble Chart [abstract] < Color Chart](#abstract-bubble-chart) +* [Bubble Chart [concrete] < Abstract Bubble Chart < CoordinateGrid Chart](#bubble-chart) +* [Bubble Overlay Chart [concrete] < Abstract Bubble Chart < Base Chart](#bubble-overlay-chart) +* [Geo Choropleth Chart [concrete] < Color Chart < Base Chart](#geo-choropleth-chart) +* [Data Count Widget [concrete] < Base Chart](#data-count) +* [Data Table Widget [concrete] < Base Chart](#data-table) +* [Number Display [Concrete] < Base Chart](#number-display) +* [Legend [concrete]](#legend) +* [Listeners](#listeners) +* [Utilities](#util) + +#### Function Chain +Majority of dc functions are designed to allow function chaining, meaning it will return the current chart instance +whenever it is appropriate. Therefore configuration of a chart can be written in the following style. +```js +chart.width(300) + .height(300) + .filter("sunday") +``` +The API references will highlight the fact if a particular function is not chainable. + +**/ +var dc = { + version: "2.0.0-dev", + constants: { + CHART_CLASS: "dc-chart", + DEBUG_GROUP_CLASS: "debug", + STACK_CLASS: "stack", + DESELECTED_CLASS: "deselected", + SELECTED_CLASS: "selected", + NODE_INDEX_NAME: "__index__", + GROUP_INDEX_NAME: "__group_index__", + DEFAULT_CHART_GROUP: "__default_chart_group__", + EVENT_DELAY: 40, + NEGLIGIBLE_NUMBER: 1e-10 + }, + _renderlet: null +}; + +dc.chartRegistry = function() { + // chartGroup:string => charts:array + var _chartMap = {}; + + function initializeChartGroup(group) { + if (!group) + group = dc.constants.DEFAULT_CHART_GROUP; + + if (!_chartMap[group]) + _chartMap[group] = []; + + return group; + } + + return { + has: function(chart) { + for (var e in _chartMap) { + if (_chartMap[e].indexOf(chart) >= 0) + return true; + } + return false; + }, + + register: function(chart, group) { + group = initializeChartGroup(group); + _chartMap[group].push(chart); + }, + + clear: function(group) { + if (group) { + delete _chartMap[group]; + } else { + _chartMap = {}; + } + }, + + list: function(group) { + group = initializeChartGroup(group); + return _chartMap[group]; + } + }; +}(); + +dc.registerChart = function(chart, group) { + dc.chartRegistry.register(chart, group); +}; + +dc.hasChart = function(chart) { + return dc.chartRegistry.has(chart); +}; + +dc.deregisterAllCharts = function(group) { + dc.chartRegistry.clear(group); +}; + +/** +## # Utilities +**/ + +/** +#### dc.filterAll([chartGroup]) +Clear all filters on every chart within the given chart group. If the chart group is not given then only charts that +belong to the default chart group will be reset. +**/ +dc.filterAll = function(group) { + var charts = dc.chartRegistry.list(group); + for (var i = 0; i < charts.length; ++i) { + charts[i].filterAll(); + } +}; + +/** +#### dc.renderAll([chartGroup]) +Re-render all charts belong to the given chart group. If the chart group is not given then only charts that belong to + the default chart group will be re-rendered. +**/ +dc.renderAll = function(group) { + var charts = dc.chartRegistry.list(group); + for (var i = 0; i < charts.length; ++i) { + charts[i].render(); + } + + if(dc._renderlet !== null) + dc._renderlet(group); +}; + +/** +#### dc.redrawAll([chartGroup]) +Redraw all charts belong to the given chart group. If the chart group is not given then only charts that belong to the + default chart group will be re-drawn. Redraw is different from re-render since when redrawing dc charts try to update + the graphic incrementally instead of starting from scratch. +**/ +dc.redrawAll = function(group) { + var charts = dc.chartRegistry.list(group); + for (var i = 0; i < charts.length; ++i) { + charts[i].redraw(); + } + + if(dc._renderlet !== null) + dc._renderlet(group); +}; + +dc.disableTransitions = false; +dc.transition = function(selections, duration, callback) { + if (duration <= 0 || duration === undefined || dc.disableTransitions) + return selections; + + var s = selections + .transition() + .duration(duration); + + if (typeof(callback) === 'function') { + callback(s); + } + + return s; +}; + +dc.units = {}; + +/** +#### dc.units.integers +This function can be used to in [Coordinate Grid Chart](#coordinate-grid-chart) to define units on x axis. +dc.units.integers is the default x unit scale used by [Coordinate Grid Chart](#coordinate-grid-chart) and should be +used when x range is a sequential of integers. + +**/ +dc.units.integers = function(s, e) { + return Math.abs(e - s); +}; + +/** +#### dc.units.ordinal +This function can be used to in [Coordinate Grid Chart](#coordinate-grid-chart) to define ordinal units on x axis. +Usually this function is used in combination with d3.scale.ordinal() on x axis. +**/ +dc.units.ordinal = function(s, e, domain){ + return domain; +}; + +/** +#### dc.units.fp.precision(precision) +This function generates xunit function in floating-point numbers with the given precision. For example if the function +is invoked with 0.001 precision then the function created will divide a range [0.5, 1.0] with 500 units. + +**/ +dc.units.fp = {}; +dc.units.fp.precision = function(precision){ + var _f = function(s, e){ + var d = Math.abs((e-s)/_f.resolution); + if(dc.utils.isNegligible(d - Math.floor(d))) + return Math.floor(d); + else + return Math.ceil(d); + }; + _f.resolution = precision; + return _f; +}; + +dc.round = {}; +dc.round.floor = function(n) { + return Math.floor(n); +}; +dc.round.ceil = function(n) { + return Math.ceil(n); +}; +dc.round.round = function(n) { + return Math.round(n); +}; + +dc.override = function(obj, functionName, newFunction) { + var existingFunction = obj[functionName]; + obj["_" + functionName] = existingFunction; + obj[functionName] = newFunction; +}; + +dc.renderlet = function(_){ + if(!arguments.length) return dc._renderlet; + dc._renderlet = _; + return dc; +}; + +dc.instanceOfChart = function (o) { + return o instanceof Object && o.__dc_flag__ && true; +}; + +dc.errors = {}; + +dc.errors.Exception = function(msg) { + var _msg = msg || "Unexpected internal error"; + + this.message = _msg; + + this.toString = function(){ + return _msg; + }; +}; + +dc.errors.InvalidStateException = function() { + dc.errors.Exception.apply(this, arguments); +}; + +dc.dateFormat = d3.time.format("%m/%d/%Y"); + +dc.printers = {}; + +dc.printers.filters = function (filters) { + var s = ""; + + for (var i = 0; i < filters.length; ++i) { + if (i > 0) s += ", "; + s += dc.printers.filter(filters[i]); + } + + return s; +}; + +dc.printers.filter = function (filter) { + var s = ""; + + if (filter) { + if (filter instanceof Array) { + if (filter.length >= 2) + s = "[" + dc.utils.printSingleValue(filter[0]) + " -> " + dc.utils.printSingleValue(filter[1]) + "]"; + else if (filter.length >= 1) + s = dc.utils.printSingleValue(filter[0]); + } else { + s = dc.utils.printSingleValue(filter); + } + } + + return s; +}; + +dc.pluck = function(n,f) { + return function(d,i) { + return f ? f.call(this,d[n],i) : d[n]; + }; +}; + +dc.utils = {}; + +dc.utils.printSingleValue = function (filter) { + var s = "" + filter; + + if (filter instanceof Date) + s = dc.dateFormat(filter); + else if (typeof(filter) == "string") + s = filter; + else if (dc.utils.isFloat(filter)) + s = dc.utils.printSingleValue.fformat(filter); + else if (dc.utils.isInteger(filter)) + s = Math.round(filter); + + return s; +}; +dc.utils.printSingleValue.fformat = d3.format(".2f"); + +dc.utils.add = function (l, r) { + if (typeof r === "string") + r = r.replace("%", ""); + + if (l instanceof Date) { + if (typeof r === "string") r = +r; + var d = new Date(); + d.setTime(l.getTime()); + d.setDate(l.getDate() + r); + return d; + } else if (typeof r === "string") { + var percentage = (+r / 100); + return l > 0 ? l * (1 + percentage) : l * (1 - percentage); + } else { + return l + r; + } +}; + +dc.utils.subtract = function (l, r) { + if (typeof r === "string") + r = r.replace("%", ""); + + if (l instanceof Date) { + if (typeof r === "string") r = +r; + var d = new Date(); + d.setTime(l.getTime()); + d.setDate(l.getDate() - r); + return d; + } else if (typeof r === "string") { + var percentage = (+r / 100); + return l < 0 ? l * (1 + percentage) : l * (1 - percentage); + } else { + return l - r; + } +}; + +dc.utils.GroupStack = function () { + var _dataLayers = [[ ]]; + var _groups = []; + var _defaultAccessor; + var _hideChartGroup; + + function initializeDataLayer(i) { + if (!_dataLayers[i]) + _dataLayers[i] = []; + } + + this.setDataPoint = function (layerIndex, pointIndex, data) { + initializeDataLayer(layerIndex); + _dataLayers[layerIndex][pointIndex] = data; + }; + + this.getDataPoint = function (x, y) { + initializeDataLayer(x); + var dataPoint = _dataLayers[x][y]; + if (dataPoint === undefined) + dataPoint = 0; + return dataPoint; + }; + + this.addGroup = function (group, accessor) { + if (!accessor) + accessor = _defaultAccessor; + _groups.push([group, accessor]); + return _groups.length - 1; + }; + + this.addNamedGroup = function (group, name, accessor) { + var groupIndex = this.addGroup(group, accessor); + _groups[groupIndex].name = name; + return name; + }; + + this.getGroupByIndex = function (index) { + return _groups[index][0]; + }; + + this.getAccessorByIndex = function (index) { + return _groups[index][1]; + }; + + this.getNameOfVisibleByIndex = function (index) { + if (index === -1) { + if (_hideChartGroup) index++; + else return; + } + + var visible = _groups.filter(function(group) { + return !group.hidden; + }); + + return visible[index].name; + }; + + this.size = function () { + return _groups.length; + }; + + this.clear = function () { + _dataLayers = []; + _groups = []; + }; + + this.setDefaultAccessor = function (retriever) { + _defaultAccessor = retriever; + }; + + this.getDataLayers = function () { + return _dataLayers; + }; + + this.clearDataLayers = function() { + _dataLayers = [[ ]]; + }; + + this.showGroups = function(name, showChartGroup) { + if (showChartGroup) _hideChartGroup = false; + this.toggleGroups(name, false); + }; + + this.hideGroups = function(name, hideChartGroup) { + if (hideChartGroup) _hideChartGroup = true; + this.toggleGroups(name, true); + }; + + this.toggleGroups = function(name, value) { + for (var i = 0; i < _groups.length; ++i) { + if (_groups[i].name === name) + _groups[i].hidden = value; + } + }; + + this.setTitle = function(name, titleAccessor) { + for (var i = 0; i < _groups.length; ++i) { + if (_groups[i].name === name) + _groups[i].title = titleAccessor; + } + }; + + this.getTitle = function(name) { + for (var i = 0; i < _groups.length; ++i) { + if (_groups[i].name === name) + return _groups[i].title; + } + }; + + this.toLayers = function () { + var layers = []; + + for (var i = 0; i < _dataLayers.length; ++i) { + if (i === 0 && _hideChartGroup) + continue; + if (i > 0 && _groups[i-1].hidden) + continue; + + var layer = {index: i, points: []}; + var dataPoints = _dataLayers[i]; + + for (var j = 0; j < dataPoints.length; ++j) + layer.points.push(dataPoints[j]); + + layers.push(layer); + } + + return layers; + }; +}; + +dc.utils.isNumber = function(n) { + return n===+n; +}; + +dc.utils.isFloat = function (n) { + return n===+n && n!==(n|0); +}; + +dc.utils.isInteger = function (n) { + return n===+n && n===(n|0); +}; + +dc.utils.isNegligible = function (max) { + return max === undefined || (max < dc.constants.NEGLIGIBLE_NUMBER && max > -dc.constants.NEGLIGIBLE_NUMBER); +}; + +dc.utils.clamp = function (val, min, max) { + return val < min ? min : (val > max ? max : val); +}; + +var _idCounter = 0; +dc.utils.uniqueId = function () { + return ++_idCounter; +}; + +dc.utils.groupMax = function (group, accessor) { + var max = d3.max(group.all(), accessor); + if (dc.utils.isNegligible(max)) max = 0; + return max; +}; + +dc.utils.groupMin = function (group, accessor) { + var min = d3.min(group.all(), accessor); + if (dc.utils.isNegligible(min)) min = 0; + return min; +}; + +dc.utils.nameToId = function (name) { + return name.toLowerCase().replace(/[\s]/g, "_").replace(/[\.']/g, ""); +}; + +dc.utils.appendOrSelect = function (parent, name) { + var element = parent.select(name); + if (element.empty()) element = parent.append(name); + return element; +}; + +dc.utils.createLegendable = function (chart, group, accessor, color) { + var legendable = {name: chart._getGroupName(group, accessor), data: group}; + if (color) legendable.color = color; + if (chart.dashStyle && chart.dashStyle()) legendable.dashstyle = chart.dashStyle(); + return legendable; +}; + +dc.utils.safeNumber = function(n){return dc.utils.isNumber(+n)?+n:0;}; + +dc.events = { + current: null +}; + +/** +#### dc.events.trigger(function[, delay]) +This function is design to trigger throttled event function optionally with certain amount of delay(in milli-seconds). +Events that are triggered repetitively due to user interaction such as the dragging of the brush might over flood +library and cause too much rendering being scheduled. In this case, using this function to wrap your event function +allows the library to smooth out the rendering by throttling event flood and only respond to the most recent event. + +```js + chart.renderlet(function(chart){ + // smooth the rendering through event throttling + dc.events.trigger(function(){ + // focus some other chart to the range selected by user on this chart + someOtherChart.focus(chart.filter()); + }); + }) +``` +**/ +dc.events.trigger = function(closure, delay) { + if (!delay){ + closure(); + return; + } + + dc.events.current = closure; + + setTimeout(function() { + if (closure == dc.events.current) + closure(); + }, delay); +}; + +/** +## # Base Chart [Abstract] +Base chart is an abstract functional object representing a basic dc chart object for all chart and widget implementation. +Every function on base chart are also inherited available on all concrete chart implementation in dc library. + +**/ +dc.baseChart = function (_chart) { + _chart.__dc_flag__ = dc.utils.uniqueId(); + + var _dimension; + var _group; + + var _anchor; + var _root; + var _svg; + + var _minWidth = 200; + var _default_width = function (element) { + var width = element && element.getBoundingClientRect && element.getBoundingClientRect().width; + return (width && width > _minWidth) ? width : _minWidth; + }; + var _width = _default_width; + + var _minHeight = 200; + var _default_height = function (element) { + var height = element && element.getBoundingClientRect && element.getBoundingClientRect().height; + return (height && height > _minHeight) ? height : _minHeight; + }; + var _height = _default_height; + + var _keyAccessor = dc.pluck('key'); + var _valueAccessor = dc.pluck('value'); + var _label = dc.pluck('key'); + + var _ordering = dc.pluck('key'); + var _orderSort; + + var _renderLabel = false; + + var _title = function (d) { + return _chart.keyAccessor()(d) + ": " + _chart.valueAccessor()(d); + }; + var _renderTitle = false; + + var _transitionDuration = 750; + + var _filterPrinter = dc.printers.filters; + + var _renderlets = []; + var _mandatoryAttributes = ['dimension', 'group']; + + var _chartGroup = dc.constants.DEFAULT_CHART_GROUP; + + var NULL_LISTENER = function () {}; + + var _listeners = { + preRender: NULL_LISTENER, + postRender: NULL_LISTENER, + preRedraw: NULL_LISTENER, + postRedraw: NULL_LISTENER, + filtered: NULL_LISTENER, + zoomed: NULL_LISTENER + }; + + var _legend; + + var _filters = []; + var _filterHandler = function (dimension, filters) { + dimension.filter(null); + + if (filters.length === 0) + dimension.filter(null); + else + dimension.filterFunction(function (d) { + for(var i = 0; i < filters.length; i++) { + var filter = filters[i]; + if (filter.isFiltered && filter.isFiltered(d)) { + return true; + } else if (filter == d) { + return true; + } + } + return false; + }); + + return filters; + }; + + + + var _data = function (group) { + return group.all(); + }; + + /** + #### .width([value]) + Set or get width attribute of a chart. See `.height` below for further description of the behavior. + + **/ + _chart.width = function (w) { + if (!arguments.length) return _width(_root.node()); + _width = d3.functor(w || _default_width); + return _chart; + }; + + /** + #### .height([value]) + Set or get height attribute of a chart. The height is applied to the SVG element + generated by the chart when rendered (or rerendered). If a value is given, then it + will be used to calculate the new height and the chart returned for method chaining. + The value can either be a numeric, a function, or falsy. If no value specified then + value of the current height attribute will be returned. + + By default, without an explicit height being given, the chart will select the width + of its anchor element. If that isn't possible it defaults to 200; + + Examples: + + ```js + chart.height(250); // Set the chart's height to 250px; + chart.height(function(anchor) { return doSomethingWith(anchor); }); // set the chart's height with a function + chart.height(null); // reset the height to the default auto calculation + ``` + + **/ + _chart.height = function (h) { + if (!arguments.length) return _height(_root.node()); + _height = d3.functor(h || _default_height); + return _chart; + }; + + /** + #### .minWidth([value]) + Set or get minimum width attribute of a chart. This only applicable if the width is calculated by DC. + + **/ + _chart.minWidth = function (w) { + if (!arguments.length) return _minWidth; + _minWidth = w; + return _chart; + }; + + /** + #### .minHeight([value]) + Set or get minimum height attribute of a chart. This only applicable if the height is calculated by DC. + + **/ + _chart.minHeight = function (w) { + if (!arguments.length) return _minHeight; + _minHeight = w; + return _chart; + }; + + /** + #### .dimension([value]) - **mandatory** + Set or get dimension attribute of a chart. In dc a dimension can be any valid + [crossfilter dimension](https://github.com/square/crossfilter/wiki/API-Reference#wiki-dimension). If the value is given, + then it will be used as the new dimension. + + If no value specified then the current dimension will be returned. + + **/ + _chart.dimension = function (d) { + if (!arguments.length) return _dimension; + _dimension = d; + _chart.expireCache(); + return _chart; + }; + + _chart.data = function(d) { + if (!arguments.length) return _data.call(_chart,_group); + _data = d3.functor(d); + _chart.expireCache(); + return _chart; + }; + + /** + #### .group([value, [name]]) - **mandatory** + Set or get group attribute of a chart. In dc a group is a + [crossfilter group](https://github.com/square/crossfilter/wiki/API-Reference#wiki-group). Usually the group should be + created from the particular dimension associated with the same chart. If the value is given, then it will be used as + the new group. + + If no value specified then the current group will be returned. + If name is specified then it will be used to generate legend label. + + **/ + _chart.group = function (g, name) { + if (!arguments.length) return _group; + _group = g; + _chart.expireCache(); + if (typeof name === 'string') _chart._setGroupName(_group, name); + return _chart; + }; + + // store groups names in the group itself + // __names__ -> + // chart (in referenced by multiple charts) -> + // array of accessors, array of names + function groupName(chart, g, accessor) { + var c = chart.chartID(), + k = '__names__'; + if (!accessor || accessor == chart.valueAccessor()) + accessor = "default"; + if (!g[k]) g[k] = {}; + if (!g[k][c]) g[k][c] = {a:[],n:[]}; + var i = g[k][c].a.indexOf(accessor); + if (i == -1) { + i = g[k][c].a.length; + g[k][c].a[i] = accessor; + g[k][c].n[i] = {name:''}; + } + return g[k][c].n[i]; + } + + + _chart._getGroupName = function (g, accessor) { + return groupName(_chart, g, accessor).name; + }; + + _chart._setGroupName = function (g, name, accessor) { + groupName(_chart, g, accessor).name = name; + }; + + /** + #### .ordering([orderFunction]) + Get or set an accessor to order ordinal charts + **/ + _chart.ordering = function(o) { + if (!arguments.length) return _ordering; + _ordering = o; + _orderSort = crossfilter.quicksort.by(_ordering); + _chart.expireCache(); + return _chart; + }; + + _chart.computeOrderedGroups = function(data) { + if (data.length <= 1) + return data; + if (!_orderSort) _orderSort = crossfilter.quicksort.by(_ordering); + return _orderSort(data,0,data.length); + }; + + /** + #### .filterAll() + Clear all filters associated with this chart. + + **/ + _chart.filterAll = function () { + return _chart.filter(null); + }; + + _chart.dataSet = function () { + return _dimension !== undefined && _group !== undefined; + }; + + /** + #### .select(selector) + Execute in scope d3 single selection using the given selector and return d3 selection result. Roughly the same as: + ```js + d3.select("#chart-id").select(selector); + ``` + This function is **not chainable** since it does not return a chart instance; however the d3 selection result is chainable + from d3's perspective. + + **/ + _chart.select = function (s) { + return _root.select(s); + }; + + /** + #### .selectAll(selector) + Execute in scope d3 selectAll using the given selector and return d3 selection result. Roughly the same as: + ```js + d3.select("#chart-id").selectAll(selector); + ``` + This function is **not chainable** since it does not return a chart instance; however the d3 selection result is + chainable from d3's perspective. + + **/ + _chart.selectAll = function (s) { + return _root ? _root.selectAll(s) : null; + }; + + /** + #### .anchor([anchorChart/anchorSelector], [chartGroup]) + Set the svg root to either be an existing chart's root or the first element returned from a d3 css string selector. Optionally registers the chart within the chartGroup. This class is called internally on chart initialization, but be called again to relocate the chart. However, it will orphan any previously created SVG elements. + + **/ + _chart.anchor = function (a, chartGroup) { + if (!arguments.length) return _anchor; + if (dc.instanceOfChart(a)) { + _anchor = a.anchor(); + _root = a.root(); + } else { + _anchor = a; + _root = d3.select(_anchor); + _root.classed(dc.constants.CHART_CLASS, true); + dc.registerChart(_chart, chartGroup); + } + _chartGroup = chartGroup; + return _chart; + }; + + /** + #### .anchorName() + Return the dom ID for chart's anchored location + + **/ + _chart.anchorName = function () { + var a = _chart.anchor(); + if (a && a.id) return a.id; + if (a && a.replace) return a.replace('#',''); + return "" + _chart.chartID(); + }; + + /** + #### .root([rootElement]) + Returns the root element where a chart resides. Usually it will be the parent div element where svg was created. You + can also pass in a new root element however this is usually handled as part of the dc internal. Resetting root element + on a chart outside of dc internal might have unexpected consequences. + + **/ + _chart.root = function (r) { + if (!arguments.length) return _root; + _root = r; + return _chart; + }; + + /** + #### .svg([svgElement]) + Returns the top svg element for this specific chart. You can also pass in a new svg element however this is usually + handled as part of the dc internal. Resetting svg element on a chart outside of dc internal might have unexpected + consequences. + + **/ + _chart.svg = function (_) { + if (!arguments.length) return _svg; + _svg = _; + return _chart; + }; + + /** + #### .resetSvg() + Remove the chart's SVG elements from the dom and recreate the container SVG element. + **/ + _chart.resetSvg = function () { + _chart.select("svg").remove(); + return generateSvg(); + }; + + function generateSvg() { + _svg = _chart.root().append("svg") + .attr("width", _chart.width()) + .attr("height", _chart.height()); + return _svg; + } + + /** + #### .filterPrinter([filterPrinterFunction]) + Set or get filter printer function. Filter printer function is used to generate human friendly text for filter value(s) + associated with the chart instance. By default dc charts shipped with a default filter printer implementation dc.printers.filter + that provides simple printing support for both single value and ranged filters. + + **/ + _chart.filterPrinter = function (_) { + if (!arguments.length) return _filterPrinter; + _filterPrinter = _; + return _chart; + }; + + /** + #### .turnOnControls() & .turnOffControls() + Turn on/off optional control elements within the root element. dc.js currently support the following html control elements. + + * root.selectAll(".reset") elements are turned on if the chart has an active filter. This type of control elements are usually used to store reset link to allow user to reset filter on a certain chart. This element will be turned off automatically if the filter is cleared. + * root.selectAll(".filter") elements are turned on if the chart has an active filter. The text content of this element is then replaced with the current filter value using the filter printer function. This type of element will be turned off automatically if the filter is cleared. + + **/ + _chart.turnOnControls = function () { + if (_root) { + _chart.selectAll(".reset").style("display", null); + _chart.selectAll(".filter").text(_filterPrinter(_chart.filters())).style("display", null); + } + return _chart; + }; + + _chart.turnOffControls = function () { + if (_root) { + _chart.selectAll(".reset").style("display", "none"); + _chart.selectAll(".filter").style("display", "none").text(_chart.filter()); + } + return _chart; + }; + + /** + #### .transitionDuration([duration]) + Set or get animation transition duration(in milliseconds) for specific chart instance. Default duration is 750ms. + + **/ + _chart.transitionDuration = function (d) { + if (!arguments.length) return _transitionDuration; + _transitionDuration = d; + return _chart; + }; + + _chart._mandatoryAttributes = function (_) { + if (!arguments.length) return _mandatoryAttributes; + _mandatoryAttributes = _; + return _chart; + }; + + function checkForMandatoryAttributes(a) { + if (!_chart[a] || !_chart[a]()) + throw new dc.errors.InvalidStateException("Mandatory attribute chart." + a + + " is missing on chart[#" + _chart.anchorName() + "]"); + } + + /** + #### .render() + Invoke this method will force the chart to re-render everything from scratch. Generally it should be only used to + render the chart for the first time on the page or if you want to make sure everything is redrawn from scratch instead + of relying on the default incremental redrawing behaviour. + + **/ + _chart.render = function () { + _listeners.preRender(_chart); + + if (_mandatoryAttributes) + _mandatoryAttributes.forEach(checkForMandatoryAttributes); + + var result = _chart.doRender(); + + if (_legend) _legend.render(); + + _chart.activateRenderlets("postRender"); + + return result; + }; + + _chart.activateRenderlets = function (event) { + if (_chart.transitionDuration() > 0 && _svg) { + _svg.transition().duration(_chart.transitionDuration()) + .each("end", function () { + runAllRenderlets(); + if (event) _listeners[event](_chart); + }); + } else { + runAllRenderlets(); + if (event) _listeners[event](_chart); + } + }; + + /** + #### .redraw() + Calling redraw will cause the chart to re-render delta in data change incrementally. If there is no change in the + underlying data dimension then calling this method will have no effect on the chart. Most of the chart interaction in + dc library will automatically trigger this method through its internal event engine, therefore you only need to manually + invoke this function if data is manipulated outside of dc's control; for example if data is loaded on a periodic basis + in the background using crossfilter.add(). + + **/ + _chart.redraw = function () { + _listeners.preRedraw(_chart); + + var result = _chart.doRedraw(); + + _chart.activateRenderlets("postRedraw"); + + return result; + }; + + _chart._invokeFilteredListener = function (f) { + if (f !== undefined) _listeners.filtered(_chart, f); + }; + + _chart._invokeZoomedListener = function () { + _listeners.zoomed(_chart); + }; + + /** + #### .hasFilter([filter]) + Check whether is any active filter or a specific filter is associated with particular chart instance. + This function is **not chainable**. + + **/ + _chart.hasFilter = function (filter) { + if (!arguments.length) return _filters.length > 0; + return _filters.indexOf(filter) >= 0; + }; + + function removeFilter(_) { + _filters.splice(_filters.indexOf(_), 1); + applyFilters(); + _chart._invokeFilteredListener(_); + } + + function addFilter(_) { + _filters.push(_); + applyFilters(); + _chart._invokeFilteredListener(_); + } + + function resetFilters() { + _filters = []; + applyFilters(); + _chart._invokeFilteredListener(null); + } + + function applyFilters() { + if (_chart.dimension() && _chart.dimension().filter) { + var fs = _filterHandler(_chart.dimension(), _filters); + _filters = fs ? fs : _filters; + } + } + + _chart.replaceFilter = function (_) { + _filters = []; + _chart.filter(_); + }; + + /** + #### .filter([filterValue]) + Filter the chart by the given value or return the current filter if the input parameter is missing. + ```js + // filter by a single string + chart.filter("Sunday"); + // filter by a single age + chart.filter(18); + ``` + + **/ + _chart.filter = function (_) { + if (!arguments.length) return _filters.length > 0 ? _filters[0] : null; + if (_ instanceof Array && _[0] instanceof Array) { + _[0].forEach(function(d){ + if (_chart.hasFilter(d)) { + _filters.splice(_filters.indexOf(d), 1); + } else { + _filters.push(d); + } + }); + applyFilters(); + _chart._invokeFilteredListener(_); + } else if (_ === null) { + resetFilters(); + } else { + if (_chart.hasFilter(_)) + removeFilter(_); + else + addFilter(_); + } + + if (_root !== null && _chart.hasFilter()) { + _chart.turnOnControls(); + } else { + _chart.turnOffControls(); + } + + return _chart; + }; + + /** + #### .filters() + Return all current filters. This method does not perform defensive cloning of the internal filter array before returning + therefore any modification of returned array will affact chart's internal filter storage. + + **/ + _chart.filters = function () { + return _filters; + }; + + _chart.highlightSelected = function (e) { + d3.select(e).classed(dc.constants.SELECTED_CLASS, true); + d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); + }; + + _chart.fadeDeselected = function (e) { + d3.select(e).classed(dc.constants.SELECTED_CLASS, false); + d3.select(e).classed(dc.constants.DESELECTED_CLASS, true); + }; + + _chart.resetHighlight = function (e) { + d3.select(e).classed(dc.constants.SELECTED_CLASS, false); + d3.select(e).classed(dc.constants.DESELECTED_CLASS, false); + }; + + _chart.onClick = function (d) { + var filter = _chart.keyAccessor()(d); + dc.events.trigger(function () { + _chart.filter(filter); + dc.redrawAll(_chart.chartGroup()); + }); + }; + + /** + #### .filterHandler([function]) + Set or get filter handler. Filter handler is a function that performs the filter action on a specific dimension. Using + custom filter handler give you the flexibility to perform additional logic before or after filtering. + + ```js + // default filter handler + function(dimension, filter){ + dimension.filter(filter); // perform filtering + return filter; // return the actual filter value + } + + // custom filter handler + chart.filterHandler(function(dimension, filter){ + var newFilter = filter + 10; + dimension.filter(newFilter); + return newFilter; // set the actual filter value to the new value + }); + ``` + + **/ + _chart.filterHandler = function (_) { + if (!arguments.length) return _filterHandler; + _filterHandler = _; + return _chart; + }; + + // abstract function stub + _chart.doRender = function () { + // do nothing in base, should be overridden by sub-function + return _chart; + }; + + _chart.doRedraw = function () { + // do nothing in base, should be overridden by sub-function + return _chart; + }; + + _chart.legendables = function () { + // do nothing in base, should be overridden by sub-function + return []; + }; + + _chart.legendHighlight = function (d) { + // do nothing in base, should be overridden by sub-function + }; + + _chart.legendReset = function (d) { + // do nothing in base, should be overridden by sub-function + }; + + _chart.legendToggle = function (d) { + // do nothing in base, should be overriden by sub-function + }; + + _chart.isLegendableHidden = function (d) { + // do nothing in base, should be overridden by sub-function + return false; + }; + + /** + #### .keyAccessor([keyAccessorFunction]) + Set or get the key accessor function. Key accessor function is used to retrieve key value in crossfilter group. Key + values are used differently in different charts, for example keys correspond to slices in pie chart and x axis position + in grid coordinate chart. + ```js + // default key accessor + chart.keyAccessor(function(d) { return d.key; }); + // custom key accessor for a multi-value crossfilter reduction + chart.keyAccessor(function(p) { return p.value.absGain; }); + ``` + + **/ + _chart.keyAccessor = function (_) { + if (!arguments.length) return _keyAccessor; + _keyAccessor = _; + return _chart; + }; + + /** + #### .valueAccessor([valueAccessorFunction]) + Set or get the value accessor function. Value accessor function is used to retrieve value in crossfilter group. Group + values are used differently in different charts, for example group values correspond to slices size in pie chart and y + axis position in grid coordinate chart. + ```js + // default value accessor + chart.valueAccessor(function(d) { return d.value; }); + // custom value accessor for a multi-value crossfilter reduction + chart.valueAccessor(function(p) { return p.value.percentageGain; }); + ``` + + **/ + _chart.valueAccessor = function (_) { + if (!arguments.length) return _valueAccessor; + _valueAccessor = _; + return _chart; + }; + + /** + #### .label([labelFunction]) + Set or get the label function. Chart class will use this function to render label for each child element in the chart, + i.e. a slice in a pie chart or a bubble in a bubble chart. Not every chart supports label function for example bar chart + and line chart do not use this function at all. + ```js + // default label function just return the key + chart.label(function(d) { return d.key; }); + // label function has access to the standard d3 data binding and can get quite complicated + chart.label(function(d) { return d.data.key + "(" + Math.floor(d.data.value / all.value() * 100) + "%)"; }); + ``` + + **/ + _chart.label = function (_) { + if (!arguments.length) return _label; + _label = _; + _renderLabel = true; + return _chart; + }; + + /** + #### .renderLabel(boolean) + Turn on/off label rendering + + **/ + _chart.renderLabel = function (_) { + if (!arguments.length) return _renderLabel; + _renderLabel = _; + return _chart; + }; + + /** + #### .title([titleFunction]) + Set or get the title function. Chart class will use this function to render svg title(usually interpreted by browser + as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. Almost + every chart supports title function however in grid coordinate chart you need to turn off brush in order to use title + otherwise the brush layer will block tooltip trigger. + ```js + // default title function just return the key + chart.title(function(d) { return d.key + ": " + d.value; }); + // title function has access to the standard d3 data binding and can get quite complicated + chart.title(function(p) { + return p.key.getFullYear() + + "\n" + + "Index Gain: " + numberFormat(p.value.absGain) + "\n" + + "Index Gain in Percentage: " + numberFormat(p.value.percentageGain) + "%\n" + + "Fluctuation / Index Ratio: " + numberFormat(p.value.fluctuationPercentage) + "%"; + }); + ``` + + **/ + _chart.title = function (_) { + if (!arguments.length) return _title; + _title = _; + _renderTitle = true; + return _chart; + }; + + /** + #### .renderTitle(boolean) + Turn on/off title rendering + + **/ + _chart.renderTitle = function (_) { + if (!arguments.length) return _renderTitle; + _renderTitle = _; + return _chart; + }; + + /** + #### .renderlet(renderletFunction) + Renderlet is similar to an event listener on rendering event. Multiple renderlets can be added to an individual chart. + Every time when chart is rerendered or redrawn renderlet then will be invoked right after the chart finishes its own + drawing routine hence given you a way to override or modify certain behaviour. Renderlet function accepts the chart + instance as the only input parameter and you can either rely on dc API or use raw d3 to achieve pretty much any effect. + ```js + // renderlet function + chart.renderlet(function(chart){ + // mix of dc API and d3 manipulation + chart.select("g.y").style("display", "none"); + // its a closure so you can also access other chart variable available in the closure scope + moveChart.filter(chart.filter()); + }); + ``` + + **/ + _chart.renderlet = function (_) { + _renderlets.push(_); + return _chart; + }; + + function runAllRenderlets() { + for (var i = 0; i < _renderlets.length; ++i) { + _renderlets[i](_chart); + } + } + + _chart.chartGroup = function (_) { + if (!arguments.length) return _chartGroup; + _chartGroup = _; + return _chart; + }; + + /** + #### .expireCache() + Expire internal chart cache. dc.js chart cache some data internally on a per chart basis so it can speed up rendering + and avoid unnecessary calculation however under certain circumstances it might be useful to clear the cache e.g. after + you invoke crossfilter.add function or if you reset group or dimension post render it is always a good idea to clear + the cache to make sure charts are rendered properly. + + **/ + _chart.expireCache = function () { + // do nothing in base, should be overridden by sub-function + return _chart; + }; + + /** + #### .legend([dc.legend]) + Attach dc.legend widget to this chart. Legend widget will automatically draw legend labels based on the color setting + and names associated with each group. + + ```js + chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) + ``` + + **/ + _chart.legend = function (l) { + if (!arguments.length) return _legend; + _legend = l; + _legend.parent(_chart); + return _chart; + }; + + /** + ## # Listeners + All dc chart instance supports the following listeners. + + #### .on("preRender", function(chart){...}) + This listener function will be invoked before chart rendering. + + #### .on("postRender", function(chart){...}) + This listener function will be invoked after chart finish rendering including all renderlets' logic. + + #### .on("preRedraw", function(chart){...}) + This listener function will be invoked before chart redrawing. + + #### .on("postRedraw", function(chart){...}) + This listener function will be invoked after chart finish redrawing including all renderlets' logic. + + #### .on("filtered", function(chart, filter){...}) + This listener function will be invoked after a filter is applied, added or removed. + + #### .on("zoomed", function(chart, filter){...}) + This listener function will be invoked after a zoom is triggered. + + **/ + _chart.on = function (event, listener) { + _listeners[event] = listener; + return _chart; + }; + + _chart.chartID = function () { + return _chart.__dc_flag__; + }; + + return _chart; +}; + +/** +## # Marginable + +Marginable is a mixin that provides margin utility functions for both the Row Chart and Coordinate Grid Charts. + +**/ +dc.marginable = function (_chart) { + var _margin = {top: 10, right: 50, bottom: 30, left: 30}; + + /** + #### .margins([margins]) + Get or set the margins for a particular coordinate grid chart instance. The margins is stored as an associative Javascript + array. Default margins: {top: 10, right: 50, bottom: 30, left: 30}. + + The margins can be accessed directly from the getter. + ```js + var leftMargin = chart.margins().left; // 30 by default + chart.margins().left = 50; + leftMargin = chart.margins().left; // now 50 + ``` + + **/ + _chart.margins = function (m) { + if (!arguments.length) return _margin; + _margin = m; + return _chart; + }; + + _chart.effectiveWidth = function () { + return _chart.width() - _chart.margins().left - _chart.margins().right; + }; + + _chart.effectiveHeight = function () { + return _chart.height() - _chart.margins().top - _chart.margins().bottom; + }; + + return _chart; +}; + +/** + +## # CoordinateGrid Chart [Abstract] < [Color Chart](#color-chart) < [Base Chart](#base-chart) +Coordinate grid chart is an abstract base chart designed to support a number of coordinate grid based concrete chart types, +i.e. bar chart, line chart, and bubble chart. + +**/ +dc.coordinateGridChart = function (_chart) { + var GRID_LINE_CLASS = "grid-line"; + var HORIZONTAL_CLASS = "horizontal"; + var VERTICAL_CLASS = "vertical"; + var Y_AXIS_LABEL_CLASS = 'y-axis-label'; + var X_AXIS_LABEL_CLASS = 'x-axis-label'; + var DEFAULT_AXIS_LABLEL_PADDING = 12; + + _chart = dc.colorChart(dc.marginable(dc.baseChart(_chart))); + + _chart.colors(d3.scale.category10()); + _chart._mandatoryAttributes().push('x'); + + var _parent; + var _g; + var _chartBodyG; + + var _x; + var _xOriginalDomain; + var _xAxis = d3.svg.axis(); + var _xUnits = dc.units.integers; + var _xAxisPadding = 0; + var _xElasticity = false; + var _xAxisLabel; + var _xAxisLabelPadding = 0; + + var _y; + var _yAxis = d3.svg.axis(); + var _yAxisPadding = 0; + var _yElasticity = false; + var _yAxisLabel; + var _yAxisLabelPadding = 0; + + var _brush = d3.svg.brush(); + var _brushOn = true; + var _round; + + var _renderHorizontalGridLine = false; + var _renderVerticalGridLine = false; + + var _refocused = false; + var _unitCount; + + var _zoomScale = [1, Infinity]; + var _zoomOutRestrict = true; + + var _zoom = d3.behavior.zoom().on("zoom", zoomHandler); + var _nullZoom = d3.behavior.zoom().on("zoom", null); + + var _rangeChart; + var _focusChart; + + var _mouseZoomable = false; + var _clipPadding = 0; + + var _outerRangeBandPadding = 0.5; + var _rangeBandPadding = 0; + + _chart.rescale = function () { + _unitCount = undefined; + }; + + /** + #### .rangeChart([chart]) + Get or set the range selection chart associated with this instance. Setting the range selection chart using this function + will automatically update its selection brush when the current chart zooms in. In return the given range chart will also + automatically attach this chart as its focus chart hence zoom in when range brush updates. See the + [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) example for this effect in action. + + **/ + _chart.rangeChart = function (_) { + if (!arguments.length) return _rangeChart; + _rangeChart = _; + _rangeChart.focusChart(_chart); + return _chart; + }; + + /** + #### .zoomScale([extent]) + Get or set the scale extent for mouse zooms. + + **/ + _chart.zoomScale = function (_) { + if (!arguments.length) return _zoomScale; + _zoomScale = _; + return _chart; + }; + + /** + #### .zoomOutRestrict([true/false]) + Get or set the zoom restriction for the chart. If true limits the zoom to origional domain of the chart. + **/ + _chart.zoomOutRestrict = function (r) { + if (!arguments.length) return _zoomOutRestrict; + _zoomScale[0] = r ? 1 : 0; + _zoomOutRestrict = r; + return _chart; + }; + + _chart._generateG = function (parent) { + if (parent === undefined) + _parent = _chart.svg(); + else + _parent = parent; + + _g = _parent.append("g"); + + _chartBodyG = _g.append("g").attr("class", "chart-body") + .attr("transform", "translate(" + _chart.margins().left + ", " + _chart.margins().top + ")") + .attr("clip-path", "url(#" + getClipPathId() + ")"); + + return _g; + }; + + /** + #### .g([gElement]) + Get or set the root g element. This method is usually used to retrieve the g element in order to overlay custom svg drawing + programatically. **Caution**: The root g element is usually generated by dc.js internals, and resetting it might produce unpredictable result. + + **/ + _chart.g = function (_) { + if (!arguments.length) return _g; + _g = _; + return _chart; + }; + + /** + #### .mouseZoomable([boolean]) + Set or get mouse zoom capability flag (default: false). When turned on the chart will be zoomable through mouse wheel + . If range selector chart is also attached zooming will also update the range selection brush on associated range + selector chart. + + **/ + _chart.mouseZoomable = function (z) { + if (!arguments.length) return _mouseZoomable; + _mouseZoomable = z; + return _chart; + }; + + /** + #### .chartBodyG() + Retreive the svg group for the chart body. + **/ + _chart.chartBodyG = function (_) { + if (!arguments.length) return _chartBodyG; + _chartBodyG = _; + return _chart; + }; + + /** + #### .x([xScale]) - **mandatory** + Get or set the x scale. x scale could be any [d3 quatitive scales](https://github.com/mbostock/d3/wiki/Quantitative-Scales). + For example a time scale for histogram or a linear/ordinal scale for visualizing data distribution. + ```js + // set x to a linear scale + chart.x(d3.scale.linear().domain([-2500, 2500])) + // set x to a time scale to generate histogram + chart.x(d3.time.scale().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) + ``` + + **/ + _chart.x = function (_) { + if (!arguments.length) return _x; + _x = _; + _xOriginalDomain = _x.domain(); + return _chart; + }; + + _chart.xOriginalDomain = function () { + return _xOriginalDomain; + }; + + /** + #### .xUnits([xUnits function]) + Set or get the xUnits function. xUnits function is the coordinate grid chart uses to calculate number of data + projections on x axis such as number bars for a bar chart and number of dots for a line chart. This function is + expected to return an Javascript array of all data points on x axis. d3 time range functions d3.time.days, d3.time.months, + and d3.time.years are all valid xUnits function. dc.js also provides a few units function, see [Utilities](#util) + section for a list of built-in units functions. Default xUnits function is dc.units.integers. + ```js + // set x units to day for a histogram + chart.xUnits(d3.time.days); + // set x units to month for a histogram + chart.xUnits(d3.time.months); + ``` + Custom xUnits function can be easily created using as long as it follows the following inteface: + ```js + // units in integer + function(start, end, xDomain) { + // simply calculates how many integers in the domain + return Math.abs(end - start); + }; + + // fixed units + function(start, end, xDomain) { + // be aware using fixed units will disable the focus/zoom ability on the chart + return 1000; + }; + ``` + + **/ + _chart.xUnits = function (_) { + if (!arguments.length) return _xUnits; + _xUnits = _; + return _chart; + }; + + /** + #### .xAxis([xAxis]) + Set or get the x axis used by a particular coordinate grid chart instance. This function is most useful when certain x + axis customization is required. x axis in dc.js is simply an instance of + [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis) therefore it supports any valid d3 axis + manipulation. **Caution**: The x axis is typically generated by dc chart internal, resetting it might cause unexpected + outcome. + ```js + // customize x axis tick format + chart.xAxis().tickFormat(function(v) {return v + "%";}); + // customize x axis tick values + chart.xAxis().tickValues([0, 100, 200, 300]); + ``` + + **/ + _chart.xAxis = function (_) { + if (!arguments.length) return _xAxis; + _xAxis = _; + return _chart; + }; + + /** + #### .elasticX([boolean]) + Turn on/off elastic x axis. If x axis elasticity is turned on, then the grid chart will attempt to generate and + recalculate x axis range whenever redraw event is triggered. + + **/ + _chart.elasticX = function (_) { + if (!arguments.length) return _xElasticity; + _xElasticity = _; + return _chart; + }; + + /** + #### .xAxisPadding([padding]) + Set or get x axis padding when elastic x axis is turned on. The padding will be added to both end of the x axis if and + only if elasticX is turned on otherwise it will be simply ignored. + + * padding - could be integer or percentage in string (e.g. "10%"). Padding can be applied to number or date. + When padding with date, integer represents number of days being padded while percentage string will be treated + as number. + + **/ + _chart.xAxisPadding = function (_) { + if (!arguments.length) return _xAxisPadding; + _xAxisPadding = _; + return _chart; + }; + + _chart.xUnitCount = function () { + if (_unitCount === undefined) { + var units = _chart.xUnits()(_chart.x().domain()[0], _chart.x().domain()[1], _chart.x().domain()); + + if (units instanceof Array) + _unitCount = units.length; + else + _unitCount = units; + } + + return _unitCount; + }; + + _chart.isOrdinal = function () { + return _chart.xUnits() === dc.units.ordinal; + }; + + function prepareXAxis(g) { + if (_chart.elasticX() && !_chart.isOrdinal()) { + _x.domain([_chart.xAxisMin(), _chart.xAxisMax()]); + } + else if (_chart.isOrdinal() && _x.domain().length===0) { + var orderedData = _chart.computeOrderedGroups(_chart.data()); + _x.domain(orderedData.map(_chart.keyAccessor())); + } + + if (_chart.isOrdinal()) { + _x.rangeBands([0,_chart.xAxisLength()],_rangeBandPadding,_outerRangeBandPadding); + } else { + _x.range([0, _chart.xAxisLength()]); + } + + _xAxis = _xAxis.scale(_chart.x()).orient("bottom"); + + renderVerticalGridLines(g); + } + + _chart.renderXAxis = function (g) { + var axisXG = g.selectAll("g.x"); + + if (axisXG.empty()) + axisXG = g.append("g") + .attr("class", "axis x") + .attr("transform", "translate(" + _chart.margins().left + "," + _chart.xAxisY() + ")"); + + var axisXLab = g.selectAll("text."+X_AXIS_LABEL_CLASS); + if (axisXLab.empty() && _chart.xAxisLabel()) + axisXLab = g.append('text') + .attr("transform", "translate(" + (_chart.margins().left + _chart.xAxisLength() / 2) + "," + (_chart.height() - _xAxisLabelPadding) + ")") + .attr('class', X_AXIS_LABEL_CLASS) + .attr('text-anchor', 'middle') + .text(_chart.xAxisLabel()); + if (_chart.xAxisLabel() && axisXLab.text() != _chart.xAxisLabel()) + axisYLab.text(_chart.xAxisLabel()); + + dc.transition(axisXG, _chart.transitionDuration()) + .call(_xAxis); + }; + + function renderVerticalGridLines(g) { + var gridLineG = g.selectAll("g." + VERTICAL_CLASS); + + if (_renderVerticalGridLine) { + if (gridLineG.empty()) + gridLineG = g.insert("g", ":first-child") + .attr("class", GRID_LINE_CLASS + " " + VERTICAL_CLASS) + .attr("transform", "translate(" + _chart.yAxisX() + "," + _chart.margins().top + ")"); + + var ticks = _xAxis.tickValues() ? _xAxis.tickValues() : _x.ticks(_xAxis.ticks()[0]); + + var lines = gridLineG.selectAll("line") + .data(ticks); + + // enter + var linesGEnter = lines.enter() + .append("line") + .attr("x1", function (d) { + return _x(d); + }) + .attr("y1", _chart.xAxisY() - _chart.margins().top) + .attr("x2", function (d) { + return _x(d); + }) + .attr("y2", 0) + .attr("opacity", 0); + dc.transition(linesGEnter, _chart.transitionDuration()) + .attr("opacity", 1); + + // update + dc.transition(lines, _chart.transitionDuration()) + .attr("x1", function (d) { + return _x(d); + }) + .attr("y1", _chart.xAxisY() - _chart.margins().top) + .attr("x2", function (d) { + return _x(d); + }) + .attr("y2", 0); + + // exit + lines.exit().remove(); + } + else { + gridLineG.selectAll("line").remove(); + } + } + + _chart.xAxisY = function () { + return (_chart.height() - _chart.margins().bottom); + }; + + _chart.xAxisLength = function () { + return _chart.effectiveWidth(); + }; + + _chart.xAxisLabel = function (_,pad) { + if (!arguments.length) return _xAxisLabel; + _xAxisLabel = _; + _chart.margins().bottom -= _xAxisLabelPadding; + _xAxisLabelPadding = (pad===undefined) ? DEFAULT_AXIS_LABLEL_PADDING : pad; + _chart.margins().bottom += _xAxisLabelPadding; + return _chart; + }; + + function prepareYAxis(g) { + if (_y === undefined || _chart.elasticY()) { + _y = d3.scale.linear(); + _y.domain([_chart.yAxisMin(), _chart.yAxisMax()]).rangeRound([_chart.yAxisHeight(), 0]); + } + + _y.range([_chart.yAxisHeight(), 0]); + _yAxis = _yAxis.scale(_y).orient("left"); + + renderHorizontalGridLines(g); + } + + _chart.renderYAxis = function (g) { + var axisYG = g.selectAll("g.y"); + if (axisYG.empty()) + axisYG = g.append("g") + .attr("class", "axis y") + .attr("transform", "translate(" + _chart.yAxisX() + "," + _chart.margins().top + ")"); + + var axisYLab = g.selectAll("text."+Y_AXIS_LABEL_CLASS); + if (axisYLab.empty() && _chart.yAxisLabel()) + axisYLab = g.append('text') + .attr("transform", "translate(" + _yAxisLabelPadding + "," + (_chart.margins().top + _chart.yAxisHeight()/2) + "),rotate(-90)") + .attr('class', Y_AXIS_LABEL_CLASS) + .attr('text-anchor', 'middle') + .text(_chart.yAxisLabel()); + if (_chart.yAxisLabel() && axisYLab.text() != _chart.yAxisLabel()) + axisYLab.text(_chart.yAxisLabel()); + + dc.transition(axisYG, _chart.transitionDuration()) + .call(_yAxis); + }; + + + function renderHorizontalGridLines(g) { + var gridLineG = g.selectAll("g." + HORIZONTAL_CLASS); + + if (_renderHorizontalGridLine) { + var ticks = _yAxis.tickValues() ? _yAxis.tickValues() : _y.ticks(_yAxis.ticks()[0]); + + if (gridLineG.empty()) + gridLineG = g.insert("g", ":first-child") + .attr("class", GRID_LINE_CLASS + " " + HORIZONTAL_CLASS) + .attr("transform", "translate(" + _chart.yAxisX() + "," + _chart.margins().top + ")"); + + var lines = gridLineG.selectAll("line") + .data(ticks); + + // enter + var linesGEnter = lines.enter() + .append("line") + .attr("x1", 1) + .attr("y1", function (d) { + return _y(d); + }) + .attr("x2", _chart.xAxisLength()) + .attr("y2", function (d) { + return _y(d); + }) + .attr("opacity", 0); + dc.transition(linesGEnter, _chart.transitionDuration()) + .attr("opacity", 1); + + // update + dc.transition(lines, _chart.transitionDuration()) + .attr("x1", 1) + .attr("y1", function (d) { + return _y(d); + }) + .attr("x2", _chart.xAxisLength()) + .attr("y2", function (d) { + return _y(d); + }); + + // exit + lines.exit().remove(); + } + else { + gridLineG.selectAll("line").remove(); + } + } + + _chart.yAxisX = function () { + return _chart.margins().left; + }; + + _chart.yAxisLabel = function (_,pad) { + if (!arguments.length) return _yAxisLabel; + _yAxisLabel = _; + _chart.margins().left -= _yAxisLabelPadding; + _yAxisLabelPadding = (pad===undefined) ? DEFAULT_AXIS_LABLEL_PADDING : pad; + _chart.margins().left += _yAxisLabelPadding; + return _chart; + }; + + /** + #### .y([yScale]) + Get or set the y scale. y scale is typically automatically generated by the chart implementation. + + **/ + _chart.y = function (_) { + if (!arguments.length) return _y; + _y = _; + return _chart; + }; + + /** + #### .yAxis([yAxis]) + Set or get the y axis used by a particular coordinate grid chart instance. This function is most useful when certain y + axis customization is required. y axis in dc.js is simply an instance + of [d3 axis object](https://github.com/mbostock/d3/wiki/SVG-Axes#wiki-_axis) therefore it supports any valid d3 axis + manipulation. **Caution**: The y axis is typically generated by dc chart internal, resetting it might cause unexpected + outcome. + ```js + // customize y axis tick format + chart.yAxis().tickFormat(function(v) {return v + "%";}); + // customize y axis tick values + chart.yAxis().tickValues([0, 100, 200, 300]); + ``` + + **/ + _chart.yAxis = function (y) { + if (!arguments.length) return _yAxis; + _yAxis = y; + return _chart; + }; + + /** + #### .elasticY([boolean]) + Turn on/off elastic y axis. If y axis elasticity is turned on, then the grid chart will attempt to generate and recalculate + y axis range whenever redraw event is triggered. + + **/ + _chart.elasticY = function (_) { + if (!arguments.length) return _yElasticity; + _yElasticity = _; + return _chart; + }; + + /** + #### .renderHorizontalGridLines([boolean]) + Turn on/off horizontal grid lines. + + **/ + _chart.renderHorizontalGridLines = function (_) { + if (!arguments.length) return _renderHorizontalGridLine; + _renderHorizontalGridLine = _; + return _chart; + }; + + /** + #### .renderVerticalGridLines([boolean]) + Turn on/off vertical grid lines. + + **/ + _chart.renderVerticalGridLines = function (_) { + if (!arguments.length) return _renderVerticalGridLine; + _renderVerticalGridLine = _; + return _chart; + }; + + _chart.xAxisMin = function () { + var min = d3.min(_chart.data(), function (e) { + return _chart.keyAccessor()(e); + }); + return dc.utils.subtract(min, _xAxisPadding); + }; + + _chart.xAxisMax = function () { + var max = d3.max(_chart.data(), function (e) { + return _chart.keyAccessor()(e); + }); + return dc.utils.add(max, _xAxisPadding); + }; + + _chart.yAxisMin = function () { + var min = d3.min(_chart.data(), function (e) { + return _chart.valueAccessor()(e); + }); + return dc.utils.subtract(min, _yAxisPadding); + }; + + _chart.yAxisMax = function () { + var max = d3.max(_chart.data(), function (e) { + return _chart.valueAccessor()(e); + }); + return dc.utils.add(max, _yAxisPadding); + }; + + /** + #### .yAxisPadding([padding]) + if elasticY is turned on otherwise it will be simply ignored. + Set or get y axis padding when elastic y axis is turned on. The padding will be added to the top of the y axis if and only + + * padding - could be integer or percentage in string (e.g. "10%"). Padding can be applied to number or date. + When padding with date, integer represents number of days being padded while percentage string will be treated + as number. + + **/ + _chart.yAxisPadding = function (_) { + if (!arguments.length) return _yAxisPadding; + _yAxisPadding = _; + return _chart; + }; + + _chart.yAxisHeight = function () { + return _chart.effectiveHeight(); + }; + + /** + #### .round([rounding function]) + Set or get the rounding function for x axis. Rounding is mainly used to provide stepping capability when in place + selection based filter is enable. + ```js + // set x unit round to by month, this will make sure range selection brash will + // extend on a month-by-month basis + chart.round(d3.time.month.round); + ``` + + **/ + _chart.round = function (_) { + if (!arguments.length) return _round; + _round = _; + return _chart; + }; + + _chart._rangeBandPadding = function (_) { + if (!arguments.length) return _rangeBandPadding; + _rangeBandPadding = _; + return _chart; + }; + + _chart._outerRangeBandPadding = function (_) { + if (!arguments.length) return _outerRangeBandPadding; + _outerRangeBandPadding = _; + return _chart; + }; + + dc.override(_chart, "filter", function (_) { + if (!arguments.length) return _chart._filter(); + + _chart._filter(_); + + if (_) { + _chart.brush().extent(_); + } else { + _chart.brush().clear(); + } + + return _chart; + }); + + _chart.brush = function (_) { + if (!arguments.length) return _brush; + _brush = _; + return _chart; + }; + + function brushHeight() { + return _chart.xAxisY() - _chart.margins().top; + } + + _chart.renderBrush = function (g) { + if (_chart.isOrdinal()) + _brushOn = false; + + if (_brushOn) { + _brush.on("brush", _chart._brushing); + _brush.on("brushstart", _chart._disableMouseZoom); + _brush.on("brushend", configureMouseZoom); + + var gBrush = g.append("g") + .attr("class", "brush") + .attr("transform", "translate(" + _chart.margins().left + "," + _chart.margins().top + ")") + .call(_brush.x(_chart.x())); + gBrush.selectAll("rect").attr("height", brushHeight()); + gBrush.selectAll(".resize").append("path").attr("d", _chart.resizeHandlePath); + + if (_chart.hasFilter()) { + _chart.redrawBrush(g); + } + } + }; + + _chart.extendBrush = function () { + var extent = _brush.extent(); + if (_chart.round()) { + extent[0] = extent.map(_chart.round())[0]; + extent[1] = extent.map(_chart.round())[1]; + + _g.select(".brush") + .call(_brush.extent(extent)); + } + return extent; + }; + + _chart.brushIsEmpty = function (extent) { + return _brush.empty() || !extent || extent[1] <= extent[0]; + }; + + _chart._brushing = function() { + var extent = _chart.extendBrush(); + + _chart.redrawBrush(_g); + + if (_chart.brushIsEmpty(extent)) { + dc.events.trigger(function () { + _chart.filter(null); + dc.redrawAll(_chart.chartGroup()); + }, dc.constants.EVENT_DELAY); + } else { + var rangedFilter = dc.filters.RangedFilter(extent[0], extent[1]); + + dc.events.trigger(function () { + _chart.replaceFilter(rangedFilter); + dc.redrawAll(_chart.chartGroup()); + }, dc.constants.EVENT_DELAY); + } + }; + + _chart.redrawBrush = function (g) { + if (_brushOn) { + if (_chart.filter() && _chart.brush().empty()) + _chart.brush().extent(_chart.filter()); + + var gBrush = g.select("g.brush"); + gBrush.call(_chart.brush().x(_chart.x())); + gBrush.selectAll("rect").attr("height", brushHeight()); + } + + _chart.fadeDeselectedArea(); + }; + + _chart.fadeDeselectedArea = function () { + // do nothing, sub-chart should override this function + }; + + // borrowed from Crossfilter example + _chart.resizeHandlePath = function (d) { + var e = +(d == "e"), x = e ? 1 : -1, y = brushHeight() / 3; + /*jshint -W014 */ + return "M" + (0.5 * x) + "," + y + + "A6,6 0 0 " + e + " " + (6.5 * x) + "," + (y + 6) + + "V" + (2 * y - 6) + + "A6,6 0 0 " + e + " " + (0.5 * x) + "," + (2 * y) + + "Z" + + "M" + (2.5 * x) + "," + (y + 8) + + "V" + (2 * y - 8) + + "M" + (4.5 * x) + "," + (y + 8) + + "V" + (2 * y - 8); + /*jshint +W014 */ + }; + + function getClipPathId() { + return _chart.anchorName() + "-clip"; + } + + /** + #### .clipPadding([padding]) + Get or set padding in pixel for clip path. Once set padding will be applied evenly to top, left, right, and bottom padding + when clip path is generated. If set to zero, then the clip area will be exactly the chart body area minus the margins. + Default: 5 + + **/ + _chart.clipPadding = function (p) { + if (!arguments.length) return _clipPadding; + _clipPadding = p; + return _chart; + }; + + function generateClipPath() { + var defs = dc.utils.appendOrSelect(_parent, "defs"); + + var chartBodyClip = dc.utils.appendOrSelect(defs, "clipPath").attr("id", getClipPathId()); + + var padding = _clipPadding * 2; + + dc.utils.appendOrSelect(chartBodyClip, "rect") + .attr("width", _chart.xAxisLength() + padding) + .attr("height", _chart.yAxisHeight() + padding); + } + + _chart._preprocessData = function() {}; + + _chart.doRender = function () { + _chart.resetSvg(); + + _chart._preprocessData(); + + _chart._generateG(); + generateClipPath(); + + drawChart(true); + + configureMouseZoom(); + + return _chart; + }; + + _chart.doRedraw = function () { + _chart._preprocessData(); + + drawChart(false); + + return _chart; + }; + + function drawChart (render) { + prepareXAxis(_chart.g()); + prepareYAxis(_chart.g()); + + _chart.plotData(); + + if (_chart.elasticX() || _refocused || render) + _chart.renderXAxis(_chart.g()); + + if (_chart.elasticY() || render) + _chart.renderYAxis(_chart.g()); + + if (render) + _chart.renderBrush(_chart.g()); + else + _chart.redrawBrush(_chart.g()); + } + + function configureMouseZoom () { + if (_mouseZoomable) + _chart._enableMouseZoom(); + else + _chart._disableMouseZoom(); + } + + _chart._enableMouseZoom = function () { + _zoom.x(_chart.x()) + .scaleExtent(_zoomScale) + .size([_chart.width(),_chart.height()]); + _chart.root().call(_zoom); + }; + + _chart._disableMouseZoom = function () { + _chart.root().call(_nullZoom); + }; + + function zoomHandler() { + _refocused = true; + if (_zoomOutRestrict) { + _chart.x().domain(constrainRange(_chart.x().domain(), _xOriginalDomain)); + if (_rangeChart) { + _chart.x().domain(constrainRange(_chart.x().domain(), _rangeChart.x().domain())); + } + } + + var domain = _chart.x().domain(); + var domFilter = dc.filters.RangedFilter(domain[0], domain[1]); + + _chart.replaceFilter(domFilter); + _chart.rescale(); + _chart.redraw(); + + if (_rangeChart && !rangesEqual(_chart.filter(), _rangeChart.filter())) { + dc.events.trigger( function () { + _rangeChart.replaceFilter(domFilter); + _rangeChart.redraw(); + }); + } + + _chart._invokeZoomedListener(); + + dc.events.trigger(function () { + dc.redrawAll(_chart.chartGroup()); + }, dc.constants.EVENT_DELAY); + + _refocused = !rangesEqual(domain, _xOriginalDomain); + } + + function constrainRange(range, constraint) { + var constrainedRange = []; + constrainedRange[0] = d3.max([range[0], constraint[0]]); + constrainedRange[1] = d3.min([range[1], constraint[1]]); + return constrainedRange; + } + + /** + #### .focus([range]) + Zoom this chart to focus on the given range. The given range should be an array containing only 2 element([start, end]) defining an range in x domain. If the range is not given or set to null, then the zoom will be reset. _For focus to work elasticX has to be turned off otherwise focus will be ignored._ + ```js + chart.renderlet(function(chart){ + // smooth the rendering through event throttling + dc.events.trigger(function(){ + // focus some other chart to the range selected by user on this chart + someOtherChart.focus(chart.filter()); + }); + }) + ``` + + **/ + _chart.focus = function (range) { + if (hasRangeSelected(range)) + _chart.x().domain(range); + else + _chart.x().domain(_xOriginalDomain); + + _zoom.x(_chart.x()); + zoomHandler(); + }; + + _chart.refocused = function () { + return _refocused; + }; + + _chart.focusChart = function (c) { + if (!arguments.length) return _focusChart; + _focusChart = c; + _chart.on("filtered", function (chart) { + if (!rangesEqual(chart.filter(), _focusChart.filter())) { + dc.events.trigger(function () { + _focusChart.focus(chart.filter()); + }); + } + }); + return _chart; + }; + + function rangesEqual(range1, range2) { + if (!range1 && !range2) { + return true; + } + + if (range1.length === 0 && range2.length === 0) { + return true; + } + + if (range1 && range2 && + range1[0].valueOf() === range2[0].valueOf() && + range1[1].valueOf() === range2[1].valueOf()) { + return true; + } + + return false; + } + + /** + #### .brushOn([boolean]) + Turn on/off the brush based in-place range filter. When the brush is on then user will be able to simply drag the mouse + across the chart to perform range filtering based on the extend of the brush. However turning on brush filter will essentially + disable other interactive elements on the chart such as the highlighting, tool-tip, and reference lines on a chart. Zooming will still + be possible if enabled, but only via scrolling (panning will be disabled.) Default value is "true". + + **/ + _chart.brushOn = function (_) { + if (!arguments.length) return _brushOn; + _brushOn = _; + return _chart; + }; + + function hasRangeSelected(range) { + return range instanceof Array && range.length > 1; + } + + return _chart; +}; + +/** +## # Color Chart [Abstract] +Color chart is an abstract chart functional class created to provide universal coloring support as a mix-in for any concrete +chart implementation. + +**/ + +dc.colorChart = function(_chart) { + var _colors = d3.scale.category20c(); + + var _colorAccessor = function(d) { return _chart.keyAccessor()(d); }; + + var _colorCalculator = function(value) { + return _colors(value,_chart); + }; + + /** + #### .colors([colorScale]) + Retrieve current color scale or set a new color scale. This methods accepts any + function the operate like a d3 scale. If not set the default is + `d3.scale.category20c()`. + ```js + // alternate categorical scale + chart.colors(d3.scale.category20b()); + + // ordinal scale + chart.colors(d3.scale.ordinal().range(['red','green','blue']); + // convience method, the same as above + chart.ordinalColors(['red','green','blue']); + + // set a linear scale + chart.linearColors(["#4575b4", "#ffffbf", "#a50026"]); + ``` + **/ + _chart.colors = function(_) { + if (!arguments.length) return _colors; + if (_ instanceof Array) _colors = d3.scale.quantize().range(_); // depricated legacy support, note: this fails for ordinal domains + else _colors = _; + return _chart; + }; + + /** + #### .ordinalColors(r) + Convenience method to set the color scale to d3.scale.ordinal with range `r`. + + **/ + _chart.ordinalColors = function(r) { + return _chart.colors(d3.scale.ordinal().range(r)); + }; + + /** + #### .linearColors(r) + Convenience method to set the color scale to an Hcl interpolated linear scale with range `r`. + + **/ + _chart.linearColors = function(r) { + return _chart.colors(d3.scale.linear() + .range(r) + .interpolate(d3.interpolateHcl)); + }; + + /** + #### .colorAccessor([colorAccessorFunction]) + Set or get color accessor function. This function will be used to map a data point on crossfilter group to a specific + color value on the color scale. Default implementation of this function simply returns the next color on the scale using + the index of a group. + ```js + // default index based color accessor + .colorAccessor(function(d, i){return i;}) + // color accessor for a multi-value crossfilter reduction + .colorAccessor(function(d){return d.value.absGain;}) + ``` + **/ + _chart.colorAccessor = function(_){ + if(!arguments.length) return _colorAccessor; + _colorAccessor = _; + return _chart; + }; + + /** + #### .colorDomain([domain]) + Set or get the current domain for the color mapping function. The domain must be supplied as an array. + + Note: previously this method accepted a callback function. Instead you may use a custom scale set by `.colors`. + + **/ + _chart.colorDomain = function(_){ + if(!arguments.length) return _colors.domain(); + _colors.domain(_); + return _chart; + }; + + /** + #### .calculateColorDomain() + Set the domain by determining the min and max values as retrived by `.colorAccessor` over the chart's dataset. + + **/ + _chart.calculateColorDomain = function () { + var newDomain = [d3.min(_chart.data(), _chart.colorAccessor()), + d3.max(_chart.data(), _chart.colorAccessor())]; + _colors.domain(newDomain); + }; + + /** + #### .getColor(d [, i]) + Get the color for the datum d and counter i. This is used internaly by charts to retrieve a color. + + **/ + _chart.getColor = function(d, i){ + return _colorCalculator(_colorAccessor(d, i)); + }; + + _chart.colorCalculator = function(_){ + if(!arguments.length) return _colorCalculator; + _colorCalculator = _; + return _chart; + }; + + return _chart; +}; + +/** +## # Stackable Chart [Abstract] +Stackable chart is an abstract chart introduced to provide cross-chart support of stackability. Concrete implementation of +charts can then selectively mix-in this capability. + +**/ +dc.stackableChart = function (_chart) { + var _groupStack = new dc.utils.GroupStack(); + var _stackLayout = d3.layout.stack() + .offset("zero") + .order("default") + .values(function (d) { + return d.points; + }); + var _allGroups; + var _allValueAccessors; + var _allKeyAccessors; + var _stackLayers; + var _hiddenStacks = []; + + var _hidableStacks = false; + + /** + #### .stack(group[, name, accessor]) + Stack a new crossfilter group into this chart with optionally a custom value accessor. All stacks in the same chart will + share the same key accessor therefore share the same set of keys. In more concrete words, imagine in a stacked bar chart + all bars will be positioned using the same set of keys on the x axis while stacked vertically. If name is specified then + it will be used to generate legend label. + ```js + // stack group using default accessor + chart.stack(valueSumGroup) + // stack group using custom accessor + .stack(avgByDayGroup, function(d){return d.value.avgByDay;}); + ``` + + **/ + _chart.stack = function (group, name, accessor) { + if(!arguments.length) + _groupStack.clear(); + + _groupStack.setDefaultAccessor(_chart.valueAccessor()); + + if (typeof name === 'string') { + _chart._setGroupName(group, name, accessor); + _groupStack.addNamedGroup(group, name, accessor); + } + else { + accessor = name; + _groupStack.addGroup(group, accessor); + } + + _chart.expireCache(); + + return _chart; + }; + + /** + #### .hidableStacks([boolean]) + Allow named stacks to be hidden or shown by clicking on legend items. + This does not affect the behavior of hideStack or showStack. + + **/ + _chart.hidableStacks = function(_) { + if (!arguments.length) return _hidableStacks; + _hidableStacks = _; + return _chart; + }; + + /** + #### .hideStack(name) + Hide all stacks on the chart with the given name. + The chart must be re-rendered for this change to appear. + + **/ + _chart.hideStack = function (stackName) { + _groupStack.hideGroups(stackName, _chart._getGroupName(_chart.group()) == stackName); + }; + + /** + #### .showStack(name) + Show all stacks on the chart with the given name. + The chart must be re-rendered for this change to appear. + + **/ + _chart.showStack = function (stackName) { + _groupStack.showGroups(stackName, _chart._getGroupName(_chart.group()) == stackName); + }; + + _chart.expireCache = function () { + _allGroups = null; + _allValueAccessors = null; + _allKeyAccessors = null; + _stackLayers = null; + return _chart; + }; + + _chart.allGroups = function () { + if (_allGroups === null) { + _allGroups = []; + + _allGroups.push(_chart.group()); + + for (var i = 0; i < _groupStack.size(); ++i) + _allGroups.push(_groupStack.getGroupByIndex(i)); + } + + return _allGroups; + }; + + _chart.allValueAccessors = function () { + if (_allValueAccessors === null) { + _allValueAccessors = []; + + _allValueAccessors.push(_chart.valueAccessor()); + + for (var i = 0; i < _groupStack.size(); ++i) + _allValueAccessors.push(_groupStack.getAccessorByIndex(i)); + } + + return _allValueAccessors; + }; + + _chart.getValueAccessorByIndex = function (groupIndex) { + return _chart.allValueAccessors()[groupIndex]; + }; + + _chart.yAxisMin = function () { + var min, all = flattenStack(); + + min = d3.min(all, function (p) { + return (p.y + p.y0 < p.y0) ? (p.y + p.y0) : p.y0; + }); + + min = dc.utils.subtract(min, _chart.yAxisPadding()); + + return min; + }; + + _chart.yAxisMax = function () { + var max, all = flattenStack(); + + max = d3.max(all, function (p) { + return p.y + p.y0; + }); + + max = dc.utils.add(max, _chart.yAxisPadding()); + + return max; + }; + + function flattenStack() { + var all = []; + + if (_chart.x()) { + var xDomain = _chart.x().domain(); + var test; + if(_chart.isOrdinal()) { + var domainSet = d3.set(xDomain); + test = function(p) { + return domainSet.has(p.x); + }; + } + else { + test = function(p) { + return p.x >= xDomain[0] && p.x <= xDomain[xDomain.length-1]; + }; + } + _chart.stackLayers().forEach(function (e) { + e.points.forEach(function (p) { + if (test(p)) + all.push(p); + }); + }); + } else { + _chart.stackLayers().forEach(function (e) { + all = all.concat(e.points); + }); + } + + return all; + } + + _chart.allKeyAccessors = function () { + if (_allKeyAccessors === null) { + _allKeyAccessors = []; + + _allKeyAccessors.push(_chart.keyAccessor()); + + for (var i = 0; i < _groupStack.size(); ++i) + _allKeyAccessors.push(_chart.keyAccessor()); + } + + return _allKeyAccessors; + }; + + _chart.getKeyAccessorByIndex = function (groupIndex) { + return _chart.allKeyAccessors()[groupIndex]; + }; + + _chart.xAxisMin = function () { + var min = _chart.allGroups().reduce(function(min,group,groupIndex) { + var m = dc.utils.groupMin(group, _chart.getKeyAccessorByIndex(groupIndex)); + return (min === null || min > m) ? m : min; + },null); + + return dc.utils.subtract(min, _chart.xAxisPadding()); + }; + + _chart.xAxisMax = function () { + var max = _chart.allGroups().reduce(function(max,group,groupIndex) { + var m = dc.utils.groupMax(group, _chart.getKeyAccessorByIndex(groupIndex)); + return (max === null || max < m) ? m : max; + },null); + + return dc.utils.add(max, _chart.xAxisPadding()); + }; + + function calculateDataPointMatrix(group, groupIndex) { + group.all().forEach(function(d, dataIndex) { + var key = _chart.getKeyAccessorByIndex(groupIndex)(d); + var value = _chart.getValueAccessorByIndex(groupIndex)(d); + _groupStack.setDataPoint(groupIndex, dataIndex, {data: d, x: key, y: value, layer: groupIndex}); + }); + } + + _chart.calculateDataPointMatrixForAll = function () { + _groupStack.clearDataLayers(); + _chart.allGroups().forEach(calculateDataPointMatrix); + }; + + _chart.getChartStack = function () { + return _groupStack; + }; + + dc.override(_chart, "valueAccessor", function (_) { + if (!arguments.length) return _chart._valueAccessor(); + _chart.expireCache(); + return _chart._valueAccessor(_); + }); + + dc.override(_chart, "keyAccessor", function (_) { + if (!arguments.length) return _chart._keyAccessor(); + _chart.expireCache(); + return _chart._keyAccessor(_); + }); + + /** + #### .title([stackName], [titleFunction]) + Set or get the title function. Chart class will use this function to render svg title (usually interpreted by browser + as tooltips) for each child element in the chart, i.e. a slice in a pie chart or a bubble in a bubble chart. Almost + every chart supports title function however in grid coordinate chart you need to turn off brush in order to use title + otherwise the brush layer will block tooltip trigger. + + If the first argument is a stack name, the title function will get or set the title for that stack. If stackName + is not provided, the first stack is implied. + ```js + // set a title function on "first stack" + chart.title("first stack", function(d) { return d.key + ": " + d.value; }); + // get a title function from "second stack" + var secondTitleFunction = chart.title("second stack"); + ); + ``` + + **/ + dc.override(_chart, "title", function (stackName, titleAccessor) { + if (!stackName) return _chart._title(); + + var firstStack = _chart.group() && stackName === _chart._getGroupName(_chart.group()); + + if (typeof stackName === 'function') { + return _chart._title(stackName); + } + else if (!titleAccessor) { + if (firstStack) + return _chart._title(); + else + return _groupStack.getTitle(stackName); + } + + if (firstStack) + return _chart._title(titleAccessor); + else + _groupStack.setTitle(stackName, titleAccessor); + + return _chart; + }); + + _chart.getTitleOfVisibleByIndex = function (index) { + return _chart.title(_groupStack.getNameOfVisibleByIndex(index - 1)) || _chart.title(); + }; + + _chart.stackLayout = function (stack) { + if (!arguments.length) return _stackLayout; + _stackLayout = stack; + return _chart; + }; + + _chart.stackLayers = function (_) { + if (!arguments.length) { + if (_stackLayers === null) { + _chart.calculateDataPointMatrixForAll(); + var layers = _groupStack.toLayers(); + if (layers.length === 0) return []; + _stackLayers = _chart.stackLayout()(layers); + } + return _stackLayers; + } else { + _stackLayers = _; + } + }; + + _chart._layerColorAccessor = function(d){return d.layer === undefined ? d.index : d.layer;}; + _chart.colorAccessor(_chart._layerColorAccessor); + + _chart.legendables = function () { + return _chart.allGroups().map(function (g, i) { + return dc.utils.createLegendable(_chart, g, _chart.getValueAccessorByIndex(i), _chart.colorCalculator()(i)); + }); + }; + + _chart.isLegendableHidden = function (d) { + return _hiddenStacks.indexOf(d.name) !== -1; + }; + + _chart.legendToggle = function (d) { + if(_hidableStacks) { + var index; + if ((index = _hiddenStacks.indexOf(d.name)) !== -1) { + _hiddenStacks.splice(index, 1); + _chart.showStack(d.name); + } + else { + _hiddenStacks.push(d.name); + _chart.hideStack(d.name); + } + } + _chart.render(); + }; + + return _chart; +}; + +/** +## # Abstract Bubble Chart [Abstract] < [Color Chart](#color-chart) +An abstraction provides reusable functionalities for any chart that needs to visualize data using bubbles. + +**/ +dc.abstractBubbleChart = function (_chart) { + var _maxBubbleRelativeSize = 0.3; + var _minRadiusWithLabel = 10; + + _chart.BUBBLE_NODE_CLASS = "node"; + _chart.BUBBLE_CLASS = "bubble"; + _chart.MIN_RADIUS = 10; + + _chart = dc.colorChart(_chart); + + _chart.renderLabel(true); + _chart.renderTitle(false); + + _chart.data(function(group) { + return group.top(Infinity); + }); + + var _r = d3.scale.linear().domain([0, 100]); + + var _rValueAccessor = function (d) { + return d.r; + }; + + /** + #### .r([bubbleRadiusScale]) + Get or set bubble radius scale. By default bubble chart uses ```d3.scale.linear().domain([0, 100])``` as it's r scale . + + **/ + _chart.r = function (_) { + if (!arguments.length) return _r; + _r = _; + return _chart; + }; + + /** + #### .radiusValueAccessor([radiusValueAccessor]) + Get or set the radius value accessor function. The radius value accessor function if set will be used to retrieve data value + for each and every bubble rendered. The data retrieved then will be mapped using r scale to be used as the actual bubble + radius. In other words, this allows you to encode a data dimension using bubble size. + + **/ + _chart.radiusValueAccessor = function (_) { + if (!arguments.length) return _rValueAccessor; + _rValueAccessor = _; + return _chart; + }; + + _chart.rMin = function () { + var min = d3.min(_chart.data(), function (e) { + return _chart.radiusValueAccessor()(e); + }); + return min; + }; + + _chart.rMax = function () { + var max = d3.max(_chart.data(), function (e) { + return _chart.radiusValueAccessor()(e); + }); + return max; + }; + + _chart.bubbleR = function (d) { + var value = _chart.radiusValueAccessor()(d); + var r = _chart.r()(value); + if (isNaN(r) || value <= 0) + r = 0; + return r; + }; + + var labelFunction = function (d) { + return _chart.label()(d); + }; + + var labelOpacity = function (d) { + return (_chart.bubbleR(d) > _minRadiusWithLabel) ? 1 : 0; + }; + + _chart.doRenderLabel = function (bubbleGEnter) { + if (_chart.renderLabel()) { + var label = bubbleGEnter.select("text"); + + if (label.empty()) { + label = bubbleGEnter.append("text") + .attr("text-anchor", "middle") + .attr("dy", ".3em") + .on("click", _chart.onClick); + } + + label + .attr("opacity", 0) + .text(labelFunction); + dc.transition(label, _chart.transitionDuration()) + .attr("opacity", labelOpacity); + } + }; + + _chart.doUpdateLabels = function (bubbleGEnter) { + if (_chart.renderLabel()) { + var labels = bubbleGEnter.selectAll("text") + .text(labelFunction); + dc.transition(labels, _chart.transitionDuration()) + .attr("opacity", labelOpacity); + } + }; + + var titleFunction = function (d) { + return _chart.title()(d); + }; + + _chart.doRenderTitles = function (g) { + if (_chart.renderTitle()) { + var title = g.select("title"); + + if (title.empty()) + g.append("title").text(titleFunction); + } + }; + + _chart.doUpdateTitles = function (g) { + if (_chart.renderTitle()) { + g.selectAll("title").text(titleFunction); + } + }; + + /** + #### .minRadiusWithLabel([radius]) + Get or set the minimum radius for label rendering. If a bubble's radius is less than this value then no label will be rendered. + Default value: 10. + + **/ + _chart.minRadiusWithLabel = function (_) { + if (!arguments.length) return _minRadiusWithLabel; + _minRadiusWithLabel = _; + return _chart; + }; + + /** + #### .maxBubbleRelativeSize([relativeSize]) + Get or set the maximum relative size of a bubble to the length of x axis. This value is useful when the radius differences among + different bubbles are too great. Default value: 0.3 + + **/ + _chart.maxBubbleRelativeSize = function (_) { + if (!arguments.length) return _maxBubbleRelativeSize; + _maxBubbleRelativeSize = _; + return _chart; + }; + + _chart.fadeDeselectedArea = function () { + if (_chart.hasFilter()) { + _chart.selectAll("g." + _chart.BUBBLE_NODE_CLASS).each(function (d) { + if (_chart.isSelectedNode(d)) { + _chart.highlightSelected(this); + } else { + _chart.fadeDeselected(this); + } + }); + } else { + _chart.selectAll("g." + _chart.BUBBLE_NODE_CLASS).each(function (d) { + _chart.resetHighlight(this); + }); + } + }; + + _chart.isSelectedNode = function (d) { + return _chart.hasFilter(d.key); + }; + + _chart.onClick = function (d) { + var filter = d.key; + dc.events.trigger(function () { + _chart.filter(filter); + dc.redrawAll(_chart.chartGroup()); + }); + }; + + return _chart; +}; + +/** +## # Pie Chart [Concrete] < [Color Chart](#color-chart) < [Base Chart](#base-chart) +This chart is a concrete pie chart implementation usually used to visualize small number of categorical distributions. +Pie chart implementation uses keyAccessor to generate slices, and valueAccessor to calculate the size of each slice(key) +relatively to the total sum of all values. Slices are ordered by `.ordering` which defaults to sorting by key. + +Examples: + +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) + +#### dc.pieChart(parent[, chartGroup]) +Create a pie chart instance and attach it to the given parent element. + +Parameters: + +* parent : string - any valid d3 single selector representing typically a dom block element such + as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created pie chart instance + +```js +// create a pie chart under #chart-container1 element using the default global chart group +var chart1 = dc.pieChart("#chart-container1"); +// create a pie chart under #chart-container2 element using chart group A +var chart2 = dc.pieChart("#chart-container2", "chartGroupA"); +``` + +**/ +dc.pieChart = function (parent, chartGroup) { + var DEFAULT_MIN_ANGLE_FOR_LABEL = 0.5; + + var _sliceCssClass = "pie-slice"; + + var _radius, + _innerRadius = 0; + + var _g; + + var _minAngleForLabel = DEFAULT_MIN_ANGLE_FOR_LABEL; + + var _externalLabelRadius; + + var _chart = dc.capped(dc.colorChart(dc.baseChart({}))); + + _chart.colorAccessor(_chart.cappedKeyAccessor); + + _chart.title(function (d) { + return _chart.cappedKeyAccessor(d) + ": " + _chart.cappedValueAccessor(d); + }); + + /** + #### .slicesCap([cap]) + Get or set the maximum number of slices the pie chart will generate. The top slices are determined by + value from high to low. Other slices exeeding the cap will be rolled up into one single *Others* slice. + The resulting data will still be sorted by .ordering (default by key). + + **/ + _chart.slicesCap = _chart.cap; + + _chart.label(_chart.cappedKeyAccessor); + _chart.renderLabel(true); + + _chart.transitionDuration(350); + + _chart.doRender = function () { + _chart.resetSvg(); + + _g = _chart.svg() + .append("g") + .attr("transform", "translate(" + _chart.cx() + "," + _chart.cy() + ")"); + + drawChart(); + + return _chart; + }; + + function drawChart() { + // set radius on basis of chart dimension if missing + _radius = _radius ? _radius : d3.min([_chart.width(), _chart.height()]) /2; + + var arc = buildArcs(); + + var pie = pieLayout(); + var pieData = pie(_chart.data()); + + if (_g) { + var slices = _g.selectAll("g." + _sliceCssClass) + .data(pieData); + + createElements(slices, arc, pieData); + + updateElements(pieData, arc); + + removeElements(slices); + + highlightFilter(); + } + } + + function createElements(slices, arc, pieData) { + var slicesEnter = createSliceNodes(slices); + + createSlicePath(slicesEnter, arc); + + createTitles(slicesEnter); + + createLabels(pieData, arc); + } + + function createSliceNodes(slices) { + var slicesEnter = slices + .enter() + .append("g") + .attr("class", function (d, i) { + return _sliceCssClass + " _" + i; + }); + return slicesEnter; + } + + function createSlicePath(slicesEnter, arc) { + var slicePath = slicesEnter.append("path") + .attr("fill", fill) + .on("click", onClick) + .attr("d", function (d, i) { + return safeArc(d, i, arc); + }); + slicePath.transition() + .duration(_chart.transitionDuration()) + .attrTween("d", tweenPie); + } + + function createTitles(slicesEnter) { + if (_chart.renderTitle()) { + slicesEnter.append("title").text(function (d) { + return _chart.title()(d); + }); + } + } + + function positionLabels(labelsEnter, arc) { + dc.transition(labelsEnter, _chart.transitionDuration()) + .attr("transform", function (d) { + return labelPosition(d, arc); + }) + .attr("text-anchor", "middle") + .text(function (d) { + var data = d.data; + if (sliceHasNoData(data) || sliceTooSmall(d)) + return ""; + return _chart.label()(d.data); + }); + } + + function createLabels(pieData, arc) { + if (_chart.renderLabel()) { + var labels = _g.selectAll("text." + _sliceCssClass) + .data(pieData); + + labels.exit().remove(); + + var labelsEnter = labels + .enter() + .append("text") + .attr("class", function (d, i) { + var classes = _sliceCssClass + " _" + i; + if(_externalLabelRadius) + classes += " external"; + return classes; + }) + .on("click", onClick); + positionLabels(labelsEnter, arc); + } + } + + function updateElements(pieData, arc) { + updateSlicePaths(pieData, arc); + updateLabels(pieData, arc); + updateTitles(pieData); + } + + function updateSlicePaths(pieData, arc) { + var slicePaths = _g.selectAll("g." + _sliceCssClass) + .data(pieData) + .select("path") + .attr("d", function (d, i) { + return safeArc(d, i, arc); + }); + dc.transition(slicePaths, _chart.transitionDuration(), + function (s) { + s.attrTween("d", tweenPie); + }).attr("fill", fill); + } + + function updateLabels(pieData, arc) { + if (_chart.renderLabel()) { + var labels = _g.selectAll("text." + _sliceCssClass) + .data(pieData); + positionLabels(labels, arc); + } + } + + function updateTitles(pieData) { + if (_chart.renderTitle()) { + _g.selectAll("g." + _sliceCssClass) + .data(pieData) + .select("title") + .text(function (d) { + return _chart.title()(d.data); + }); + } + } + + function removeElements(slices) { + slices.exit().remove(); + } + + function highlightFilter() { + if (_chart.hasFilter()) { + _chart.selectAll("g." + _sliceCssClass).each(function (d) { + if (isSelectedSlice(d)) { + _chart.highlightSelected(this); + } else { + _chart.fadeDeselected(this); + } + }); + } else { + _chart.selectAll("g." + _sliceCssClass).each(function (d) { + _chart.resetHighlight(this); + }); + } + } + + /** + #### .innerRadius([innerRadius]) + Get or set the inner radius on a particular pie chart instance. If inner radius is greater than 0px then the pie chart + will be essentially rendered as a doughnut chart. Default inner radius is 0px. + + **/ + _chart.innerRadius = function (r) { + if (!arguments.length) return _innerRadius; + _innerRadius = r; + return _chart; + }; + + /** + #### .radius([radius]) + Get or set the radius on a particular pie chart instance. Default radius is 90px. + + **/ + _chart.radius = function (r) { + if (!arguments.length) return _radius; + _radius = r; + return _chart; + }; + + /** + #### .cx() + Get center x coordinate position. This function is **not chainable**. + + **/ + _chart.cx = function () { + return _chart.width() / 2; + }; + + /** + #### .cy() + Get center y coordinate position. This function is **not chainable**. + + **/ + _chart.cy = function () { + return _chart.height() / 2; + }; + + function buildArcs() { + return d3.svg.arc().outerRadius(_radius).innerRadius(_innerRadius); + } + + function isSelectedSlice(d) { + return _chart.hasFilter(_chart.cappedKeyAccessor(d.data)); + } + + _chart.doRedraw = function () { + drawChart(); + return _chart; + }; + + /** + #### .minAngelForLabel([minAngle]) + Get or set the minimal slice angle for label rendering. Any slice with a smaller angle will not render slice label. + Default min angel is 0.5. + **/ + _chart.minAngleForLabel = function (_) { + if (!arguments.length) return _minAngleForLabel; + _minAngleForLabel = _; + return _chart; + }; + + function pieLayout() { + return d3.layout.pie().sort(null).value(_chart.cappedValueAccessor); + } + + function sliceTooSmall(d) { + var angle = (d.endAngle - d.startAngle); + return isNaN(angle) || angle < _minAngleForLabel; + } + + function sliceHasNoData(d) { + return _chart.cappedValueAccessor(d) === 0; + } + + function tweenPie(b) { + b.innerRadius = _innerRadius; + var current = this._current; + if (isOffCanvas(current)) + current = {startAngle: 0, endAngle: 0}; + var i = d3.interpolate(current, b); + this._current = i(0); + return function (t) { + return safeArc(i(t), 0, buildArcs()); + }; + } + + function isOffCanvas(current) { + return !current || isNaN(current.startAngle) || isNaN(current.endAngle); + } + + function fill(d, i) { + return _chart.getColor(d.data, i); + } + + function onClick(d, i) { + _chart.onClick(d.data, i); + } + + function safeArc(d, i, arc) { + var path = arc(d, i); + if (path.indexOf("NaN") >= 0) + path = "M0,0"; + return path; + } + + /** + #### .externalLabels([radius]) + Position slice labels offset from the outer edge of the chart + + The given argument sets the radial offset. + */ + _chart.externalLabels = function(radius) { + if (arguments.length === 0) { + return _externalLabelRadius; + } else if(radius) { + _externalLabelRadius = radius; + } else { + _externalLabelRadius = undefined; + } + + return _chart; + }; + + function labelPosition(d, arc) { + var centroid; + if( _externalLabelRadius ) { + centroid = d3.svg.arc() + .outerRadius(_radius+_externalLabelRadius) + .innerRadius(_radius+_externalLabelRadius) + .centroid(d); + } else { + centroid = arc.centroid(d); + } + if (isNaN(centroid[0]) || isNaN(centroid[1])) { + return "translate(0,0)"; + } else { + return "translate(" + centroid + ")"; + } + } + + _chart.legendables = function() { + return _chart.data().map(function (d, i) { + var legendable = { name: d.key, data: d.value, others: d.others }; + legendable.color = _chart.getColor(d,i); + return legendable; + }); + }; + + _chart.getColor = function(d,i) { + return _chart.colorCalculator()(_chart.colorAccessor()(d, i)); + }; + + _chart.legendHighlight = function(d) { + highlightSliceFromLegendable(d, true); + }; + + _chart.legendReset = function(d) { + highlightSliceFromLegendable(d, false); + }; + + _chart.legendToggle = function(d) { + _chart.onClick({ key: d.name, others: d.others }); + }; + + function highlightSliceFromLegendable(legendable, highlighted) { + _chart.selectAll('g.pie-slice').each(function (d) { + if (legendable.name == d.data.key) { + d3.select(this).classed("highlight", highlighted); + } + }); + } + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Bar Chart [Concrete] < [Stackable Chart](#stackable-chart) < [CoordinateGrid Chart](#coordinate-grid-chart) +Concrete bar chart/histogram implementation. + +Examples: + +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) +* [Canadian City Crime Stats](http://nickqizhu.github.com/dc.js/crime/index.html) + +#### dc.barChart(parent[, chartGroup]) +Create a bar chart instance and attach it to the given parent element. + +Parameters: +* parent : string|compositeChart - any valid d3 single selector representing typically a dom block element such + as a div, or if this bar chart is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created bar chart instance + +```js +// create a bar chart under #chart-container1 element using the default global chart group +var chart1 = dc.barChart("#chart-container1"); +// create a bar chart under #chart-container2 element using chart group A +var chart2 = dc.barChart("#chart-container2", "chartGroupA"); +// create a sub-chart under a composite parent chart +var chart3 = dc.barChart(compositeChart); +``` + +**/ +dc.barChart = function (parent, chartGroup) { + var MIN_BAR_WIDTH = 1; + var DEFAULT_GAP_BETWEEN_BARS = 2; + + var _chart = dc.stackableChart(dc.coordinateGridChart({})); + + var _gap = DEFAULT_GAP_BETWEEN_BARS; + var _centerBar = false; + + var _barWidth; + + dc.override(_chart, 'rescale', function () { + _chart._rescale(); + _barWidth = undefined; + }); + + _chart.plotData = function () { + var layers = _chart.chartBodyG().selectAll("g.stack") + .data(_chart.stackLayers()); + + calculateBarWidth(); + + layers + .enter() + .append("g") + .attr("class", function (d, i) { + return "stack " + "_" + i; + }); + + layers.each(function (d, i) { + var layer = d3.select(this); + + renderBars(layer, i, d); + }); + + _chart.stackLayers(null); + }; + + function barHeight(d) { + return dc.utils.safeNumber(Math.abs(_chart.y()(d.y + d.y0) - _chart.y()(d.y0))); + } + + function renderBars(layer, layerIndex, d) { + var bars = layer.selectAll("rect.bar") + .data(d.points, dc.pluck('data', _chart.keyAccessor())); + + bars.enter() + .append("rect") + .attr("class", "bar") + .attr("fill", _chart.getColor); + + if (_chart.renderTitle()) { + bars.append("title").text(dc.pluck('data', _chart.getTitleOfVisibleByIndex(layerIndex))); + + } + + if (_chart.isOrdinal()) + bars.on("click", onClick); + + dc.transition(bars, _chart.transitionDuration()) + .attr("x", function (d) { + var x = _chart.x()(d.x); + if (_centerBar) x -= _barWidth / 2; + if (_chart.isOrdinal()) x += _gap/2; + return dc.utils.safeNumber(x); + }) + .attr("y", function (d) { + var y = _chart.y()(d.y + d.y0); + + if (d.y < 0) + y -= barHeight(d); + + return dc.utils.safeNumber(y); + }) + .attr("width", _barWidth) + .attr("height", function (d) { + return barHeight(d); + }) + .attr("fill", _chart.getColor) + .select("title").text(dc.pluck('data', _chart.getTitleOfVisibleByIndex(layerIndex))); + + dc.transition(bars.exit(), _chart.transitionDuration()) + .attr("height", 0) + .remove(); + } + + function calculateBarWidth() { + if (_barWidth === undefined) { + var numberOfBars = _chart.xUnitCount(); + + if (_chart.isOrdinal() && !_gap) + _barWidth = Math.floor(_chart.x().rangeBand()); + else if (_gap) + _barWidth = Math.floor((_chart.xAxisLength() - (numberOfBars - 1) * _gap) / numberOfBars); + else + _barWidth = Math.floor(_chart.xAxisLength() / (1 + _chart.barPadding()) / numberOfBars); + + if (_barWidth == Infinity || isNaN(_barWidth) || _barWidth < MIN_BAR_WIDTH) + _barWidth = MIN_BAR_WIDTH; + } + } + + _chart.fadeDeselectedArea = function () { + var bars = _chart.chartBodyG().selectAll("rect.bar"); + var extent = _chart.brush().extent(); + + if (_chart.isOrdinal()) { + if (_chart.hasFilter()) { + bars.classed(dc.constants.SELECTED_CLASS, function (d) { + return _chart.hasFilter(_chart.keyAccessor()(d.data)); + }); + bars.classed(dc.constants.DESELECTED_CLASS, function (d) { + return !_chart.hasFilter(_chart.keyAccessor()(d.data)); + }); + } else { + bars.classed(dc.constants.SELECTED_CLASS, false); + bars.classed(dc.constants.DESELECTED_CLASS, false); + } + } else { + if (!_chart.brushIsEmpty(extent)) { + var start = extent[0]; + var end = extent[1]; + + bars.classed(dc.constants.DESELECTED_CLASS, function (d) { + var xValue = _chart.keyAccessor()(d.data); + return xValue < start || xValue >= end; + }); + } else { + bars.classed(dc.constants.DESELECTED_CLASS, false); + } + } + }; + + /** + #### .centerBar(boolean) + Whether the bar chart will render each bar centered around the data position on x axis. Default to false. + + **/ + _chart.centerBar = function (_) { + if (!arguments.length) return _centerBar; + _centerBar = _; + return _chart; + }; + + function onClick(d) { + _chart.onClick(d.data); + } + + /** + ### .barPadding([padding]) + Get or set the spacing between bars as a fraction of bar size. Valid values are within 0-1. + Setting this value will also remove any previously set `gap`. See the + [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) + for a visual description of how the padding is applied. + **/ + _chart.barPadding = function (_) { + if (!arguments.length) return _chart._rangeBandPadding(); + _chart._rangeBandPadding(_); + _gap = 0; + return _chart; + }; + + /** + ### .outerPadding([padding]) + Get or set the outer padding on an ordinal bar chart. This setting has no effect on non-ordinal charts. + Padding equivlent in width to `padding * barWidth` will be added on each side of the chart. + + Default: 0.5 + **/ + _chart.outerPadding = _chart._outerRangeBandPadding; + + /** + #### .gap(gapBetweenBars) + Manually set fixed gap (in px) between bars instead of relying on the default auto-generated gap. By default bar chart + implementation will calculate and set the gap automatically based on the number of data points and the length of the x axis. + + **/ + _chart.gap = function (_) { + if (!arguments.length) return _gap; + _gap = _; + return _chart; + }; + + _chart.extendBrush = function () { + var extent = _chart.brush().extent(); + if (_chart.round() && !_centerBar) { + extent[0] = extent.map(_chart.round())[0]; + extent[1] = extent.map(_chart.round())[1]; + + _chart.chartBodyG().select(".brush") + .call(_chart.brush().extent(extent)); + } + return extent; + }; + + _chart.legendHighlight = function (d) { + if(!_chart.isLegendableHidden(d)) { + _chart.select('.chart-body').selectAll('rect.bar').filter(function () { + return d3.select(this).attr('fill') == d.color; + }).classed('highlight', true); + _chart.select('.chart-body').selectAll('rect.bar').filter(function () { + return d3.select(this).attr('fill') != d.color; + }).classed('fadeout', true); + } + }; + + _chart.legendReset = function (d) { + _chart.selectAll('.chart-body').selectAll('rect.bar').filter(function () { + return d3.select(this).attr('fill') == d.color; + }).classed('highlight', false); + _chart.selectAll('.chart-body').selectAll('rect.bar').filter(function () { + return d3.select(this).attr('fill') != d.color; + }).classed('fadeout', false); + }; + + dc.override(_chart, "xAxisMax", function() { + var max = this._xAxisMax(); + if('resolution' in _chart.xUnits()) { + var res = _chart.xUnits().resolution; + max += res; + } + return max; + }); + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Line Chart [Concrete] < [Stackable Chart](#stackable-chart) < [CoordinateGrid Chart](#coordinate-grid-chart) +Concrete line/area chart implementation. + +Examples: +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) +* [Canadian City Crime Stats](http://nickqizhu.github.com/dc.js/crime/index.html) + +#### dc.lineChart(parent[, chartGroup]) +Create a line chart instance and attach it to the given parent element. + +Parameters: + +* parent : string|compositeChart - any valid d3 single selector representing typically a dom block element such + as a div, or if this line chart is a sub-chart in a [Composite Chart](#composite-chart) then pass in the parent composite chart instance. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created line chart instance + +```js +// create a line chart under #chart-container1 element using the default global chart group +var chart1 = dc.lineChart("#chart-container1"); +// create a line chart under #chart-container2 element using chart group A +var chart2 = dc.lineChart("#chart-container2", "chartGroupA"); +// create a sub-chart under a composite parent chart +var chart3 = dc.lineChart(compositeChart); +``` + +**/ +dc.lineChart = function (parent, chartGroup) { + var DEFAULT_DOT_RADIUS = 5; + var TOOLTIP_G_CLASS = "dc-tooltip"; + var DOT_CIRCLE_CLASS = "dot"; + var Y_AXIS_REF_LINE_CLASS = "yRef"; + var X_AXIS_REF_LINE_CLASS = "xRef"; + var DEFAULT_DOT_OPACITY = 1e-6; + + var _chart = dc.stackableChart(dc.coordinateGridChart({})); + var _renderArea = false; + var _dotRadius = DEFAULT_DOT_RADIUS; + var _dataPointRadius = null; + var _dataPointFillOpacity = DEFAULT_DOT_OPACITY; + var _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; + var _interpolate = 'linear'; + var _tension = 0.7; + var _defined; + var _dashStyle; + + _chart.transitionDuration(500); + + _chart.plotData = function () { + var chartBody = _chart.chartBodyG(); + var layersList = chartBody.selectAll("g.stack-list"); + + if (layersList.empty()) layersList = chartBody.append("g").attr("class", "stack-list"); + + var layers = layersList.selectAll("g.stack").data(_chart.stackLayers()); + + var layersEnter = layers + .enter() + .append("g") + .attr("class", function (d, i) { + return "stack " + "_" + i; + }); + + drawLine(layersEnter, layers); + + drawArea(layersEnter, layers); + + drawDots(chartBody, layers); + + _chart.stackLayers(null); + }; + + _chart.interpolate = function(_){ + if (!arguments.length) return _interpolate; + _interpolate = _; + return _chart; + }; + + _chart.tension = function(_){ + if (!arguments.length) return _tension; + _tension = _; + return _chart; + }; + + _chart.defined = function(_){ + if (!arguments.length) return _defined; + _defined = _; + return _chart; + }; + /** + #### .dashStyle([array]) + Set the line's d3 dashstyle. This value becomes "stroke-dasharray" of line. Defaults to empty array (solid line). + ```js + // create a Dash Dot Dot Dot + chart.dashStyle([3,1,1,1]); + ``` + **/ + _chart.dashStyle = function (_) { + if (!arguments.length) return _dashStyle; + _dashStyle = _; + return _chart; + }; + + /** + #### .renderArea([boolean]) + Get or set render area flag. If the flag is set to true then the chart will render the area beneath each line and effectively + becomes an area chart. + + **/ + _chart.renderArea = function (_) { + if (!arguments.length) return _renderArea; + _renderArea = _; + return _chart; + }; + + function drawLine(layersEnter, layers) { + var line = d3.svg.line() + .x(function (d) { + return _chart.x()(d.x); + }) + .y(function (d) { + return _chart.y()(d.y + d.y0); + }) + .interpolate(_interpolate) + .tension(_tension); + if (_defined) + line.defined(_defined); + + + var path = layersEnter.append("path") + .attr("class", "line") + .attr("stroke", _chart.getColor) + .attr("fill", _chart.getColor); + if (_dashStyle) + path.attr("stroke-dasharray", _dashStyle); + + dc.transition(layers.select("path.line"), _chart.transitionDuration()) + .attr("d", function (d) { + return safeD(line(d.points)); + }); + } + + function drawArea(layersEnter, layers) { + if (_renderArea) { + var area = d3.svg.area() + .x(function (d) { + return _chart.x()(d.x); + }) + .y(function (d) { + return _chart.y()(d.y + d.y0); + }) + .y0(function (d) { + return _chart.y()(d.y0); + }) + .interpolate(_interpolate) + .tension(_tension); + if (_defined) + area.defined(_defined); + + + layersEnter.append("path") + .attr("class", "area") + .attr("fill", _chart.getColor) + .attr("d", function (d) { + return safeD(area(d.points)); + }); + + dc.transition(layers.select("path.area"), _chart.transitionDuration()) + .attr("d", function (d) { + return safeD(area(d.points)); + }); + } + } + + function safeD(d){ + return (!d || d.indexOf("NaN") >= 0) ? "M0,0" : d; + } + + function drawDots(chartBody, layers) { + if (!_chart.brushOn()) { + + var tooltipListClass = TOOLTIP_G_CLASS + "-list"; + var tooltips = chartBody.select("g." + tooltipListClass); + + if (tooltips.empty()) tooltips = chartBody.append("g").attr("class", tooltipListClass); + + layers.each(function (d, layerIndex) { + var layer = d3.select(this); + var points = layer.datum().points; + if (_defined) points = points.filter(_defined); + + var g = tooltips.select("g." + TOOLTIP_G_CLASS + "._" + layerIndex); + if (g.empty()) g = tooltips.append("g").attr("class", TOOLTIP_G_CLASS + " _" + layerIndex); + + createRefLines(g); + + var dots = g.selectAll("circle." + DOT_CIRCLE_CLASS).data(points); + + dots.enter() + .append("circle") + .attr("class", DOT_CIRCLE_CLASS) + .attr("r", getDotRadius()) + .attr("fill", _chart.getColor) + .style("fill-opacity", _dataPointFillOpacity) + .style("stroke-opacity", _dataPointStrokeOpacity) + .on("mousemove", function (d) { + var dot = d3.select(this); + showDot(dot); + showRefLines(dot, g); + }) + .on("mouseout", function (d) { + var dot = d3.select(this); + hideDot(dot); + hideRefLines(g); + }) + .append("title").text(dc.pluck('data', _chart.getTitleOfVisibleByIndex(layerIndex))); + + dots.attr("cx", function (d) { + return dc.utils.safeNumber(_chart.x()(d.x)); + }) + .attr("cy", function (d) { + return dc.utils.safeNumber(_chart.y()(d.y + d.y0)); + }) + .select("title").text(dc.pluck('data', _chart.getTitleOfVisibleByIndex(layerIndex))); + + dots.exit().remove(); + }); + } + } + + function createRefLines(g) { + var yRefLine = g.select("path." + Y_AXIS_REF_LINE_CLASS).empty() ? g.append("path").attr("class", Y_AXIS_REF_LINE_CLASS) : g.select("path." + Y_AXIS_REF_LINE_CLASS); + yRefLine.style("display", "none").attr("stroke-dasharray", "5,5"); + + var xRefLine = g.select("path." + X_AXIS_REF_LINE_CLASS).empty() ? g.append("path").attr("class", X_AXIS_REF_LINE_CLASS) : g.select("path." + X_AXIS_REF_LINE_CLASS); + xRefLine.style("display", "none").attr("stroke-dasharray", "5,5"); + } + + function showDot(dot) { + dot.style("fill-opacity", 0.8); + dot.style("stroke-opacity", 0.8); + dot.attr("r", _dotRadius); + return dot; + } + + function showRefLines(dot, g) { + var x = dot.attr("cx"); + var y = dot.attr("cy"); + g.select("path." + Y_AXIS_REF_LINE_CLASS).style("display", "").attr("d", "M0 " + y + "L" + (x) + " " + (y)); + g.select("path." + X_AXIS_REF_LINE_CLASS).style("display", "").attr("d", "M" + x + " " + _chart.yAxisHeight() + "L" + x + " " + y); + } + + function getDotRadius() { + return _dataPointRadius || _dotRadius; + } + + function hideDot(dot) { + dot.style("fill-opacity", _dataPointFillOpacity) + .style("stroke-opacity", _dataPointStrokeOpacity) + .attr("r", getDotRadius()); + } + + function hideRefLines(g) { + g.select("path." + Y_AXIS_REF_LINE_CLASS).style("display", "none"); + g.select("path." + X_AXIS_REF_LINE_CLASS).style("display", "none"); + } + + /** + #### .dotRadius([dotRadius]) + Get or set the radius (in px) for data points. Default dot radius is 5. + **/ + _chart.dotRadius = function (_) { + if (!arguments.length) return _dotRadius; + _dotRadius = _; + return _chart; + }; + + /** + #### .renderDataPoints([options]) + Always show individual dots for each datapoint. + + Options, if given, is an object that can contain the following: + + * fillOpacity (default 0.8) + * strokeOpacity (default 0.8) + * radius (default 2) + + If `options` is falsy, it disable data point rendering. + + If no `options` are provded, the current `options` values are instead returned + + Example: + ``` + chart.renderDataPoints([{radius: 2, fillOpacity: 0.8, strokeOpacity: 0.8}]) + ``` + **/ + _chart.renderDataPoints = function (options) { + if (!arguments.length) { + return { + fillOpacity: _dataPointFillOpacity, + strokeOpacity: _dataPointStrokeOpacity, + radius: _dataPointRadius + }; + } else if (!options) { + _dataPointFillOpacity = DEFAULT_DOT_OPACITY; + _dataPointStrokeOpacity = DEFAULT_DOT_OPACITY; + _dataPointRadius = null; + } else { + _dataPointFillOpacity = options.fillOpacity || 0.8; + _dataPointStrokeOpacity = options.strokeOpacity || 0.8; + _dataPointRadius = options.radius || 2; + } + return _chart; + }; + + _chart.legendHighlight = function (d) { + if(!_chart.isLegendableHidden(d)) { + _chart.selectAll('.chart-body').selectAll('path').filter(function () { + return d3.select(this).attr('fill') == d.color; + }).classed('highlight', true); + _chart.selectAll('.chart-body').selectAll('path').filter(function () { + return d3.select(this).attr('fill') != d.color; + }).classed('fadeout', true); + } + }; + + _chart.legendReset = function (d) { + _chart.selectAll('.chart-body').selectAll('path').filter(function () { + return d3.select(this).attr('fill') == d.color; + }).classed('highlight', false); + _chart.selectAll('.chart-body').selectAll('path').filter(function () { + return d3.select(this).attr('fill') != d.color; + }).classed('fadeout', false); + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Data Count Widget [Concrete] < [Base Chart](#base-chart) +Data count is a simple widget designed to display total number records in the data set vs. the number records selected +by the current filters. Once created data count widget will automatically update the text content of the following elements +under the parent element. + +* ".total-count" - total number of records +* ".filter-count" - number of records matched by the current filters + +Examples: + +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) + +#### dc.dataCount(parent[, chartGroup]) +Create a data count widget instance and attach it to the given parent element. + +Parameters: + +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created data count widget instance + +#### .dimension(allData) - **mandatory** +For data count widget the only valid dimension is the entire data set. + +#### .group(groupAll) - **mandatory** +For data count widget the only valid group is the all group. + +```js +var ndx = crossfilter(data); +var all = ndx.groupAll(); + +dc.dataCount(".dc-data-count") + .dimension(ndx) + .group(all); +``` + +**/ +dc.dataCount = function(parent, chartGroup) { + var _formatNumber = d3.format(",d"); + var _chart = dc.baseChart({}); + + _chart.doRender = function() { + _chart.selectAll(".total-count").text(_formatNumber(_chart.dimension().size())); + _chart.selectAll(".filter-count").text(_formatNumber(_chart.group().value())); + + return _chart; + }; + + _chart.doRedraw = function(){ + return _chart.doRender(); + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Data Table Widget [Concrete] < [Base Chart](#base-chart) +Data table is a simple widget designed to list crossfilter focused data set (rows being filtered) in a good old tabular +fashion. + +Examples: +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) + +#### dc.dataTable(parent[, chartGroup]) +Create a data table widget instance and attach it to the given parent element. + +Parameters: +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created data table widget instance + +**/ +dc.dataTable = function(parent, chartGroup) { + var LABEL_CSS_CLASS = "dc-table-label"; + var ROW_CSS_CLASS = "dc-table-row"; + var COLUMN_CSS_CLASS = "dc-table-column"; + var GROUP_CSS_CLASS = "dc-table-group"; + + var _chart = dc.baseChart({}); + + var _size = 25; + var _columns = []; + var _sortBy = function(d) { + return d; + }; + var _order = d3.ascending; + + _chart.doRender = function() { + _chart.selectAll("tbody").remove(); + + renderRows(renderGroups()); + + return _chart; + }; + + function renderGroups() { + var groups = _chart.root().selectAll("tbody") + .data(nestEntries(), function(d) { + return _chart.keyAccessor()(d); + }); + + var rowGroup = groups + .enter() + .append("tbody"); + + rowGroup + .append("tr") + .attr("class", GROUP_CSS_CLASS) + .append("td") + .attr("class", LABEL_CSS_CLASS) + .attr("colspan", _columns.length) + .html(function(d) { + return _chart.keyAccessor()(d); + }); + + groups.exit().remove(); + + return rowGroup; + } + + function nestEntries() { + var entries = _chart.dimension().top(_size); + + return d3.nest() + .key(_chart.group()) + .sortKeys(_order) + .entries(entries.sort(function(a, b){ + return _order(_sortBy(a), _sortBy(b)); + })); + } + + function renderRows(groups) { + var rows = groups.order() + .selectAll("tr." + ROW_CSS_CLASS) + .data(function(d) { + return d.values; + }); + + var rowEnter = rows.enter() + .append("tr") + .attr("class", ROW_CSS_CLASS); + + _columns.forEach(function(f,i) { + rowEnter.append("td") + .attr("class", COLUMN_CSS_CLASS + " _" + i) + .html(f); + }); + + rows.exit().remove(); + + return rows; + } + + _chart.doRedraw = function() { + return _chart.doRender(); + }; + + /** + #### .size([size]) + Get or set the table size which determines the number of rows displayed by the widget. + + **/ + _chart.size = function(s) { + if (!arguments.length) return _size; + _size = s; + return _chart; + }; + + /** + #### .columns([columnFunctionArray]) + Get or set column functions. Data table widget uses an array of functions to generate dynamic columns. Column functions are + simple javascript function with only one input argument d which represents a row in the data set, and the return value of + these functions will be used directly to generate table content for each cell. + + ```js + chart.columns([ + function(d) { + return d.date; + }, + function(d) { + return d.open; + }, + function(d) { + return d.close; + }, + function(d) { + return numberFormat(d.close - d.open); + }, + function(d) { + return d.volume; + } + ]); + ``` + + **/ + _chart.columns = function(_) { + if (!arguments.length) return _columns; + _columns = _; + return _chart; + }; + + /** + #### .sortBy([sortByFunction]) + Get or set sort-by function. This function works as a value accessor at row level and returns a particular field to be sorted + by. Default value: ``` function(d) {return d;}; ``` + + ```js + chart.sortBy(function(d) { + return d.date; + }); + ``` + + **/ + _chart.sortBy = function(_) { + if (!arguments.length) return _sortBy; + _sortBy = _; + return _chart; + }; + + /** + #### .order([order]) + Get or set sort order. Default value: ``` d3.ascending ``` + + ```js + chart.order(d3.descending); + ``` + + **/ + _chart.order = function(_) { + if (!arguments.length) return _order; + _order = _; + return _chart; + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Bubble Chart [Concrete] < [Abstract Bubble Chart](#abstract-bubble-chart) < [CoordinateGrid Chart](#coordinate-grid-chart) +A concrete implementation of a general purpose bubble chart that allows data visualization using the following dimensions: + +* x axis position +* y axis position +* bubble radius +* color + +Examples: +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) +* [US Venture Capital Landscape 2011](http://nickqizhu.github.com/dc.js/vc/index.html) + +#### dc.bubbleChart(parent[, chartGroup]) +Create a bubble chart instance and attach it to the given parent element. + +Parameters: +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created bubble chart instance + +```js +// create a bubble chart under #chart-container1 element using the default global chart group +var bubbleChart1 = dc.bubbleChart("#chart-container1"); +// create a bubble chart under #chart-container2 element using chart group A +var bubbleChart2 = dc.bubbleChart("#chart-container2", "chartGroupA"); +``` + +**/ +dc.bubbleChart = function(parent, chartGroup) { + var _chart = dc.abstractBubbleChart(dc.coordinateGridChart({})); + + var _elasticRadius = false; + + _chart.transitionDuration(750); + + var bubbleLocator = function(d) { + return "translate(" + (bubbleX(d)) + "," + (bubbleY(d)) + ")"; + }; + + /** + #### .elasticRadius([boolean]) + Turn on or off elastic bubble radius feature. If this feature is turned on, then bubble radiuses will be automatically rescaled + to fit the chart better. + + **/ + _chart.elasticRadius = function(_) { + if (!arguments.length) return _elasticRadius; + _elasticRadius = _; + return _chart; + }; + + _chart.plotData = function() { + if (_elasticRadius) + _chart.r().domain([_chart.rMin(), _chart.rMax()]); + + _chart.r().range([_chart.MIN_RADIUS, _chart.xAxisLength() * _chart.maxBubbleRelativeSize()]); + + var bubbleG = _chart.chartBodyG().selectAll("g." + _chart.BUBBLE_NODE_CLASS) + .data(_chart.data(),_chart.keyAccessor()); + + renderNodes(bubbleG); + + updateNodes(bubbleG); + + removeNodes(bubbleG); + + _chart.fadeDeselectedArea(); + }; + + function renderNodes(bubbleG) { + var bubbleGEnter = bubbleG.enter().append("g"); + + bubbleGEnter + .attr("class", _chart.BUBBLE_NODE_CLASS) + .attr("transform", bubbleLocator) + .append("circle").attr("class", function(d, i) { + return _chart.BUBBLE_CLASS + " _" + i; + }) + .on("click", _chart.onClick) + .attr("fill", _chart.getColor) + .attr("r", 0); + dc.transition(bubbleG, _chart.transitionDuration()) + .selectAll("circle." + _chart.BUBBLE_CLASS) + .attr("r", function(d) { + return _chart.bubbleR(d); + }) + .attr("opacity", function(d) { + return (_chart.bubbleR(d) > 0) ? 1 : 0; + }); + + _chart.doRenderLabel(bubbleGEnter); + + _chart.doRenderTitles(bubbleGEnter); + } + + function updateNodes(bubbleG) { + dc.transition(bubbleG, _chart.transitionDuration()) + .attr("transform", bubbleLocator) + .selectAll("circle." + _chart.BUBBLE_CLASS) + .attr("fill", _chart.getColor) + .attr("r", function(d) { + return _chart.bubbleR(d); + }) + .attr("opacity", function(d) { + return (_chart.bubbleR(d) > 0) ? 1 : 0; + }); + + _chart.doUpdateLabels(bubbleG); + _chart.doUpdateTitles(bubbleG); + } + + function removeNodes(bubbleG) { + bubbleG.exit().remove(); + } + + function bubbleX(d) { + var x = _chart.x()(_chart.keyAccessor()(d)); + if (isNaN(x)) + x = 0; + return x; + } + + function bubbleY(d) { + var y = _chart.y()(_chart.valueAccessor()(d)); + if (isNaN(y)) + y = 0; + return y; + } + + _chart.renderBrush = function(g) { + // override default x axis brush from parent chart + }; + + _chart.redrawBrush = function(g) { + // override default x axis brush from parent chart + _chart.fadeDeselectedArea(); + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Composite Chart [Concrete] < [CoordinateGrid Chart](#coordinate-grid-chart) +Composite chart is a special kind of chart that resides somewhere between abstract and concrete charts. It does not +generate data visualization directly, but rather working with other concrete charts to do the job. You can essentially +overlay(compose) different bar/line/area charts in a single composite chart to achieve some quite flexible charting +effects. + +Examples: +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) + +#### dc.compositeChart(parent[, chartGroup]) +Create a composite chart instance and attach it to the given parent element. + +Parameters: +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created composite chart instance + +```js +// create a composite chart under #chart-container1 element using the default global chart group +var compositeChart1 = dc.compositeChart("#chart-container1"); +// create a composite chart under #chart-container2 element using chart group A +var compositeChart2 = dc.compositeChart("#chart-container2", "chartGroupA"); +``` + +**/ +dc.compositeChart = function (parent, chartGroup) { + var SUB_CHART_CLASS = "sub"; + + var _chart = dc.coordinateGridChart({}); + var _children = []; + + var _shareColors = false, + _shareTitle = true; + + _chart._mandatoryAttributes([]); + _chart.transitionDuration(500); + + dc.override(_chart, "_generateG", function () { + var g = this.__generateG(); + + for (var i = 0; i < _children.length; ++i) { + var child = _children[i]; + + generateChildG(child, i); + + if (!child.dimension()) child.dimension(_chart.dimension()); + if (!child.group()) child.group(_chart.group()); + child.chartGroup(_chart.chartGroup()); + child.svg(_chart.svg()); + child.xUnits(_chart.xUnits()); + child.transitionDuration(_chart.transitionDuration()); + child.brushOn(_chart.brushOn()); + } + + return g; + }); + + function generateChildG(child, i) { + child._generateG(_chart.g()); + child.g().attr("class", SUB_CHART_CLASS + " _" + i); + } + + _chart.plotData = function () { + for (var i = 0; i < _children.length; ++i) { + var child = _children[i]; + + if (!child.g()) { + generateChildG(child, i); + } + + if (_shareColors) + child.colors(_chart.colors()); + + child.x(_chart.x()); + child.y(_chart.y()); + child.xAxis(_chart.xAxis()); + child.yAxis(_chart.yAxis()); + + child.plotData(); + + child.activateRenderlets(); + } + }; + + _chart.fadeDeselectedArea = function () { + for (var i = 0; i < _children.length; ++i) { + var child = _children[i]; + child.brush(_chart.brush()); + child.fadeDeselectedArea(); + } + }; + + /** + #### .compose(subChartArray) + Combine the given charts into one single composite coordinate grid chart. + + ```js + // compose the given charts in the array into one single composite chart + moveChart.compose([ + // when creating sub-chart you need to pass in the parent chart + dc.lineChart(moveChart) + .group(indexAvgByMonthGroup) // if group is missing then parent's group will be used + .valueAccessor(function(d){return d.value.avg;}) + // most of the normal functions will continue to work in a composed chart + .renderArea(true) + .stack(monthlyMoveGroup, function(d){return d.value;}) + .title(function(d){ + var value = d.value.avg?d.value.avg:d.value; + if(isNaN(value)) value = 0; + return dateFormat(d.key) + "\n" + numberFormat(value); + }), + dc.barChart(moveChart) + .group(volumeByMonthGroup) + .centerBar(true) + ]); + ``` + + **/ + _chart.compose = function (charts) { + _children = charts; + _children.forEach(function(child, i) { + child.height(_chart.height()); + child.width(_chart.width()); + child.margins(_chart.margins()); + + if (_shareTitle) { + child.title(_chart.title()); + } + + if (_shareColors && child.colorAccessor() === child._layerColorAccessor) + child.colorCalculator(function() {return child.colors()(i);}); + + }); + return _chart; + }; + + _chart.children = function () { + return _children; + }; + + /** + #### .shareColors([boolean]) + Get or set color sharing for the chart. If set, the `.colors()` value from this chart + will be shared with composed children. Additionally if the child chart implements + Stackable and has not set a custom .colorAccessor, then it will generate a color + specific to its order in the composition. + **/ + _chart.shareColors = function (_) { + if (!arguments.length) return _shareColors; + _shareColors = _; + return _chart; + }; + + /** + #### .shareTitle([[boolean]) + Get or set title sharing for the chart. If set, the `.title()` value from this chart + will be shared with composed children. Default value is true. + **/ + _chart.shareTitle = function (_) { + if (!arguments.length) return _shareTitle; + _shareTitle = _; + return _chart; + }; + + function getAllYAxisMinFromChildCharts() { + var allMins = []; + for (var i = 0; i < _children.length; ++i) { + allMins.push(_children[i].yAxisMin()); + } + return allMins; + } + + _chart.yAxisMin = function () { + return d3.min(getAllYAxisMinFromChildCharts()); + }; + + function getAllYAxisMaxFromChildCharts() { + var allMaxes = []; + for (var i = 0; i < _children.length; ++i) { + allMaxes.push(_children[i].yAxisMax()); + } + return allMaxes; + } + + _chart.yAxisMax = function () { + return dc.utils.add(d3.max(getAllYAxisMaxFromChildCharts()), _chart.yAxisPadding()); + }; + + function getAllXAxisMinFromChildCharts() { + var allMins = []; + for (var i = 0; i < _children.length; ++i) { + allMins.push(_children[i].xAxisMin()); + } + return allMins; + } + + _chart.xAxisMin = function () { + return dc.utils.subtract(d3.min(getAllXAxisMinFromChildCharts()), _chart.xAxisPadding()); + }; + + function getAllXAxisMaxFromChildCharts() { + var allMaxes = []; + for (var i = 0; i < _children.length; ++i) { + allMaxes.push(_children[i].xAxisMax()); + } + return allMaxes; + } + + _chart.xAxisMax = function () { + return dc.utils.add(d3.max(getAllXAxisMaxFromChildCharts()), _chart.xAxisPadding()); + }; + + _chart.legendables = function () { + var items = []; + _children.forEach(function(child, i) { + if (_shareColors) + child.colors(_chart.colors()); + + var childLegendables = child.legendables(); + if (childLegendables.length) + items.push.apply(items,childLegendables); + else + items.push(dc.utils.createLegendable(child, child.group(), child.valueAccessor(), child.colorCalculator()(i))); + }); + return items; + }; + + _chart.legendHighlight = function (d) { + for (var j = 0; j < _children.length; ++j) { + var child = _children[j]; + child.legendHighlight(d); + } + }; + + _chart.legendReset = function (d) { + for (var j = 0; j < _children.length; ++j) { + var child = _children[j]; + child.legendReset(d); + } + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Series Chart [Concrete] < [Color Chart](#color-chart) < [Base Chart](#base-chart) + A series chart is a chart that shows multiple series of data as lines, where the series + is specified in the data. + + #### dc.seriesChart(parent[, chartGroup]) + Create a series chart instance and attach it to the given parent element. + + Parameters: + * parent : string - any valid d3 single selector representing typically a dom block element such as a div. + * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + + Return: + A newly created series chart instance + + ```js + // create a series chart under #chart-container1 element using the default global chart group + var seriesChart1 = dc.seriesChart("#chart-container1"); + // create a series chart under #chart-container2 element using chart group A + var seriesChart2 = dc.seriesChart("#chart-container2", "chartGroupA"); + ``` + + **/ +dc.seriesChart = function (parent, chartGroup) { + var _chart = dc.compositeChart(parent, chartGroup); + + var _charts = {}; + var _chartFunction = dc.lineChart; + var _seriesAccessor; + var _seriesSort = d3.ascending; + var _valueSort = keySort; + + _chart._mandatoryAttributes().push('seriesAccessor','chart'); + _chart.shareColors(true); + + function keySort(a,b) { + return d3.ascending(_chart.keyAccessor()(a), _chart.keyAccessor()(b)); + } + + _chart._preprocessData = function () { + var keep = []; + var children_changed; + var nester = d3.nest().key(_seriesAccessor); + if(_seriesSort) + nester.sortKeys(_seriesSort); + if(_valueSort) + nester.sortValues(_valueSort); + var nesting = nester.entries(_chart.data()); + var children = + nesting.map(function(sub,i) { + var subChart = _charts[sub.key] || _chartFunction.call(_chart,_chart,chartGroup,sub.key,i); + if(!_charts[sub.key]) + children_changed = true; + _charts[sub.key] = subChart; + keep.push(sub.key); + return subChart + .dimension(_chart.dimension()) + .group({all:d3.functor(sub.values)}, sub.key) + .keyAccessor(_chart.keyAccessor()) + .valueAccessor(_chart.valueAccessor()) + .colorCalculator(function() {return subChart.colors()(sub.key);}); + }); + // this works around the fact compositeChart doesn't really + // have a removal interface + Object.keys(_charts) + .filter(function(c) {return keep.indexOf(c) === -1;}) + .forEach(function(c) { + clearChart(c); + children_changed = true; + }); + _chart._compose(children); + if(children_changed && _chart.legend()) + _chart.legend().render(); + }; + + function clearChart(c) { + if(_charts[c].g()) + _charts[c].g().remove(); + delete _charts[c]; + } + + function resetChildren() { + Object.keys(_charts).map(clearChart); + _charts = {}; + } + + _chart.chart = function(_) { + if (!arguments.length) return _chartFunction; + _chartFunction = _; + resetChildren(); + return _chart; + }; + + /** + #### .seriesAccessor([accessor]) + Get or set accessor function for the displayed series. Given a datum, this function + should return the series that datum belongs to. + **/ + _chart.seriesAccessor = function(_) { + if (!arguments.length) return _seriesAccessor; + _seriesAccessor = _; + resetChildren(); + return _chart; + }; + + /** + #### .seriesSort([sortFunction]) + Get or set a function to sort the list of series by, given series values. + + Example: + ``` + chart.seriesSort(d3.descending); + ``` + **/ + _chart.seriesSort = function(_) { + if (!arguments.length) return _seriesSort; + _seriesSort = _; + resetChildren(); + return _chart; + }; + + _chart.valueSort = function(_) { + if (!arguments.length) return _valueSort; + _valueSort = _; + resetChildren(); + return _chart; + }; + + // make compose private + _chart._compose = _chart.compose; + delete _chart.compose; + + return _chart; +}; + +/** +## # Geo Choropleth Chart [Concrete] < [Color Chart](#color-chart) < [Base Chart](#base-chart) +Geo choropleth chart is design to make creating crossfilter driven choropleth map from GeoJson data an easy process. This +chart implementation was inspired by [the great d3 choropleth example](http://bl.ocks.org/4060606). + +Examples: +* [US Venture Capital Landscape 2011](http://nickqizhu.github.com/dc.js/vc/index.html) + +#### dc.geoChoroplethChart(parent[, chartGroup]) +Create a choropleth chart instance and attach it to the given parent element. + +Parameters: +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created choropleth chart instance + +```js +// create a choropleth chart under "#us-chart" element using the default global chart group +var chart1 = dc.geoChoroplethChart("#us-chart"); +// create a choropleth chart under "#us-chart2" element using chart group A +var chart2 = dc.compositeChart("#us-chart2", "chartGroupA"); +``` + +**/ +dc.geoChoroplethChart = function (parent, chartGroup) { + var _chart = dc.colorChart(dc.baseChart({})); + + _chart.colorAccessor(function (d, i) { + return d || 0; + }); + + var _geoPath = d3.geo.path(); + var _projectionFlag; + + var _geoJsons = []; + + _chart.doRender = function () { + _chart.resetSvg(); + for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { + var states = _chart.svg().append("g") + .attr("class", "layer" + layerIndex); + + var regionG = states.selectAll("g." + geoJson(layerIndex).name) + .data(geoJson(layerIndex).data) + .enter() + .append("g") + .attr("class", geoJson(layerIndex).name); + + regionG + .append("path") + .attr("fill", "white") + .attr("d", _geoPath); + + regionG.append("title"); + + plotData(layerIndex); + } + _projectionFlag = false; + }; + + function plotData(layerIndex) { + var data = generateLayeredData(); + + if (isDataLayer(layerIndex)) { + var regionG = renderRegionG(layerIndex); + + renderPaths(regionG, layerIndex, data); + + renderTitle(regionG, layerIndex, data); + } + } + + function generateLayeredData() { + var data = {}; + var groupAll = _chart.data(); + for (var i = 0; i < groupAll.length; ++i) { + data[_chart.keyAccessor()(groupAll[i])] = _chart.valueAccessor()(groupAll[i]); + } + return data; + } + + function isDataLayer(layerIndex) { + return geoJson(layerIndex).keyAccessor; + } + + function renderRegionG(layerIndex) { + var regionG = _chart.svg() + .selectAll(layerSelector(layerIndex)) + .classed("selected", function (d) { + return isSelected(layerIndex, d); + }) + .classed("deselected", function (d) { + return isDeselected(layerIndex, d); + }) + .attr("class", function (d) { + var layerNameClass = geoJson(layerIndex).name; + var regionClass = dc.utils.nameToId(geoJson(layerIndex).keyAccessor(d)); + var baseClasses = layerNameClass + " " + regionClass; + if (isSelected(layerIndex, d)) baseClasses += " selected"; + if (isDeselected(layerIndex, d)) baseClasses += " deselected"; + return baseClasses; + }); + return regionG; + } + + function layerSelector(layerIndex) { + return "g.layer" + layerIndex + " g." + geoJson(layerIndex).name; + } + + function isSelected(layerIndex, d) { + return _chart.hasFilter() && _chart.hasFilter(getKey(layerIndex, d)); + } + + function isDeselected(layerIndex, d) { + return _chart.hasFilter() && !_chart.hasFilter(getKey(layerIndex, d)); + } + + function getKey(layerIndex, d) { + return geoJson(layerIndex).keyAccessor(d); + } + + function geoJson(index) { + return _geoJsons[index]; + } + + function renderPaths(regionG, layerIndex, data) { + var paths = regionG + .select("path") + .attr("fill", function (d) { + var currentFill = d3.select(this).attr("fill"); + if (currentFill) + return currentFill; + return "none"; + }) + .on("click", function (d) { + return _chart.onClick(d, layerIndex); + }); + + dc.transition(paths, _chart.transitionDuration()).attr("fill", function (d, i) { + return _chart.getColor(data[geoJson(layerIndex).keyAccessor(d)], i); + }); + } + + _chart.onClick = function (d, layerIndex) { + var selectedRegion = geoJson(layerIndex).keyAccessor(d); + dc.events.trigger(function () { + _chart.filter(selectedRegion); + dc.redrawAll(_chart.chartGroup()); + }); + }; + + function renderTitle(regionG, layerIndex, data) { + if (_chart.renderTitle()) { + regionG.selectAll("title").text(function (d) { + var key = getKey(layerIndex, d); + var value = data[key]; + return _chart.title()({key: key, value: value}); + }); + } + } + + _chart.doRedraw = function () { + for (var layerIndex = 0; layerIndex < _geoJsons.length; ++layerIndex) { + plotData(layerIndex); + if(_projectionFlag) { + _chart.svg().selectAll("g." + geoJson(layerIndex).name + " path").attr("d", _geoPath); + } + } + _projectionFlag = false; + }; + + /** + #### .overlayGeoJson(json, name, keyAccessor) - **mandatory** + Use this function to insert a new GeoJson map layer. This function can be invoked multiple times if you have multiple GeoJson + data layer to render on top of each other. If you overlay mutiple layers with the same name the new overlay will simply + override the existing one. + + Parameters: + * json - GeoJson feed + * name - name of the layer + * keyAccessor - accessor function used to extract "key" from the GeoJson data. Key extracted by this function should match + the keys generated in crossfilter groups. + + ```js + // insert a layer for rendering US states + chart.overlayGeoJson(statesJson.features, "state", function(d) { + return d.properties.name; + }); + ``` + + **/ + _chart.overlayGeoJson = function (json, name, keyAccessor) { + for (var i = 0; i < _geoJsons.length; ++i) { + if (_geoJsons[i].name == name) { + _geoJsons[i].data = json; + _geoJsons[i].keyAccessor = keyAccessor; + return _chart; + } + } + _geoJsons.push({name: name, data: json, keyAccessor: keyAccessor}); + return _chart; + }; + + /** + #### .projection(projection) + Set custom geo projection function. Available [d3 geo projection functions](https://github.com/mbostock/d3/wiki/Geo-Projections). + Default value: albersUsa. + + **/ + _chart.projection = function (projection) { + _geoPath.projection(projection); + _projectionFlag = true; + return _chart; + }; + + /** + #### .geoJsons() + Return all GeoJson layers currently registered with thit chart. The returned array is a reference to this chart's internal + registration data structure without copying thus any modification to this array will also modify this chart's internal + registration. + + Return: + An array of objects containing fields {name, data, accessor} + + **/ + _chart.geoJsons = function () { + return _geoJsons; + }; + + /** + #### .removeGeoJson(name) + Remove a GeoJson layer from this chart by name + + Return: chart instance + + **/ + _chart.removeGeoJson = function (name) { + var geoJsons = []; + + for (var i = 0; i < _geoJsons.length; ++i) { + var layer = _geoJsons[i]; + if (layer.name != name) { + geoJsons.push(layer); + } + } + + _geoJsons = geoJsons; + + return _chart; + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Bubble Overlay Chart [Concrete] < [Abstract Bubble Chart](#abstract-bubble-chart) < [Base Chart](#base-chart) +Bubble overlay chart is quite different from the typical bubble chart. With bubble overlay chart you can arbitrarily place +a finite number of bubbles on an existing svg or bitmap image (overlay on top of it), thus losing the typical x and y +positioning that we are used to whiling retaining the capability to visualize data using it's bubble radius and +coloring. + +Examples: +* [Canadian City Crime Stats](http://nickqizhu.github.com/dc.js/crime/index.html) + +#### dc.bubbleOverlay(parent[, chartGroup]) +Create a bubble overlay chart instance and attach it to the given parent element. + +Parameters: +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. Typically + this element should also be the parent of the underlying image. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created bubble overlay chart instance + +```js +// create a bubble overlay chart on top of "#chart-container1 svg" element using the default global chart group +var bubbleChart1 = dc.bubbleOverlayChart("#chart-container1").svg(d3.select("#chart-container1 svg")); +// create a bubble overlay chart on top of "#chart-container2 svg" element using chart group A +var bubbleChart2 = dc.compositeChart("#chart-container2", "chartGroupA").svg(d3.select("#chart-container2 svg")); +``` + +#### .svg(imageElement) - **mandatory** +Set the underlying svg image element. Unlike other dc charts this chart will not generate svg element therefore bubble overlay +chart will not work if this function is not properly invoked. If the underlying image is a bitmap, then an empty svg will need +to be manually created on top of the image. + +```js +// set up underlying svg element +chart.svg(d3.select("#chart svg")); +``` + +**/ +dc.bubbleOverlay = function(root, chartGroup) { + var BUBBLE_OVERLAY_CLASS = "bubble-overlay"; + var BUBBLE_NODE_CLASS = "node"; + var BUBBLE_CLASS = "bubble"; + + var _chart = dc.abstractBubbleChart(dc.baseChart({})); + var _g; + var _points = []; + + _chart.transitionDuration(750); + + _chart.radiusValueAccessor(function(d) { + return d.value; + }); + + /** + #### .point(name, x, y) - **mandatory** + Set up a data point on the overlay. The name of a data point should match a specific "key" among data groups generated using keyAccessor. + If a match is found (point name <-> data group key) then a bubble will be automatically generated at the position specified by the + function. x and y value specified here are relative to the underlying svg. + + **/ + _chart.point = function(name, x, y) { + _points.push({name: name, x: x, y: y}); + return _chart; + }; + + _chart.doRender = function() { + _g = initOverlayG(); + + _chart.r().range([_chart.MIN_RADIUS, _chart.width() * _chart.maxBubbleRelativeSize()]); + + initializeBubbles(); + + _chart.fadeDeselectedArea(); + + return _chart; + }; + + function initOverlayG() { + _g = _chart.select("g." + BUBBLE_OVERLAY_CLASS); + if (_g.empty()) + _g = _chart.svg().append("g").attr("class", BUBBLE_OVERLAY_CLASS); + return _g; + } + + function initializeBubbles() { + var data = mapData(); + + _points.forEach(function(point) { + var nodeG = getNodeG(point, data); + + var circle = nodeG.select("circle." + BUBBLE_CLASS); + + if (circle.empty()) + circle = nodeG.append("circle") + .attr("class", BUBBLE_CLASS) + .attr("r", 0) + .attr("fill", _chart.getColor) + .on("click", _chart.onClick); + + dc.transition(circle, _chart.transitionDuration()) + .attr("r", function(d) { + return _chart.bubbleR(d); + }); + + _chart.doRenderLabel(nodeG); + + _chart.doRenderTitles(nodeG); + }); + } + + function mapData() { + var data = {}; + _chart.data().forEach(function(datum) { + data[_chart.keyAccessor()(datum)] = datum; + }); + return data; + } + + function getNodeG(point, data) { + var bubbleNodeClass = BUBBLE_NODE_CLASS + " " + dc.utils.nameToId(point.name); + + var nodeG = _g.select("g." + dc.utils.nameToId(point.name)); + + if (nodeG.empty()) { + nodeG = _g.append("g") + .attr("class", bubbleNodeClass) + .attr("transform", "translate(" + point.x + "," + point.y + ")"); + } + + nodeG.datum(data[point.name]); + + return nodeG; + } + + _chart.doRedraw = function() { + updateBubbles(); + + _chart.fadeDeselectedArea(); + + return _chart; + }; + + function updateBubbles() { + var data = mapData(); + + _points.forEach(function(point) { + var nodeG = getNodeG(point, data); + + var circle = nodeG.select("circle." + BUBBLE_CLASS); + + dc.transition(circle, _chart.transitionDuration()) + .attr("r", function(d) { + return _chart.bubbleR(d); + }) + .attr("fill", _chart.getColor); + + _chart.doUpdateLabels(nodeG); + + _chart.doUpdateTitles(nodeG); + }); + } + + _chart.debug = function(flag) { + if(flag){ + var debugG = _chart.select("g." + dc.constants.DEBUG_GROUP_CLASS); + + if(debugG.empty()) + debugG = _chart.svg() + .append("g") + .attr("class", dc.constants.DEBUG_GROUP_CLASS); + + var debugText = debugG.append("text") + .attr("x", 10) + .attr("y", 20); + + debugG + .append("rect") + .attr("width", _chart.width()) + .attr("height", _chart.height()) + .on("mousemove", function() { + var position = d3.mouse(debugG.node()); + var msg = position[0] + ", " + position[1]; + debugText.text(msg); + }); + }else{ + _chart.selectAll(".debug").remove(); + } + + return _chart; + }; + + _chart.anchor(root, chartGroup); + + return _chart; +}; + +/** +## # Row Chart [Concrete] < [Color Chart](#color-chart) < [Base Chart](#base-chart) +Concrete row chart implementation. + +#### dc.rowChart(parent[, chartGroup]) +Create a row chart instance and attach it to the given parent element. + +Parameters: + +* parent : string - any valid d3 single selector representing typically a dom block element such as a div. +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed in a certain chart group then any interaction with such instance will only trigger events and redraw within the same chart group. + +Return a newly created row chart instance + +```js +// create a row chart under #chart-container1 element using the default global chart group +var chart1 = dc.rowChart("#chart-container1"); +// create a row chart under #chart-container2 element using chart group A +var chart2 = dc.rowChart("#chart-container2", "chartGroupA"); +``` + +**/ +dc.rowChart = function (parent, chartGroup) { + + var _g; + + var _labelOffsetX = 10; + + var _labelOffsetY = 15; + + var _gap = 5; + + var _rowCssClass = "row"; + + var _chart = dc.capped(dc.marginable(dc.colorChart(dc.baseChart({})))); + + var _x; + + var _elasticX; + + var _xAxis = d3.svg.axis().orient("bottom"); + + var _rowData; + + _chart.rowsCap = _chart.cap; + + function calculateAxisScale() { + if (!_x || _elasticX) { + var extent = d3.extent(_rowData, _chart.cappedValueAccessor); + if (extent[0] > 0) extent[0] = 0; + _x = d3.scale.linear().domain(extent) + .range([0, _chart.effectiveWidth()]); + } + _xAxis.scale(_x); + } + + function drawAxis() { + var axisG = _g.select("g.axis"); + + calculateAxisScale(); + + if (axisG.empty()) + axisG = _g.append("g").attr("class", "axis") + .attr("transform", "translate(0, " + _chart.effectiveHeight() + ")"); + + dc.transition(axisG, _chart.transitionDuration()) + .call(_xAxis); + } + + _chart.doRender = function () { + _chart.resetSvg(); + + _g = _chart.svg() + .append("g") + .attr("transform", "translate(" + _chart.margins().left + "," + _chart.margins().top + ")"); + + drawChart(); + + return _chart; + }; + + _chart.title(function (d) { + return _chart.cappedKeyAccessor(d) + ": " + _chart.cappedValueAccessor(d); + }); + + _chart.label(_chart.cappedKeyAccessor); + + _chart.x = function(x){ + if(!arguments.length) return _x; + _x = x; + return _chart; + }; + + function drawGridLines() { + _g.selectAll("g.tick") + .select("line.grid-line") + .remove(); + + _g.selectAll("g.tick") + .append("line") + .attr("class", "grid-line") + .attr("x1", 0) + .attr("y1", 0) + .attr("x2", 0) + .attr("y2", function () { + return -_chart.effectiveHeight(); + }); + } + + function drawChart() { + _rowData = _chart.data(); + + drawAxis(); + drawGridLines(); + + var rows = _g.selectAll("g." + _rowCssClass) + .data(_rowData); + + createElements(rows); + removeElements(rows); + updateElements(rows); + } + + function createElements(rows) { + var rowEnter = rows.enter() + .append("g") + .attr("class", function (d, i) { + return _rowCssClass + " _" + i; + }); + + rowEnter.append("rect").attr("width", 0); + + createLabels(rowEnter); + updateLabels(rows); + } + + function removeElements(rows) { + rows.exit().remove(); + } + + function updateElements(rows) { + var n = _rowData.length; + + var height = (_chart.effectiveHeight() - (n + 1) * _gap) / n; + + var rect = rows.attr("transform",function (d, i) { + return "translate(0," + ((i + 1) * _gap + i * height) + ")"; + }).select("rect") + .attr("height", height) + .attr("fill", _chart.getColor) + .on("click", onClick) + .classed("deselected", function (d) { + return (_chart.hasFilter()) ? !isSelectedRow(d) : false; + }) + .classed("selected", function (d) { + return (_chart.hasFilter()) ? isSelectedRow(d) : false; + }); + + dc.transition(rect, _chart.transitionDuration()) + .attr("width", function (d) { + var start = _x(0) == -Infinity ? _x(1) : _x(0); + return Math.abs(start - _x(_chart.valueAccessor()(d))); + }) + .attr("transform", translateX); + + createTitles(rows); + updateLabels(rows); + } + + function createTitles(rows) { + if (_chart.renderTitle()) { + rows.selectAll("title").remove(); + rows.append("title").text(_chart.title()); + } + } + + function createLabels(rowEnter) { + if (_chart.renderLabel()) { + rowEnter.append("text") + .on("click", onClick); + } + } + + function updateLabels(rows) { + if (_chart.renderLabel()) { + var lab = rows.select("text") + .attr("x", _labelOffsetX) + .attr("y", _labelOffsetY) + .on("click", onClick) + .attr("class", function (d, i) { + return _rowCssClass + " _" + i; + }) + .text(function (d) { + return _chart.label()(d); + }); + dc.transition(lab, _chart.transitionDuration()) + .attr("transform", translateX); + } + } + + function onClick(d) { + _chart.onClick(d); + } + + function translateX(d) { + var x = _x(_chart.cappedValueAccessor(d)), + x0 = _x(0), + s = x > x0 ? x0 : x; + return "translate("+s+",0)"; + } + + _chart.doRedraw = function () { + drawChart(); + return _chart; + }; + + _chart.xAxis = function () { + return _xAxis; + }; + + /** + #### .gap([gap]) + Get or set the vertical gap space between rows on a particular row chart instance. Default gap is 5px; + + **/ + _chart.gap = function (g) { + if (!arguments.length) return _gap; + _gap = g; + return _chart; + }; + + /** + #### .elasticX([boolean]) + Get or set the elasticity on x axis. If this attribute is set to true, then the x axis will rescle to auto-fit the data + range when filtered. + + **/ + _chart.elasticX = function (_) { + if (!arguments.length) return _elasticX; + _elasticX = _; + return _chart; + }; + + /** + #### .labelOffsetX([x]) + Get or set the x offset (horizontal space to the top left corner of a row) for labels on a particular row chart. Default x offset is 10px; + + **/ + _chart.labelOffsetX = function (o) { + if (!arguments.length) return _labelOffsetX; + _labelOffsetX = o; + return _chart; + }; + + /** + #### .labelOffsetY([y]) + Get of set the y offset (vertical space to the top left corner of a row) for labels on a particular row chart. Default y offset is 15px; + + **/ + _chart.labelOffsetY = function (o) { + if (!arguments.length) return _labelOffsetY; + _labelOffsetY = o; + return _chart; + }; + + function isSelectedRow (d) { + return _chart.hasFilter(_chart.cappedKeyAccessor(d)); + } + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Legend [Concrete] +Legend is a attachable widget that can be added to other dc charts to render horizontal legend labels. + +```js +chart.legend(dc.legend().x(400).y(10).itemHeight(13).gap(5)) +``` + +Examples: +* [Nasdaq 100 Index](http://nickqizhu.github.com/dc.js/) +* [Canadian City Crime Stats](http://nickqizhu.github.com/dc.js/crime/index.html) + +**/ +dc.legend = function () { + var LABEL_GAP = 2; + + var _legend = {}, + _parent, + _x = 0, + _y = 0, + _itemHeight = 12, + _gap = 5, + _horizontal = false, + _legendWidth = 560, + _itemWidth = 70; + + var _g; + + _legend.parent = function (p) { + if (!arguments.length) return _parent; + _parent = p; + return _legend; + }; + + _legend.render = function () { + _parent.svg().select("g.dc-legend").remove(); + _g = _parent.svg().append("g") + .attr("class", "dc-legend") + .attr("transform", "translate(" + _x + "," + _y + ")"); + + var itemEnter = _g.selectAll('g.dc-legend-item') + .data(_parent.legendables()) + .enter() + .append("g") + .attr("class", "dc-legend-item") + .classed("fadeout", function(d) { + return _parent.isLegendableHidden(d); + }) + .on("mouseover", function(d) { + _parent.legendHighlight(d); + }) + .on("mouseout", function (d) { + _parent.legendReset(d); + }) + .on("click", function (d) { + _parent.legendToggle(d); + }); + + if (_parent.legendables().some(function (legendItem) { return legendItem.dashstyle; })) { + itemEnter + .append("line") + .attr("x1", 0) + .attr("y1", _itemHeight / 2) + .attr("x2", _itemHeight) + .attr("y2", _itemHeight / 2) + .attr("stroke-width", 2) + .attr("stroke-dasharray", function(d){return d.dashstyle;}) + .attr("stroke", function(d){return d.color;}); + } else { + itemEnter + .append("rect") + .attr("width", _itemHeight) + .attr("height", _itemHeight) + .attr("fill", function(d){return d.color;}); + } + + itemEnter.append("text") + .text(function(d){return d.name;}) + .attr("x", _itemHeight + LABEL_GAP) + .attr("y", function(){return _itemHeight / 2 + (this.clientHeight?this.clientHeight:13) / 2 - 2;}); + + var _cumulativeLegendTextWidth = 0; + var row = 0; + itemEnter.attr("transform", function(d, i) { + if(_horizontal) { + var translateBy = "translate(" + _cumulativeLegendTextWidth + "," + row * legendItemHeight() + ")"; + if ((_cumulativeLegendTextWidth + _itemWidth) >= _legendWidth) { + ++row ; + _cumulativeLegendTextWidth = 0 ; + } else { + _cumulativeLegendTextWidth += _itemWidth; + } + return translateBy; + } + else { + return "translate(0," + i * legendItemHeight() + ")"; + } + }); + }; + + function legendItemHeight() { + return _gap + _itemHeight; + } + + /** + #### .x([value]) + Set or get x coordinate for legend widget. Default value: 0. + **/ + _legend.x = function (x) { + if (!arguments.length) return _x; + _x = x; + return _legend; + }; + + /** + #### .y([value]) + Set or get y coordinate for legend widget. Default value: 0. + **/ + _legend.y = function (y) { + if (!arguments.length) return _y; + _y = y; + return _legend; + }; + + /** + #### .gap([value]) + Set or get gap between legend items. Default value: 5. + **/ + _legend.gap = function (gap) { + if (!arguments.length) return _gap; + _gap = gap; + return _legend; + }; + + /** + #### .itemHeight([value]) + Set or get legend item height. Default value: 12. + **/ + _legend.itemHeight = function (h) { + if (!arguments.length) return _itemHeight; + _itemHeight = h; + return _legend; + }; + + /** + #### .horizontal([boolean]) + Position legend horizontally instead of vertically + **/ + _legend.horizontal = function(_) { + if (!arguments.length) return _horizontal; + _horizontal = _; + return _legend; + }; + + /** + #### .legendWidth([value]) + Maximum width for horizontal legend. Default value: 560. + **/ + _legend.legendWidth = function(_) { + if (!arguments.length) return _legendWidth; + _legendWidth = _; + return _legend; + }; + + /** + #### .itemWidth([value]) + legendItem width for horizontal legend. Default value: 70. + **/ + _legend.itemWidth = function(_) { + if (!arguments.length) return _itemWidth; + _itemWidth = _; + return _legend; + }; + + return _legend; +}; + +/** +## # Capped + +Capped is a mixin that groups small data elements below a _cap_ into an *others* grouping for both the Row and Pie Charts. + +The top ordered elements in the group up to the cap amount will be kept in the chart and +the sum of those below will be added to the *others* element. The keys of the elements below the cap limit are recorded +in order to repsond to onClick events and trigger filtering of all the within that grouping. + +**/ +dc.capped = function (_chart) { + + var _cap = Infinity; + + var _othersLabel = "Others"; + + var _othersGrouper = function (topRows) { + var topRowsSum = d3.sum(topRows, _chart.valueAccessor()), + allRows = _chart.group().all(), + allRowsSum = d3.sum(allRows, _chart.valueAccessor()), + topKeys = topRows.map(_chart.keyAccessor()), + allKeys = allRows.map(_chart.keyAccessor()), + topSet = d3.set(topKeys), + others = allKeys.filter(function(d){return !topSet.has(d);}); + if (allRowsSum > topRowsSum) + return topRows.concat([{"others": others, "key": _othersLabel, "value": allRowsSum - topRowsSum}]); + return topRows; + }; + + _chart.cappedKeyAccessor = function(d,i) { + if (d.others) + return d.key; + return _chart.keyAccessor()(d,i); + }; + + _chart.cappedValueAccessor = function(d,i) { + if (d.others) + return d.value; + return _chart.valueAccessor()(d,i); + }; + + _chart.data(function(group) { + if (_cap == Infinity) { + return _chart.computeOrderedGroups(group.all()); + } else { + var topRows = group.top(_cap); // ordered by crossfilter group order (default value) + topRows = _chart.computeOrderedGroups(topRows); // re-order using ordering (default key) + if (_othersGrouper) return _othersGrouper(topRows); + return topRows; + } + }); + + /** + #### .cap([count]) + Get or set the count of elements to that will be included in the cap. + **/ + _chart.cap = function (_) { + if (!arguments.length) return _cap; + _cap = _; + return _chart; + }; + + /** + #### .othersLabel([label]) + Get or set the label for *Others* slice when slices cap is specified. Default label is **Others**. + **/ + _chart.othersLabel = function (_) { + if (!arguments.length) return _othersLabel; + _othersLabel = _; + return _chart; + }; + + /** + #### .othersGrouper([grouperFunction]) + Get or set the grouper function that will perform the insertion of data for the *Others* slice if the slices cap is + specified. If set to a falsy value, no others will be added. By default the grouper function computes the sum of all + values below the cap. + ```js + chart.othersGrouper(function (data) { + // compute the value for others, presumably the sum of all values below the cap + var othersSum = yourComputeOthersValueLogic(data) + + // the keys are needed to properly filter when the others element is clicked + var othersKeys = yourComputeOthersKeysArrayLogic(data); + + // add the others row to the dataset + data.push({"key": "Others", "value": othersSum, "others": othersKeys }); + + return data; + }); + ``` + **/ + _chart.othersGrouper = function (_) { + if (!arguments.length) return _othersGrouper; + _othersGrouper = _; + return _chart; + }; + + dc.override(_chart, "onClick", function (d) { + if (d.others) + _chart.filter([d.others]); + _chart._onClick(d); + }); + + return _chart; +}; + +dc.scatterPlot = function (parent, chartGroup) { + var _chart = dc.coordinateGridChart({}); + + var _locator = function (d) { + return "translate(" + _chart.x()(_chart.keyAccessor()(d)) + "," + _chart.y()(_chart.valueAccessor()(d)) + ")"; + }; + + var _symbolSize = 3; + + _chart.transitionDuration(0); // turn off transition by default for scatterplot + + _chart.plotData = function () { + var symbols = _chart.chartBodyG().selectAll("circle.symbol") + .data(_chart.data()); + + symbols + .enter() + .append("circle") + .attr("class", "symbol") + .attr("fill", _chart.getColor(0)) + .attr("transform", _locator); + + dc.transition(symbols, _chart.transitionDuration()) + .attr("transform", _locator) + .attr("r", _symbolSize); + + dc.transition(symbols.filter(function(d){return _chart.valueAccessor()(d) === 0;}), _chart.transitionDuration()) + .attr("r", 0).remove(); // remove empty groups + + dc.transition(symbols.exit(), _chart.transitionDuration()) + .attr("r", 0).remove(); + }; + + /** + #### .symbolSize([radius]) + Set or get radius for symbols, default: 3. + + **/ + _chart.symbolSize = function(s){ + if(!arguments.length) return _symbolSize; + _symbolSize = s; + return _chart; + }; + + return _chart.anchor(parent, chartGroup); +}; + +/** +## # Number Display [Concrete] < [Base Chart](#base-chart) +A display of a single numeric value. + +Examples: + +* [Test Example](http://nickqizhu.github.io/dc.js/examples/number.html) + +#### dc.numberDisplay(parent[, chartGroup]) +Create a Number Display instance and attach it to the given parent element. + +Unlike other charts, you do not need to set a dimension. Instead a valid group object must be provided and valueAccessor that is expected to return a single value. + +Parameters: + +* parent : string - any valid d3 single selector representing typically a dom block element such as a div or span +* chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + +Return: +A newly created number display instance + +```js +// create a number display under #chart-container1 element using the default global chart group +var display1 = dc.numberDisplay("#chart-container1"); +``` + +**/ +dc.numberDisplay = function (parent, chartGroup) { + var SPAN_CLASS = 'number-display'; + var _formatNumber = d3.format(".2s"); + var _chart = dc.baseChart({}); + + // dimension not required + _chart._mandatoryAttributes(['group']); + + /** + #### .value() + Calculate and return the underlying value of the display + **/ + _chart.value = function () { + return _chart.data(); + }; + + _chart.data(function (group) { + var valObj = group.value ? group.value() : group.top(1)[0]; + return _chart.valueAccessor()(valObj); + }); + + _chart.transitionDuration(250); // good default + + _chart.doRender = function () { + var newValue = _chart.value(), + span = _chart.selectAll("."+SPAN_CLASS); + + if(span.empty()) + span = span.data([0]) + .enter() + .append("span") + .attr("class", SPAN_CLASS); + + span.transition() + .duration(_chart.transitionDuration()) + .ease('quad-out-in') + .tween("text", function () { + var interp = d3.interpolateNumber(this.lastValue || 0, newValue); + this.lastValue = newValue; + return function (t) { + this.textContent = _chart.formatNumber()(interp(t)); + }; + }); + + return _chart; + }; + + _chart.doRedraw = function(){ + return _chart.doRender(); + }; + + /** + #### .formatNumber([formatter]) + Get or set a function to format the value for the display. By default `d3.format(".2s");` is used. + + **/ + _chart.formatNumber = function (_) { + if (!arguments.length) return _formatNumber; + _formatNumber = _; + return _chart; + }; + + return _chart.anchor(parent, chartGroup); +}; + + +/** + ## # Heat Map [Concrete] < [Color Chart](#color-chart) < [Base Chart](#base-chart) + A heat map is matrix that represents the values of two dimensions of data using colors. + + #### dc.heatMap(parent[, chartGroup]) + Create a heat map instance and attach it to the given parent element. + + Parameters: + * parent : string - any valid d3 single selector representing typically a dom block element such as a div. + * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + + Return: + A newly created heat map instance + + ```js + // create a heat map under #chart-container1 element using the default global chart group + var heatMap1 = dc.heatMap("#chart-container1"); + // create a heat map under #chart-container2 element using chart group A + var heatMap2 = dc.heatMap("#chart-container2", "chartGroupA"); + ``` + + **/ +dc.heatMap = function (parent, chartGroup) { + + var DEFAULT_BORDER_RADIUS = 6.75; + + var _chartBody; + + var _cols; + var _rows; + var _xBorderRadius = DEFAULT_BORDER_RADIUS; + var _yBorderRadius = DEFAULT_BORDER_RADIUS; + + var _chart = dc.colorChart(dc.marginable(dc.baseChart({}))); + _chart._mandatoryAttributes(['group']); + _chart.title(_chart.colorAccessor()); + + var _xAxisOnClick = function (d) { filterAxis(0, d); }; + var _yAxisOnClick = function (d) { filterAxis(1, d); }; + var _boxOnClick = function (d) { + var filter = d.key; + dc.events.trigger(function() { + _chart.filter(filter); + dc.redrawAll(_chart.chartGroup()); + }); + }; + + function filterAxis(axis, value) { + var cellsOnAxis = _chart.selectAll(".box-group").filter( function (d) { + return d.key[axis] == value; + }); + var unfilteredCellsOnAxis = cellsOnAxis.filter( function (d) { + return !_chart.hasFilter(d.key); + }); + dc.events.trigger(function() { + if(unfilteredCellsOnAxis.empty()) { + cellsOnAxis.each( function (d) { + _chart.filter(d.key); + }); + } else { + unfilteredCellsOnAxis.each( function (d) { + _chart.filter(d.key); + }); + } + dc.redrawAll(_chart.chartGroup()); + }); + } + + dc.override(_chart, "filter", function(filter) { + if(filter) { + return _chart._filter(dc.filters.TwoDimensionalFilter(filter)); + } else { + return _chart._filter(); + } + + }); + + function uniq(d,i,a) { + return !i || a[i-1] != d; + } + + _chart.rows = function (_) { + if (arguments.length) { + _rows = _; + return _chart; + } + if (_rows) return _rows; + var rowValues = _chart.data().map(_chart.valueAccessor()); + rowValues.sort(d3.ascending); + return d3.scale.ordinal().domain(rowValues.filter(uniq)); + }; + + _chart.cols = function (_) { + if (arguments.length) { + _cols = _; + return _chart; + } + if (_cols) return _cols; + var colValues = _chart.data().map(_chart.keyAccessor()); + colValues.sort(d3.ascending); + return d3.scale.ordinal().domain(colValues.filter(uniq)); + }; + + _chart.doRender = function () { + _chart.resetSvg(); + + _chartBody = _chart.svg() + .append("g") + .attr("class", "heatmap") + .attr("transform", "translate(" + _chart.margins().left + "," + _chart.margins().top + ")"); + + return _chart.doRedraw(); + }; + + _chart.doRedraw = function () { + var rows = _chart.rows(), + cols = _chart.cols(), + rowCount = rows.domain().length, + colCount = cols.domain().length, + boxWidth = Math.floor(_chart.effectiveWidth() / colCount), + boxHeight = Math.floor(_chart.effectiveHeight() / rowCount); + + cols.rangeRoundBands([0, _chart.effectiveWidth()]); + rows.rangeRoundBands([_chart.effectiveHeight(), 0]); + + var boxes = _chartBody.selectAll("g.box-group").data(_chart.data(), function(d,i) { + return _chart.keyAccessor()(d,i) + '\0' + _chart.valueAccessor()(d,i); + }); + var gEnter = boxes.enter().append("g") + .attr("class", "box-group"); + + gEnter.append("rect") + .attr("class","heat-box") + .attr("fill", "white") + .on("click", _chart.boxOnClick()); + + gEnter.append("title") + .text(_chart.title()); + + dc.transition(boxes.selectAll("rect"), _chart.transitionDuration()) + .attr("x", function(d,i) { return cols(_chart.keyAccessor()(d,i)); }) + .attr("y", function(d,i) { return rows(_chart.valueAccessor()(d,i)); }) + .attr("rx", _xBorderRadius) + .attr("ry", _yBorderRadius) + .attr("fill", _chart.getColor) + .attr("width", boxWidth) + .attr("height", boxHeight); + + boxes.exit().remove(); + + var gCols = _chartBody.selectAll("g.cols"); + if (gCols.empty()) + gCols = _chartBody.append("g").attr("class", "cols axis"); + gCols.selectAll('text').data(cols.domain()) + .enter().append("text") + .attr("x", function(d) { return cols(d) + boxWidth/2; }) + .style("text-anchor", "middle") + .attr("y", _chart.effectiveHeight()) + .attr("dy", 12) + .on("click", _chart.xAxisOnClick()) + .text(function(d) { return d; }); + var gRows = _chartBody.selectAll("g.rows"); + if (gRows.empty()) + gRows = _chartBody.append("g").attr("class", "rows axis"); + gRows.selectAll('text').data(rows.domain()) + .enter().append("text") + .attr("dy", 6) + .style("text-anchor", "end") + .attr("x", 0) + .attr("dx", -2) + .on("click", _chart.yAxisOnClick()) + .text(function(d) { return d; }); + dc.transition(gRows.selectAll('text'), _chart.transitionDuration()) + .text(function(d) { return d; }) + .attr("y", function(d) { return rows(d) + boxHeight/2; }); + + if (_chart.hasFilter()) { + _chart.selectAll("g.box-group").each(function (d) { + if (_chart.isSelectedNode(d)) { + _chart.highlightSelected(this); + } else { + _chart.fadeDeselected(this); + } + }); + } else { + _chart.selectAll("g.box-group").each(function (d) { + _chart.resetHighlight(this); + }); + } + }; + + _chart.boxOnClick = function (f) { + if (!arguments.length) return _boxOnClick; + _boxOnClick = f; + return _chart; + }; + + _chart.xAxisOnClick = function (f) { + if (!arguments.length) return _xAxisOnClick; + _xAxisOnClick = f; + return _chart; + }; + + _chart.yAxisOnClick = function (f) { + if (!arguments.length) return _yAxisOnClick; + _yAxisOnClick = f; + return _chart; + }; + + _chart.xBorderRadius = function (d) { + if (arguments.length) { + _xBorderRadius = d; + } + return _xBorderRadius; + }; + + _chart.yBorderRadius = function (d) { + if (arguments.length) { + _yBorderRadius = d; + } + return _yBorderRadius; + }; + + _chart.isSelectedNode = function (d) { + return _chart.hasFilter(d.key); + }; + + return _chart.anchor(parent, chartGroup); +}; + +// https://raw.github.com/d3/d3-plugins/56f25a3b54446c921e23a7360f1a0dea2508870f/box/box.js +(function() { + +// Inspired by http://informationandvisualization.de/blog/box-plot +d3.box = function() { + var width = 1, + height = 1, + duration = 0, + domain = null, + value = Number, + whiskers = boxWhiskers, + quartiles = boxQuartiles, + tickFormat = null; + + // For each small multiple… + function box(g) { + g.each(function(d, i) { + d = d.map(value).sort(d3.ascending); + var g = d3.select(this), + n = d.length, + min = d[0], + max = d[n - 1]; + + // Compute quartiles. Must return exactly 3 elements. + var quartileData = d.quartiles = quartiles(d); + + // Compute whiskers. Must return exactly 2 elements, or null. + var whiskerIndices = whiskers && whiskers.call(this, d, i), + whiskerData = whiskerIndices && whiskerIndices.map(function(i) { return d[i]; }); + + // Compute outliers. If no whiskers are specified, all data are "outliers". + // We compute the outliers as indices, so that we can join across transitions! + var outlierIndices = whiskerIndices + ? d3.range(0, whiskerIndices[0]).concat(d3.range(whiskerIndices[1] + 1, n)) + : d3.range(n); + + // Compute the new x-scale. + var x1 = d3.scale.linear() + .domain(domain && domain.call(this, d, i) || [min, max]) + .range([height, 0]); + + // Retrieve the old x-scale, if this is an update. + var x0 = this.__chart__ || d3.scale.linear() + .domain([0, Infinity]) + .range(x1.range()); + + // Stash the new scale. + this.__chart__ = x1; + + // Note: the box, median, and box tick elements are fixed in number, + // so we only have to handle enter and update. In contrast, the outliers + // and other elements are variable, so we need to exit them! Variable + // elements also fade in and out. + + // Update center line: the vertical line spanning the whiskers. + var center = g.selectAll("line.center") + .data(whiskerData ? [whiskerData] : []); + + center.enter().insert("line", "rect") + .attr("class", "center") + .attr("x1", width / 2) + .attr("y1", function(d) { return x0(d[0]); }) + .attr("x2", width / 2) + .attr("y2", function(d) { return x0(d[1]); }) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .style("opacity", 1) + .attr("y1", function(d) { return x1(d[0]); }) + .attr("y2", function(d) { return x1(d[1]); }); + + center.transition() + .duration(duration) + .style("opacity", 1) + .attr("y1", function(d) { return x1(d[0]); }) + .attr("y2", function(d) { return x1(d[1]); }); + + center.exit().transition() + .duration(duration) + .style("opacity", 1e-6) + .attr("y1", function(d) { return x1(d[0]); }) + .attr("y2", function(d) { return x1(d[1]); }) + .remove(); + + // Update innerquartile box. + var box = g.selectAll("rect.box") + .data([quartileData]); + + box.enter().append("rect") + .attr("class", "box") + .attr("x", 0) + .attr("y", function(d) { return x0(d[2]); }) + .attr("width", width) + .attr("height", function(d) { return x0(d[0]) - x0(d[2]); }) + .transition() + .duration(duration) + .attr("y", function(d) { return x1(d[2]); }) + .attr("height", function(d) { return x1(d[0]) - x1(d[2]); }); + + box.transition() + .duration(duration) + .attr("y", function(d) { return x1(d[2]); }) + .attr("height", function(d) { return x1(d[0]) - x1(d[2]); }); + + // Update median line. + var medianLine = g.selectAll("line.median") + .data([quartileData[1]]); + + medianLine.enter().append("line") + .attr("class", "median") + .attr("x1", 0) + .attr("y1", x0) + .attr("x2", width) + .attr("y2", x0) + .transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1); + + medianLine.transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1); + + // Update whiskers. + var whisker = g.selectAll("line.whisker") + .data(whiskerData || []); + + whisker.enter().insert("line", "circle, text") + .attr("class", "whisker") + .attr("x1", 0) + .attr("y1", x0) + .attr("x2", width) + .attr("y2", x0) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1) + .style("opacity", 1); + + whisker.transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1) + .style("opacity", 1); + + whisker.exit().transition() + .duration(duration) + .attr("y1", x1) + .attr("y2", x1) + .style("opacity", 1e-6) + .remove(); + + // Update outliers. + var outlier = g.selectAll("circle.outlier") + .data(outlierIndices, Number); + + outlier.enter().insert("circle", "text") + .attr("class", "outlier") + .attr("r", 5) + .attr("cx", width / 2) + .attr("cy", function(i) { return x0(d[i]); }) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("cy", function(i) { return x1(d[i]); }) + .style("opacity", 1); + + outlier.transition() + .duration(duration) + .attr("cy", function(i) { return x1(d[i]); }) + .style("opacity", 1); + + outlier.exit().transition() + .duration(duration) + .attr("cy", function(i) { return x1(d[i]); }) + .style("opacity", 1e-6) + .remove(); + + // Compute the tick format. + var format = tickFormat || x1.tickFormat(8); + + // Update box ticks. + var boxTick = g.selectAll("text.box") + .data(quartileData); + + boxTick.enter().append("text") + .attr("class", "box") + .attr("dy", ".3em") + .attr("dx", function(d, i) { return i & 1 ? 6 : -6; }) + .attr("x", function(d, i) { return i & 1 ? width : 0; }) + .attr("y", x0) + .attr("text-anchor", function(d, i) { return i & 1 ? "start" : "end"; }) + .text(format) + .transition() + .duration(duration) + .attr("y", x1); + + boxTick.transition() + .duration(duration) + .text(format) + .attr("y", x1); + + // Update whisker ticks. These are handled separately from the box + // ticks because they may or may not exist, and we want don't want + // to join box ticks pre-transition with whisker ticks post-. + var whiskerTick = g.selectAll("text.whisker") + .data(whiskerData || []); + + whiskerTick.enter().append("text") + .attr("class", "whisker") + .attr("dy", ".3em") + .attr("dx", 6) + .attr("x", width) + .attr("y", x0) + .text(format) + .style("opacity", 1e-6) + .transition() + .duration(duration) + .attr("y", x1) + .style("opacity", 1); + + whiskerTick.transition() + .duration(duration) + .text(format) + .attr("y", x1) + .style("opacity", 1); + + whiskerTick.exit().transition() + .duration(duration) + .attr("y", x1) + .style("opacity", 1e-6) + .remove(); + }); + d3.timer.flush(); + } + + box.width = function(x) { + if (!arguments.length) return width; + width = x; + return box; + }; + + box.height = function(x) { + if (!arguments.length) return height; + height = x; + return box; + }; + + box.tickFormat = function(x) { + if (!arguments.length) return tickFormat; + tickFormat = x; + return box; + }; + + box.duration = function(x) { + if (!arguments.length) return duration; + duration = x; + return box; + }; + + box.domain = function(x) { + if (!arguments.length) return domain; + domain = x == null ? x : d3.functor(x); + return box; + }; + + box.value = function(x) { + if (!arguments.length) return value; + value = x; + return box; + }; + + box.whiskers = function(x) { + if (!arguments.length) return whiskers; + whiskers = x; + return box; + }; + + box.quartiles = function(x) { + if (!arguments.length) return quartiles; + quartiles = x; + return box; + }; + + return box; +}; + +function boxWhiskers(d) { + return [0, d.length - 1]; +} + +function boxQuartiles(d) { + return [ + d3.quantile(d, .25), + d3.quantile(d, .5), + d3.quantile(d, .75) + ]; +} + +})(); + +/** + ## # Box Plot [Concrete] < [CoordinateGrid Chart](#coordinate-grid-chart) + A box plot is a chart that depicts numerical data via their quartile ranges. + + #### dc.boxPlot(parent[, chartGroup]) + Create a box plot instance and attach it to the given parent element. + + Parameters: + * parent : string - any valid d3 single selector representing typically a dom block element such as a div. + * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed + in a certain chart group then any interaction with such instance will only trigger events and redraw within the same + chart group. + + Return: + A newly created box plot instance + + ```js + // create a box plot under #chart-container1 element using the default global chart group + var boxPlot1 = dc.boxPlot("#chart-container1"); + // create a box plot under #chart-container2 element using chart group A + var boxPlot2 = dc.boxPlot("#chart-container2", "chartGroupA"); + ``` + + **/ +dc.boxPlot = function (parent, chartGroup) { + var _chart = dc.coordinateGridChart({}); + + var _whisker_iqr_factor = 1.5; + var _whiskers_iqr = default_whiskers_iqr; + var _whiskers = _whiskers_iqr(_whisker_iqr_factor); + + var _box = d3.box(); + var _tickFormat = null; + + + var _boxWidth = function (innerChartWidth, xUnits) { + if (_chart.isOrdinal()) + return _chart.x().rangeBand(); + else + return innerChartWidth / (1 + _chart.boxPadding()) / xUnits; + }; + + // default padding to handle min/max whisker text + _chart.yAxisPadding(12); + + // default to ordinal + _chart.x(d3.scale.ordinal()); + _chart.xUnits(dc.units.ordinal); + + // valueAccessor should return an array of values that can be coerced into numbers + // or if data is overloaded for a static array of arrays, it should be `Number` + _chart.data(function(group) { + return group.all().map(function (d) { + d.map = function(accessor) { return accessor.call(d,d); }; + return d; + }); + }); + + /** + ### .boxPadding([padding]) + Get or set the spacing between boxes as a fraction of bar size. Valid values are within 0-1. + See the [d3 docs](https://github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-ordinal_rangeBands) + for a visual description of how the padding is applied. + + Default: 0.8 + **/ + _chart.boxPadding = _chart._rangeBandPadding; + _chart.boxPadding(0.8); + + /** + ### .outerPadding([padding]) + Get or set the outer padding on an ordinal box chart. This setting has no effect on non-ordinal charts + or on charts with a custom `.boxWidth`. Padding equivlent in width to `padding * barWidth` will be + added on each side of the chart. + + Default: 0.5 + **/ + _chart.outerPadding = _chart._outerRangeBandPadding; + _chart.outerPadding(0.5); + + /** + #### .boxWidth(width || function(innerChartWidth, xUnits) { ... }) + Get or set the numerical width of the boxplot box. Provided width may also be a function. + This function takes as parameters the chart width without the right and left margins + as well as the number of x units. + **/ + _chart.boxWidth = function(_) { + if (!arguments.length) return _boxWidth; + _boxWidth = d3.functor(_); + return _chart; + }; + + var boxTransform = function (d, i) { + var xOffset = _chart.x()(_chart.keyAccessor()(d,i)); + return "translate(" + xOffset + ",0)"; + }; + + _chart.plotData = function () { + var _calculatedBoxWidth = _boxWidth(_chart.effectiveWidth(), _chart.xUnitCount()); + + _box.whiskers(_whiskers) + .width(_calculatedBoxWidth) + .height(_chart.effectiveHeight()) + .value(_chart.valueAccessor()) + .domain(_chart.y().domain()) + .duration(_chart.transitionDuration()) + .tickFormat(_tickFormat); + + + var boxesG = _chart.chartBodyG().selectAll('g.box').data(_chart.data()); + + renderBoxes(boxesG); + updateBoxes(boxesG); + removeBoxes(boxesG); + + _chart.fadeDeselectedArea(); + }; + + function renderBoxes(boxesG) { + var boxesGEnter = boxesG.enter().append("g"); + + boxesGEnter + .attr("class", "box") + .attr("transform", boxTransform) + .call(_box) + .on("click", function(d) { + _chart.filter(d.key); + //_chart.focus(_chart.filter()); + dc.redrawAll(_chart.chartGroup()); + }); + } + + function updateBoxes(boxesG) { + dc.transition(boxesG, _chart.transitionDuration()) + .attr("transform", boxTransform) + .call(_box) + .each(function() { + d3.select(this).select('rect.box').attr("fill", _chart.getColor); + }); + } + + function removeBoxes(boxesG) { + boxesG.exit().remove().call(_box); + } + + _chart.fadeDeselectedArea = function () { + if (_chart.hasFilter()) { + _chart.selectAll("g.box").each(function (d) { + if (_chart.isSelectedNode(d)) { + _chart.highlightSelected(this); + } else { + _chart.fadeDeselected(this); + } + }); + } else { + _chart.selectAll("g.box").each(function () { + _chart.resetHighlight(this); + }); + } + }; + + _chart.isSelectedNode = function (d) { + return _chart.hasFilter(d.key); + }; + + _chart.yAxisMin = function () { + var min = d3.min(_chart.data(), function (e) { + return d3.min(_chart.valueAccessor()(e)); + }); + return dc.utils.subtract(min, _chart.yAxisPadding()); + }; + + _chart.yAxisMax = function () { + var max = d3.max(_chart.data(), function (e) { + return d3.max(_chart.valueAccessor()(e)); + }); + return dc.utils.add(max, _chart.yAxisPadding()); + }; + + /** + #### .tickFormat() + Set the numerical format of the boxplot median, whiskers and quartile labels. Defaults to integer. + ```js + // format ticks to 2 decimal places + chart.tickFormat(d3.format(".2f")); + ``` + **/ + _chart.tickFormat = function(x) { + if (!arguments.length) return _tickFormat; + _tickFormat = x; + return _chart; + }; + + // Returns a function to compute the interquartile range. + function default_whiskers_iqr(k) { + return function (d) { + var q1 = d.quartiles[0], + q3 = d.quartiles[2], + iqr = (q3 - q1) * k, + i = -1, + j = d.length; + while (d[++i] < q1 - iqr); + while (d[--j] > q3 + iqr); + return [i, j]; + }; + } + + return _chart.anchor(parent, chartGroup); +}; + +return dc;})(); + +dc.filters = {}; + +dc.filters.RangedFilter = function(low, high) { + var range = Array(low, high); + range.isFiltered = function(value) { + return value >= this[0] && value < this[1]; + }; + + return range; +}; + +dc.filters.TwoDimensionalFilter = function(array) { + var filter = array; + filter.isFiltered = function(value) { + return value.length && value.length == filter.length && + value[0] == filter[0] && value[1] == filter[1]; + }; + + return filter; +}; diff --git a/admin/view/javascript/shopunity/charts_svg/dc.min.js b/admin/view/javascript/shopunity/charts_svg/dc.min.js new file mode 100755 index 0000000..3763b52 --- /dev/null +++ b/admin/view/javascript/shopunity/charts_svg/dc.min.js @@ -0,0 +1,4 @@ +dc=function(){"use strict";var a={version:"2.0.0-dev",constants:{CHART_CLASS:"dc-chart",DEBUG_GROUP_CLASS:"debug",STACK_CLASS:"stack",DESELECTED_CLASS:"deselected",SELECTED_CLASS:"selected",NODE_INDEX_NAME:"__index__",GROUP_INDEX_NAME:"__group_index__",DEFAULT_CHART_GROUP:"__default_chart_group__",EVENT_DELAY:40,NEGLIGIBLE_NUMBER:1e-10},_renderlet:null};a.chartRegistry=function(){function b(b){return b||(b=a.constants.DEFAULT_CHART_GROUP),c[b]||(c[b]=[]),b}var c={};return{has:function(a){for(var b in c)if(c[b].indexOf(a)>=0)return!0;return!1},register:function(a,d){d=b(d),c[d].push(a)},clear:function(a){a?delete c[a]:c={}},list:function(a){return a=b(a),c[a]}}}(),a.registerChart=function(b,c){a.chartRegistry.register(b,c)},a.hasChart=function(b){return a.chartRegistry.has(b)},a.deregisterAllCharts=function(b){a.chartRegistry.clear(b)},a.filterAll=function(b){for(var c=a.chartRegistry.list(b),d=0;d=c||void 0===c||a.disableTransitions)return b;var e=b.transition().duration(c);return"function"==typeof d&&d(e),e},a.units={},a.units.integers=function(a,b){return Math.abs(b-a)},a.units.ordinal=function(a,b,c){return c},a.units.fp={},a.units.fp.precision=function(b){var c=function(b,d){var e=Math.abs((d-b)/c.resolution);return a.utils.isNegligible(e-Math.floor(e))?Math.floor(e):Math.ceil(e)};return c.resolution=b,c},a.round={},a.round.floor=function(a){return Math.floor(a)},a.round.ceil=function(a){return Math.ceil(a)},a.round.round=function(a){return Math.round(a)},a.override=function(a,b,c){var d=a[b];a["_"+b]=d,a[b]=c},a.renderlet=function(b){return arguments.length?(a._renderlet=b,a):a._renderlet},a.instanceOfChart=function(a){return a instanceof Object&&a.__dc_flag__&&!0},a.errors={},a.errors.Exception=function(a){var b=a||"Unexpected internal error";this.message=b,this.toString=function(){return b}},a.errors.InvalidStateException=function(){a.errors.Exception.apply(this,arguments)},a.dateFormat=d3.time.format("%m/%d/%Y"),a.printers={},a.printers.filters=function(b){for(var c="",d=0;d0&&(c+=", "),c+=a.printers.filter(b[d]);return c},a.printers.filter=function(b){var c="";return b&&(b instanceof Array?b.length>=2?c="["+a.utils.printSingleValue(b[0])+" -> "+a.utils.printSingleValue(b[1])+"]":b.length>=1&&(c=a.utils.printSingleValue(b[0])):c=a.utils.printSingleValue(b)),c},a.pluck=function(a,b){return function(c,d){return b?b.call(this,c[a],d):c[a]}},a.utils={},a.utils.printSingleValue=function(b){var c=""+b;return b instanceof Date?c=a.dateFormat(b):"string"==typeof b?c=b:a.utils.isFloat(b)?c=a.utils.printSingleValue.fformat(b):a.utils.isInteger(b)&&(c=Math.round(b)),c},a.utils.printSingleValue.fformat=d3.format(".2f"),a.utils.add=function(a,b){if("string"==typeof b&&(b=b.replace("%","")),a instanceof Date){"string"==typeof b&&(b=+b);var c=new Date;return c.setTime(a.getTime()),c.setDate(a.getDate()+b),c}if("string"==typeof b){var d=+b/100;return a>0?a*(1+d):a*(1-d)}return a+b},a.utils.subtract=function(a,b){if("string"==typeof b&&(b=b.replace("%","")),a instanceof Date){"string"==typeof b&&(b=+b);var c=new Date;return c.setTime(a.getTime()),c.setDate(a.getDate()-b),c}if("string"==typeof b){var d=+b/100;return 0>a?a*(1+d):a*(1-d)}return a-b},a.utils.GroupStack=function(){function a(a){d[a]||(d[a]=[])}var b,c,d=[[]],e=[];this.setDataPoint=function(b,c,e){a(b),d[b][c]=e},this.getDataPoint=function(b,c){a(b);var e=d[b][c];return void 0===e&&(e=0),e},this.addGroup=function(a,c){return c||(c=b),e.push([a,c]),e.length-1},this.addNamedGroup=function(a,b,c){var d=this.addGroup(a,c);return e[d].name=b,b},this.getGroupByIndex=function(a){return e[a][0]},this.getAccessorByIndex=function(a){return e[a][1]},this.getNameOfVisibleByIndex=function(a){if(-1===a){if(!c)return;a++}var b=e.filter(function(a){return!a.hidden});return b[a].name},this.size=function(){return e.length},this.clear=function(){d=[],e=[]},this.setDefaultAccessor=function(a){b=a},this.getDataLayers=function(){return d},this.clearDataLayers=function(){d=[[]]},this.showGroups=function(a,b){b&&(c=!1),this.toggleGroups(a,!1)},this.hideGroups=function(a,b){b&&(c=!0),this.toggleGroups(a,!0)},this.toggleGroups=function(a,b){for(var c=0;c0&&e[b-1].hidden)){for(var f={index:b,points:[]},g=d[b],h=0;h-a.constants.NEGLIGIBLE_NUMBER},a.utils.clamp=function(a,b,c){return b>a?b:a>c?c:a};var b=0;return a.utils.uniqueId=function(){return++b},a.utils.groupMax=function(b,c){var d=d3.max(b.all(),c);return a.utils.isNegligible(d)&&(d=0),d},a.utils.groupMin=function(b,c){var d=d3.min(b.all(),c);return a.utils.isNegligible(d)&&(d=0),d},a.utils.nameToId=function(a){return a.toLowerCase().replace(/[\s]/g,"_").replace(/[\.']/g,"")},a.utils.appendOrSelect=function(a,b){var c=a.select(b);return c.empty()&&(c=a.append(b)),c},a.utils.createLegendable=function(a,b,c,d){var e={name:a._getGroupName(b,c),data:b};return d&&(e.color=d),a.dashStyle&&a.dashStyle()&&(e.dashstyle=a.dashStyle()),e},a.utils.safeNumber=function(b){return a.utils.isNumber(+b)?+b:0},a.events={current:null},a.events.trigger=function(b,c){return c?(a.events.current=b,setTimeout(function(){b==a.events.current&&b()},c),void 0):(b(),void 0)},a.baseChart=function(b){function c(a,b,c){var d=a.chartID(),e="__names__";c&&c!=a.valueAccessor()||(c="default"),b[e]||(b[e]={}),b[e][d]||(b[e][d]={a:[],n:[]});var f=b[e][d].a.indexOf(c);return-1==f&&(f=b[e][d].a.length,b[e][d].a[f]=c,b[e][d].n[f]={name:""}),b[e][d].n[f]}function d(){return o=b.root().append("svg").attr("width",b.width()).attr("height",b.height())}function e(c){if(!b[c]||!b[c]())throw new a.errors.InvalidStateException("Mandatory attribute chart."+c+" is missing on chart[#"+b.anchorName()+"]")}function f(a){L.splice(L.indexOf(a),1),i(),b._invokeFilteredListener(a)}function g(a){L.push(a),i(),b._invokeFilteredListener(a)}function h(){L=[],i(),b._invokeFilteredListener(null)}function i(){if(b.dimension()&&b.dimension().filter){var a=M(b.dimension(),L);L=a?a:L}}function j(){for(var a=0;ar?b:r},t=s,u=200,v=function(a){var b=a&&a.getBoundingClientRect&&a.getBoundingClientRect().height;return b&&b>u?b:u},w=v,x=a.pluck("key"),y=a.pluck("value"),z=a.pluck("key"),A=a.pluck("key"),B=!1,C=function(a){return b.keyAccessor()(a)+": "+b.valueAccessor()(a)},D=!1,E=750,F=a.printers.filters,G=[],H=["dimension","group"],I=a.constants.DEFAULT_CHART_GROUP,J=function(){},K={preRender:J,postRender:J,preRedraw:J,postRedraw:J,filtered:J,zoomed:J},L=[],M=function(a,b){return a.filter(null),0===b.length?a.filter(null):a.filterFunction(function(a){for(var c=0;c0&&o?o.transition().duration(b.transitionDuration()).each("end",function(){j(),a&&K[a](b)}):(j(),a&&K[a](b))},b.redraw=function(){K.preRedraw(b);var a=b.doRedraw();return b.activateRenderlets("postRedraw"),a},b._invokeFilteredListener=function(a){void 0!==a&&K.filtered(b,a)},b._invokeZoomedListener=function(){K.zoomed(b)},b.hasFilter=function(a){return arguments.length?L.indexOf(a)>=0:L.length>0},b.replaceFilter=function(a){L=[],b.filter(a)},b.filter=function(a){return arguments.length?(a instanceof Array&&a[0]instanceof Array?(a[0].forEach(function(a){b.hasFilter(a)?L.splice(L.indexOf(a),1):L.push(a)}),i(),b._invokeFilteredListener(a)):null===a?h():b.hasFilter(a)?f(a):g(a),null!==n&&b.hasFilter()?b.turnOnControls():b.turnOffControls(),b):L.length>0?L[0]:null},b.filters=function(){return L},b.highlightSelected=function(b){d3.select(b).classed(a.constants.SELECTED_CLASS,!0),d3.select(b).classed(a.constants.DESELECTED_CLASS,!1)},b.fadeDeselected=function(b){d3.select(b).classed(a.constants.SELECTED_CLASS,!1),d3.select(b).classed(a.constants.DESELECTED_CLASS,!0)},b.resetHighlight=function(b){d3.select(b).classed(a.constants.SELECTED_CLASS,!1),d3.select(b).classed(a.constants.DESELECTED_CLASS,!1)},b.onClick=function(c){var d=b.keyAccessor()(c);a.events.trigger(function(){b.filter(d),a.redrawAll(b.chartGroup())})},b.filterHandler=function(a){return arguments.length?(M=a,b):M},b.doRender=function(){return b},b.doRedraw=function(){return b},b.legendables=function(){return[]},b.legendHighlight=function(){},b.legendReset=function(){},b.legendToggle=function(){},b.isLegendableHidden=function(){return!1},b.keyAccessor=function(a){return arguments.length?(x=a,b):x},b.valueAccessor=function(a){return arguments.length?(y=a,b):y},b.label=function(a){return arguments.length?(z=a,B=!0,b):z},b.renderLabel=function(a){return arguments.length?(B=a,b):B},b.title=function(a){return arguments.length?(C=a,D=!0,b):C},b.renderTitle=function(a){return arguments.length?(D=a,b):D},b.renderlet=function(a){return G.push(a),b},b.chartGroup=function(a){return arguments.length?(I=a,b):I},b.expireCache=function(){return b},b.legend=function(a){return arguments.length?(q=a,q.parent(b),b):q},b.on=function(a,c){return K[a]=c,b},b.chartID=function(){return b.__dc_flag__},b},a.marginable=function(a){var b={top:10,right:50,bottom:30,left:30};return a.margins=function(c){return arguments.length?(b=c,a):b},a.effectiveWidth=function(){return a.width()-a.margins().left-a.margins().right},a.effectiveHeight=function(){return a.height()-a.margins().top-a.margins().bottom},a},a.coordinateGridChart=function(b){function c(a){if(b.elasticX()&&!b.isOrdinal())y.domain([b.xAxisMin(),b.xAxisMax()]);else if(b.isOrdinal()&&0===y.domain().length){var c=b.computeOrderedGroups(b.data());y.domain(c.map(b.keyAccessor()))}b.isOrdinal()?y.rangeBands([0,b.xAxisLength()],ab,_):y.range([0,b.xAxisLength()]),H=H.scale(b.x()).orient("bottom"),d(a)}function d(c){var d=c.selectAll("g."+r);if(T){d.empty()&&(d=c.insert("g",":first-child").attr("class",p+" "+r).attr("transform","translate("+b.yAxisX()+","+b.margins().top+")"));var e=H.tickValues()?H.tickValues():y.ticks(H.ticks()[0]),f=d.selectAll("line").data(e),g=f.enter().append("line").attr("x1",function(a){return y(a)}).attr("y1",b.xAxisY()-b.margins().top).attr("x2",function(a){return y(a)}).attr("y2",0).attr("opacity",0);a.transition(g,b.transitionDuration()).attr("opacity",1),a.transition(f,b.transitionDuration()).attr("x1",function(a){return y(a)}).attr("y1",b.xAxisY()-b.margins().top).attr("x2",function(a){return y(a)}).attr("y2",0),f.exit().remove()}else d.selectAll("line").remove()}function e(a){(void 0===B||b.elasticY())&&(B=d3.scale.linear(),B.domain([b.yAxisMin(),b.yAxisMax()]).rangeRound([b.yAxisHeight(),0])),B.range([b.yAxisHeight(),0]),M=M.scale(B).orient("left"),f(a)}function f(c){var d=c.selectAll("g."+q);if(S){var e=M.tickValues()?M.tickValues():B.ticks(M.ticks()[0]);d.empty()&&(d=c.insert("g",":first-child").attr("class",p+" "+q).attr("transform","translate("+b.yAxisX()+","+b.margins().top+")"));var f=d.selectAll("line").data(e),g=f.enter().append("line").attr("x1",1).attr("y1",function(a){return B(a)}).attr("x2",b.xAxisLength()).attr("y2",function(a){return B(a)}).attr("opacity",0);a.transition(g,b.transitionDuration()).attr("opacity",1),a.transition(f,b.transitionDuration()).attr("x1",1).attr("y1",function(a){return B(a)}).attr("x2",b.xAxisLength()).attr("y2",function(a){return B(a)}),f.exit().remove()}else d.selectAll("line").remove()}function g(){return b.xAxisY()-b.margins().top}function h(){return b.anchorName()+"-clip"}function i(){var c=a.utils.appendOrSelect(v,"defs"),d=a.utils.appendOrSelect(c,"clipPath").attr("id",h()),e=2*$;a.utils.appendOrSelect(d,"rect").attr("width",b.xAxisLength()+e).attr("height",b.yAxisHeight()+e)}function j(a){c(b.g()),e(b.g()),b.plotData(),(b.elasticX()||U||a)&&b.renderXAxis(b.g()),(b.elasticY()||a)&&b.renderYAxis(b.g()),a?b.renderBrush(b.g()):b.redrawBrush(b.g())}function k(){Z?b._enableMouseZoom():b._disableMouseZoom()}function l(){U=!0,W&&(b.x().domain(m(b.x().domain(),z)),F&&b.x().domain(m(b.x().domain(),F.x().domain())));var c=b.x().domain(),d=a.filters.RangedFilter(c[0],c[1]);b.replaceFilter(d),b.rescale(),b.redraw(),F&&!n(b.filter(),F.filter())&&a.events.trigger(function(){F.replaceFilter(d),F.redraw()}),b._invokeZoomedListener(),a.events.trigger(function(){a.redrawAll(b.chartGroup())},a.constants.EVENT_DELAY),U=!n(c,z)}function m(a,b){var c=[];return c[0]=d3.max([a[0],b[0]]),c[1]=d3.min([a[1],b[1]]),c}function n(a,b){return a||b?0===a.length&&0===b.length?!0:a&&b&&a[0].valueOf()===b[0].valueOf()&&a[1].valueOf()===b[1].valueOf()?!0:!1:!0}function o(a){return a instanceof Array&&a.length>1}var p="grid-line",q="horizontal",r="vertical",s="y-axis-label",t="x-axis-label",u=12;b=a.colorChart(a.marginable(a.baseChart(b))),b.colors(d3.scale.category10()),b._mandatoryAttributes().push("x");var v,w,x,y,z,A,B,C,D,E,F,G,H=d3.svg.axis(),I=a.units.integers,J=0,K=!1,L=0,M=d3.svg.axis(),N=0,O=!1,P=0,Q=d3.svg.brush(),R=!0,S=!1,T=!1,U=!1,V=[1,1/0],W=!0,X=d3.behavior.zoom().on("zoom",l),Y=d3.behavior.zoom().on("zoom",null),Z=!1,$=0,_=.5,ab=0;return b.rescale=function(){E=void 0},b.rangeChart=function(a){return arguments.length?(F=a,F.focusChart(b),b):F},b.zoomScale=function(a){return arguments.length?(V=a,b):V},b.zoomOutRestrict=function(a){return arguments.length?(V[0]=a?1:0,W=a,b):W},b._generateG=function(a){return v=void 0===a?b.svg():a,w=v.append("g"),x=w.append("g").attr("class","chart-body").attr("transform","translate("+b.margins().left+", "+b.margins().top+")").attr("clip-path","url(#"+h()+")"),w},b.g=function(a){return arguments.length?(w=a,b):w},b.mouseZoomable=function(a){return arguments.length?(Z=a,b):Z},b.chartBodyG=function(a){return arguments.length?(x=a,b):x},b.x=function(a){return arguments.length?(y=a,z=y.domain(),b):y},b.xOriginalDomain=function(){return z},b.xUnits=function(a){return arguments.length?(I=a,b):I},b.xAxis=function(a){return arguments.length?(H=a,b):H},b.elasticX=function(a){return arguments.length?(K=a,b):K},b.xAxisPadding=function(a){return arguments.length?(J=a,b):J},b.xUnitCount=function(){if(void 0===E){var a=b.xUnits()(b.x().domain()[0],b.x().domain()[1],b.x().domain());E=a instanceof Array?a.length:a}return E},b.isOrdinal=function(){return b.xUnits()===a.units.ordinal},b.renderXAxis=function(c){var d=c.selectAll("g.x");d.empty()&&(d=c.append("g").attr("class","axis x").attr("transform","translate("+b.margins().left+","+b.xAxisY()+")"));var e=c.selectAll("text."+t);e.empty()&&b.xAxisLabel()&&(e=c.append("text").attr("transform","translate("+(b.margins().left+b.xAxisLength()/2)+","+(b.height()-L)+")").attr("class",t).attr("text-anchor","middle").text(b.xAxisLabel())),b.xAxisLabel()&&e.text()!=b.xAxisLabel()&&axisYLab.text(b.xAxisLabel()),a.transition(d,b.transitionDuration()).call(H)},b.xAxisY=function(){return b.height()-b.margins().bottom},b.xAxisLength=function(){return b.effectiveWidth()},b.xAxisLabel=function(a,c){return arguments.length?(A=a,b.margins().bottom-=L,L=void 0===c?u:c,b.margins().bottom+=L,b):A},b.renderYAxis=function(c){var d=c.selectAll("g.y");d.empty()&&(d=c.append("g").attr("class","axis y").attr("transform","translate("+b.yAxisX()+","+b.margins().top+")"));var e=c.selectAll("text."+s);e.empty()&&b.yAxisLabel()&&(e=c.append("text").attr("transform","translate("+P+","+(b.margins().top+b.yAxisHeight()/2)+"),rotate(-90)").attr("class",s).attr("text-anchor","middle").text(b.yAxisLabel())),b.yAxisLabel()&&e.text()!=b.yAxisLabel()&&e.text(b.yAxisLabel()),a.transition(d,b.transitionDuration()).call(M)},b.yAxisX=function(){return b.margins().left},b.yAxisLabel=function(a,c){return arguments.length?(C=a,b.margins().left-=P,P=void 0===c?u:c,b.margins().left+=P,b):C},b.y=function(a){return arguments.length?(B=a,b):B},b.yAxis=function(a){return arguments.length?(M=a,b):M},b.elasticY=function(a){return arguments.length?(O=a,b):O},b.renderHorizontalGridLines=function(a){return arguments.length?(S=a,b):S},b.renderVerticalGridLines=function(a){return arguments.length?(T=a,b):T},b.xAxisMin=function(){var c=d3.min(b.data(),function(a){return b.keyAccessor()(a)});return a.utils.subtract(c,J)},b.xAxisMax=function(){var c=d3.max(b.data(),function(a){return b.keyAccessor()(a)});return a.utils.add(c,J)},b.yAxisMin=function(){var c=d3.min(b.data(),function(a){return b.valueAccessor()(a)});return a.utils.subtract(c,N)},b.yAxisMax=function(){var c=d3.max(b.data(),function(a){return b.valueAccessor()(a)});return a.utils.add(c,N)},b.yAxisPadding=function(a){return arguments.length?(N=a,b):N},b.yAxisHeight=function(){return b.effectiveHeight()},b.round=function(a){return arguments.length?(D=a,b):D},b._rangeBandPadding=function(a){return arguments.length?(ab=a,b):ab},b._outerRangeBandPadding=function(a){return arguments.length?(_=a,b):_},a.override(b,"filter",function(a){return arguments.length?(b._filter(a),a?b.brush().extent(a):b.brush().clear(),b):b._filter()}),b.brush=function(a){return arguments.length?(Q=a,b):Q},b.renderBrush=function(a){if(b.isOrdinal()&&(R=!1),R){Q.on("brush",b._brushing),Q.on("brushstart",b._disableMouseZoom),Q.on("brushend",k);var c=a.append("g").attr("class","brush").attr("transform","translate("+b.margins().left+","+b.margins().top+")").call(Q.x(b.x()));c.selectAll("rect").attr("height",g()),c.selectAll(".resize").append("path").attr("d",b.resizeHandlePath),b.hasFilter()&&b.redrawBrush(a)}},b.extendBrush=function(){var a=Q.extent();return b.round()&&(a[0]=a.map(b.round())[0],a[1]=a.map(b.round())[1],w.select(".brush").call(Q.extent(a))),a},b.brushIsEmpty=function(a){return Q.empty()||!a||a[1]<=a[0]},b._brushing=function(){var c=b.extendBrush();if(b.redrawBrush(w),b.brushIsEmpty(c))a.events.trigger(function(){b.filter(null),a.redrawAll(b.chartGroup())},a.constants.EVENT_DELAY);else{var d=a.filters.RangedFilter(c[0],c[1]);a.events.trigger(function(){b.replaceFilter(d),a.redrawAll(b.chartGroup())},a.constants.EVENT_DELAY)}},b.redrawBrush=function(a){if(R){b.filter()&&b.brush().empty()&&b.brush().extent(b.filter());var c=a.select("g.brush");c.call(b.brush().x(b.x())),c.selectAll("rect").attr("height",g())}b.fadeDeselectedArea()},b.fadeDeselectedArea=function(){},b.resizeHandlePath=function(a){var b=+("e"==a),c=b?1:-1,d=g()/3;return"M"+.5*c+","+d+"A6,6 0 0 "+b+" "+6.5*c+","+(d+6)+"V"+(2*d-6)+"A6,6 0 0 "+b+" "+.5*c+","+2*d+"ZM"+2.5*c+","+(d+8)+"V"+(2*d-8)+"M"+4.5*c+","+(d+8)+"V"+(2*d-8)},b.clipPadding=function(a){return arguments.length?($=a,b):$},b._preprocessData=function(){},b.doRender=function(){return b.resetSvg(),b._preprocessData(),b._generateG(),i(),j(!0),k(),b},b.doRedraw=function(){return b._preprocessData(),j(!1),b},b._enableMouseZoom=function(){X.x(b.x()).scaleExtent(V).size([b.width(),b.height()]),b.root().call(X)},b._disableMouseZoom=function(){b.root().call(Y)},b.focus=function(a){o(a)?b.x().domain(a):b.x().domain(z),X.x(b.x()),l()},b.refocused=function(){return U},b.focusChart=function(c){return arguments.length?(G=c,b.on("filtered",function(b){n(b.filter(),G.filter())||a.events.trigger(function(){G.focus(b.filter())})}),b):G},b.brushOn=function(a){return arguments.length?(R=a,b):R},b},a.colorChart=function(a){var b=d3.scale.category20c(),c=function(b){return a.keyAccessor()(b)},d=function(c){return b(c,a)};return a.colors=function(c){return arguments.length?(b=c instanceof Array?d3.scale.quantize().range(c):c,a):b},a.ordinalColors=function(b){return a.colors(d3.scale.ordinal().range(b))},a.linearColors=function(b){return a.colors(d3.scale.linear().range(b).interpolate(d3.interpolateHcl))},a.colorAccessor=function(b){return arguments.length?(c=b,a):c},a.colorDomain=function(c){return arguments.length?(b.domain(c),a):b.domain()},a.calculateColorDomain=function(){var c=[d3.min(a.data(),a.colorAccessor()),d3.max(a.data(),a.colorAccessor())];b.domain(c)},a.getColor=function(a,b){return d(c(a,b))},a.colorCalculator=function(b){return arguments.length?(d=b,a):d},a},a.stackableChart=function(b){function c(){var a=[];if(b.x()){var c,d=b.x().domain();if(b.isOrdinal()){var e=d3.set(d);c=function(a){return e.has(a.x)}}else c=function(a){return a.x>=d[0]&&a.x<=d[d.length-1]};b.stackLayers().forEach(function(b){b.points.forEach(function(b){c(b)&&a.push(b)})})}else b.stackLayers().forEach(function(b){a=a.concat(b.points)});return a}function d(a,c){a.all().forEach(function(a,d){var e=b.getKeyAccessorByIndex(c)(a),f=b.getValueAccessorByIndex(c)(a);i.setDataPoint(c,d,{data:a,x:e,y:f,layer:c})})}var e,f,g,h,i=new a.utils.GroupStack,j=d3.layout.stack().offset("zero").order("default").values(function(a){return a.points}),k=[],l=!1;return b.stack=function(a,c,d){return arguments.length||i.clear(),i.setDefaultAccessor(b.valueAccessor()),"string"==typeof c?(b._setGroupName(a,c,d),i.addNamedGroup(a,c,d)):(d=c,i.addGroup(a,d)),b.expireCache(),b},b.hidableStacks=function(a){return arguments.length?(l=a,b):l},b.hideStack=function(a){i.hideGroups(a,b._getGroupName(b.group())==a)},b.showStack=function(a){i.showGroups(a,b._getGroupName(b.group())==a)},b.expireCache=function(){return e=null,f=null,g=null,h=null,b},b.allGroups=function(){if(null===e){e=[],e.push(b.group());for(var a=0;af?f:c},null);return a.utils.subtract(c,b.xAxisPadding())},b.xAxisMax=function(){var c=b.allGroups().reduce(function(c,d,e){var f=a.utils.groupMax(d,b.getKeyAccessorByIndex(e));return null===c||f>c?f:c},null);return a.utils.add(c,b.xAxisPadding())},b.calculateDataPointMatrixForAll=function(){i.clearDataLayers(),b.allGroups().forEach(d)},b.getChartStack=function(){return i},a.override(b,"valueAccessor",function(a){return arguments.length?(b.expireCache(),b._valueAccessor(a)):b._valueAccessor()}),a.override(b,"keyAccessor",function(a){return arguments.length?(b.expireCache(),b._keyAccessor(a)):b._keyAccessor()}),a.override(b,"title",function(a,c){if(!a)return b._title();var d=b.group()&&a===b._getGroupName(b.group());return"function"==typeof a?b._title(a):c?d?b._title(c):(i.setTitle(a,c),b):d?b._title():i.getTitle(a)}),b.getTitleOfVisibleByIndex=function(a){return b.title(i.getNameOfVisibleByIndex(a-1))||b.title()},b.stackLayout=function(a){return arguments.length?(j=a,b):j},b.stackLayers=function(a){if(!arguments.length){if(null===h){b.calculateDataPointMatrixForAll();var c=i.toLayers();if(0===c.length)return[];h=b.stackLayout()(c)}return h}h=a},b._layerColorAccessor=function(a){return void 0===a.layer?a.index:a.layer},b.colorAccessor(b._layerColorAccessor),b.legendables=function(){return b.allGroups().map(function(c,d){return a.utils.createLegendable(b,c,b.getValueAccessorByIndex(d),b.colorCalculator()(d))})},b.isLegendableHidden=function(a){return-1!==k.indexOf(a.name)},b.legendToggle=function(a){if(l){var c;-1!==(c=k.indexOf(a.name))?(k.splice(c,1),b.showStack(a.name)):(k.push(a.name),b.hideStack(a.name))}b.render()},b},a.abstractBubbleChart=function(b){var c=.3,d=10;b.BUBBLE_NODE_CLASS="node",b.BUBBLE_CLASS="bubble",b.MIN_RADIUS=10,b=a.colorChart(b),b.renderLabel(!0),b.renderTitle(!1),b.data(function(a){return a.top(1/0)});var e=d3.scale.linear().domain([0,100]),f=function(a){return a.r};b.r=function(a){return arguments.length?(e=a,b):e},b.radiusValueAccessor=function(a){return arguments.length?(f=a,b):f},b.rMin=function(){var a=d3.min(b.data(),function(a){return b.radiusValueAccessor()(a)});return a},b.rMax=function(){var a=d3.max(b.data(),function(a){return b.radiusValueAccessor()(a)});return a},b.bubbleR=function(a){var c=b.radiusValueAccessor()(a),d=b.r()(c);return(isNaN(d)||0>=c)&&(d=0),d};var g=function(a){return b.label()(a)},h=function(a){return b.bubbleR(a)>d?1:0};b.doRenderLabel=function(c){if(b.renderLabel()){var d=c.select("text");d.empty()&&(d=c.append("text").attr("text-anchor","middle").attr("dy",".3em").on("click",b.onClick)),d.attr("opacity",0).text(g),a.transition(d,b.transitionDuration()).attr("opacity",h)}},b.doUpdateLabels=function(c){if(b.renderLabel()){var d=c.selectAll("text").text(g);a.transition(d,b.transitionDuration()).attr("opacity",h)}};var i=function(a){return b.title()(a)};return b.doRenderTitles=function(a){if(b.renderTitle()){var c=a.select("title");c.empty()&&a.append("title").text(i)}},b.doUpdateTitles=function(a){b.renderTitle()&&a.selectAll("title").text(i)},b.minRadiusWithLabel=function(a){return arguments.length?(d=a,b):d},b.maxBubbleRelativeSize=function(a){return arguments.length?(c=a,b):c},b.fadeDeselectedArea=function(){b.hasFilter()?b.selectAll("g."+b.BUBBLE_NODE_CLASS).each(function(a){b.isSelectedNode(a)?b.highlightSelected(this):b.fadeDeselected(this)}):b.selectAll("g."+b.BUBBLE_NODE_CLASS).each(function(){b.resetHighlight(this)})},b.isSelectedNode=function(a){return b.hasFilter(a.key)},b.onClick=function(c){var d=c.key;a.events.trigger(function(){b.filter(d),a.redrawAll(b.chartGroup())})},b},a.pieChart=function(b,c){function d(){C=C?C:d3.min([J.width(),J.height()])/2;var a=q(),b=s(),c=b(J.data());if(D){var d=D.selectAll("g."+G).data(c);e(d,a,c),k(c,a),o(d),p()}}function e(a,b,c){var d=f(a);g(d,b),h(d),j(c,b)}function f(a){var b=a.enter().append("g").attr("class",function(a,b){return G+" _"+b});return b}function g(a,b){var c=a.append("path").attr("fill",x).on("click",y).attr("d",function(a,c){return z(a,c,b)});c.transition().duration(J.transitionDuration()).attrTween("d",v)}function h(a){J.renderTitle()&&a.append("title").text(function(a){return J.title()(a)})}function i(b,c){a.transition(b,J.transitionDuration()).attr("transform",function(a){return A(a,c)}).attr("text-anchor","middle").text(function(a){var b=a.data;return u(b)||t(a)?"":J.label()(a.data)})}function j(a,b){if(J.renderLabel()){var c=D.selectAll("text."+G).data(a);c.exit().remove();var d=c.enter().append("text").attr("class",function(a,b){var c=G+" _"+b;return E&&(c+=" external"),c}).on("click",y);i(d,b)}}function k(a,b){l(a,b),m(a,b),n(a)}function l(b,c){var d=D.selectAll("g."+G).data(b).select("path").attr("d",function(a,b){return z(a,b,c)});a.transition(d,J.transitionDuration(),function(a){a.attrTween("d",v)}).attr("fill",x)}function m(a,b){if(J.renderLabel()){var c=D.selectAll("text."+G).data(a);i(c,b)}}function n(a){J.renderTitle()&&D.selectAll("g."+G).data(a).select("title").text(function(a){return J.title()(a.data)})}function o(a){a.exit().remove()}function p(){J.hasFilter()?J.selectAll("g."+G).each(function(a){r(a)?J.highlightSelected(this):J.fadeDeselected(this)}):J.selectAll("g."+G).each(function(){J.resetHighlight(this)})}function q(){return d3.svg.arc().outerRadius(C).innerRadius(H)}function r(a){return J.hasFilter(J.cappedKeyAccessor(a.data))}function s(){return d3.layout.pie().sort(null).value(J.cappedValueAccessor)}function t(a){var b=a.endAngle-a.startAngle;return isNaN(b)||I>b}function u(a){return 0===J.cappedValueAccessor(a)}function v(a){a.innerRadius=H;var b=this._current;w(b)&&(b={startAngle:0,endAngle:0});var c=d3.interpolate(b,a);return this._current=c(0),function(a){return z(c(a),0,q())}}function w(a){return!a||isNaN(a.startAngle)||isNaN(a.endAngle)}function x(a,b){return J.getColor(a.data,b)}function y(a,b){J.onClick(a.data,b)}function z(a,b,c){var d=c(a,b);return d.indexOf("NaN")>=0&&(d="M0,0"),d}function A(a,b){var c;return c=E?d3.svg.arc().outerRadius(C+E).innerRadius(C+E).centroid(a):b.centroid(a),isNaN(c[0])||isNaN(c[1])?"translate(0,0)":"translate("+c+")"}function B(a,b){J.selectAll("g.pie-slice").each(function(c){a.name==c.data.key&&d3.select(this).classed("highlight",b)})}var C,D,E,F=.5,G="pie-slice",H=0,I=F,J=a.capped(a.colorChart(a.baseChart({})));return J.colorAccessor(J.cappedKeyAccessor),J.title(function(a){return J.cappedKeyAccessor(a)+": "+J.cappedValueAccessor(a)}),J.slicesCap=J.cap,J.label(J.cappedKeyAccessor),J.renderLabel(!0),J.transitionDuration(350),J.doRender=function(){return J.resetSvg(),D=J.svg().append("g").attr("transform","translate("+J.cx()+","+J.cy()+")"),d(),J},J.innerRadius=function(a){return arguments.length?(H=a,J):H},J.radius=function(a){return arguments.length?(C=a,J):C},J.cx=function(){return J.width()/2},J.cy=function(){return J.height()/2},J.doRedraw=function(){return d(),J},J.minAngleForLabel=function(a){return arguments.length?(I=a,J):I +},J.externalLabels=function(a){return 0===arguments.length?E:(E=a?a:void 0,J)},J.legendables=function(){return J.data().map(function(a,b){var c={name:a.key,data:a.value,others:a.others};return c.color=J.getColor(a,b),c})},J.getColor=function(a,b){return J.colorCalculator()(J.colorAccessor()(a,b))},J.legendHighlight=function(a){B(a,!0)},J.legendReset=function(a){B(a,!1)},J.legendToggle=function(a){J.onClick({key:a.name,others:a.others})},J.anchor(b,c)},a.barChart=function(b,c){function d(b){return a.utils.safeNumber(Math.abs(k.y()(b.y+b.y0)-k.y()(b.y0)))}function e(b,c,e){var f=b.selectAll("rect.bar").data(e.points,a.pluck("data",k.keyAccessor()));f.enter().append("rect").attr("class","bar").attr("fill",k.getColor),k.renderTitle()&&f.append("title").text(a.pluck("data",k.getTitleOfVisibleByIndex(c))),k.isOrdinal()&&f.on("click",g),a.transition(f,k.transitionDuration()).attr("x",function(b){var c=k.x()(b.x);return m&&(c-=h/2),k.isOrdinal()&&(c+=l/2),a.utils.safeNumber(c)}).attr("y",function(b){var c=k.y()(b.y+b.y0);return b.y<0&&(c-=d(b)),a.utils.safeNumber(c)}).attr("width",h).attr("height",function(a){return d(a)}).attr("fill",k.getColor).select("title").text(a.pluck("data",k.getTitleOfVisibleByIndex(c))),a.transition(f.exit(),k.transitionDuration()).attr("height",0).remove()}function f(){if(void 0===h){var a=k.xUnitCount();h=k.isOrdinal()&&!l?Math.floor(k.x().rangeBand()):l?Math.floor((k.xAxisLength()-(a-1)*l)/a):Math.floor(k.xAxisLength()/(1+k.barPadding())/a),(1/0==h||isNaN(h)||i>h)&&(h=i)}}function g(a){k.onClick(a.data)}var h,i=1,j=2,k=a.stackableChart(a.coordinateGridChart({})),l=j,m=!1;return a.override(k,"rescale",function(){k._rescale(),h=void 0}),k.plotData=function(){var a=k.chartBodyG().selectAll("g.stack").data(k.stackLayers());f(),a.enter().append("g").attr("class",function(a,b){return"stack _"+b}),a.each(function(a,b){var c=d3.select(this);e(c,b,a)}),k.stackLayers(null)},k.fadeDeselectedArea=function(){var b=k.chartBodyG().selectAll("rect.bar"),c=k.brush().extent();if(k.isOrdinal())k.hasFilter()?(b.classed(a.constants.SELECTED_CLASS,function(a){return k.hasFilter(k.keyAccessor()(a.data))}),b.classed(a.constants.DESELECTED_CLASS,function(a){return!k.hasFilter(k.keyAccessor()(a.data))})):(b.classed(a.constants.SELECTED_CLASS,!1),b.classed(a.constants.DESELECTED_CLASS,!1));else if(k.brushIsEmpty(c))b.classed(a.constants.DESELECTED_CLASS,!1);else{var d=c[0],e=c[1];b.classed(a.constants.DESELECTED_CLASS,function(a){var b=k.keyAccessor()(a.data);return d>b||b>=e})}},k.centerBar=function(a){return arguments.length?(m=a,k):m},k.barPadding=function(a){return arguments.length?(k._rangeBandPadding(a),l=0,k):k._rangeBandPadding()},k.outerPadding=k._outerRangeBandPadding,k.gap=function(a){return arguments.length?(l=a,k):l},k.extendBrush=function(){var a=k.brush().extent();return k.round()&&!m&&(a[0]=a.map(k.round())[0],a[1]=a.map(k.round())[1],k.chartBodyG().select(".brush").call(k.brush().extent(a))),a},k.legendHighlight=function(a){k.isLegendableHidden(a)||(k.select(".chart-body").selectAll("rect.bar").filter(function(){return d3.select(this).attr("fill")==a.color}).classed("highlight",!0),k.select(".chart-body").selectAll("rect.bar").filter(function(){return d3.select(this).attr("fill")!=a.color}).classed("fadeout",!0))},k.legendReset=function(a){k.selectAll(".chart-body").selectAll("rect.bar").filter(function(){return d3.select(this).attr("fill")==a.color}).classed("highlight",!1),k.selectAll(".chart-body").selectAll("rect.bar").filter(function(){return d3.select(this).attr("fill")!=a.color}).classed("fadeout",!1)},a.override(k,"xAxisMax",function(){var a=this._xAxisMax();if("resolution"in k.xUnits()){var b=k.xUnits().resolution;a+=b}return a}),k.anchor(b,c)},a.lineChart=function(b,c){function d(b,c){var d=d3.svg.line().x(function(a){return v.x()(a.x)}).y(function(a){return v.y()(a.y+a.y0)}).interpolate(B).tension(C);n&&d.defined(n);var e=b.append("path").attr("class","line").attr("stroke",v.getColor).attr("fill",v.getColor);o&&e.attr("stroke-dasharray",o),a.transition(c.select("path.line"),v.transitionDuration()).attr("d",function(a){return f(d(a.points))})}function e(b,c){if(w){var d=d3.svg.area().x(function(a){return v.x()(a.x)}).y(function(a){return v.y()(a.y+a.y0)}).y0(function(a){return v.y()(a.y0)}).interpolate(B).tension(C);n&&d.defined(n),b.append("path").attr("class","area").attr("fill",v.getColor).attr("d",function(a){return f(d(a.points))}),a.transition(c.select("path.area"),v.transitionDuration()).attr("d",function(a){return f(d(a.points))})}}function f(a){return!a||a.indexOf("NaN")>=0?"M0,0":a}function g(b,c){if(!v.brushOn()){var d=q+"-list",e=b.select("g."+d);e.empty()&&(e=b.append("g").attr("class",d)),c.each(function(b,c){var d=d3.select(this),f=d.datum().points;n&&(f=f.filter(n));var g=e.select("g."+q+"._"+c);g.empty()&&(g=e.append("g").attr("class",q+" _"+c)),h(g);var o=g.selectAll("circle."+r).data(f);o.enter().append("circle").attr("class",r).attr("r",k()).attr("fill",v.getColor).style("fill-opacity",z).style("stroke-opacity",A).on("mousemove",function(){var a=d3.select(this);i(a),j(a,g)}).on("mouseout",function(){var a=d3.select(this);l(a),m(g)}).append("title").text(a.pluck("data",v.getTitleOfVisibleByIndex(c))),o.attr("cx",function(b){return a.utils.safeNumber(v.x()(b.x))}).attr("cy",function(b){return a.utils.safeNumber(v.y()(b.y+b.y0))}).select("title").text(a.pluck("data",v.getTitleOfVisibleByIndex(c))),o.exit().remove()})}}function h(a){var b=a.select("path."+s).empty()?a.append("path").attr("class",s):a.select("path."+s);b.style("display","none").attr("stroke-dasharray","5,5");var c=a.select("path."+t).empty()?a.append("path").attr("class",t):a.select("path."+t);c.style("display","none").attr("stroke-dasharray","5,5")}function i(a){return a.style("fill-opacity",.8),a.style("stroke-opacity",.8),a.attr("r",x),a}function j(a,b){var c=a.attr("cx"),d=a.attr("cy");b.select("path."+s).style("display","").attr("d","M0 "+d+"L"+c+" "+d),b.select("path."+t).style("display","").attr("d","M"+c+" "+v.yAxisHeight()+"L"+c+" "+d)}function k(){return y||x}function l(a){a.style("fill-opacity",z).style("stroke-opacity",A).attr("r",k())}function m(a){a.select("path."+s).style("display","none"),a.select("path."+t).style("display","none")}var n,o,p=5,q="dc-tooltip",r="dot",s="yRef",t="xRef",u=1e-6,v=a.stackableChart(a.coordinateGridChart({})),w=!1,x=p,y=null,z=u,A=u,B="linear",C=.7;return v.transitionDuration(500),v.plotData=function(){var a=v.chartBodyG(),b=a.selectAll("g.stack-list");b.empty()&&(b=a.append("g").attr("class","stack-list"));var c=b.selectAll("g.stack").data(v.stackLayers()),f=c.enter().append("g").attr("class",function(a,b){return"stack _"+b});d(f,c),e(f,c),g(a,c),v.stackLayers(null)},v.interpolate=function(a){return arguments.length?(B=a,v):B},v.tension=function(a){return arguments.length?(C=a,v):C},v.defined=function(a){return arguments.length?(n=a,v):n},v.dashStyle=function(a){return arguments.length?(o=a,v):o},v.renderArea=function(a){return arguments.length?(w=a,v):w},v.dotRadius=function(a){return arguments.length?(x=a,v):x},v.renderDataPoints=function(a){return arguments.length?(a?(z=a.fillOpacity||.8,A=a.strokeOpacity||.8,y=a.radius||2):(z=u,A=u,y=null),v):{fillOpacity:z,strokeOpacity:A,radius:y}},v.legendHighlight=function(a){v.isLegendableHidden(a)||(v.selectAll(".chart-body").selectAll("path").filter(function(){return d3.select(this).attr("fill")==a.color}).classed("highlight",!0),v.selectAll(".chart-body").selectAll("path").filter(function(){return d3.select(this).attr("fill")!=a.color}).classed("fadeout",!0))},v.legendReset=function(a){v.selectAll(".chart-body").selectAll("path").filter(function(){return d3.select(this).attr("fill")==a.color}).classed("highlight",!1),v.selectAll(".chart-body").selectAll("path").filter(function(){return d3.select(this).attr("fill")!=a.color}).classed("fadeout",!1)},v.anchor(b,c)},a.dataCount=function(b,c){var d=d3.format(",d"),e=a.baseChart({});return e.doRender=function(){return e.selectAll(".total-count").text(d(e.dimension().size())),e.selectAll(".filter-count").text(d(e.group().value())),e},e.doRedraw=function(){return e.doRender()},e.anchor(b,c)},a.dataTable=function(b,c){function d(){var a=k.root().selectAll("tbody").data(e(),function(a){return k.keyAccessor()(a)}),b=a.enter().append("tbody");return b.append("tr").attr("class",j).append("td").attr("class",g).attr("colspan",m.length).html(function(a){return k.keyAccessor()(a)}),a.exit().remove(),b}function e(){var a=k.dimension().top(l);return d3.nest().key(k.group()).sortKeys(o).entries(a.sort(function(a,b){return o(n(a),n(b))}))}function f(a){var b=a.order().selectAll("tr."+h).data(function(a){return a.values}),c=b.enter().append("tr").attr("class",h);return m.forEach(function(a,b){c.append("td").attr("class",i+" _"+b).html(a)}),b.exit().remove(),b}var g="dc-table-label",h="dc-table-row",i="dc-table-column",j="dc-table-group",k=a.baseChart({}),l=25,m=[],n=function(a){return a},o=d3.ascending;return k.doRender=function(){return k.selectAll("tbody").remove(),f(d()),k},k.doRedraw=function(){return k.doRender()},k.size=function(a){return arguments.length?(l=a,k):l},k.columns=function(a){return arguments.length?(m=a,k):m},k.sortBy=function(a){return arguments.length?(n=a,k):n},k.order=function(a){return arguments.length?(o=a,k):o},k.anchor(b,c)},a.bubbleChart=function(b,c){function d(b){var c=b.enter().append("g");c.attr("class",i.BUBBLE_NODE_CLASS).attr("transform",k).append("circle").attr("class",function(a,b){return i.BUBBLE_CLASS+" _"+b}).on("click",i.onClick).attr("fill",i.getColor).attr("r",0),a.transition(b,i.transitionDuration()).selectAll("circle."+i.BUBBLE_CLASS).attr("r",function(a){return i.bubbleR(a)}).attr("opacity",function(a){return i.bubbleR(a)>0?1:0}),i.doRenderLabel(c),i.doRenderTitles(c)}function e(b){a.transition(b,i.transitionDuration()).attr("transform",k).selectAll("circle."+i.BUBBLE_CLASS).attr("fill",i.getColor).attr("r",function(a){return i.bubbleR(a)}).attr("opacity",function(a){return i.bubbleR(a)>0?1:0}),i.doUpdateLabels(b),i.doUpdateTitles(b)}function f(a){a.exit().remove()}function g(a){var b=i.x()(i.keyAccessor()(a));return isNaN(b)&&(b=0),b}function h(a){var b=i.y()(i.valueAccessor()(a));return isNaN(b)&&(b=0),b}var i=a.abstractBubbleChart(a.coordinateGridChart({})),j=!1;i.transitionDuration(750);var k=function(a){return"translate("+g(a)+","+h(a)+")"};return i.elasticRadius=function(a){return arguments.length?(j=a,i):j},i.plotData=function(){j&&i.r().domain([i.rMin(),i.rMax()]),i.r().range([i.MIN_RADIUS,i.xAxisLength()*i.maxBubbleRelativeSize()]);var a=i.chartBodyG().selectAll("g."+i.BUBBLE_NODE_CLASS).data(i.data(),i.keyAccessor());d(a),e(a),f(a),i.fadeDeselectedArea()},i.renderBrush=function(){},i.redrawBrush=function(){i.fadeDeselectedArea()},i.anchor(b,c)},a.compositeChart=function(b,c){function d(a,b){a._generateG(j.g()),a.g().attr("class",i+" _"+b)}function e(){for(var a=[],b=0;b0&&(a[0]=0),r=d3.scale.linear().domain(a).range([0,y.effectiveWidth()])}z.scale(r)}function e(){var b=q.select("g.axis");d(),b.empty()&&(b=q.append("g").attr("class","axis").attr("transform","translate(0, "+y.effectiveHeight()+")")),a.transition(b,y.transitionDuration()).call(z)}function f(){q.selectAll("g.tick").select("line.grid-line").remove(),q.selectAll("g.tick").append("line").attr("class","grid-line").attr("x1",0).attr("y1",0).attr("x2",0).attr("y2",function(){return-y.effectiveHeight()})}function g(){t=y.data(),e(),f();var a=q.selectAll("g."+x).data(t);h(a),i(a),j(a)}function h(a){var b=a.enter().append("g").attr("class",function(a,b){return x+" _"+b});b.append("rect").attr("width",0),l(b),m(a)}function i(a){a.exit().remove()}function j(b){var c=t.length,d=(y.effectiveHeight()-(c+1)*w)/c,e=b.attr("transform",function(a,b){return"translate(0,"+((b+1)*w+b*d)+")"}).select("rect").attr("height",d).attr("fill",y.getColor).on("click",n).classed("deselected",function(a){return y.hasFilter()?!p(a):!1}).classed("selected",function(a){return y.hasFilter()?p(a):!1});a.transition(e,y.transitionDuration()).attr("width",function(a){var b=r(0)==-1/0?r(1):r(0);return Math.abs(b-r(y.valueAccessor()(a)))}).attr("transform",o),k(b),m(b)}function k(a){y.renderTitle()&&(a.selectAll("title").remove(),a.append("title").text(y.title()))}function l(a){y.renderLabel()&&a.append("text").on("click",n)}function m(b){if(y.renderLabel()){var c=b.select("text").attr("x",u).attr("y",v).on("click",n).attr("class",function(a,b){return x+" _"+b}).text(function(a){return y.label()(a)});a.transition(c,y.transitionDuration()).attr("transform",o)}}function n(a){y.onClick(a)}function o(a){var b=r(y.cappedValueAccessor(a)),c=r(0),d=b>c?c:b;return"translate("+d+",0)"}function p(a){return y.hasFilter(y.cappedKeyAccessor(a))}var q,r,s,t,u=10,v=15,w=5,x="row",y=a.capped(a.marginable(a.colorChart(a.baseChart({})))),z=d3.svg.axis().orient("bottom");return y.rowsCap=y.cap,y.doRender=function(){return y.resetSvg(),q=y.svg().append("g").attr("transform","translate("+y.margins().left+","+y.margins().top+")"),g(),y},y.title(function(a){return y.cappedKeyAccessor(a)+": "+y.cappedValueAccessor(a)}),y.label(y.cappedKeyAccessor),y.x=function(a){return arguments.length?(r=a,y):r},y.doRedraw=function(){return g(),y},y.xAxis=function(){return z},y.gap=function(a){return arguments.length?(w=a,y):w},y.elasticX=function(a){return arguments.length?(s=a,y):s},y.labelOffsetX=function(a){return arguments.length?(u=a,y):u},y.labelOffsetY=function(a){return arguments.length?(v=a,y):v},y.anchor(b,c)},a.legend=function(){function a(){return i+h}var b,c,d=2,e={},f=0,g=0,h=12,i=5,j=!1,k=560,l=70;return e.parent=function(a){return arguments.length?(b=a,e):b},e.render=function(){b.svg().select("g.dc-legend").remove(),c=b.svg().append("g").attr("class","dc-legend").attr("transform","translate("+f+","+g+")");var e=c.selectAll("g.dc-legend-item").data(b.legendables()).enter().append("g").attr("class","dc-legend-item").classed("fadeout",function(a){return b.isLegendableHidden(a)}).on("mouseover",function(a){b.legendHighlight(a)}).on("mouseout",function(a){b.legendReset(a)}).on("click",function(a){b.legendToggle(a)});b.legendables().some(function(a){return a.dashstyle})?e.append("line").attr("x1",0).attr("y1",h/2).attr("x2",h).attr("y2",h/2).attr("stroke-width",2).attr("stroke-dasharray",function(a){return a.dashstyle}).attr("stroke",function(a){return a.color}):e.append("rect").attr("width",h).attr("height",h).attr("fill",function(a){return a.color}),e.append("text").text(function(a){return a.name}).attr("x",h+d).attr("y",function(){return h/2+(this.clientHeight?this.clientHeight:13)/2-2});var i=0,m=0;e.attr("transform",function(b,c){if(j){var d="translate("+i+","+m*a()+")";return i+l>=k?(++m,i=0):i+=l,d}return"translate(0,"+c*a()+")"})},e.x=function(a){return arguments.length?(f=a,e):f},e.y=function(a){return arguments.length?(g=a,e):g},e.gap=function(a){return arguments.length?(i=a,e):i},e.itemHeight=function(a){return arguments.length?(h=a,e):h},e.horizontal=function(a){return arguments.length?(j=a,e):j},e.legendWidth=function(a){return arguments.length?(k=a,e):k},e.itemWidth=function(a){return arguments.length?(l=a,e):l},e},a.capped=function(b){var c=1/0,d="Others",e=function(a){var c=d3.sum(a,b.valueAccessor()),e=b.group().all(),f=d3.sum(e,b.valueAccessor()),g=a.map(b.keyAccessor()),h=e.map(b.keyAccessor()),i=d3.set(g),j=h.filter(function(a){return!i.has(a)});return f>c?a.concat([{others:j,key:d,value:f-c}]):a};return b.cappedKeyAccessor=function(a,c){return a.others?a.key:b.keyAccessor()(a,c)},b.cappedValueAccessor=function(a,c){return a.others?a.value:b.valueAccessor()(a,c)},b.data(function(a){if(1/0==c)return b.computeOrderedGroups(a.all());var d=a.top(c);return d=b.computeOrderedGroups(d),e?e(d):d}),b.cap=function(a){return arguments.length?(c=a,b):c},b.othersLabel=function(a){return arguments.length?(d=a,b):d},b.othersGrouper=function(a){return arguments.length?(e=a,b):e},a.override(b,"onClick",function(a){a.others&&b.filter([a.others]),b._onClick(a)}),b},a.scatterPlot=function(b,c){var d=a.coordinateGridChart({}),e=function(a){return"translate("+d.x()(d.keyAccessor()(a))+","+d.y()(d.valueAccessor()(a))+")"},f=3;return d.transitionDuration(0),d.plotData=function(){var b=d.chartBodyG().selectAll("circle.symbol").data(d.data());b.enter().append("circle").attr("class","symbol").attr("fill",d.getColor(0)).attr("transform",e),a.transition(b,d.transitionDuration()).attr("transform",e).attr("r",f),a.transition(b.filter(function(a){return 0===d.valueAccessor()(a)}),d.transitionDuration()).attr("r",0).remove(),a.transition(b.exit(),d.transitionDuration()).attr("r",0).remove()},d.symbolSize=function(a){return arguments.length?(f=a,d):f},d.anchor(b,c)},a.numberDisplay=function(b,c){var d="number-display",e=d3.format(".2s"),f=a.baseChart({});return f._mandatoryAttributes(["group"]),f.value=function(){return f.data()},f.data(function(a){var b=a.value?a.value():a.top(1)[0];return f.valueAccessor()(b)}),f.transitionDuration(250),f.doRender=function(){var a=f.value(),b=f.selectAll("."+d);return b.empty()&&(b=b.data([0]).enter().append("span").attr("class",d)),b.transition().duration(f.transitionDuration()).ease("quad-out-in").tween("text",function(){var b=d3.interpolateNumber(this.lastValue||0,a);return this.lastValue=a,function(a){this.textContent=f.formatNumber()(b(a))}}),f},f.doRedraw=function(){return f.doRender()},f.formatNumber=function(a){return arguments.length?(e=a,f):e},f.anchor(b,c)},a.heatMap=function(b,c){function d(b,c){var d=l.selectAll(".box-group").filter(function(a){return a.key[b]==c}),e=d.filter(function(a){return!l.hasFilter(a.key)});a.events.trigger(function(){e.empty()?d.each(function(a){l.filter(a.key)}):e.each(function(a){l.filter(a.key)}),a.redrawAll(l.chartGroup())})}function e(a,b,c){return!b||c[b-1]!=a}var f,g,h,i=6.75,j=i,k=i,l=a.colorChart(a.marginable(a.baseChart({})));l._mandatoryAttributes(["group"]),l.title(l.colorAccessor());var m=function(a){d(0,a)},n=function(a){d(1,a)},o=function(b){var c=b.key;a.events.trigger(function(){l.filter(c),a.redrawAll(l.chartGroup())})};return a.override(l,"filter",function(b){return b?l._filter(a.filters.TwoDimensionalFilter(b)):l._filter()}),l.rows=function(a){if(arguments.length)return h=a,l;if(h)return h;var b=l.data().map(l.valueAccessor());return b.sort(d3.ascending),d3.scale.ordinal().domain(b.filter(e))},l.cols=function(a){if(arguments.length)return g=a,l;if(g)return g;var b=l.data().map(l.keyAccessor());return b.sort(d3.ascending),d3.scale.ordinal().domain(b.filter(e))},l.doRender=function(){return l.resetSvg(),f=l.svg().append("g").attr("class","heatmap").attr("transform","translate("+l.margins().left+","+l.margins().top+")"),l.doRedraw()},l.doRedraw=function(){var b=l.rows(),c=l.cols(),d=b.domain().length,e=c.domain().length,g=Math.floor(l.effectiveWidth()/e),h=Math.floor(l.effectiveHeight()/d);c.rangeRoundBands([0,l.effectiveWidth()]),b.rangeRoundBands([l.effectiveHeight(),0]);var i=f.selectAll("g.box-group").data(l.data(),function(a,b){return l.keyAccessor()(a,b)+"\x00"+l.valueAccessor()(a,b)}),m=i.enter().append("g").attr("class","box-group");m.append("rect").attr("class","heat-box").attr("fill","white").on("click",l.boxOnClick()),m.append("title").text(l.title()),a.transition(i.selectAll("rect"),l.transitionDuration()).attr("x",function(a,b){return c(l.keyAccessor()(a,b))}).attr("y",function(a,c){return b(l.valueAccessor()(a,c))}).attr("rx",j).attr("ry",k).attr("fill",l.getColor).attr("width",g).attr("height",h),i.exit().remove();var n=f.selectAll("g.cols");n.empty()&&(n=f.append("g").attr("class","cols axis")),n.selectAll("text").data(c.domain()).enter().append("text").attr("x",function(a){return c(a)+g/2}).style("text-anchor","middle").attr("y",l.effectiveHeight()).attr("dy",12).on("click",l.xAxisOnClick()).text(function(a){return a});var o=f.selectAll("g.rows");o.empty()&&(o=f.append("g").attr("class","rows axis")),o.selectAll("text").data(b.domain()).enter().append("text").attr("dy",6).style("text-anchor","end").attr("x",0).attr("dx",-2).on("click",l.yAxisOnClick()).text(function(a){return a}),a.transition(o.selectAll("text"),l.transitionDuration()).text(function(a){return a}).attr("y",function(a){return b(a)+h/2}),l.hasFilter()?l.selectAll("g.box-group").each(function(a){l.isSelectedNode(a)?l.highlightSelected(this):l.fadeDeselected(this)}):l.selectAll("g.box-group").each(function(){l.resetHighlight(this)})},l.boxOnClick=function(a){return arguments.length?(o=a,l):o},l.xAxisOnClick=function(a){return arguments.length?(m=a,l):m},l.yAxisOnClick=function(a){return arguments.length?(n=a,l):n},l.xBorderRadius=function(a){return arguments.length&&(j=a),j},l.yBorderRadius=function(a){return arguments.length&&(k=a),k},l.isSelectedNode=function(a){return l.hasFilter(a.key)},l.anchor(b,c)},function(){function a(a){return[0,a.length-1]}function b(a){return[d3.quantile(a,.25),d3.quantile(a,.5),d3.quantile(a,.75)]}d3.box=function(){function c(a){a.each(function(a,b){a=a.map(h).sort(d3.ascending);var c=d3.select(this),l=a.length,m=a[0],n=a[l-1],o=a.quartiles=j(a),p=i&&i.call(this,a,b),q=p&&p.map(function(b){return a[b]}),r=p?d3.range(0,p[0]).concat(d3.range(p[1]+1,l)):d3.range(l),s=d3.scale.linear().domain(g&&g.call(this,a,b)||[m,n]).range([e,0]),t=this.__chart__||d3.scale.linear().domain([0,1/0]).range(s.range());this.__chart__=s;var u=c.selectAll("line.center").data(q?[q]:[]);u.enter().insert("line","rect").attr("class","center").attr("x1",d/2).attr("y1",function(a){return t(a[0])}).attr("x2",d/2).attr("y2",function(a){return t(a[1])}).style("opacity",1e-6).transition().duration(f).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.transition().duration(f).style("opacity",1).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}),u.exit().transition().duration(f).style("opacity",1e-6).attr("y1",function(a){return s(a[0])}).attr("y2",function(a){return s(a[1])}).remove();var v=c.selectAll("rect.box").data([o]);v.enter().append("rect").attr("class","box").attr("x",0).attr("y",function(a){return t(a[2])}).attr("width",d).attr("height",function(a){return t(a[0])-t(a[2])}).transition().duration(f).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])}),v.transition().duration(f).attr("y",function(a){return s(a[2])}).attr("height",function(a){return s(a[0])-s(a[2])});var w=c.selectAll("line.median").data([o[1]]);w.enter().append("line").attr("class","median").attr("x1",0).attr("y1",t).attr("x2",d).attr("y2",t).transition().duration(f).attr("y1",s).attr("y2",s),w.transition().duration(f).attr("y1",s).attr("y2",s);var x=c.selectAll("line.whisker").data(q||[]);x.enter().insert("line","circle, text").attr("class","whisker").attr("x1",0).attr("y1",t).attr("x2",d).attr("y2",t).style("opacity",1e-6).transition().duration(f).attr("y1",s).attr("y2",s).style("opacity",1),x.transition().duration(f).attr("y1",s).attr("y2",s).style("opacity",1),x.exit().transition().duration(f).attr("y1",s).attr("y2",s).style("opacity",1e-6).remove();var y=c.selectAll("circle.outlier").data(r,Number);y.enter().insert("circle","text").attr("class","outlier").attr("r",5).attr("cx",d/2).attr("cy",function(b){return t(a[b])}).style("opacity",1e-6).transition().duration(f).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.transition().duration(f).attr("cy",function(b){return s(a[b])}).style("opacity",1),y.exit().transition().duration(f).attr("cy",function(b){return s(a[b])}).style("opacity",1e-6).remove();var z=k||s.tickFormat(8),A=c.selectAll("text.box").data(o);A.enter().append("text").attr("class","box").attr("dy",".3em").attr("dx",function(a,b){return 1&b?6:-6}).attr("x",function(a,b){return 1&b?d:0}).attr("y",t).attr("text-anchor",function(a,b){return 1&b?"start":"end"}).text(z).transition().duration(f).attr("y",s),A.transition().duration(f).text(z).attr("y",s);var B=c.selectAll("text.whisker").data(q||[]);B.enter().append("text").attr("class","whisker").attr("dy",".3em").attr("dx",6).attr("x",d).attr("y",t).text(z).style("opacity",1e-6).transition().duration(f).attr("y",s).style("opacity",1),B.transition().duration(f).text(z).attr("y",s).style("opacity",1),B.exit().transition().duration(f).attr("y",s).style("opacity",1e-6).remove()}),d3.timer.flush()}var d=1,e=1,f=0,g=null,h=Number,i=a,j=b,k=null;return c.width=function(a){return arguments.length?(d=a,c):d},c.height=function(a){return arguments.length?(e=a,c):e},c.tickFormat=function(a){return arguments.length?(k=a,c):k},c.duration=function(a){return arguments.length?(f=a,c):f +},c.domain=function(a){return arguments.length?(g=null==a?a:d3.functor(a),c):g},c.value=function(a){return arguments.length?(h=a,c):h},c.whiskers=function(a){return arguments.length?(i=a,c):i},c.quartiles=function(a){return arguments.length?(j=a,c):j},c}}(),a.boxPlot=function(b,c){function d(b){var c=b.enter().append("g");c.attr("class","box").attr("transform",o).call(l).on("click",function(b){h.filter(b.key),a.redrawAll(h.chartGroup())})}function e(b){a.transition(b,h.transitionDuration()).attr("transform",o).call(l).each(function(){d3.select(this).select("rect.box").attr("fill",h.getColor)})}function f(a){a.exit().remove().call(l)}function g(a){return function(b){for(var c=b.quartiles[0],d=b.quartiles[2],e=(d-c)*a,f=-1,g=b.length;b[++f]d+e;);return[f,g]}}var h=a.coordinateGridChart({}),i=1.5,j=g,k=j(i),l=d3.box(),m=null,n=function(a,b){return h.isOrdinal()?h.x().rangeBand():a/(1+h.boxPadding())/b};h.yAxisPadding(12),h.x(d3.scale.ordinal()),h.xUnits(a.units.ordinal),h.data(function(a){return a.all().map(function(a){return a.map=function(b){return b.call(a,a)},a})}),h.boxPadding=h._rangeBandPadding,h.boxPadding(.8),h.outerPadding=h._outerRangeBandPadding,h.outerPadding(.5),h.boxWidth=function(a){return arguments.length?(n=d3.functor(a),h):n};var o=function(a,b){var c=h.x()(h.keyAccessor()(a,b));return"translate("+c+",0)"};return h.plotData=function(){var a=n(h.effectiveWidth(),h.xUnitCount());l.whiskers(k).width(a).height(h.effectiveHeight()).value(h.valueAccessor()).domain(h.y().domain()).duration(h.transitionDuration()).tickFormat(m);var b=h.chartBodyG().selectAll("g.box").data(h.data());d(b),e(b),f(b),h.fadeDeselectedArea()},h.fadeDeselectedArea=function(){h.hasFilter()?h.selectAll("g.box").each(function(a){h.isSelectedNode(a)?h.highlightSelected(this):h.fadeDeselected(this)}):h.selectAll("g.box").each(function(){h.resetHighlight(this)})},h.isSelectedNode=function(a){return h.hasFilter(a.key)},h.yAxisMin=function(){var b=d3.min(h.data(),function(a){return d3.min(h.valueAccessor()(a))});return a.utils.subtract(b,h.yAxisPadding())},h.yAxisMax=function(){var b=d3.max(h.data(),function(a){return d3.max(h.valueAccessor()(a))});return a.utils.add(b,h.yAxisPadding())},h.tickFormat=function(a){return arguments.length?(m=a,h):m},h.anchor(b,c)},a}(),dc.filters={},dc.filters.RangedFilter=function(a,b){var c=Array(a,b);return c.isFiltered=function(a){return a>=this[0]&&a + + + + + \ No newline at end of file diff --git a/admin/view/javascript/shopunity/codemirror/codemirror.css b/admin/view/javascript/shopunity/codemirror/codemirror.css new file mode 100755 index 0000000..52881f7 --- /dev/null +++ b/admin/view/javascript/shopunity/codemirror/codemirror.css @@ -0,0 +1,248 @@ +/* BASICS */ + +.CodeMirror { + /* Set height, width, borders, and global font properties here */ + font-family: monospace; + height: 300px; +} +.CodeMirror-scroll { + /* Set scrolling behaviour here */ + overflow: auto; +} + +/* PADDING */ + +.CodeMirror-lines { + padding: 4px 0; /* Vertical padding around content */ +} +.CodeMirror pre { + padding: 0 4px; /* Horizontal padding of content */ +} + +.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + background-color: white; /* The little square between H and V scrollbars */ +} + +/* GUTTER */ + +.CodeMirror-gutters { + border-right: 1px solid #ddd; + background-color: #f7f7f7; + white-space: nowrap; +} +.CodeMirror-linenumbers {} +.CodeMirror-linenumber { + padding: 0 3px 0 5px; + min-width: 20px; + text-align: right; + color: #999; +} + +/* CURSOR */ + +.CodeMirror div.CodeMirror-cursor { + border-left: 1px solid black; + z-index: 3; +} +/* Shown when moving in bi-directional text */ +.CodeMirror div.CodeMirror-secondarycursor { + border-left: 1px solid silver; +} +.CodeMirror.cm-keymap-fat-cursor div.CodeMirror-cursor { + width: auto; + border: 0; + background: #7e7; + z-index: 1; +} +/* Can style cursor different in overwrite (non-insert) mode */ +.CodeMirror div.CodeMirror-cursor.CodeMirror-overwrite {} + +.cm-tab { display: inline-block; } + +/* DEFAULT THEME */ + +.cm-s-default .cm-keyword {color: #708;} +.cm-s-default .cm-atom {color: #219;} +.cm-s-default .cm-number {color: #164;} +.cm-s-default .cm-def {color: #00f;} +.cm-s-default .cm-variable {color: black;} +.cm-s-default .cm-variable-2 {color: #05a;} +.cm-s-default .cm-variable-3 {color: #085;} +.cm-s-default .cm-property {color: black;} +.cm-s-default .cm-operator {color: black;} +.cm-s-default .cm-comment {color: #a50;} +.cm-s-default .cm-string {color: #a11;} +.cm-s-default .cm-string-2 {color: #f50;} +.cm-s-default .cm-meta {color: #555;} +.cm-s-default .cm-error {color: #f00;} +.cm-s-default .cm-qualifier {color: #555;} +.cm-s-default .cm-builtin {color: #30a;} +.cm-s-default .cm-bracket {color: #997;} +.cm-s-default .cm-tag {color: #170;} +.cm-s-default .cm-attribute {color: #00c;} +.cm-s-default .cm-header {color: blue;} +.cm-s-default .cm-quote {color: #090;} +.cm-s-default .cm-hr {color: #999;} +.cm-s-default .cm-link {color: #00c;} + +.cm-negative {color: #d44;} +.cm-positive {color: #292;} +.cm-header, .cm-strong {font-weight: bold;} +.cm-em {font-style: italic;} +.cm-link {text-decoration: underline;} + +.cm-invalidchar {color: #f00;} + +div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;} +div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} + +/* STOP */ + +/* The rest of this file contains styles related to the mechanics of + the editor. You probably shouldn't touch them. */ + +.CodeMirror { + line-height: 1; + position: relative; + overflow: hidden; + background: white; + color: black; +} + +.CodeMirror-scroll { + /* 30px is the magic margin used to hide the element's real scrollbars */ + /* See overflow: hidden in .CodeMirror */ + margin-bottom: -30px; margin-right: -30px; + padding-bottom: 30px; padding-right: 30px; + height: 100%; + outline: none; /* Prevent dragging from highlighting the element */ + position: relative; +} +.CodeMirror-sizer { + position: relative; +} + +/* The fake, visible scrollbars. Used to force redraw during scrolling + before actuall scrolling happens, thus preventing shaking and + flickering artifacts. */ +.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { + position: absolute; + z-index: 6; + display: none; +} +.CodeMirror-vscrollbar { + right: 0; top: 0; + overflow-x: hidden; + overflow-y: scroll; +} +.CodeMirror-hscrollbar { + bottom: 0; left: 0; + overflow-y: hidden; + overflow-x: scroll; +} +.CodeMirror-scrollbar-filler { + right: 0; bottom: 0; +} +.CodeMirror-gutter-filler { + left: 0; bottom: 0; +} + +.CodeMirror-gutters { + position: absolute; left: 0; top: 0; + padding-bottom: 30px; + z-index: 3; +} +.CodeMirror-gutter { + white-space: normal; + height: 100%; + padding-bottom: 30px; + margin-bottom: -32px; + display: inline-block; + /* Hack to make IE7 behave */ + *zoom:1; + *display:inline; +} +.CodeMirror-gutter-elt { + position: absolute; + cursor: default; + z-index: 4; +} + +.CodeMirror-lines { + cursor: text; +} +.CodeMirror pre { + /* Reset some styles that the rest of the page might have set */ + -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; + border-width: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + z-index: 2; + position: relative; + overflow: visible; +} +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal; +} +.CodeMirror-linebackground { + position: absolute; + left: 0; right: 0; top: 0; bottom: 0; + z-index: 0; +} + +.CodeMirror-linewidget { + position: relative; + z-index: 2; + overflow: auto; +} + +.CodeMirror-widget { +} + +.CodeMirror-wrap .CodeMirror-scroll { + overflow-x: hidden; +} + +.CodeMirror-measure { + position: absolute; + width: 100%; height: 0px; + overflow: hidden; + visibility: hidden; +} +.CodeMirror-measure pre { position: static; } + +.CodeMirror div.CodeMirror-cursor { + position: absolute; + visibility: hidden; + border-right: none; + width: 0; +} +.CodeMirror-focused div.CodeMirror-cursor { + visibility: visible; +} + +.CodeMirror-selected { background: #d9d9d9; } +.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } + +.cm-searching { + background: #ffa; + background: rgba(255, 255, 0, .4); +} + +/* IE7 hack to prevent it from returning funny offsetTops on the spans */ +.CodeMirror span { *vertical-align: text-bottom; } + +@media print { + /* Hide the cursor when printing */ + .CodeMirror div.CodeMirror-cursor { + visibility: hidden; + } +} diff --git a/admin/view/javascript/shopunity/codemirror/codemirror.js b/admin/view/javascript/shopunity/codemirror/codemirror.js new file mode 100755 index 0000000..ac0f324 --- /dev/null +++ b/admin/view/javascript/shopunity/codemirror/codemirror.js @@ -0,0 +1,5715 @@ +// CodeMirror version 3.14 +// +// CodeMirror is the only global var we claim +window.CodeMirror = (function() { + "use strict"; + + // BROWSER SNIFFING + + // Crude, but necessary to handle a number of hard-to-feature-detect + // bugs and behavior differences. + var gecko = /gecko\/\d/i.test(navigator.userAgent); + var ie = /MSIE \d/.test(navigator.userAgent); + var ie_lt8 = ie && (document.documentMode == null || document.documentMode < 8); + var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9); + var webkit = /WebKit\//.test(navigator.userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var opera = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var khtml = /KHTML\//.test(navigator.userAgent); + var mac_geLion = /Mac OS X 1\d\D([7-9]|\d\d)\D/.test(navigator.userAgent); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); + var phantom = /PhantomJS/.test(navigator.userAgent); + + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var windows = /windows/i.test(navigator.platform); + + var opera_version = opera && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (opera_version) opera_version = Number(opera_version[1]); + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || opera && (opera_version == null || opera_version < 12.11)); + var captureMiddleClick = gecko || (ie && !ie_lt9); + + // Optimize some code when these features are not used + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // CONSTRUCTOR + + function CodeMirror(place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options || {}; + // Determine effective options based on given values and defaults. + for (var opt in defaults) if (!options.hasOwnProperty(opt) && defaults.hasOwnProperty(opt)) + options[opt] = defaults[opt]; + setGuttersForLineNumbers(options); + + var docStart = typeof options.value == "string" ? 0 : options.value.first; + var display = this.display = makeDisplay(place, docStart); + display.wrapper.CodeMirror = this; + updateGutters(this); + if (options.autofocus && !mobile) focusInput(this); + + this.state = {keyMaps: [], + overlays: [], + modeGen: 0, + overwrite: false, focused: false, + suppressEdits: false, pasteIncoming: false, + draggingText: false, + highlight: new Delayed()}; + + themeChanged(this); + if (options.lineWrapping) + this.display.wrapper.className += " CodeMirror-wrap"; + + var doc = options.value; + if (typeof doc == "string") doc = new Doc(options.value, options.mode); + operation(this, attachDoc)(this, doc); + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie) setTimeout(bind(resetInput, this, true), 20); + + registerEventHandlers(this); + // IE throws unspecified error in certain cases, when + // trying to access activeElement before onload + var hasFocus; try { hasFocus = (document.activeElement == display.input); } catch(e) { } + if (hasFocus || (options.autofocus && !mobile)) setTimeout(bind(onFocus, this), 20); + else onBlur(this); + + operation(this, function() { + for (var opt in optionHandlers) + if (optionHandlers.propertyIsEnumerable(opt)) + optionHandlers[opt](this, options[opt], Init); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + })(); + } + + // DISPLAY CONSTRUCTOR + + function makeDisplay(place, docStart) { + var d = {}; + + var input = d.input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none; font-size: 4px;"); + if (webkit) input.style.width = "1000px"; + else input.setAttribute("wrap", "off"); + // if border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) input.style.border = "1px solid black"; + input.setAttribute("autocorrect", "off"); input.setAttribute("autocapitalize", "off"); input.setAttribute("spellcheck", "false"); + + // Wraps and hides input textarea + d.inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The actual fake scrollbars. + d.scrollbarH = elt("div", [elt("div", null, null, "height: 1px")], "CodeMirror-hscrollbar"); + d.scrollbarV = elt("div", [elt("div", null, null, "width: 1px")], "CodeMirror-vscrollbar"); + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + // DIVs containing the selection and the actual code + d.lineDiv = elt("div", null, "CodeMirror-code"); + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + // Blinky cursor, and element used to ensure cursor fits at the end of a line + d.cursor = elt("div", "\u00a0", "CodeMirror-cursor"); + // Secondary cursor, shown when on a 'jump' in bi-directional text + d.otherCursor = elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"); + // Used to measure text size + d.measure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.selectionDiv, d.lineDiv, d.cursor, d.otherCursor], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the text, causes scrolling + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + // D is needed because behavior of elts with overflow: auto and padding is inconsistent across browsers + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerCutOff + "px; width: 1px;"); + // Will contain the gutters, if any + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Provides scrolling + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.inputDiv, d.scrollbarH, d.scrollbarV, + d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + // Work around IE7 z-index bug + if (ie_lt8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (place.appendChild) place.appendChild(d.wrapper); else place(d.wrapper); + + // Needed to hide big blue blinking cursor on Mobile Safari + if (ios) input.style.width = "0px"; + if (!webkit) d.scroller.draggable = true; + // Needed to handle Tab key in KHTML + if (khtml) { d.inputDiv.style.height = "1px"; d.inputDiv.style.position = "absolute"; } + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + else if (ie_lt8) d.scrollbarH.style.minWidth = d.scrollbarV.style.minWidth = "18px"; + + // Current visible range (may be bigger than the view window). + d.viewOffset = d.lastSizeC = 0; + d.showingFrom = d.showingTo = docStart; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // See readInput and resetInput + d.prevInput = ""; + // Set to true when a non-horizontal-scrolling widget is added. As + // an optimization, widget aligning is skipped when d is false. + d.alignWidgets = false; + // Flag that indicates whether we currently expect input to appear + // (after some event like 'keypress' or 'input') and are polling + // intensively. + d.pollingFast = false; + // Self-resetting timeout for the poller + d.poll = new Delayed(); + + d.cachedCharWidth = d.cachedTextHeight = null; + d.measureLineCache = []; + d.measureLineCachePos = 0; + + // Tracks when resetInput has punted to just putting a short + // string instead of the (large) selection. + d.inaccurateSelection = false; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + return d; + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode(cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + cm.doc.iter(function(line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } + + function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + cm.display.wrapper.className += " CodeMirror-wrap"; + cm.display.sizer.style.minWidth = ""; + } else { + cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-wrap", ""); + computeMaxLength(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function(){updateScrollbars(cm);}, 100); + } + + function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function(line) { + if (lineIsHidden(cm.doc, line)) + return 0; + else if (wrapping) + return (Math.ceil(line.text.length / perLine) || 1) * th; + else + return th; + }; + } + + function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function(line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); + } + + function keyMapChanged(cm) { + var map = keyMap[cm.options.keyMap], style = map.style; + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + + (style ? " cm-keymap-" + style : ""); + cm.state.disableInput = map.disableInput; + } + + function themeChanged(cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + function guttersChanged(cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function(){alignHorizontally(cm);}, 20); + } + + function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + } + + function lineLength(doc, line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(); + cur = getLine(doc, found.from.line); + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(); + len -= cur.text.length - found.from.ch; + cur = getLine(doc, found.to.line); + len += cur.text.length - found.to.ch; + } + return len; + } + + function computeMaxLength(cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(doc, d.maxLine); + d.maxLineChanged = true; + doc.iter(function(line) { + var len = lineLength(doc, line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } + + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers(options) { + var found = false; + for (var i = 0; i < options.gutters.length; ++i) { + if (options.gutters[i] == "CodeMirror-linenumbers") { + if (options.lineNumbers) found = true; + else options.gutters.splice(i--, 1); + } + } + if (!found && options.lineNumbers) + options.gutters.push("CodeMirror-linenumbers"); + } + + // SCROLLBARS + + // Re-synchronize the fake scrollbars with the actual size of the + // content. Optionally force a scrollTop. + function updateScrollbars(cm) { + var d = cm.display, docHeight = cm.doc.height; + var totalHeight = docHeight + paddingVert(d); + d.sizer.style.minHeight = d.heightForcer.style.top = totalHeight + "px"; + d.gutters.style.height = Math.max(totalHeight, d.scroller.clientHeight - scrollerCutOff) + "px"; + var scrollHeight = Math.max(totalHeight, d.scroller.scrollHeight); + var needsH = d.scroller.scrollWidth > (d.scroller.clientWidth + 1); + var needsV = scrollHeight > (d.scroller.clientHeight + 1); + if (needsV) { + d.scrollbarV.style.display = "block"; + d.scrollbarV.style.bottom = needsH ? scrollbarWidth(d.measure) + "px" : "0"; + d.scrollbarV.firstChild.style.height = + (scrollHeight - d.scroller.clientHeight + d.scrollbarV.clientHeight) + "px"; + } else d.scrollbarV.style.display = ""; + if (needsH) { + d.scrollbarH.style.display = "block"; + d.scrollbarH.style.right = needsV ? scrollbarWidth(d.measure) + "px" : "0"; + d.scrollbarH.firstChild.style.width = + (d.scroller.scrollWidth - d.scroller.clientWidth + d.scrollbarH.clientWidth) + "px"; + } else d.scrollbarH.style.display = ""; + if (needsH && needsV) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = d.scrollbarFiller.style.width = scrollbarWidth(d.measure) + "px"; + } else d.scrollbarFiller.style.display = ""; + if (needsH && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = scrollbarWidth(d.measure) + "px"; + d.gutterFiller.style.width = d.gutters.offsetWidth + "px"; + } else d.gutterFiller.style.display = ""; + + if (mac_geLion && scrollbarWidth(d.measure) === 0) + d.scrollbarV.style.minWidth = d.scrollbarH.style.minHeight = mac_geMountainLion ? "18px" : "12px"; + } + + function visibleLines(display, doc, viewPort) { + var top = display.scroller.scrollTop, height = display.wrapper.clientHeight; + if (typeof viewPort == "number") top = viewPort; + else if (viewPort) {top = viewPort.top; height = viewPort.bottom - viewPort.top;} + top = Math.floor(top - paddingTop(display)); + var bottom = Math.ceil(top + height); + return {from: lineAtHeight(doc, top), to: lineAtHeight(doc, bottom)}; + } + + // LINE NUMBERS + + function alignHorizontally(cm) { + var display = cm.display; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, l = comp + "px"; + for (var n = display.lineDiv.firstChild; n; n = n.nextSibling) if (n.alignable) { + for (var i = 0, a = n.alignable; i < a.length; ++i) a[i].style.left = l; + } + if (cm.options.fixedGutter) + display.gutters.style.left = (comp + gutterW) + "px"; + } + + function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding); + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + return true; + } + return false; + } + + function lineNumberFor(options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); + } + function compensateForHScroll(display) { + return getRect(display.scroller).left - getRect(display.sizer).left; + } + + // DISPLAY DRAWING + + function updateDisplay(cm, changes, viewPort) { + var oldFrom = cm.display.showingFrom, oldTo = cm.display.showingTo, updated; + var visible = visibleLines(cm.display, cm.doc, viewPort); + for (;;) { + if (!updateDisplayInner(cm, changes, visible)) break; + updated = true; + updateSelection(cm); + updateScrollbars(cm); + + // Clip forced viewport to actual scrollable area + if (viewPort) + viewPort = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, + typeof viewPort == "number" ? viewPort : viewPort.top); + visible = visibleLines(cm.display, cm.doc, viewPort); + if (visible.from >= cm.display.showingFrom && visible.to <= cm.display.showingTo) + break; + changes = []; + } + + if (updated) { + signalLater(cm, "update", cm); + if (cm.display.showingFrom != oldFrom || cm.display.showingTo != oldTo) + signalLater(cm, "viewportChange", cm, cm.display.showingFrom, cm.display.showingTo); + } + return updated; + } + + // Uses a set of changes plus the current scroll position to + // determine which DOM updates have to be made, and makes the + // updates. + function updateDisplayInner(cm, changes, visible) { + var display = cm.display, doc = cm.doc; + if (!display.wrapper.clientWidth) { + display.showingFrom = display.showingTo = doc.first; + display.viewOffset = 0; + return; + } + + // Bail out if the visible area is already rendered and nothing changed. + if (changes.length == 0 && + visible.from > display.showingFrom && visible.to < display.showingTo) + return; + + if (maybeUpdateLineNumberWidth(cm)) + changes = [{from: doc.first, to: doc.first + doc.size}]; + var gutterW = display.sizer.style.marginLeft = display.gutters.offsetWidth + "px"; + display.scrollbarH.style.left = cm.options.fixedGutter ? gutterW : "0"; + + // Used to determine which lines need their line numbers updated + var positionsChangedFrom = Infinity; + if (cm.options.lineNumbers) + for (var i = 0; i < changes.length; ++i) + if (changes[i].diff) { positionsChangedFrom = changes[i].from; break; } + + var end = doc.first + doc.size; + var from = Math.max(visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, visible.to + cm.options.viewportMargin); + if (display.showingFrom < from && from - display.showingFrom < 20) from = Math.max(doc.first, display.showingFrom); + if (display.showingTo > to && display.showingTo - to < 20) to = Math.min(end, display.showingTo); + if (sawCollapsedSpans) { + from = lineNo(visualLine(doc, getLine(doc, from))); + while (to < end && lineIsHidden(doc, getLine(doc, to))) ++to; + } + + // Create a range of theoretically intact lines, and punch holes + // in that using the change info. + var intact = [{from: Math.max(display.showingFrom, doc.first), + to: Math.min(display.showingTo, end)}]; + if (intact[0].from >= intact[0].to) intact = []; + else intact = computeIntact(intact, changes); + // When merged lines are present, we might have to reduce the + // intact ranges because changes in continued fragments of the + // intact lines do require the lines to be redrawn. + if (sawCollapsedSpans) + for (var i = 0; i < intact.length; ++i) { + var range = intact[i], merged; + while (merged = collapsedSpanAtEnd(getLine(doc, range.to - 1))) { + var newTo = merged.find().from.line; + if (newTo > range.from) range.to = newTo; + else { intact.splice(i--, 1); break; } + } + } + + // Clip off the parts that won't be visible + var intactLines = 0; + for (var i = 0; i < intact.length; ++i) { + var range = intact[i]; + if (range.from < from) range.from = from; + if (range.to > to) range.to = to; + if (range.from >= range.to) intact.splice(i--, 1); + else intactLines += range.to - range.from; + } + if (intactLines == to - from && from == display.showingFrom && to == display.showingTo) { + updateViewOffset(cm); + return; + } + intact.sort(function(a, b) {return a.from - b.from;}); + + // Avoid crashing on IE's "unspecified error" when in iframes + try { + var focused = document.activeElement; + } catch(e) {} + if (intactLines < (to - from) * .7) display.lineDiv.style.display = "none"; + patchDisplay(cm, from, to, intact, positionsChangedFrom); + display.lineDiv.style.display = ""; + if (focused && document.activeElement != focused && focused.offsetHeight) focused.focus(); + + var different = from != display.showingFrom || to != display.showingTo || + display.lastSizeC != display.wrapper.clientHeight; + // This is just a bogus formula that detects when the editor is + // resized or the font size changes. + if (different) { + display.lastSizeC = display.wrapper.clientHeight; + startWorker(cm, 400); + } + display.showingFrom = from; display.showingTo = to; + + var prevBottom = display.lineDiv.offsetTop; + for (var node = display.lineDiv.firstChild, height; node; node = node.nextSibling) if (node.lineObj) { + if (ie_lt8) { + var bot = node.offsetTop + node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = getRect(node); + height = box.bottom - box.top; + } + var diff = node.lineObj.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(node.lineObj, height); + var widgets = node.lineObj.widgets; + if (widgets) for (var i = 0; i < widgets.length; ++i) + widgets[i].height = widgets[i].node.offsetHeight; + } + } + updateViewOffset(cm); + + return true; + } + + function updateViewOffset(cm) { + var off = cm.display.viewOffset = heightAtLine(cm, getLine(cm.doc, cm.display.showingFrom)); + // Position the mover div to align with the current virtual scroll position + cm.display.mover.style.top = off + "px"; + } + + function computeIntact(intact, changes) { + for (var i = 0, l = changes.length || 0; i < l; ++i) { + var change = changes[i], intact2 = [], diff = change.diff || 0; + for (var j = 0, l2 = intact.length; j < l2; ++j) { + var range = intact[j]; + if (change.to <= range.from && change.diff) { + intact2.push({from: range.from + diff, to: range.to + diff}); + } else if (change.to <= range.from || change.from >= range.to) { + intact2.push(range); + } else { + if (change.from > range.from) + intact2.push({from: range.from, to: change.from}); + if (change.to < range.to) + intact2.push({from: change.to + diff, to: range.to + diff}); + } + } + intact = intact2; + } + return intact; + } + + function getDimensions(cm) { + var d = cm.display, left = {}, width = {}; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft; + width[cm.options.gutters[i]] = n.offsetWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; + } + + function patchDisplay(cm, from, to, intact, updateNumbersFrom) { + var dims = getDimensions(cm); + var display = cm.display, lineNumbers = cm.options.lineNumbers; + if (!intact.length && (!webkit || !cm.display.currentWheelTarget)) + removeChildren(display.lineDiv); + var container = display.lineDiv, cur = container.firstChild; + + function rm(node) { + var next = node.nextSibling; + if (webkit && mac && cm.display.currentWheelTarget == node) { + node.style.display = "none"; + node.lineObj = null; + } else { + node.parentNode.removeChild(node); + } + return next; + } + + var nextIntact = intact.shift(), lineN = from; + cm.doc.iter(from, to, function(line) { + if (nextIntact && nextIntact.to == lineN) nextIntact = intact.shift(); + if (lineIsHidden(cm.doc, line)) { + if (line.height != 0) updateLineHeight(line, 0); + if (line.widgets && cur.previousSibling) for (var i = 0; i < line.widgets.length; ++i) { + var w = line.widgets[i]; + if (w.showIfHidden) { + var prev = cur.previousSibling; + if (/pre/i.test(prev.nodeName)) { + var wrap = elt("div", null, null, "position: relative"); + prev.parentNode.replaceChild(wrap, prev); + wrap.appendChild(prev); + prev = wrap; + } + var wnode = prev.appendChild(elt("div", [w.node], "CodeMirror-linewidget")); + if (!w.handleMouseEvents) wnode.ignoreEvents = true; + positionLineWidget(w, wnode, prev, dims); + } + } + } else if (nextIntact && nextIntact.from <= lineN && nextIntact.to > lineN) { + // This line is intact. Skip to the actual node. Update its + // line number if needed. + while (cur.lineObj != line) cur = rm(cur); + if (lineNumbers && updateNumbersFrom <= lineN && cur.lineNumber) + setTextContent(cur.lineNumber, lineNumberFor(cm.options, lineN)); + cur = cur.nextSibling; + } else { + // For lines with widgets, make an attempt to find and reuse + // the existing element, so that widgets aren't needlessly + // removed and re-inserted into the dom + if (line.widgets) for (var j = 0, search = cur, reuse; search && j < 20; ++j, search = search.nextSibling) + if (search.lineObj == line && /div/i.test(search.nodeName)) { reuse = search; break; } + // This line needs to be generated. + var lineNode = buildLineElement(cm, line, lineN, dims, reuse); + if (lineNode != reuse) { + container.insertBefore(lineNode, cur); + } else { + while (cur != reuse) cur = rm(cur); + cur = cur.nextSibling; + } + + lineNode.lineObj = line; + } + ++lineN; + }); + while (cur) cur = rm(cur); + } + + function buildLineElement(cm, line, lineNo, dims, reuse) { + var lineElement = lineContent(cm, line); + var markers = line.gutterMarkers, display = cm.display, wrap; + + if (!cm.options.lineNumbers && !markers && !line.bgClass && !line.wrapClass && !line.widgets) + return lineElement; + + // Lines with gutter elements, widgets or a background class need + // to be wrapped again, and have the extra elements added to the + // wrapper div + + if (reuse) { + reuse.alignable = null; + var isOk = true, widgetsSeen = 0, insertBefore = null; + for (var n = reuse.firstChild, next; n; n = next) { + next = n.nextSibling; + if (!/\bCodeMirror-linewidget\b/.test(n.className)) { + reuse.removeChild(n); + } else { + for (var i = 0, first = true; i < line.widgets.length; ++i) { + var widget = line.widgets[i]; + if (!widget.above) { insertBefore = n; first = false; } + if (widget.node == n.firstChild) { + positionLineWidget(widget, n, reuse, dims); + ++widgetsSeen; + break; + } + } + if (i == line.widgets.length) { isOk = false; break; } + } + } + reuse.insertBefore(lineElement, insertBefore); + if (isOk && widgetsSeen == line.widgets.length) { + wrap = reuse; + reuse.className = line.wrapClass || ""; + } + } + if (!wrap) { + wrap = elt("div", null, line.wrapClass, "position: relative"); + wrap.appendChild(lineElement); + } + // Kludge to make sure the styled element lies behind the selection (by z-index) + if (line.bgClass) + wrap.insertBefore(elt("div", null, line.bgClass + " CodeMirror-linebackground"), wrap.firstChild); + if (cm.options.lineNumbers || markers) { + var gutterWrap = wrap.insertBefore(elt("div", null, null, "position: absolute; left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"), + wrap.firstChild); + if (cm.options.fixedGutter) (wrap.alignable || (wrap.alignable = [])).push(gutterWrap); + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) + wrap.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineNo), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + display.lineNumInnerWidth + "px")); + if (markers) + for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + if (ie_lt8) wrap.style.zIndex = 2; + if (line.widgets && wrap != reuse) for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.ignoreEvents = true; + positionLineWidget(widget, node, wrap, dims); + if (widget.above) + wrap.insertBefore(node, cm.options.lineNumbers && line.height != 0 ? gutterWrap : lineElement); + else + wrap.appendChild(node); + signalLater(widget, "redraw"); + } + return wrap; + } + + function positionLineWidget(widget, node, wrap, dims) { + if (widget.noHScroll) { + (wrap.alignable || (wrap.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + + // SELECTION / CURSOR + + function updateSelection(cm) { + var display = cm.display; + var collapsed = posEq(cm.doc.sel.from, cm.doc.sel.to); + if (collapsed || cm.options.showCursorWhenSelecting) + updateSelectionCursor(cm); + else + display.cursor.style.display = display.otherCursor.style.display = "none"; + if (!collapsed) + updateSelectionRange(cm); + else + display.selectionDiv.style.display = "none"; + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, cm.doc.sel.head, "div"); + var wrapOff = getRect(display.wrapper), lineOff = getRect(display.lineDiv); + display.inputDiv.style.top = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)) + "px"; + display.inputDiv.style.left = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)) + "px"; + } + } + + // No selection, plain cursor + function updateSelectionCursor(cm) { + var display = cm.display, pos = cursorCoords(cm, cm.doc.sel.head, "div"); + display.cursor.style.left = pos.left + "px"; + display.cursor.style.top = pos.top + "px"; + display.cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + display.cursor.style.display = ""; + + if (pos.other) { + display.otherCursor.style.display = ""; + display.otherCursor.style.left = pos.other.left + "px"; + display.otherCursor.style.top = pos.other.top + "px"; + display.otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } else { display.otherCursor.style.display = "none"; } + } + + // Highlight selection + function updateSelectionRange(cm) { + var display = cm.display, doc = cm.doc, sel = cm.doc.sel; + var fragment = document.createDocumentFragment(); + var clientWidth = display.lineSpace.offsetWidth, pl = paddingLeft(cm.display); + + function add(left, top, width, bottom) { + if (top < 0) top = 0; + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? clientWidth - left : width) + + "px; height: " + (bottom - top) + "px")); + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = pl; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = pl; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = clientWidth; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + start = leftPos; + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + end = rightPos; + if (left < pl + 1) left = pl; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return {start: start, end: end}; + } + + if (sel.from.line == sel.to.line) { + drawForLine(sel.from.line, sel.from.ch, sel.to.ch); + } else { + var fromLine = getLine(doc, sel.from.line), toLine = getLine(doc, sel.to.line); + var singleVLine = visualLine(doc, fromLine) == visualLine(doc, toLine); + var leftEnd = drawForLine(sel.from.line, sel.from.ch, singleVLine ? fromLine.text.length : null).end; + var rightStart = drawForLine(sel.to.line, singleVLine ? 0 : null, sel.to.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(pl, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) + add(pl, leftEnd.bottom, null, rightStart.top); + } + + removeChildrenAndAdd(display.selectionDiv, fragment); + display.selectionDiv.style.display = ""; + } + + // Cursor-blinking + function restartBlink(cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursor.style.visibility = display.otherCursor.style.visibility = ""; + display.blinker = setInterval(function() { + display.cursor.style.visibility = display.otherCursor.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } + + // HIGHLIGHT WORKER + + function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.showingTo) + cm.state.highlight.set(time, bind(highlightWorker, cm)); + } + + function highlightWorker(cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.showingTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changed = [], prevChange; + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.showingTo + 500), function(line) { + if (doc.frontier >= cm.display.showingFrom) { // Visible + var oldStyles = line.styles; + line.styles = highlightLine(cm, line, state); + var ischange = !oldStyles || oldStyles.length != line.styles.length; + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) { + if (prevChange && prevChange.end == doc.frontier) prevChange.end++; + else changed.push(prevChange = {start: doc.frontier, end: doc.frontier + 1}); + } + line.stateAfter = copyState(doc.mode, state); + } else { + processLine(cm, line, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changed.length) + operation(cm, function() { + for (var i = 0; i < changed.length; ++i) + regChange(this, changed[i].start, changed[i].end); + })(); + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc; + for (var search = n, lim = n - 100; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function(line) { + processLine(cm, line, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.showingFrom && pos < display.showingTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + return state; + } + + // POSITION MEASUREMENT + + function paddingTop(display) {return display.lineSpace.offsetTop;} + function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingLeft(display) { + var e = removeChildrenAndAdd(display.measure, elt("pre", null, null, "text-align: left")).appendChild(elt("span", "x")); + return e.offsetLeft; + } + + function measureChar(cm, line, ch, data, bias) { + var dir = -1; + data = data || measureLine(cm, line); + + for (var pos = ch;; pos += dir) { + var r = data[pos]; + if (r) break; + if (dir < 0 && pos == 0) dir = 1; + } + var rightV = (pos < ch || bias == "right") && r.topRight != null; + return {left: pos < ch ? r.right : r.left, + right: pos > ch ? r.left : r.right, + top: rightV ? r.topRight : r.top, + bottom: rightV ? r.bottomRight : r.bottom}; + } + + function findCachedMeasurement(cm, line) { + var cache = cm.display.measureLineCache; + for (var i = 0; i < cache.length; ++i) { + var memo = cache[i]; + if (memo.text == line.text && memo.markedSpans == line.markedSpans && + cm.display.scroller.clientWidth == memo.width && + memo.classes == line.textClass + "|" + line.bgClass + "|" + line.wrapClass) + return memo; + } + } + + function clearCachedMeasurement(cm, line) { + var exists = findCachedMeasurement(cm, line); + if (exists) exists.text = exists.measure = exists.markedSpans = null; + } + + function measureLine(cm, line) { + // First look in the cache + var cached = findCachedMeasurement(cm, line); + if (cached) return cached.measure; + + // Failing that, recompute and store result in cache + var measure = measureLineInner(cm, line); + var cache = cm.display.measureLineCache; + var memo = {text: line.text, width: cm.display.scroller.clientWidth, + markedSpans: line.markedSpans, measure: measure, + classes: line.textClass + "|" + line.bgClass + "|" + line.wrapClass}; + if (cache.length == 16) cache[++cm.display.measureLineCachePos % 16] = memo; + else cache.push(memo); + return measure; + } + + function measureLineInner(cm, line) { + var display = cm.display, measure = emptyArray(line.text.length); + var pre = lineContent(cm, line, measure); + + // IE does not cache element positions of inline elements between + // calls to getBoundingClientRect. This makes the loop below, + // which gathers the positions of all the characters on the line, + // do an amount of layout work quadratic to the number of + // characters. When line wrapping is off, we try to improve things + // by first subdividing the line into a bunch of inline blocks, so + // that IE can reuse most of the layout information from caches + // for those blocks. This does interfere with line wrapping, so it + // doesn't work when wrapping is on, but in that case the + // situation is slightly better, since IE does cache line-wrapping + // information and only recomputes per-line. + if (ie && !ie_lt8 && !cm.options.lineWrapping && pre.childNodes.length > 100) { + var fragment = document.createDocumentFragment(); + var chunk = 10, n = pre.childNodes.length; + for (var i = 0, chunks = Math.ceil(n / chunk); i < chunks; ++i) { + var wrap = elt("div", null, null, "display: inline-block"); + for (var j = 0; j < chunk && n; ++j) { + wrap.appendChild(pre.firstChild); + --n; + } + fragment.appendChild(wrap); + } + pre.appendChild(fragment); + } + + removeChildrenAndAdd(display.measure, pre); + + var outer = getRect(display.lineDiv); + var vranges = [], data = emptyArray(line.text.length), maxBot = pre.offsetHeight; + // Work around an IE7/8 bug where it will sometimes have randomly + // replaced our pre with a clone at this point. + if (ie_lt9 && display.measure.first != pre) + removeChildrenAndAdd(display.measure, pre); + + function categorizeVSpan(top, bot) { + if (bot > maxBot) bot = maxBot; + if (top < 0) top = 0; + for (var j = 0; j < vranges.length; j += 2) { + var rtop = vranges[j], rbot = vranges[j+1]; + if (rtop > bot || rbot < top) continue; + if (rtop <= top && rbot >= bot || + top <= rtop && bot >= rbot || + Math.min(bot, rbot) - Math.max(top, rtop) >= (bot - top) >> 1) { + vranges[j] = Math.min(top, rtop); + vranges[j+1] = Math.max(bot, rbot); + return j; + } + } + vranges.push(top, bot); + return j; + } + + for (var i = 0, cur; i < measure.length; ++i) if (cur = measure[i]) { + var size, node = cur; + // A widget might wrap, needs special care + if (/\bCodeMirror-widget\b/.test(cur.className) && cur.getClientRects) { + if (cur.firstChild.nodeType == 1) node = cur.firstChild; + var rects = node.getClientRects(), rLeft = rects[0], rRight = rects[rects.length - 1]; + if (rects.length > 1) { + var vCatLeft = categorizeVSpan(rLeft.top - outer.top, rLeft.bottom - outer.top); + var vCatRight = categorizeVSpan(rRight.top - outer.top, rRight.bottom - outer.top); + data[i] = {left: rLeft.left - outer.left, right: rRight.right - outer.left, + top: vCatLeft, topRight: vCatRight}; + continue; + } + } + size = getRect(node); + var vCat = categorizeVSpan(size.top - outer.top, size.bottom - outer.top); + var right = size.right; + if (cur.measureRight) right = getRect(cur.measureRight).left; + data[i] = {left: size.left - outer.left, right: right - outer.left, top: vCat}; + } + for (var i = 0, cur; i < data.length; ++i) if (cur = data[i]) { + var vr = cur.top, vrRight = cur.topRight; + cur.top = vranges[vr]; cur.bottom = vranges[vr+1]; + if (vrRight != null) { cur.topRight = vranges[vrRight]; cur.bottomRight = vranges[vrRight+1]; } + } + return data; + } + + function measureLineWidth(cm, line) { + var hasBadSpan = false; + if (line.markedSpans) for (var i = 0; i < line.markedSpans; ++i) { + var sp = line.markedSpans[i]; + if (sp.collapsed && (sp.to == null || sp.to == line.text.length)) hasBadSpan = true; + } + var cached = !hasBadSpan && findCachedMeasurement(cm, line); + if (cached) return measureChar(cm, line, line.text.length, cached.measure, "right").right; + + var pre = lineContent(cm, line); + var end = pre.appendChild(zeroWidthElement(cm.display.measure)); + removeChildrenAndAdd(cm.display.measure, pre); + return getRect(end).right - getRect(cm.display.lineDiv).left; + } + + function clearCaches(cm) { + cm.display.measureLineCache.length = cm.display.measureLineCachePos = 0; + cm.display.cachedCharWidth = cm.display.cachedTextHeight = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Context is one of "line", "div" (display.lineDiv), "local"/null (editor), or "page" + function intoCoordSystem(cm, lineObj, rect, context) { + if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(cm, lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = getRect(cm.display.lineSpace); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Context may be "window", "page", "div", or "local"/null + // Result is in "div" coords + function fromCoordSystem(cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = getRect(cm.display.sizer); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = getRect(cm.display.lineSpace); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, null, bias), context); + } + + function cursorCoords(cm, pos, context, lineObj, measurement) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!measurement) measurement = measureLine(cm, lineObj); + function get(ch, right) { + var m = measureChar(cm, lineObj, ch, measurement, right ? "right" : "left"); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi(ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + function PosWithInfo(line, ch, outside, xRel) { + var pos = new Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Coords must be lineSpace-local + function coordsChar(cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineNo = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineNo > last) + return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); + if (x < 0) x = 0; + + for (;;) { + var lineObj = getLine(doc, lineNo); + var found = coordsCharInner(cm, lineObj, lineNo, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + lineNo = mergedPos.to.line; + else + return found; + } + } + + function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(cm, lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var measurement = measureLine(cm, lineObj); + + function getX(ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", + lineObj, measurement); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + else wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar.test(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < 0 ? -1 : xDiff ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + function textHeight(display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + function charWidth(display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "x"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var width = anchor.offsetWidth; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap changes in such a way that each + // change won't have to update the cursor and display (which would + // be awkward, slow, and error-prone), but instead updates are + // batched and then all combined and executed at once. + + var nextOpId = 0; + function startOperation(cm) { + cm.curOp = { + // An array of ranges of lines that have to be updated. See + // updateDisplay. + changes: [], + updateInput: null, + userSelChange: null, + textChanged: null, + selectionChanged: false, + cursorActivity: false, + updateMaxLine: false, + updateScrollPos: false, + id: ++nextOpId + }; + if (!delayedCallbackDepth++) delayedCallbacks = []; + } + + function endOperation(cm) { + var op = cm.curOp, doc = cm.doc, display = cm.display; + cm.curOp = null; + + if (op.updateMaxLine) computeMaxLength(cm); + if (display.maxLineChanged && !cm.options.lineWrapping && display.maxLine) { + var width = measureLineWidth(cm, display.maxLine); + display.sizer.style.minWidth = Math.max(0, width + 3 + scrollerCutOff) + "px"; + display.maxLineChanged = false; + var maxScrollLeft = Math.max(0, display.sizer.offsetLeft + display.sizer.offsetWidth - display.scroller.clientWidth); + if (maxScrollLeft < doc.scrollLeft && !op.updateScrollPos) + setScrollLeft(cm, Math.min(display.scroller.scrollLeft, maxScrollLeft), true); + } + var newScrollPos, updated; + if (op.updateScrollPos) { + newScrollPos = op.updateScrollPos; + } else if (op.selectionChanged && display.scroller.clientHeight) { // don't rescroll if not visible + var coords = cursorCoords(cm, doc.sel.head); + newScrollPos = calculateScrollPos(cm, coords.left, coords.top, coords.left, coords.bottom); + } + if (op.changes.length || newScrollPos && newScrollPos.scrollTop != null) { + updated = updateDisplay(cm, op.changes, newScrollPos && newScrollPos.scrollTop); + if (cm.display.scroller.offsetHeight) cm.doc.scrollTop = cm.display.scroller.scrollTop; + } + if (!updated && op.selectionChanged) updateSelection(cm); + if (op.updateScrollPos) { + display.scroller.scrollTop = display.scrollbarV.scrollTop = doc.scrollTop = newScrollPos.scrollTop; + display.scroller.scrollLeft = display.scrollbarH.scrollLeft = doc.scrollLeft = newScrollPos.scrollLeft; + alignHorizontally(cm); + if (op.scrollToPos) + scrollPosIntoView(cm, clipPos(cm.doc, op.scrollToPos), op.scrollToPosMargin); + } else if (newScrollPos) { + scrollCursorIntoView(cm); + } + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) + resetInput(cm, op.userSelChange); + + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) for (var i = 0; i < hidden.length; ++i) + if (!hidden[i].lines.length) signal(hidden[i], "hide"); + if (unhidden) for (var i = 0; i < unhidden.length; ++i) + if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); + + var delayed; + if (!--delayedCallbackDepth) { + delayed = delayedCallbacks; + delayedCallbacks = null; + } + if (op.textChanged) + signal(cm, "change", cm, op.textChanged); + if (op.cursorActivity) signal(cm, "cursorActivity", cm); + if (delayed) for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // Wraps a function in an operation. Returns the wrapped function. + function operation(cm1, f) { + return function() { + var cm = cm1 || this, withOp = !cm.curOp; + if (withOp) startOperation(cm); + try { var result = f.apply(cm, arguments); } + finally { if (withOp) endOperation(cm); } + return result; + }; + } + function docOperation(f) { + return function() { + var withOp = this.cm && !this.cm.curOp, result; + if (withOp) startOperation(this.cm); + try { result = f.apply(this, arguments); } + finally { if (withOp) endOperation(this.cm); } + return result; + }; + } + function runInOp(cm, f) { + var withOp = !cm.curOp, result; + if (withOp) startOperation(cm); + try { result = f(); } + finally { if (withOp) endOperation(cm); } + return result; + } + + function regChange(cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + cm.curOp.changes.push({from: from, to: to, diff: lendiff}); + } + + // INPUT HANDLING + + function slowPoll(cm) { + if (cm.display.pollingFast) return; + cm.display.poll.set(cm.options.pollInterval, function() { + readInput(cm); + if (cm.state.focused) slowPoll(cm); + }); + } + + function fastPoll(cm) { + var missed = false; + cm.display.pollingFast = true; + function p() { + var changed = readInput(cm); + if (!changed && !missed) {missed = true; cm.display.poll.set(60, p);} + else {cm.display.pollingFast = false; slowPoll(cm);} + } + cm.display.poll.set(20, p); + } + + // prevInput is a hack to work with IME. If we reset the textarea + // on every change, that breaks IME. So we look for changes + // compared to the previous content instead. (Modern browsers have + // events that indicate IME taking place, but these are not widely + // supported or compatible enough yet to rely on.) + function readInput(cm) { + var input = cm.display.input, prevInput = cm.display.prevInput, doc = cm.doc, sel = doc.sel; + if (!cm.state.focused || hasSelection(input) || isReadOnly(cm) || cm.state.disableInput) return false; + var text = input.value; + if (text == prevInput && posEq(sel.from, sel.to)) return false; + if (ie && !ie_lt9 && cm.display.inputHasSelection === text) { + resetInput(cm, true); + return false; + } + + var withOp = !cm.curOp; + if (withOp) startOperation(cm); + sel.shift = false; + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + var from = sel.from, to = sel.to; + if (same < prevInput.length) + from = Pos(from.line, from.ch - (prevInput.length - same)); + else if (cm.state.overwrite && posEq(from, to) && !cm.state.pasteIncoming) + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + (text.length - same))); + + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: splitLines(text.slice(same)), + origin: cm.state.pasteIncoming ? "paste" : "+input"}; + makeChange(cm.doc, changeEvent, "end"); + cm.curOp.updateInput = updateInput; + signalLater(cm, "inputRead", cm, changeEvent); + + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = cm.display.prevInput = ""; + else cm.display.prevInput = text; + if (withOp) endOperation(cm); + cm.state.pasteIncoming = false; + return true; + } + + function resetInput(cm, user) { + var minimal, selected, doc = cm.doc; + if (!posEq(doc.sel.from, doc.sel.to)) { + cm.display.prevInput = ""; + minimal = hasCopyEvent && + (doc.sel.to.line - doc.sel.from.line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + cm.display.input.value = content; + if (cm.state.focused) selectInput(cm.display.input); + if (ie && !ie_lt9) cm.display.inputHasSelection = content; + } else if (user) { + cm.display.prevInput = cm.display.input.value = ""; + if (ie && !ie_lt9) cm.display.inputHasSelection = null; + } + cm.display.inaccurateSelection = minimal; + } + + function focusInput(cm) { + if (cm.options.readOnly != "nocursor" && (!mobile || document.activeElement != cm.display.input)) + cm.display.input.focus(); + } + + function isReadOnly(cm) { + return cm.options.readOnly || cm.doc.cantEdit; + } + + // EVENT HANDLERS + + function registerEventHandlers(cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + if (ie) + on(d.scroller, "dblclick", operation(cm, function(e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = findWordAt(getLine(cm.doc, pos.line).text, pos); + extendSelection(cm.doc, word.from, word.to); + })); + else + on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); + on(d.lineSpace, "selectstart", function(e) { + if (!eventInWidget(d, e)) e_preventDefault(e); + }); + // Gecko browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for Gecko. + if (!captureMiddleClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); + + on(d.scroller, "scroll", function() { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + on(d.scrollbarV, "scroll", function() { + if (d.scroller.clientHeight) setScrollTop(cm, d.scrollbarV.scrollTop); + }); + on(d.scrollbarH, "scroll", function() { + if (d.scroller.clientHeight) setScrollLeft(cm, d.scrollbarH.scrollLeft); + }); + + on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + + function reFocus() { if (cm.state.focused) setTimeout(bind(focusInput, cm), 0); } + on(d.scrollbarH, "mousedown", reFocus); + on(d.scrollbarV, "mousedown", reFocus); + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + var resizeTimer; + function onResize() { + if (resizeTimer == null) resizeTimer = setTimeout(function() { + resizeTimer = null; + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = knownScrollbarWidth = null; + clearCaches(cm); + runInOp(cm, bind(regChange, cm)); + }, 100); + } + on(window, "resize", onResize); + // Above handler holds on to the editor and its data structures. + // Here we poll to unregister it when the editor is no longer in + // the document, so that it can be garbage-collected. + function unregister() { + for (var p = d.wrapper.parentNode; p && p != document.body; p = p.parentNode) {} + if (p) setTimeout(unregister, 5000); + else off(window, "resize", onResize); + } + setTimeout(unregister, 5000); + + on(d.input, "keyup", operation(cm, function(e) { + if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; + if (e.keyCode == 16) cm.doc.sel.shift = false; + })); + on(d.input, "input", bind(fastPoll, cm)); + on(d.input, "keydown", operation(cm, onKeyDown)); + on(d.input, "keypress", operation(cm, onKeyPress)); + on(d.input, "focus", bind(onFocus, cm)); + on(d.input, "blur", bind(onBlur, cm)); + + function drag_(e) { + if (signalDOMEvent(cm, e) || cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e))) return; + e_stop(e); + } + if (cm.options.dragDrop) { + on(d.scroller, "dragstart", function(e){onDragStart(cm, e);}); + on(d.scroller, "dragenter", drag_); + on(d.scroller, "dragover", drag_); + on(d.scroller, "drop", operation(cm, onDrop)); + } + on(d.scroller, "paste", function(e){ + if (eventInWidget(d, e)) return; + focusInput(cm); + fastPoll(cm); + }); + on(d.input, "paste", function() { + cm.state.pasteIncoming = true; + fastPoll(cm); + }); + + function prepareCopy() { + if (d.inaccurateSelection) { + d.prevInput = ""; + d.inaccurateSelection = false; + d.input.value = cm.getSelection(); + selectInput(d.input); + } + } + on(d.input, "cut", prepareCopy); + on(d.input, "copy", prepareCopy); + + // Needed to handle Tab key in KHTML + if (khtml) on(d.sizer, "mouseup", function() { + if (document.activeElement == d.input) d.input.blur(); + focusInput(cm); + }); + } + + function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || n.ignoreEvents || n.parentNode == display.sizer && n != display.mover) return true; + } + } + + function posFromMouse(cm, e, liberal) { + var display = cm.display; + if (!liberal) { + var target = e_target(e); + if (target == display.scrollbarH || target == display.scrollbarH.firstChild || + target == display.scrollbarV || target == display.scrollbarV.firstChild || + target == display.scrollbarFiller || target == display.gutterFiller) return null; + } + var x, y, space = getRect(display.lineSpace); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX; y = e.clientY; } catch (e) { return null; } + return coordsChar(cm, x - space.left, y - space.top); + } + + var lastClick, lastDoubleClick; + function onMouseDown(e) { + if (signalDOMEvent(this, e)) return; + var cm = this, display = cm.display, doc = cm.doc, sel = doc.sel; + sel.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + display.scroller.draggable = false; + setTimeout(function(){display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + + switch (e_button(e)) { + case 3: + if (captureMiddleClick) onContextMenu.call(cm, cm, e); + return; + case 2: + if (start) extendSelection(cm.doc, start); + setTimeout(bind(focusInput, cm), 20); + e_preventDefault(e); + return; + } + // For button 1, if it was clicked inside the editor + // (posFromMouse returning non-null), we have to adjust the + // selection. + if (!start) {if (e_target(e) == display.scroller) e_preventDefault(e); return;} + + if (!cm.state.focused) onFocus(cm); + + var now = +new Date, type = "single"; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { + type = "triple"; + e_preventDefault(e); + setTimeout(bind(focusInput, cm), 20); + selectLine(cm, start.line); + } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + e_preventDefault(e); + var word = findWordAt(getLine(doc, start.line).text, start); + extendSelection(cm.doc, word.from, word.to); + } else { lastClick = {time: now, pos: start}; } + + var last = start; + if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && !posEq(sel.from, sel.to) && + !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { + var dragEnd = operation(cm, function(e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + extendSelection(cm.doc, start); + focusInput(cm); + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + return; + } + e_preventDefault(e); + if (type == "single") extendSelection(cm.doc, clipPos(doc, start)); + + var startstart = sel.from, startend = sel.to, lastPos = start; + + function doSelect(cur) { + if (posEq(lastPos, cur)) return; + lastPos = cur; + + if (type == "single") { + extendSelection(cm.doc, clipPos(doc, start), cur); + return; + } + + startstart = clipPos(doc, startstart); + startend = clipPos(doc, startend); + if (type == "double") { + var word = findWordAt(getLine(doc, cur.line).text, cur); + if (posLess(cur, startstart)) extendSelection(cm.doc, word.from, startend); + else extendSelection(cm.doc, startstart, word.to); + } else if (type == "triple") { + if (posLess(cur, startstart)) extendSelection(cm.doc, startend, clipPos(doc, Pos(cur.line, 0))); + else extendSelection(cm.doc, startstart, clipPos(doc, Pos(cur.line + 1, 0))); + } + } + + var editorSize = getRect(display.wrapper); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend(e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true); + if (!cur) return; + if (!posEq(cur, last)) { + if (!cm.state.focused) onFocus(cm); + last = cur; + doSelect(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) + setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) setTimeout(operation(cm, function() { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + + function done(e) { + counter = Infinity; + e_preventDefault(e); + focusInput(cm); + off(document, "mousemove", move); + off(document, "mouseup", up); + } + + var move = operation(cm, function(e) { + if (!ie && !e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + function clickInGutter(cm, e) { + var display = cm.display; + try { var mX = e.clientX, mY = e.clientY; } + catch(e) { return false; } + + if (mX >= Math.floor(getRect(display.gutters).right)) return false; + e_preventDefault(e); + if (!hasHandler(cm, "gutterClick")) return true; + + var lineBox = getRect(display.lineDiv); + if (mY > lineBox.bottom) return true; + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && getRect(g).right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signalLater(cm, "gutterClick", cm, line, gutter, e); + break; + } + } + return true; + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop(e) { + var cm = this; + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e) || (cm.options.onDragEvent && cm.options.onDragEvent(cm, addStop(e)))) + return; + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || isReadOnly(cm)) return; + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function(file, i) { + var reader = new FileReader; + reader.onload = function() { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(cm.doc, pos); + makeChange(cm.doc, {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}, "around"); + } + }; + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && !(posLess(pos, cm.doc.sel.from) || posLess(cm.doc.sel.to, pos))) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(bind(focusInput, cm), 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + var curFrom = cm.doc.sel.from, curTo = cm.doc.sel.to; + setSelection(cm.doc, pos, pos); + if (cm.state.draggingText) replaceRange(cm.doc, "", curFrom, curTo, "paste"); + cm.replaceSelection(text, null, "paste"); + focusInput(cm); + onFocus(cm); + } + } + catch(e){} + } + } + + function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + var txt = cm.getSelection(); + e.dataTransfer.setData("Text", txt); + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + if (opera) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (opera) img.parentNode.removeChild(img); + } + } + + function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplay(cm, [], val); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + if (cm.display.scrollbarV.scrollTop != val) cm.display.scrollbarV.scrollTop = val; + if (gecko) updateDisplay(cm, []); + startWorker(cm, 100); + } + function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + if (cm.display.scrollbarH.scrollLeft != val) cm.display.scrollbarH.scrollLeft = val; + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1/3; + + function onScrollWheel(cm, e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + if (!(dx && scroll.scrollWidth > scroll.clientWidth || + dy && scroll.scrollHeight > scroll.clientHeight)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + for (var cur = e.target; cur != scroll; cur = cur.parentNode) { + if (cur.lineObj) { + cm.display.currentWheelTarget = cur; + break; + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { + if (dy) + setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplay(cm, [], {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function() { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + if (cm.display.pollingFast && readInput(cm)) cm.display.pollingFast = false; + var doc = cm.doc, prevShift = doc.sel.shift, done = false; + try { + if (isReadOnly(cm)) cm.state.suppressEdits = true; + if (dropShift) doc.sel.shift = false; + done = bound(cm) != Pass; + } finally { + doc.sel.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function allKeyMaps(cm) { + var maps = cm.state.keyMaps.slice(0); + if (cm.options.extraKeys) maps.push(cm.options.extraKeys); + maps.push(cm.options.keyMap); + return maps; + } + + var maybeTransition; + function handleKeyBinding(cm, e) { + // Handle auto keymap transitions + var startMap = getKeyMap(cm.options.keyMap), next = startMap.auto; + clearTimeout(maybeTransition); + if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { + if (getKeyMap(cm.options.keyMap) == startMap) { + cm.options.keyMap = (next.call ? next.call(null, cm) : next); + keyMapChanged(cm); + } + }, 50); + + var name = keyName(e, true), handled = false; + if (!name) return false; + var keymaps = allKeyMaps(cm); + + if (e.shiftKey) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + handled = lookupKey("Shift-" + name, keymaps, function(b) {return doHandleBinding(cm, b, true);}) + || lookupKey(name, keymaps, function(b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + return doHandleBinding(cm, b); + }); + } else { + handled = lookupKey(name, keymaps, function(b) { return doHandleBinding(cm, b); }); + } + + if (handled) { + e_preventDefault(e); + restartBlink(cm); + if (ie_lt9) { e.oldKeyCode = e.keyCode; e.keyCode = 0; } + signalLater(cm, "keyHandled", cm, name, e); + } + return handled; + } + + function handleCharBinding(cm, e, ch) { + var handled = lookupKey("'" + ch + "'", allKeyMaps(cm), + function(b) { return doHandleBinding(cm, b, true); }); + if (handled) { + e_preventDefault(e); + restartBlink(cm); + signalLater(cm, "keyHandled", cm, "'" + ch + "'", e); + } + return handled; + } + + var lastStoppedKey = null; + function onKeyDown(e) { + var cm = this; + if (!cm.state.focused) onFocus(cm); + if (ie && e.keyCode == 27) { e.returnValue = false; } + if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; + var code = e.keyCode; + // IE does strange things with escape. + cm.doc.sel.shift = code == 16 || e.shiftKey; + // First give onKeyEvent option a chance to handle this. + var handled = handleKeyBinding(cm, e); + if (opera) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + cm.replaceSelection(""); + } + } + + function onKeyPress(e) { + var cm = this; + if (signalDOMEvent(cm, e) || cm.options.onKeyEvent && cm.options.onKeyEvent(cm, addStop(e))) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (opera && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (this.options.electricChars && this.doc.mode.electricChars && + this.options.smartIndent && !isReadOnly(this) && + this.doc.mode.electricChars.indexOf(ch) > -1) + setTimeout(operation(cm, function() {indentLine(cm, cm.doc.sel.to.line, "smart");}), 75); + if (handleCharBinding(cm, e, ch)) return; + if (ie && !ie_lt9) cm.display.inputHasSelection = null; + fastPoll(cm); + } + + function onFocus(cm) { + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + if (cm.display.wrapper.className.search(/\bCodeMirror-focused\b/) == -1) + cm.display.wrapper.className += " CodeMirror-focused"; + resetInput(cm, true); + } + slowPoll(cm); + restartBlink(cm); + } + function onBlur(cm) { + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + cm.display.wrapper.className = cm.display.wrapper.className.replace(" CodeMirror-focused", ""); + } + clearInterval(cm.display.blinker); + setTimeout(function() {if (!cm.state.focused) cm.doc.sel.shift = false;}, 150); + } + + var detectingSelectAll; + function onContextMenu(cm, e) { + var display = cm.display, sel = cm.doc.sel; + if (eventInWidget(display, e)) return; + + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || opera) return; // Opera is difficult. + if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) + operation(cm, setSelection)(cm.doc, pos, pos); + + var oldCSS = display.input.style.cssText; + display.inputDiv.style.position = "absolute"; + display.input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; outline: none;" + + "border-width: 0; outline: none; overflow: hidden; opacity: .05; -ms-opacity: .05; filter: alpha(opacity=5);"; + focusInput(cm); + resetInput(cm, true); + // Adds "Select all" to context menu in FF + if (posEq(sel.from, sel.to)) display.input.value = display.prevInput = " "; + + function prepareSelectAllHack() { + if (display.input.selectionStart != null) { + var extval = display.input.value = " " + (posEq(sel.from, sel.to) ? "" : display.input.value); + display.prevInput = " "; + display.input.selectionStart = 1; display.input.selectionEnd = extval.length; + } + } + function rehide() { + display.inputDiv.style.position = "relative"; + display.input.style.cssText = oldCSS; + if (ie_lt9) display.scrollbarV.scrollTop = display.scroller.scrollTop = scrollPos; + slowPoll(cm); + + // Try to detect the user choosing select-all + if (display.input.selectionStart != null) { + if (!ie || ie_lt9) prepareSelectAllHack(); + clearTimeout(detectingSelectAll); + var i = 0, poll = function(){ + if (display.prevInput == " " && display.input.selectionStart == 0) + operation(cm, commands.selectAll)(cm); + else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); + else resetInput(cm); + }; + detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && !ie_lt9) prepareSelectAllHack(); + if (captureMiddleClick) { + e_stop(e); + var mouseup = function() { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + } + + // UPDATING + + var changeEnd = CodeMirror.changeEnd = function(change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Make sure a position will be valid after the given change. + function clipPostChange(doc, change, pos) { + if (!posLess(change.from, pos)) return clipPos(doc, pos); + var diff = (change.text.length - 1) - (change.to.line - change.from.line); + if (pos.line > change.to.line + diff) { + var preLine = pos.line - diff, lastLine = doc.first + doc.size - 1; + if (preLine > lastLine) return Pos(lastLine, getLine(doc, lastLine).text.length); + return clipToLen(pos, getLine(doc, preLine).text.length); + } + if (pos.line == change.to.line + diff) + return clipToLen(pos, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0) + + getLine(doc, change.to.line).text.length - change.to.ch); + var inside = pos.line - change.from.line; + return clipToLen(pos, change.text[inside].length + (inside ? 0 : change.from.ch)); + } + + // Hint can be null|"end"|"start"|"around"|{anchor,head} + function computeSelAfterChange(doc, change, hint) { + if (hint && typeof hint == "object") // Assumed to be {anchor, head} object + return {anchor: clipPostChange(doc, change, hint.anchor), + head: clipPostChange(doc, change, hint.head)}; + + if (hint == "start") return {anchor: change.from, head: change.from}; + + var end = changeEnd(change); + if (hint == "around") return {anchor: change.from, head: end}; + if (hint == "end") return {anchor: end, head: end}; + + // hint is null, leave the selection alone as much as possible + var adjustPos = function(pos) { + if (posLess(pos, change.from)) return pos; + if (!posLess(change.to, pos)) return end; + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += end.ch - change.to.ch; + return Pos(line, ch); + }; + return {anchor: adjustPos(doc.sel.anchor), head: adjustPos(doc.sel.head)}; + } + + function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function() { this.canceled = true; } + }; + if (update) obj.update = function(from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Replace the range from from to to by the strings in replacement. + // change is a {from, to, text [, origin]} object + function makeChange(doc, change, selUpdate, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, selUpdate, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 1; --i) + makeChangeNoReadonly(doc, {from: split[i].from, to: split[i].to, text: [""]}); + if (split.length) + makeChangeNoReadonly(doc, {from: split[0].from, to: split[0].to, text: change.text}, selUpdate); + } else { + makeChangeNoReadonly(doc, change, selUpdate); + } + } + + function makeChangeNoReadonly(doc, change, selUpdate) { + var selAfter = computeSelAfterChange(doc, change, selUpdate); + addToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + function makeChangeFromHistory(doc, type) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history; + var event = (type == "undo" ? hist.done : hist.undone).pop(); + if (!event) return; + + var anti = {changes: [], anchorBefore: event.anchorAfter, headBefore: event.headAfter, + anchorAfter: event.anchorBefore, headAfter: event.headBefore, + generation: hist.generation}; + (type == "undo" ? hist.undone : hist.done).push(anti); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + (type == "undo" ? hist.done : hist.undone).length = 0; + return; + } + + anti.changes.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change, null) + : {anchor: event.anchorBefore, head: event.headBefore}; + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + var rebased = []; + + linkedDocs(doc, function(doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + function shiftDoc(doc, distance) { + function shiftPos(pos) {return Pos(pos.line + distance, pos.ch);} + doc.first += distance; + if (doc.cm) regChange(doc.cm, doc.first, doc.first, distance); + doc.sel.head = shiftPos(doc.sel.head); doc.sel.anchor = shiftPos(doc.sel.anchor); + doc.sel.from = shiftPos(doc.sel.from); doc.sel.to = shiftPos(doc.sel.to); + } + + function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change, null); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans, selAfter); + else updateDoc(doc, change, spans, selAfter); + } + + function makeChangeSingleDocInEditor(cm, change, spans, selAfter) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(doc, getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function(line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (!posLess(doc.sel.head, change.from) && !posLess(change.to, doc.sel.head)) + cm.curOp.cursorActivity = true; + + updateDoc(doc, change, spans, selAfter, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function(line) { + var len = lineLength(doc, line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + regChange(cm, from.line, to.line + 1, lendiff); + + if (hasHandler(cm, "change")) { + var changeObj = {from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin}; + if (cm.curOp.textChanged) { + for (var cur = cm.curOp.textChanged; cur.next; cur = cur.next) {} + cur.next = changeObj; + } else cm.curOp.textChanged = changeObj; + } + } + + function replaceRange(doc, code, from, to, origin) { + if (!to) to = from; + if (posLess(to, from)) { var tmp = to; to = from; from = tmp; } + if (typeof code == "string") code = splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}, null); + } + + // POSITION OBJECT + + function Pos(line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + } + CodeMirror.Pos = Pos; + + function posEq(a, b) {return a.line == b.line && a.ch == b.ch;} + function posLess(a, b) {return a.line < b.line || (a.line == b.line && a.ch < b.ch);} + function copyPos(x) {return Pos(x.line, x.ch);} + + // SELECTION + + function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos(doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen(pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + else return pos; + } + function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} + + // If shift is held, this will move the selection anchor. Otherwise, + // it'll set the whole selection. + function extendSelection(doc, pos, other, bias) { + if (doc.sel.shift || doc.sel.extend) { + var anchor = doc.sel.anchor; + if (other) { + var posBefore = posLess(pos, anchor); + if (posBefore != posLess(other, anchor)) { + anchor = pos; + pos = other; + } else if (posBefore != posLess(pos, other)) { + pos = other; + } + } + setSelection(doc, anchor, pos, bias); + } else { + setSelection(doc, pos, other || pos, bias); + } + if (doc.cm) doc.cm.curOp.userSelChange = true; + } + + function filterSelectionChange(doc, anchor, head) { + var obj = {anchor: anchor, head: head}; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + obj.anchor = clipPos(doc, obj.anchor); obj.head = clipPos(doc, obj.head); + return obj; + } + + // Update the selection. Last two args are only used by + // updateDoc, since they have to be expressed in the line + // numbers before the update. + function setSelection(doc, anchor, head, bias, checkAtomic) { + if (!checkAtomic && hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { + var filtered = filterSelectionChange(doc, anchor, head); + head = filtered.head; + anchor = filtered.anchor; + } + + var sel = doc.sel; + sel.goalColumn = null; + // Skip over atomic spans. + if (checkAtomic || !posEq(anchor, sel.anchor)) + anchor = skipAtomic(doc, anchor, bias, checkAtomic != "push"); + if (checkAtomic || !posEq(head, sel.head)) + head = skipAtomic(doc, head, bias, checkAtomic != "push"); + + if (posEq(sel.anchor, anchor) && posEq(sel.head, head)) return; + + sel.anchor = anchor; sel.head = head; + var inv = posLess(head, anchor); + sel.from = inv ? head : anchor; + sel.to = inv ? anchor : head; + + if (doc.cm) + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = + doc.cm.curOp.cursorActivity = true; + + signalLater(doc, "cursorActivity", doc); + } + + function reCheckSelection(cm) { + setSelection(cm.doc, cm.doc.sel.from, cm.doc.sel.to, null, "push"); + } + + function skipAtomic(doc, pos, bias, mayClear) { + var flipped = false, curPos = pos; + var dir = bias || 1; + doc.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line); + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + var newPos = m.find()[dir < 0 ? "from" : "to"]; + if (posEq(newPos, curPos)) { + newPos.ch += dir; + if (newPos.ch < 0) { + if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); + else newPos = null; + } + if (!newPos) { + if (flipped) { + // Driven in a corner -- no valid cursor position found at all + // -- try again *with* clearing, if we didn't already + if (!mayClear) return skipAtomic(doc, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + doc.cantEdit = true; + return Pos(doc.first, 0); + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } + } + return curPos; + } + } + + // SCROLLING + + function scrollCursorIntoView(cm) { + var coords = scrollPosIntoView(cm, cm.doc.sel.head, cm.options.cursorScrollMargin); + if (!cm.state.focused) return; + var display = cm.display, box = getRect(display.sizer), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var hidden = display.cursor.style.display == "none"; + if (hidden) { + display.cursor.style.display = ""; + display.cursor.style.left = coords.left + "px"; + display.cursor.style.top = (coords.top - display.viewOffset) + "px"; + } + display.cursor.scrollIntoView(doScroll); + if (hidden) display.cursor.style.display = "none"; + } + } + + function scrollPosIntoView(cm, pos, margin) { + if (margin == null) margin = 0; + for (;;) { + var changed = false, coords = cursorCoords(cm, pos); + var scrollPos = calculateScrollPos(cm, coords.left, coords.top - margin, coords.left, coords.bottom + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) return coords; + } + } + + function scrollIntoView(cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + function calculateScrollPos(cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screen = display.scroller.clientHeight - scrollerCutOff, screentop = display.scroller.scrollTop, result = {}; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenw = display.scroller.clientWidth - scrollerCutOff, screenleft = display.scroller.scrollLeft; + x1 += display.gutters.offsetWidth; x2 += display.gutters.offsetWidth; + var gutterw = display.gutters.offsetWidth; + var atLeft = x1 < gutterw + 10; + if (x1 < screenleft + gutterw || atLeft) { + if (atLeft) x1 = 0; + result.scrollLeft = Math.max(0, x1 - 10 - gutterw); + } else if (x2 > screenw + screenleft - 3) { + result.scrollLeft = x2 + 10 - screenw; + } + return result; + } + + function updateScrollPos(cm, left, top) { + cm.curOp.updateScrollPos = {scrollLeft: left == null ? cm.doc.scrollLeft : left, + scrollTop: top == null ? cm.doc.scrollTop : top}; + } + + function addToScrollPos(cm, left, top) { + var pos = cm.curOp.updateScrollPos || (cm.curOp.updateScrollPos = {scrollLeft: cm.doc.scrollLeft, scrollTop: cm.doc.scrollTop}); + var scroll = cm.display.scroller; + pos.scrollTop = Math.max(0, Math.min(scroll.scrollHeight - scroll.clientHeight, pos.scrollTop + top)); + pos.scrollLeft = Math.max(0, Math.min(scroll.scrollWidth - scroll.clientWidth, pos.scrollLeft + left)); + } + + // API UTILITIES + + function indentLine(cm, n, how, aggressive) { + var doc = cm.doc; + if (how == null) how = "add"; + if (how == "smart") { + if (!cm.doc.mode.indent) how = "prev"; + else var state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (how == "smart") { + indentation = cm.doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how == "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) + for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) + replaceRange(cm.doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + } + + function changeLine(cm, handle, op) { + var no = handle, line = handle, doc = cm.doc; + if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no)) regChange(cm, no, no + 1); + else return null; + return line; + } + + function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + var possible = true; + function findNextLine() { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce(boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return (possible = false); + } else ch = next; + return true; + } + + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur) ? "w" + : !group ? null + : /\s/.test(cur) ? null + : "p"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), origDir, true); + if (!possible) result.hitSide = true; + return result; + } + + function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + function findWordAt(line, pos) { + var start = pos.ch, end = pos.ch; + if (line) { + if (pos.xRel < 0 || end == line.length) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar) ? isWordChar + : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} + : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return {from: Pos(pos.line, start), to: Pos(pos.line, end)}; + } + + function selectLine(cm, line) { + extendSelection(cm.doc, Pos(line, 0), clipPos(cm.doc, Pos(line + 1, 0))); + } + + // PROTOTYPE + + // The publicly visible API. Note that operation(null, f) means + // 'wrap f in an operation, performed on its `this` parameter' + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); focusInput(this); onFocus(this); fastPoll(this);}, + + setOption: function(option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) + operation(this, optionHandlers[option])(this, value, old); + }, + + getOption: function(option) {return this.options[option];}, + getDoc: function() {return this.doc;}, + + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](map); + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) + if ((typeof map == "string" ? maps[i].name : maps[i]) == map) { + maps.splice(i, 1); + return true; + } + }, + + addOverlay: operation(null, function(spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: operation(null, function(spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: operation(null, function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: operation(null, function(how) { + var sel = this.doc.sel; + if (posEq(sel.from, sel.to)) return indentLine(this, sel.from.line, how); + var e = sel.to.line - (sel.to.ch ? 0 : 1); + for (var i = sel.from.line; i <= e; ++i) indentLine(this, i, how); + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + var doc = this.doc; + pos = clipPos(doc, pos); + var state = getStateBefore(this, pos.line, precise), mode = this.doc.mode; + var line = getLine(doc, pos.line); + var stream = new StringStream(line.text, this.options.tabSize); + while (stream.pos < pos.ch && !stream.eol()) { + stream.start = stream.pos; + var style = mode.token(stream, state); + } + return {start: stream.start, + end: stream.pos, + string: stream.current(), + className: style || null, // Deprecated, use 'type' instead + type: style || null, + state: state}; + }, + + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else return styles[mid * 2 + 2]; + } + }, + + getStateAfter: function(line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function(start, mode) { + var pos, sel = this.doc.sel; + if (start == null) pos = sel.head; + else if (typeof start == "object") pos = clipPos(this.doc, start); + else pos = start ? sel.from : sel.to; + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function(line, mode) { + var end = false, last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + var lineObj = getLine(this.doc, line); + return intoCoordSystem(this, getLine(this.doc, line), {top: 0, left: 0}, mode || "page").top + + (end ? lineObj.height : 0); + }, + + defaultTextHeight: function() { return textHeight(this.display); }, + defaultCharWidth: function() { return charWidth(this.display); }, + + setGutterMarker: operation(null, function(line, gutterID, value) { + return changeLine(this, line, function(line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: operation(null, function(gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function(line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regChange(cm, i, i + 1); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + addLineClass: operation(null, function(handle, where, cls) { + return changeLine(this, handle, function(line) { + var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (new RegExp("(?:^|\\s)" + cls + "(?:$|\\s)").test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + + removeLineClass: operation(null, function(handle, where, cls) { + return changeLine(this, handle, function(line) { + var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(new RegExp("(?:^|\\s+)" + cls + "(?:$|\\s+)")); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: operation(null, function(handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + + removeLineWidget: function(widget) { widget.clear(); }, + + lineInfo: function(line) { + if (typeof line == "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function() { return {from: this.display.showingFrom, to: this.display.showingTo};}, + + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + top = pos.top - node.offsetHeight; + else if (pos.bottom + node.offsetHeight <= vspace) + top = pos.bottom; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) + scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); + }, + + triggerOnKeyDown: operation(null, onKeyDown), + + execCommand: function(cmd) {return commands[cmd](this);}, + + findPosH: function(from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: operation(null, function(dir, unit) { + var sel = this.doc.sel, pos; + if (sel.shift || sel.extend || posEq(sel.from, sel.to)) + pos = findPosH(this.doc, sel.head, dir, unit, this.options.rtlMoveVisually); + else + pos = dir < 0 ? sel.from : sel.to; + extendSelection(this.doc, pos, pos, dir); + }), + + deleteH: operation(null, function(dir, unit) { + var sel = this.doc.sel; + if (!posEq(sel.from, sel.to)) replaceRange(this.doc, "", sel.from, sel.to, "+delete"); + else replaceRange(this.doc, "", sel.from, findPosH(this.doc, sel.head, dir, unit, false), "+delete"); + this.curOp.userSelChange = true; + }), + + findPosV: function(from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: operation(null, function(dir, unit) { + var sel = this.doc.sel; + var pos = cursorCoords(this, sel.head, "div"); + if (sel.goalColumn != null) pos.left = sel.goalColumn; + var target = findPosV(this, pos, dir, unit); + + if (unit == "page") addToScrollPos(this, 0, charCoords(this, target, "div").top - pos.top); + extendSelection(this.doc, target, target, dir); + sel.goalColumn = pos.left; + }), + + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) + this.display.cursor.className += " CodeMirror-overwrite"; + else + this.display.cursor.className = this.display.cursor.className.replace(" CodeMirror-overwrite", ""); + }, + hasFocus: function() { return this.state.focused; }, + + scrollTo: operation(null, function(x, y) { + updateScrollPos(this, x, y); + }), + getScrollInfo: function() { + var scroller = this.display.scroller, co = scrollerCutOff; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - co, width: scroller.scrollWidth - co, + clientHeight: scroller.clientHeight - co, clientWidth: scroller.clientWidth - co}; + }, + + scrollIntoView: operation(null, function(pos, margin) { + if (typeof pos == "number") pos = Pos(pos, 0); + if (!margin) margin = 0; + var coords = pos; + + if (!pos || pos.line != null) { + this.curOp.scrollToPos = pos ? clipPos(this.doc, pos) : this.doc.sel.head; + this.curOp.scrollToPosMargin = margin; + coords = cursorCoords(this, this.curOp.scrollToPos); + } + var sPos = calculateScrollPos(this, coords.left, coords.top - margin, coords.right, coords.bottom + margin); + updateScrollPos(this, sPos.scrollLeft, sPos.scrollTop); + }), + + setSize: function(width, height) { + function interpret(val) { + return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) this.display.wrapper.style.width = interpret(width); + if (height != null) this.display.wrapper.style.height = interpret(height); + this.refresh(); + }, + + on: function(type, f) {on(this, type, f);}, + off: function(type, f) {off(this, type, f);}, + + operation: function(f){return runInOp(this, f);}, + + refresh: operation(null, function() { + clearCaches(this); + updateScrollPos(this, this.doc.scrollLeft, this.doc.scrollTop); + regChange(this); + }), + + swapDoc: operation(null, function(doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + resetInput(this, true); + updateScrollPos(this, doc.scrollLeft, doc.scrollTop); + return old; + }), + + getInputField: function(){return this.display.input;}, + getWrapperElement: function(){return this.display.wrapper;}, + getScrollerElement: function(){return this.display.scroller;}, + getGutterElement: function(){return this.display.gutters;} + }; + + // OPTION DEFAULTS + + var optionHandlers = CodeMirror.optionHandlers = {}; + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) optionHandlers[name] = + notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + + var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function(cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function(cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function(cm) { + loadMode(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("electricChars", true); + option("rtlMoveVisually", !windows); + + option("theme", "default", function(cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", keyMapChanged); + option("extraKeys", null); + + option("onKeyEvent", null); + option("onDragEvent", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function(cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, updateScrollbars, true); + option("lineNumbers", false, function(cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("readOnly", false, function(cm, val) { + if (val == "nocursor") {onBlur(cm); cm.display.input.blur();} + else if (!val) resetInput(cm, true); + }); + option("dragDrop", true); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true); + option("pollInterval", 100); + option("undoDepth", 40, function(cm, val){cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 500); + option("viewportMargin", 10, function(cm){cm.refresh();}, true); + option("maxHighlightLength", 10000, function(cm){loadMode(cm); cm.refresh();}, true); + option("moveInputWithCursor", true, function(cm, val) { + if (!val) cm.display.inputDiv.style.top = cm.display.inputDiv.style.left = 0; + }); + + option("tabindex", null, function(cm, val) { + cm.display.input.tabIndex = val || ""; + }); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) { + mode.dependencies = []; + for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); + } + modes[name] = mode; + }; + + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + + CodeMirror.resolveMode = function(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec == "string") return {name: spec}; + else return spec || {name: "null"}; + }; + + CodeMirror.getMode = function(options, spec) { + spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + return modeObj; + }; + + CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function(name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function(name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because modes + // sometimes need to do this. + function copyState(mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + } + CodeMirror.copyState = copyState; + + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + CodeMirror.startState = startState; + + CodeMirror.innerMode = function(mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + var commands = CodeMirror.commands = { + selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()));}, + killLine: function(cm) { + var from = cm.getCursor(true), to = cm.getCursor(false), sel = !posEq(from, to); + if (!sel && cm.getLine(from.line).length == from.ch) + cm.replaceRange("", from, Pos(from.line + 1, 0), "+delete"); + else cm.replaceRange("", from, sel ? to : Pos(from.line), "+delete"); + }, + deleteLine: function(cm) { + var l = cm.getCursor().line; + cm.replaceRange("", Pos(l, 0), Pos(l), "+delete"); + }, + delLineLeft: function(cm) { + var cur = cm.getCursor(); + cm.replaceRange("", Pos(cur.line, 0), cur, "+delete"); + }, + undo: function(cm) {cm.undo();}, + redo: function(cm) {cm.redo();}, + goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function(cm) { + cm.extendSelection(lineStart(cm, cm.getCursor().line)); + }, + goLineStartSmart: function(cm) { + var cur = cm.getCursor(), start = lineStart(cm, cur.line); + var line = cm.getLineHandle(start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = cur.line == start.line && cur.ch <= firstNonWS && cur.ch; + cm.extendSelection(Pos(start.line, inWS ? 0 : firstNonWS)); + } else cm.extendSelection(start); + }, + goLineEnd: function(cm) { + cm.extendSelection(lineEnd(cm, cm.getCursor().line)); + }, + goLineRight: function(cm) { + var top = cm.charCoords(cm.getCursor(), "div").top + 5; + cm.extendSelection(cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")); + }, + goLineLeft: function(cm) { + var top = cm.charCoords(cm.getCursor(), "div").top + 5; + cm.extendSelection(cm.coordsChar({left: 0, top: top}, "div")); + }, + goLineUp: function(cm) {cm.moveV(-1, "line");}, + goLineDown: function(cm) {cm.moveV(1, "line");}, + goPageUp: function(cm) {cm.moveV(-1, "page");}, + goPageDown: function(cm) {cm.moveV(1, "page");}, + goCharLeft: function(cm) {cm.moveH(-1, "char");}, + goCharRight: function(cm) {cm.moveH(1, "char");}, + goColumnLeft: function(cm) {cm.moveH(-1, "column");}, + goColumnRight: function(cm) {cm.moveH(1, "column");}, + goWordLeft: function(cm) {cm.moveH(-1, "word");}, + goGroupRight: function(cm) {cm.moveH(1, "group");}, + goGroupLeft: function(cm) {cm.moveH(-1, "group");}, + goWordRight: function(cm) {cm.moveH(1, "word");}, + delCharBefore: function(cm) {cm.deleteH(-1, "char");}, + delCharAfter: function(cm) {cm.deleteH(1, "char");}, + delWordBefore: function(cm) {cm.deleteH(-1, "word");}, + delWordAfter: function(cm) {cm.deleteH(1, "word");}, + delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function(cm) {cm.deleteH(1, "group");}, + indentAuto: function(cm) {cm.indentSelection("smart");}, + indentMore: function(cm) {cm.indentSelection("add");}, + indentLess: function(cm) {cm.indentSelection("subtract");}, + insertTab: function(cm) {cm.replaceSelection("\t", "end", "+input");}, + defaultTab: function(cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.replaceSelection("\t", "end", "+input"); + }, + transposeChars: function(cm) { + var cur = cm.getCursor(), line = cm.getLine(cur.line); + if (cur.ch > 0 && cur.ch < line.length - 1) + cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), + Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1)); + }, + newlineAndIndent: function(cm) { + operation(cm, function() { + cm.replaceSelection("\n", "end", "+input"); + cm.indentLine(cm.getCursor().line, null, true); + })(); + }, + toggleOverwrite: function(cm) {cm.toggleOverwrite();} + }; + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite" + }; + // Note that the save and find-related commands aren't defined by + // default. Unknown commands are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Alt-Up": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Down": "goDocEnd", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + fallthrough: "basic" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineStart", "Cmd-Right": "goLineEnd", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delLineLeft", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" + }; + + // KEYMAP DISPATCH + + function getKeyMap(val) { + if (typeof val == "string") return keyMap[val]; + else return val; + } + + function lookupKey(name, maps, handle) { + function lookup(map) { + map = getKeyMap(map); + var found = map[name]; + if (found === false) return "stop"; + if (found != null && handle(found)) return true; + if (map.nofallthrough) return "stop"; + + var fallthrough = map.fallthrough; + if (fallthrough == null) return false; + if (Object.prototype.toString.call(fallthrough) != "[object Array]") + return lookup(fallthrough); + for (var i = 0, e = fallthrough.length; i < e; ++i) { + var done = lookup(fallthrough[i]); + if (done) return done; + } + return false; + } + + for (var i = 0; i < maps.length; ++i) { + var done = lookup(maps[i]); + if (done) return done != "stop"; + } + } + function isModifierKey(event) { + var name = keyNames[event.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + function keyName(event, noShift) { + if (opera && event.keyCode == 34 && event["char"]) return false; + var name = keyNames[event.keyCode]; + if (name == null || event.altGraphKey) return false; + if (event.altKey) name = "Alt-" + name; + if (flipCtrlCmd ? event.metaKey : event.ctrlKey) name = "Ctrl-" + name; + if (flipCtrlCmd ? event.ctrlKey : event.metaKey) name = "Cmd-" + name; + if (!noShift && event.shiftKey) name = "Shift-" + name; + return name; + } + CodeMirror.lookupKey = lookupKey; + CodeMirror.isModifierKey = isModifierKey; + CodeMirror.keyName = keyName; + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function(textarea, options) { + if (!options) options = {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabindex) + options.tabindex = textarea.tabindex; + if (!options.placeholder && textarea.placeholder) + options.placeholder = textarea.placeholder; + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = document.body; + // doc.activeElement occasionally throws on IE + try { hasFocus = document.activeElement; } catch(e) {} + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function() { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + textarea.style.display = "none"; + var cm = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + cm.save = save; + cm.getTextArea = function() { return textarea; }; + cm.toTextArea = function() { + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + // The character stream used by a mode's parser. + function StringStream(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + } + + StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == 0;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue; + }, + indentation: function() {return countColumn(this.string, null, this.tabSize);}, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);} + }; + CodeMirror.StringStream = StringStream; + + // TEXTMARKERS + + function TextMarker(doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + } + CodeMirror.TextMarker = TextMarker; + + TextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.to != null) max = lineNo(line); + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from != null) + min = lineNo(line); + else if (this.collapsed && !lineIsHidden(this.doc, line) && cm) + updateLineHeight(line, textHeight(cm.display)); + } + if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(cm.doc, this.lines[i]), len = lineLength(cm.doc, visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + + if (min != null && cm) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm); + } + if (withOp) endOperation(cm); + signalLater(this, "clear"); + }; + + TextMarker.prototype.find = function() { + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null || span.to != null) { + var found = lineNo(line); + if (span.from != null) from = Pos(found, span.from); + if (span.to != null) to = Pos(found, span.to); + } + } + if (this.type == "bookmark") return from; + return from && {from: from, to: to}; + }; + + TextMarker.prototype.changed = function() { + var pos = this.find(), cm = this.doc.cm; + if (!pos || !cm) return; + var line = getLine(this.doc, pos.from.line); + clearCachedMeasurement(cm, line); + if (pos.from.line >= cm.display.showingFrom && pos.from.line < cm.display.showingTo) { + for (var node = cm.display.lineDiv.firstChild; node; node = node.nextSibling) if (node.lineObj == line) { + if (node.offsetHeight != line.height) updateLineHeight(line, node.offsetHeight); + break; + } + runInOp(cm, function() { cm.curOp.selectionChanged = true; }); + } + }; + + TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + function markText(doc, from, to, options, type) { + if (options && options.shared) return markTextShared(doc, from, to, options, type); + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type); + if (type == "range" && !posLess(from, to)) return marker; + if (options) copyObj(options, marker); + if (marker.replacedWith) { + marker.collapsed = true; + marker.replacedWith = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.replacedWith.ignoreEvents = true; + } + if (marker.collapsed) sawCollapsedSpans = true; + + if (marker.addToHistory) + addToHistory(doc, {from: from, to: to, origin: "markText"}, + {head: doc.sel.head, anchor: doc.sel.anchor}, NaN); + + var curLine = from.line, size = 0, collapsedAtStart, collapsedAtEnd, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function(line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(doc, line) == cm.display.maxLine) + updateMaxLine = true; + var span = {from: null, to: null, marker: marker}; + size += line.text.length; + if (curLine == from.line) {span.from = from.ch; size -= from.ch;} + if (curLine == to.line) {span.to = to.ch; size -= line.text.length - to.ch;} + if (marker.collapsed) { + if (curLine == to.line) collapsedAtEnd = collapsedSpanAt(line, to.ch); + if (curLine == from.line) collapsedAtStart = collapsedSpanAt(line, from.ch); + else updateLineHeight(line, 0); + } + addMarkedSpan(line, span); + ++curLine; + }); + if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) + doc.clearHistory(); + } + if (marker.collapsed) { + if (collapsedAtStart != collapsedAtEnd) + throw new Error("Inserting collapsed marker overlapping an existing one"); + marker.size = size; + marker.atomic = true; + } + if (cm) { + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.className || marker.startStyle || marker.endStyle || marker.collapsed) + regChange(cm, from.line, to.line + 1); + if (marker.atomic) reCheckSelection(cm); + } + return marker; + } + + // SHARED TEXTMARKERS + + function SharedTextMarker(markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0, me = this; i < markers.length; ++i) { + markers[i].parent = this; + on(markers[i], "clear", function(){me.clear();}); + } + } + CodeMirror.SharedTextMarker = SharedTextMarker; + + SharedTextMarker.prototype.clear = function() { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) + this.markers[i].clear(); + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function() { + return this.primary.find(); + }; + + function markTextShared(doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.replacedWith; + linkedDocs(doc, function(doc) { + if (widget) options.replacedWith = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) + if (doc.linked[i].isParent) return; + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + // TEXTMARKER SPANS + + function getMarkedSpanFor(spans, marker) { + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + function removeMarkedSpan(spans, span) { + for (var r, i = 0; i < spans.length; ++i) + if (spans[i] != span) (r || (r = [])).push(spans[i]); + return r; + } + function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + function markedSpansBefore(old, startCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || marker.type == "bookmark" && span.from == startCh && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push({from: span.from, + to: endsAfter ? null : span.to, + marker: marker}); + } + } + return nw; + } + + function markedSpansAfter(old, endCh, isInsert) { + if (old) for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || marker.type == "bookmark" && span.from == endCh && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push({from: startsBefore ? null : span.from - endCh, + to: span.to == null ? null : span.to - endCh, + marker: marker}); + } + } + return nw; + } + + function stretchSpansOverChange(doc, change) { + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = posEq(change.from, change.to); + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + if (sameLine && first) { + // Make sure we didn't create any zero-length spans + for (var i = 0; i < first.length; ++i) + if (first[i].from != null && first[i].from == first[i].to && first[i].marker.type != "bookmark") + first.splice(i--, 1); + if (!first.length) first = null; + } + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) + for (var i = 0; i < first.length; ++i) + if (first[i].to == null) + (gapMarkers || (gapMarkers = [])).push({from: null, to: null, marker: first[i].marker}); + for (var i = 0; i < gap; ++i) + newMarkers.push(gapMarkers); + newMarkers.push(last); + } + return newMarkers; + } + + function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) + if (oldCur[k].marker == span.marker) continue spans; + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + function removeReadOnlyRanges(doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function(line) { + if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + (markers || (markers = [])).push(mark); + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (posLess(p.to, m.from) || posLess(m.to, p.from)) continue; + var newParts = [j, 1]; + if (posLess(p.from, m.from) || !mk.inclusiveLeft && posEq(p.from, m.from)) + newParts.push({from: p.from, to: m.from}); + if (posLess(m.to, p.to) || !mk.inclusiveRight && posEq(p.to, m.to)) + newParts.push({from: m.to, to: p.to}); + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + function collapsedSpanAt(line, ch) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if ((sp.from == null || sp.from < ch) && + (sp.to == null || sp.to > ch) && + (!found || found.width < sp.marker.width)) + found = sp.marker; + } + return found; + } + function collapsedSpanAtStart(line) { return collapsedSpanAt(line, -1); } + function collapsedSpanAtEnd(line) { return collapsedSpanAt(line, line.text.length + 1); } + + function visualLine(doc, line) { + var merged; + while (merged = collapsedSpanAtStart(line)) + line = getLine(doc, merged.find().from.line); + return line; + } + + function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.replacedWith) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + return true; + } + } + function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find().to, endLine = getLine(doc, end.line); + return lineIsHiddenInner(doc, endLine, getMarkedSpanFor(endLine.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) + return true; + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.replacedWith && sp.from == span.to && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.detachLine(line); + line.markedSpans = null; + } + + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + spans[i].marker.attachLine(line); + line.markedSpans = spans; + } + + // LINE WIDGETS + + var LineWidget = CodeMirror.LineWidget = function(cm, node, options) { + for (var opt in options) if (options.hasOwnProperty(opt)) + this[opt] = options[opt]; + this.cm = cm; + this.node = node; + }; + function widgetOperation(f) { + return function() { + var withOp = !this.cm.curOp; + if (withOp) startOperation(this.cm); + try {var result = f.apply(this, arguments);} + finally {if (withOp) endOperation(this.cm);} + return result; + }; + } + LineWidget.prototype.clear = widgetOperation(function() { + var ws = this.line.widgets, no = lineNo(this.line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) this.line.widgets = null; + updateLineHeight(this.line, Math.max(0, this.line.height - widgetHeight(this))); + regChange(this.cm, no, no + 1); + }); + LineWidget.prototype.changed = widgetOperation(function() { + var oldH = this.height; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(this.line, this.line.height + diff); + var no = lineNo(this.line); + regChange(this.cm, no, no + 1); + }); + + function widgetHeight(widget) { + if (widget.height != null) return widget.height; + if (!widget.node.parentNode || widget.node.parentNode.nodeType != 1) + removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, "position: relative")); + return widget.height = widget.node.offsetHeight; + } + + function addLineWidget(cm, handle, node, options) { + var widget = new LineWidget(cm, node, options); + if (widget.noHScroll) cm.display.alignWidgets = true; + changeLine(cm, handle, function(line) { + (line.widgets || (line.widgets = [])).push(widget); + widget.line = line; + if (!lineIsHidden(cm.doc, line) || widget.showIfHidden) { + var aboveVisible = heightAtLine(cm, line) < cm.display.scroller.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, 0, widget.height); + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + function makeLine(text, markedSpans, estimateHeight) { + var line = {text: text}; + attachMarkedSpans(line, markedSpans); + line.height = estimateHeight ? estimateHeight(line) : 1; + return line; + } + + function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + function cleanUpLine(line) { + line.parent = null; + detachMarkedSpans(line); + } + + // Run the given mode's parser over a line, update the styles + // array, which contains alternating fragments of text and CSS + // classes. + function runMode(cm, text, mode, state, f) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + if (text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + // Webkit seems to refuse to render text nodes longer than 57444 characters + stream.pos = Math.min(text.length, stream.start + 50000); + style = null; + } else { + style = mode.token(stream, state); + } + if (!flattenSpans || curStyle != style) { + if (curStart < stream.start) f(stream.start, curStyle); + curStart = stream.start; curStyle = style; + } + stream.start = stream.pos; + } + if (curStart < stream.pos) f(stream.pos, curStyle); + } + + function highlightLine(cm, line, state) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen]; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function(end, style) {st.push(end, style);}); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function(end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) + st.splice(i, 1, end, st[i+1], i_end); + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start+1]; + st[start+1] = cur ? cur + " " + style : style; + } + } + }); + } + + return st; + } + + function getLineStyles(cm, line) { + if (!line.styles || line.styles[0] != cm.state.modeGen) + line.styles = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. + function processLine(cm, line, state) { + var mode = cm.doc.mode; + var stream = new StringStream(line.text, cm.options.tabSize); + if (line.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { + mode.token(stream, state); + stream.start = stream.pos; + } + } + + var styleToClassCache = {}; + function styleToClass(style) { + if (!style) return null; + return styleToClassCache[style] || + (styleToClassCache[style] = "cm-" + style.replace(/ +/g, " cm-")); + } + + function lineContent(cm, realLine, measure) { + var merged, line = realLine, empty = true; + while (merged = collapsedSpanAtStart(line)) + line = getLine(cm.doc, merged.find().from.line); + + var builder = {pre: elt("pre"), col: 0, pos: 0, display: !measure, + measure: null, measuredSomething: false, cm: cm}; + if (line.textClass) builder.pre.className = line.textClass; + + do { + if (line.text) empty = false; + builder.measure = line == realLine && measure; + builder.pos = 0; + builder.addToken = builder.measure ? buildTokenMeasure : buildToken; + if ((ie || webkit) && cm.getOption("lineWrapping")) + builder.addToken = buildTokenSplitSpaces(builder.addToken); + var next = insertLineContent(line, builder, getLineStyles(cm, line)); + if (measure && line == realLine && !builder.measuredSomething) { + measure[0] = builder.pre.appendChild(zeroWidthElement(cm.display.measure)); + builder.measuredSomething = true; + } + if (next) line = getLine(cm.doc, next.to.line); + } while (next); + + if (measure && !builder.measuredSomething && !measure[0]) + measure[0] = builder.pre.appendChild(empty ? elt("span", "\u00a0") : zeroWidthElement(cm.display.measure)); + if (!builder.pre.firstChild && !lineIsHidden(cm.doc, realLine)) + builder.pre.appendChild(document.createTextNode("\u00a0")); + + var order; + // Work around problem with the reported dimensions of single-char + // direction spans on IE (issue #1129). See also the comment in + // cursorCoords. + if (measure && ie && (order = getOrder(line))) { + var l = order.length - 1; + if (order[l].from == order[l].to) --l; + var last = order[l], prev = order[l - 1]; + if (last.from + 1 == last.to && prev && last.level < prev.level) { + var span = measure[builder.pos - 1]; + if (span) span.parentNode.insertBefore(span.measureRight = zeroWidthElement(cm.display.measure), + span.nextSibling); + } + } + + signal(cm, "renderLine", cm, realLine, builder.pre); + return builder.pre; + } + + var tokenSpecialChars = /[\t\u0000-\u0019\u00ad\u200b\u2028\u2029\uFEFF]/g; + function buildToken(builder, text, style, startStyle, endStyle) { + if (!text) return; + if (!tokenSpecialChars.test(text)) { + builder.col += text.length; + var content = document.createTextNode(text); + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + tokenSpecialChars.lastIndex = pos; + var m = tokenSpecialChars.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); + builder.col += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + builder.col += tabWidth; + } else { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + m[0].charCodeAt(0).toString(16); + content.appendChild(token); + builder.col += 1; + } + } + } + if (style || startStyle || endStyle || builder.measure) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + return builder.pre.appendChild(elt("span", [content], fullStyle)); + } + builder.pre.appendChild(content); + } + + function buildTokenMeasure(builder, text, style, startStyle, endStyle) { + var wrapping = builder.cm.options.lineWrapping; + for (var i = 0; i < text.length; ++i) { + var ch = text.charAt(i), start = i == 0; + if (ch >= "\ud800" && ch < "\udbff" && i < text.length - 1) { + ch = text.slice(i, i + 2); + ++i; + } else if (i && wrapping && spanAffectsWrapping(text, i)) { + builder.pre.appendChild(elt("wbr")); + } + var span = builder.measure[builder.pos] = + buildToken(builder, ch, style, + start && startStyle, i == text.length - 1 && endStyle); + // In IE single-space nodes wrap differently than spaces + // embedded in larger text nodes, except when set to + // white-space: normal (issue #1268). + if (ie && wrapping && ch == " " && i && !/\s/.test(text.charAt(i - 1)) && + i < text.length - 1 && !/\s/.test(text.charAt(i + 1))) + span.style.whiteSpace = "normal"; + builder.pos += ch.length; + } + if (text.length) builder.measuredSomething = true; + } + + function buildTokenSplitSpaces(inner) { + function split(old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + return function(builder, text, style, startStyle, endStyle) { + return inner(builder, text.replace(/ {3,}/, split), style, startStyle, endStyle); + }; + } + + function buildCollapsedSpan(builder, size, widget) { + if (widget) { + if (!builder.display) widget = widget.cloneNode(true); + if (builder.measure) { + builder.measure[builder.pos] = size ? widget + : builder.pre.appendChild(zeroWidthElement(builder.cm.display.measure)); + builder.measuredSomething = true; + } + builder.pre.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i+=2) + builder.addToken(builder, allText.slice(at, at = styles[i]), styleToClass(styles[i+1])); + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = ""; + collapsed = null; nextChange = Infinity; + var foundBookmark = null; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (sp.from <= pos && (sp.to == null || sp.to > pos)) { + if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } + if (m.className) spanStyle += " " + m.className; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; + if (m.collapsed && (!collapsed || collapsed.marker.size < m.size)) + collapsed = sp; + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + if (m.type == "bookmark" && sp.from == pos && m.replacedWith) + foundBookmark = m.replacedWith; + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len : collapsed.to) - pos, + collapsed.from != null && collapsed.marker.replacedWith); + if (collapsed.to == null) return collapsed.marker.find(); + } + if (foundBookmark && !collapsed) buildCollapsedSpan(builder, 0, foundBookmark); + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : ""); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = styleToClass(styles[i++]); + } + } + } + + // DOCUMENT DATA STRUCTURE + + function updateDoc(doc, change, markedSpans, selAfter, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null;} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // First adjust the line structure + if (from.ch == 0 && to.ch == 0 && lastText == "") { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + for (var i = 0, e = text.length - 1, added = []; i < e; ++i) + added.push(makeLine(text[i], spansFor(i), estimateHeight)); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + for (var added = [], i = 1, e = text.length - 1; i < e; ++i) + added.push(makeLine(text[i], spansFor(i), estimateHeight)); + added.push(makeLine(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + for (var i = 1, e = text.length - 1, added = []; i < e; ++i) + added.push(makeLine(text[i], spansFor(i), estimateHeight)); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + setSelection(doc, selAfter.anchor, selAfter.head, null, true); + } + + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, e = lines.length, height = 0; i < e; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function() { return this.lines.length; }, + removeInner: function(at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + collapse: function(lines) { + lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); + }, + insertInner: function(at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0, e = lines.length; i < e; ++i) lines[i].parent = this; + }, + iterN: function(at, n, op) { + for (var e = at + n; at < e; ++at) + if (op(this.lines[at])) return true; + } + }; + + function BranchChunk(children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0, e = children.length; i < e; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function() { return this.size; }, + removeInner: function(at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + if (this.size - n < 25) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); + }, + insertInner: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0, e = this.children.length; i < e; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + maybeSpill: function() { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function(at, n, op) { + for (var i = 0, e = this.children.length; i < e; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function(text, mode, firstLine) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([makeLine("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.history = makeHistory(); + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = {from: start, to: start, head: start, anchor: start, shift: false, extend: false, goalColumn: null}; + this.id = ++nextDocId; + this.modeOption = mode; + + if (typeof text == "string") text = splitLines(text); + updateDoc(this, {from: start, to: start, text: text}, null, {head: start, anchor: start}); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + iter: function(from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + insert: function(at, lines) { + var height = 0; + for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function(at, n) { this.removeInner(at - this.first, n); }, + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + setValue: function(code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: splitLines(code), origin: "setValue"}, + {head: top, anchor: top}, true); + }, + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, + setLine: function(line, text) { + if (isLine(this, line)) + replaceRange(this, text, Pos(line, 0), clipPos(this, Pos(line))); + }, + removeLine: function(line) { + if (line) replaceRange(this, "", clipPos(this, Pos(line - 1)), clipPos(this, Pos(line))); + else replaceRange(this, "", Pos(0, 0), clipPos(this, Pos(1, 0))); + }, + + getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function(line) {return lineNo(line);}, + + lineCount: function() {return this.size;}, + firstLine: function() {return this.first;}, + lastLine: function() {return this.first + this.size - 1;}, + + clipPos: function(pos) {return clipPos(this, pos);}, + + getCursor: function(start) { + var sel = this.sel, pos; + if (start == null || start == "head") pos = sel.head; + else if (start == "anchor") pos = sel.anchor; + else if (start == "end" || start === false) pos = sel.to; + else pos = sel.from; + return copyPos(pos); + }, + somethingSelected: function() {return !posEq(this.sel.head, this.sel.anchor);}, + + setCursor: docOperation(function(line, ch, extend) { + var pos = clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line); + if (extend) extendSelection(this, pos); + else setSelection(this, pos, pos); + }), + setSelection: docOperation(function(anchor, head) { + setSelection(this, clipPos(this, anchor), clipPos(this, head || anchor)); + }), + extendSelection: docOperation(function(from, to) { + extendSelection(this, clipPos(this, from), to && clipPos(this, to)); + }), + + getSelection: function(lineSep) {return this.getRange(this.sel.from, this.sel.to, lineSep);}, + replaceSelection: function(code, collapse, origin) { + makeChange(this, {from: this.sel.from, to: this.sel.to, text: splitLines(code), origin: origin}, collapse || "around"); + }, + undo: docOperation(function() {makeChangeFromHistory(this, "undo");}), + redo: docOperation(function() {makeChangeFromHistory(this, "redo");}), + + setExtending: function(val) {this.sel.extend = val;}, + + historySize: function() { + var hist = this.history; + return {undo: hist.done.length, redo: hist.undone.length}; + }, + clearHistory: function() {this.history = makeHistory(this.history.maxGeneration);}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(); + }, + changeGeneration: function() { + this.history.lastOp = this.history.lastOrigin = null; + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function() { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function(histData) { + var hist = this.history = makeHistory(this.history.maxGeneration); + hist.done = histData.done.slice(0); + hist.undone = histData.undone.slice(0); + }, + + markText: function(from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); + }, + setBookmark: function(pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) + markers.push(span.marker.parent || span.marker); + } + return markers; + }, + getAllMarks: function() { + var markers = []; + this.iter(function(line) { + var sps = line.markedSpans; + if (sps) for (var i = 0; i < sps.length; ++i) + if (sps[i].from != null) markers.push(sps[i].marker); + }); + return markers; + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first; + this.iter(function(line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = {from: this.sel.from, to: this.sel.to, head: this.sel.head, anchor: this.sel.anchor, + shift: this.sel.shift, extend: false, goalColumn: this.sel.goalColumn}; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function(options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + return copy; + }, + unlinkDoc: function(other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + break; + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); + other.history = makeHistory(); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function(f) {linkedDocs(this, f);}, + + getMode: function() {return this.mode;}, + getEditor: function() {return this.cm;} + }); + + Doc.prototype.eachLine = Doc.prototype.iter; + + // The Doc methods that should be available on CodeMirror instances + var dontDelegate = "iter insert remove copy getEditor".split(" "); + for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + + function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + propagate(doc, null, true); + } + + function attachDoc(cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) computeMaxLength(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + function getLine(chunk, n) { + n -= chunk.first; + while (!chunk.lines) { + for (var i = 0;; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + function getBetween(doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function(line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + function getLines(doc, from, to) { + var out = []; + doc.iter(from, to, function(line) { out.push(line.text); }); + return out; + } + + function updateLineHeight(line, height) { + var diff = height - line.height; + for (var n = line; n; n = n.parent) n.height += diff; + } + + function lineNo(line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + function lineAtHeight(chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0, e = chunk.children.length; i < e; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0, e = chunk.lines.length; i < e; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + function heightAtLine(cm, lineObj) { + lineObj = visualLine(cm.doc, lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + function getOrder(line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function makeHistory(startGen) { + return { + // Arrays of history events. Doing something adds an event to + // done and clears undo. Undoing moves events from done to + // undone, redoing moves them in the other direction. + done: [], undone: [], undoDepth: Infinity, + // Used to track when changes can be merged into a single undo + // event + lastTime: 0, lastOp: null, lastOrigin: null, + // Used by the isClean() method + generation: startGen || 1, maxGeneration: startGen || 1 + }; + } + + function attachLocalSpans(doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { + if (line.markedSpans) + (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; + ++n; + }); + } + + function historyChangeFromChange(doc, change) { + var histChange = {from: change.from, to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + function addToHistory(doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur = lst(hist.done); + + if (cur && + (hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*"))) { + // Merge this change into the last event + var last = lst(cur.changes); + if (posEq(change.from, change.to) && posEq(change.from, last.to)) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + cur.anchorAfter = selAfter.anchor; cur.headAfter = selAfter.head; + } else { + // Can not be merged, start a new event. + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation, + anchorBefore: doc.sel.anchor, headBefore: doc.sel.head, + anchorAfter: selAfter.anchor, headAfter: selAfter.head}; + hist.done.push(cur); + hist.generation = ++hist.maxGeneration; + while (hist.done.length > hist.undoDepth) + hist.done.shift(); + } + hist.lastTime = time; + hist.lastOp = opId; + hist.lastOrigin = change.origin; + } + + function removeClearedSpans(spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } + else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + function getOldSpans(doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) + nw.push(removeClearedSpans(found[i])); + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray(events, newGroup) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i], changes = event.changes, newChanges = []; + copy.push({changes: newChanges, anchorBefore: event.anchorBefore, headBefore: event.headBefore, + anchorAfter: event.anchorAfter, headAfter: event.headAfter}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSel(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (!sub.copied) { cur.from = copyPos(cur.from); cur.to = copyPos(cur.to); } + if (to < cur.from.line) { + cur.from.line += diff; + cur.to.line += diff; + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!sub.copied) { + sub.anchorBefore = copyPos(sub.anchorBefore); sub.headBefore = copyPos(sub.headBefore); + sub.anchorAfter = copyPos(sub.anchorAfter); sub.readAfter = copyPos(sub.headAfter); + sub.copied = true; + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } else { + rebaseHistSel(sub.anchorBefore); rebaseHistSel(sub.headBefore); + rebaseHistSel(sub.anchorAfter); rebaseHistSel(sub.headAfter); + } + } + } + + function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT OPERATORS + + function stopMethod() {e_stop(this);} + // Ensure an event has a stop method. + function addStop(event) { + if (!event.stop) event.stop = stopMethod; + return event; + } + + function e_preventDefault(e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + } + function e_stopPropagation(e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + } + function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} + CodeMirror.e_stop = e_stop; + CodeMirror.e_preventDefault = e_preventDefault; + CodeMirror.e_stopPropagation = e_stopPropagation; + + function e_target(e) {return e.target || e.srcElement;} + function e_button(e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + function on(emitter, type, f) { + if (emitter.addEventListener) + emitter.addEventListener(type, f, false); + else if (emitter.attachEvent) + emitter.attachEvent("on" + type, f); + else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + } + + function off(emitter, type, f) { + if (emitter.removeEventListener) + emitter.removeEventListener(type, f, false); + else if (emitter.detachEvent) + emitter.detachEvent("on" + type, f); + else { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + for (var i = 0; i < arr.length; ++i) + if (arr[i] == f) { arr.splice(i, 1); break; } + } + } + + function signal(emitter, type /*, values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); + } + + var delayedCallbacks, delayedCallbackDepth = 0; + function signalLater(emitter, type /*, values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2); + if (!delayedCallbacks) { + ++delayedCallbackDepth; + delayedCallbacks = []; + setTimeout(fireDelayed, 0); + } + function bnd(f) {return function(){f.apply(null, args);};}; + for (var i = 0; i < arr.length; ++i) + delayedCallbacks.push(bnd(arr[i])); + } + + function signalDOMEvent(cm, e) { + signal(cm, e.type, cm, e); + return e_defaultPrevented(e); + } + + function fireDelayed() { + --delayedCallbackDepth; + var delayed = delayedCallbacks; + delayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + function hasHandler(emitter, type) { + var arr = emitter._handlers && emitter._handlers[type]; + return arr && arr.length > 0; + } + + CodeMirror.on = on; CodeMirror.off = off; CodeMirror.signal = signal; + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerCutOff = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; + + function Delayed() {this.id = null;} + Delayed.prototype = {set: function(ms, f) {clearTimeout(this.id); this.id = setTimeout(f, ms);}}; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0; i < end; ++i) { + if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); + else ++n; + } + return n; + } + CodeMirror.countColumn = countColumn; + + var spaceStrs = [""]; + function spaceStr(n) { + while (spaceStrs.length <= n) + spaceStrs.push(lst(spaceStrs) + " "); + return spaceStrs[n]; + } + + function lst(arr) { return arr[arr.length-1]; } + + function selectInput(node) { + if (ios) { // Mobile Safari apparently has a bug where select() is broken. + node.selectionStart = 0; + node.selectionEnd = node.value.length; + } else { + // Suppress mysterious IE10 errors + try { node.select(); } + catch(_e) {} + } + } + + function indexOf(collection, elt) { + if (collection.indexOf) return collection.indexOf(elt); + for (var i = 0, e = collection.length; i < e; ++i) + if (collection[i] == elt) return i; + return -1; + } + + function createObj(base, props) { + function Obj() {} + Obj.prototype = base; + var inst = new Obj(); + if (props) copyObj(props, inst); + return inst; + } + + function copyObj(obj, target) { + if (!target) target = {}; + for (var prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop]; + return target; + } + + function emptyArray(size) { + for (var a = [], i = 0; i < size; ++i) a.push(undefined); + return a; + } + + function bind(f) { + var args = Array.prototype.slice.call(arguments, 1); + return function(){return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + function isWordChar(ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + + function isEmpty(obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + var isExtendingChar = /[\u0300-\u036F\u0483-\u0487\u0488-\u0489\u0591-\u05BD\u05BF\u05C1-\u05C2\u05C4-\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7-\u06E8\u06EA-\u06ED\uA66F\uA670-\uA672\uA674-\uA67D\uA69F\udc00-\udfff]/; + + // DOM UTILITIES + + function elt(tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content == "string") setTextContent(e, content); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --count) + e.removeChild(e.firstChild); + return e; + } + + function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e); + } + + function setTextContent(e, str) { + if (ie_lt9) { + e.innerHTML = ""; + e.appendChild(document.createTextNode(str)); + } else e.textContent = str; + } + + function getRect(node) { + return node.getBoundingClientRect(); + } + CodeMirror.replaceGetRect = function(f) { getRect = f; }; + + // FEATURE DETECTION + + // Detect drag-and-drop + var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie_lt9) return false; + var div = elt('div'); + return "draggable" in div || "dragDrop" in div; + }(); + + // For a reason I have yet to figure out, some browsers disallow + // word wrapping between certain characters *only* if a new inline + // element is started between them. This makes it hard to reliably + // measure the position of things, since that requires inserting an + // extra span. This terribly fragile set of tests matches the + // character combinations that suffer from this phenomenon on the + // various browsers. + function spanAffectsWrapping() { return false; } + if (gecko) // Only for "$'" + spanAffectsWrapping = function(str, i) { + return str.charCodeAt(i - 1) == 36 && str.charCodeAt(i) == 39; + }; + else if (safari && !/Version\/([6-9]|\d\d)\b/.test(navigator.userAgent)) + spanAffectsWrapping = function(str, i) { + return /\-[^ \-?]|\?[^ !\'\"\),.\-\/:;\?\]\}]/.test(str.slice(i - 1, i + 1)); + }; + else if (webkit) + spanAffectsWrapping = function(str, i) { + if (i > 1 && str.charCodeAt(i - 1) == 45 && /\w/.test(str.charAt(i - 2)) && /[^\-?\.]/.test(str.charAt(i))) + return true; + return /[~!#%&*)=+}\]|\"\.>,:;][({[<]|-[^\-?\.\u2010-\u201f\u2026]|\?[\w~`@#$%\^&*(_=+{[|><]|…[\w~`@#$%\^&*(_=+{[><]/.test(str.slice(i - 1, i + 1)); + }; + + var knownScrollbarWidth; + function scrollbarWidth(measure) { + if (knownScrollbarWidth != null) return knownScrollbarWidth; + var test = elt("div", null, null, "width: 50px; height: 50px; overflow-x: scroll"); + removeChildrenAndAdd(measure, test); + if (test.offsetWidth) + knownScrollbarWidth = test.offsetHeight - test.clientHeight; + return knownScrollbarWidth || 0; + } + + var zwspSupported; + function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !ie_lt8; + } + if (zwspSupported) return elt("span", "\u200b"); + else return elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function(string){return string.split(/\r\n?|\n/);}; + CodeMirror.splitLines = splitLines; + + var hasSelection = window.getSelection ? function(te) { + try { return te.selectionStart != te.selectionEnd; } + catch(e) { return false; } + } : function(te) { + try {var range = te.ownerDocument.selection.createRange();} + catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function() { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy == 'function'; + })(); + + // KEY NAMING + + var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 91: "Mod", 92: "Mod", 93: "Mod", 109: "-", 107: "=", 127: "Delete", + 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63276: "PageUp", 63277: "PageDown", 63275: "End", 63273: "Home", + 63234: "Left", 63232: "Up", 63235: "Right", 63233: "Down", 63302: "Insert", 63272: "Delete"}; + CodeMirror.keyNames = keyNames; + (function() { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections(order, from, to, f) { + if (!order) return f(from, to, "ltr"); + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + } + } + + function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } + function bidiRight(part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight(line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart(cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(cm.doc, line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd(cm, lineN) { + var merged, line; + while (merged = collapsedSpanAtEnd(line = getLine(cm.doc, lineN))) + lineN = merged.find().to.line; + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN, ch); + } + + function compareBidiLevel(order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt(order, pos) { + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) { bidiOther = null; return i; } + if (cur.from == pos || cur.to == pos) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + bidiOther = found; + return i; + } else { + bidiOther = i; + return found; + } + } + } + bidiOther = null; + return found; + } + + function moveInLine(line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar.test(line.text.charAt(pos))); + return pos; + } + + // This is somewhat involved. It is needed in order to move + // 'visually' through bi-directional text -- i.e., pressing left + // should make the cursor go left, even when in RTL text. The + // tricky part is the 'jumps', where RTL and LTR text touch each + // other. This often requires the cursor offset to move more than + // one unit, in order to visually move one unit. + function moveVisually(line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } else { + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) + target = moveInLine(line, part.to, -1, byUnit); + else + target = moveInLine(line, part.from, 1, byUnit); + } + } + } + + function moveLogically(line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar.test(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLL"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmmrrrrrrrrrrrrrrrrrr"; + function charType(code) { + if (code <= 0xff) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ff) return arabicTypes.charAt(code - 0x600); + else if (0x700 <= code && code <= 0x8ac) return "r"; + else return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + return function(str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) + types.push(type = charType(str.charCodeAt(i))); + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i+1] && + (prev == "1" || prev == "n")) types[i] = prev; + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i-1] == "!") || (end < len - 1 && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i-1] : outerType) == "L"; + var after = (end < len - 1 ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push({from: start, to: i, level: 0}); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, {from: pos, to: j, level: 1}); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, {from: nstart, to: j, level: 2}); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, {from: pos, to: i, level: 1}); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift({from: 0, to: m[0].length, level: 0}); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push({from: len - m[0].length, to: len, level: 0}); + } + if (order[0].level != lst(order).level) + order.push({from: len, to: len, level: order[0].level}); + + return order; + }; + })(); + + // THE END + + CodeMirror.version = "3.14.0"; + + return CodeMirror; +})(); diff --git a/admin/view/javascript/shopunity/codemirror/css.js b/admin/view/javascript/shopunity/codemirror/css.js new file mode 100755 index 0000000..27c97f3 --- /dev/null +++ b/admin/view/javascript/shopunity/codemirror/css.js @@ -0,0 +1,606 @@ +CodeMirror.defineMode("css", function(config) { + return CodeMirror.getMode(config, "text/css"); +}); + +CodeMirror.defineMode("css-base", function(config, parserConfig) { + "use strict"; + + var indentUnit = config.indentUnit, + hooks = parserConfig.hooks || {}, + atMediaTypes = parserConfig.atMediaTypes || {}, + atMediaFeatures = parserConfig.atMediaFeatures || {}, + propertyKeywords = parserConfig.propertyKeywords || {}, + colorKeywords = parserConfig.colorKeywords || {}, + valueKeywords = parserConfig.valueKeywords || {}, + allowNested = !!parserConfig.allowNested, + type = null; + + function ret(style, tp) { type = tp; return style; } + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + // result[0] is style and result[1] is type + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current());} + else if (ch == "=") ret(null, "compare"); + else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); + else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } + else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } + else if (ch === "-") { + if (/\d/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^[^-]+-/)) { + return ret("meta", "meta"); + } + } + else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } + else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", "qualifier"); + } + else if (ch == ":") { + return ret("operator", ch); + } + else if (/[;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } + else if (ch == "u" && stream.match("rl(")) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "variable"); + } + else { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "variable"); + } + } + + function tokenString(quote, nonInclusive) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) + break; + escaped = !escaped && ch == "\\"; + } + if (!escaped) { + if (nonInclusive) stream.backUp(1); + state.tokenize = tokenBase; + } + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\']/, false)) + state.tokenize = tokenString(")", true); + else + state.tokenize = tokenBase; + return ret(null, "("); + } + + return { + startState: function(base) { + return {tokenize: tokenBase, + baseIndent: base || 0, + stack: []}; + }, + + token: function(stream, state) { + + // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50) + // + // rule** or **ruleset: + // A selector + braces combo, or an at-rule. + // + // declaration block: + // A sequence of declarations. + // + // declaration: + // A property + colon + value combo. + // + // property value: + // The entire value of a property. + // + // component value: + // A single piece of a property value. Like the 5px in + // text-shadow: 0 0 5px blue;. Can also refer to things that are + // multiple terms, like the 1-4 terms that make up the background-size + // portion of the background shorthand. + // + // term: + // The basic unit of author-facing CSS, like a single number (5), + // dimension (5px), string ("foo"), or function. Officially defined + // by the CSS 2.1 grammar (look for the 'term' production) + // + // + // simple selector: + // A single atomic selector, like a type selector, an attr selector, a + // class selector, etc. + // + // compound selector: + // One or more simple selectors without a combinator. div.example is + // compound, div > .example is not. + // + // complex selector: + // One or more compound selectors chained with combinators. + // + // combinator: + // The parts of selectors that express relationships. There are four + // currently - the space (descendant combinator), the greater-than + // bracket (child combinator), the plus sign (next sibling combinator), + // and the tilda (following sibling combinator). + // + // sequence of selectors: + // One or more of the named type of selector chained with commas. + + state.tokenize = state.tokenize || tokenBase; + if (state.tokenize == tokenBase && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (style && typeof style != "string") style = ret(style[0], style[1]); + + // Changing style returned based on context + var context = state.stack[state.stack.length-1]; + if (style == "variable") { + if (type == "variable-definition") state.stack.push("propertyValue"); + return "variable-2"; + } else if (style == "property") { + var word = stream.current().toLowerCase(); + if (context == "propertyValue") { + if (valueKeywords.hasOwnProperty(word)) { + style = "string-2"; + } else if (colorKeywords.hasOwnProperty(word)) { + style = "keyword"; + } else { + style = "variable-2"; + } + } else if (context == "rule") { + if (!propertyKeywords.hasOwnProperty(word)) { + style += " error"; + } + } else if (context == "block") { + // if a value is present in both property, value, or color, the order + // of preference is property -> color -> value + if (propertyKeywords.hasOwnProperty(word)) { + style = "property"; + } else if (colorKeywords.hasOwnProperty(word)) { + style = "keyword"; + } else if (valueKeywords.hasOwnProperty(word)) { + style = "string-2"; + } else { + style = "tag"; + } + } else if (!context || context == "@media{") { + style = "tag"; + } else if (context == "@media") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; // Known attribute + } else if (/^(only|not)$/.test(word)) { + style = "keyword"; + } else if (word == "and") { + style = "error"; // "and" is only allowed in @mediaType + } else if (atMediaFeatures.hasOwnProperty(word)) { + style = "error"; // Known property, should be in @mediaType( + } else { + // Unknown, expecting keyword or attribute, assuming attribute + style = "attribute error"; + } + } else if (context == "@mediaType") { + if (atMediaTypes.hasOwnProperty(word)) { + style = "attribute"; + } else if (word == "and") { + style = "operator"; + } else if (/^(only|not)$/.test(word)) { + style = "error"; // Only allowed in @media + } else { + // Unknown attribute or property, but expecting property (preceded + // by "and"). Should be in parentheses + style = "error"; + } + } else if (context == "@mediaType(") { + if (propertyKeywords.hasOwnProperty(word)) { + // do nothing, remains "property" + } else if (atMediaTypes.hasOwnProperty(word)) { + style = "error"; // Known property, should be in parentheses + } else if (word == "and") { + style = "operator"; + } else if (/^(only|not)$/.test(word)) { + style = "error"; // Only allowed in @media + } else { + style += " error"; + } + } else if (context == "@import") { + style = "tag"; + } else { + style = "error"; + } + } else if (style == "atom") { + if(!context || context == "@media{" || context == "block") { + style = "builtin"; + } else if (context == "propertyValue") { + if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { + style += " error"; + } + } else { + style = "error"; + } + } else if (context == "@media" && type == "{") { + style = "error"; + } + + // Push/pop context stack + if (type == "{") { + if (context == "@media" || context == "@mediaType") { + state.stack.pop(); + state.stack[state.stack.length-1] = "@media{"; + } + else { + var newContext = allowNested ? "block" : "rule"; + state.stack.push(newContext); + } + } + else if (type == "}") { + var lastState = state.stack[state.stack.length - 1]; + if (lastState == "interpolation") style = "operator"; + state.stack.pop(); + if (context == "propertyValue") state.stack.pop(); + } + else if (type == "interpolation") state.stack.push("interpolation"); + else if (type == "@media") state.stack.push("@media"); + else if (type == "@import") state.stack.push("@import"); + else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) + state.stack.push("@mediaType"); + else if (context == "@mediaType" && stream.current() == ",") state.stack.pop(); + else if (context == "@mediaType" && type == "(") state.stack.push("@mediaType("); + else if (context == "@mediaType(" && type == ")") state.stack.pop(); + else if ((context == "rule" || context == "block") && type == ":") state.stack.push("propertyValue"); + else if (context == "propertyValue" && type == ";") state.stack.pop(); + else if (context == "@import" && type == ";") state.stack.pop(); + return style; + }, + + indent: function(state, textAfter) { + var n = state.stack.length; + if (/^\}/.test(textAfter)) + n -= state.stack[state.stack.length-1] == "propertyValue" ? 2 : 1; + return state.baseIndent + n * indentUnit; + }, + + electricChars: "}", + blockCommentStart: "/*", + blockCommentEnd: "*/" + }; +}); + +(function() { + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) { + keys[array[i]] = true; + } + return keys; + } + + var atMediaTypes = keySet([ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ]); + + var atMediaFeatures = keySet([ + "width", "min-width", "max-width", "height", "min-height", "max-height", + "device-width", "min-device-width", "max-device-width", "device-height", + "min-device-height", "max-device-height", "aspect-ratio", + "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio", + "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color", + "max-color", "color-index", "min-color-index", "max-color-index", + "monochrome", "min-monochrome", "max-monochrome", "resolution", + "min-resolution", "max-resolution", "scan", "grid" + ]); + + var propertyKeywords = keySet([ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "animation-iteration-count", + "animation-name", "animation-play-state", "animation-timing-function", + "appearance", "azimuth", "backface-visibility", "background", + "background-attachment", "background-clip", "background-color", + "background-image", "background-origin", "background-position", + "background-repeat", "background-size", "baseline-shift", "binding", + "bleed", "bookmark-label", "bookmark-level", "bookmark-state", + "bookmark-target", "border", "border-bottom", "border-bottom-color", + "border-bottom-left-radius", "border-bottom-right-radius", + "border-bottom-style", "border-bottom-width", "border-collapse", + "border-color", "border-image", "border-image-outset", + "border-image-repeat", "border-image-slice", "border-image-source", + "border-image-width", "border-left", "border-left-color", + "border-left-style", "border-left-width", "border-radius", "border-right", + "border-right-color", "border-right-style", "border-right-width", + "border-spacing", "border-style", "border-top", "border-top-color", + "border-top-left-radius", "border-top-right-radius", "border-top-style", + "border-top-width", "border-width", "bottom", "box-decoration-break", + "box-shadow", "box-sizing", "break-after", "break-before", "break-inside", + "caption-side", "clear", "clip", "color", "color-profile", "column-count", + "column-fill", "column-gap", "column-rule", "column-rule-color", + "column-rule-style", "column-rule-width", "column-span", "column-width", + "columns", "content", "counter-increment", "counter-reset", "crop", "cue", + "cue-after", "cue-before", "cursor", "direction", "display", + "dominant-baseline", "drop-initial-after-adjust", + "drop-initial-after-align", "drop-initial-before-adjust", + "drop-initial-before-align", "drop-initial-size", "drop-initial-value", + "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis", + "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap", + "float", "float-offset", "font", "font-feature-settings", "font-family", + "font-kerning", "font-language-override", "font-size", "font-size-adjust", + "font-stretch", "font-style", "font-synthesis", "font-variant", + "font-variant-alternates", "font-variant-caps", "font-variant-east-asian", + "font-variant-ligatures", "font-variant-numeric", "font-variant-position", + "font-weight", "grid-cell", "grid-column", "grid-column-align", + "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow", + "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span", + "grid-rows", "grid-template", "hanging-punctuation", "height", "hyphens", + "icon", "image-orientation", "image-rendering", "image-resolution", + "inline-box-align", "justify-content", "left", "letter-spacing", + "line-break", "line-height", "line-stacking", "line-stacking-ruby", + "line-stacking-shift", "line-stacking-strategy", "list-style", + "list-style-image", "list-style-position", "list-style-type", "margin", + "margin-bottom", "margin-left", "margin-right", "margin-top", + "marker-offset", "marks", "marquee-direction", "marquee-loop", + "marquee-play-count", "marquee-speed", "marquee-style", "max-height", + "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index", + "nav-left", "nav-right", "nav-up", "opacity", "order", "orphans", "outline", + "outline-color", "outline-offset", "outline-style", "outline-width", + "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y", + "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", + "page", "page-break-after", "page-break-before", "page-break-inside", + "page-policy", "pause", "pause-after", "pause-before", "perspective", + "perspective-origin", "pitch", "pitch-range", "play-during", "position", + "presentation-level", "punctuation-trim", "quotes", "rendering-intent", + "resize", "rest", "rest-after", "rest-before", "richness", "right", + "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "size", "speak", "speak-as", "speak-header", + "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set", + "tab-size", "table-layout", "target", "target-name", "target-new", + "target-position", "text-align", "text-align-last", "text-decoration", + "text-decoration-color", "text-decoration-line", "text-decoration-skip", + "text-decoration-style", "text-emphasis", "text-emphasis-color", + "text-emphasis-position", "text-emphasis-style", "text-height", + "text-indent", "text-justify", "text-outline", "text-shadow", + "text-space-collapse", "text-transform", "text-underline-position", + "text-wrap", "top", "transform", "transform-origin", "transform-style", + "transition", "transition-delay", "transition-duration", + "transition-property", "transition-timing-function", "unicode-bidi", + "vertical-align", "visibility", "voice-balance", "voice-duration", + "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress", + "voice-volume", "volume", "white-space", "widows", "width", "word-break", + "word-spacing", "word-wrap", "z-index", + // SVG-specific + "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color", + "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events", + "color-interpolation", "color-interpolation-filters", "color-profile", + "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering", + "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke", + "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering", + "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal", + "glyph-orientation-vertical", "kerning", "text-anchor", "writing-mode" + ]); + + var colorKeywords = keySet([ + "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", + "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", + "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", + "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", + "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", + "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", + "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", + "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick", + "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", + "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", + "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", + "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", + "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink", + "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", + "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", + "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", + "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", + "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", + "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", + "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", + "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", + "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", + "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", + "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", + "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", + "whitesmoke", "yellow", "yellowgreen" + ]); + + var valueKeywords = keySet([ + "above", "absolute", "activeborder", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background", + "backwards", "baseline", "below", "bidi-override", "binary", "bengali", + "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break-all", "break-word", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "compact", "condensed", "contain", "content", + "content-box", "context-menu", "continuous", "copy", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", + "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", + "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede", + "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er", + "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er", + "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et", + "ethiopic-halehame-gez", "ethiopic-halehame-om-et", + "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et", + "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", + "ethiopic-halehame-tig", "ew-resize", "expanded", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", + "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", + "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", + "help", "hidden", "hide", "higher", "highlight", "highlighttext", + "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", + "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", + "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", + "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", + "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer", + "landscape", "lao", "large", "larger", "left", "level", "lighter", + "line-through", "linear", "lines", "list-item", "listbox", "listitem", + "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian", + "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian", + "lower-roman", "lowercase", "ltr", "malayalam", "match", + "media-controls-background", "media-current-time-display", + "media-fullscreen-button", "media-mute-button", "media-play-button", + "media-return-to-realtime-button", "media-rewind-button", + "media-seek-back-button", "media-seek-forward-button", "media-slider", + "media-sliderthumb", "media-time-remaining-display", "media-volume-slider", + "media-volume-slider-container", "media-volume-sliderthumb", "medium", + "menu", "menulist", "menulist-button", "menulist-text", + "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic", + "mix", "mongolian", "monospace", "move", "multiple", "myanmar", "n-resize", + "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "overlay", "overline", "padding", "padding-box", "painted", + "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait", + "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", + "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", + "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", + "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", + "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "single", "skip-white-space", "slide", "slider-horizontal", + "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", + "small", "small-caps", "small-caption", "smaller", "solid", "somali", + "source-atop", "source-in", "source-out", "source-over", "space", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", + "sub", "subpixel-antialiased", "super", "sw-resize", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai", + "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight", + "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er", + "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "wider", + "window", "windowframe", "windowtext", "x-large", "x-small", "xor", + "xx-large", "xx-small" + ]); + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + CodeMirror.defineMIME("text/css", { + atMediaTypes: atMediaTypes, + atMediaFeatures: atMediaFeatures, + propertyKeywords: propertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + hooks: { + "<": function(stream, state) { + function tokenSGMLComment(stream, state) { + var dashes = 0, ch; + while ((ch = stream.next()) != null) { + if (dashes >= 2 && ch == ">") { + state.tokenize = null; + break; + } + dashes = (ch == "-") ? dashes + 1 : 0; + } + return ["comment", "comment"]; + } + if (stream.eat("!")) { + state.tokenize = tokenSGMLComment; + return tokenSGMLComment(stream, state); + } + }, + "/": function(stream, state) { + if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + return false; + } + }, + name: "css-base" + }); + + CodeMirror.defineMIME("text/x-scss", { + atMediaTypes: atMediaTypes, + atMediaFeatures: atMediaFeatures, + propertyKeywords: propertyKeywords, + colorKeywords: colorKeywords, + valueKeywords: valueKeywords, + allowNested: true, + hooks: { + "$": function(stream) { + stream.match(/^[\w-]+/); + if (stream.peek() == ":") { + return ["variable", "variable-definition"]; + } + return ["variable", "variable"]; + }, + "/": function(stream, state) { + if (stream.eat("/")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } else if (stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else { + return ["operator", "operator"]; + } + }, + "#": function(stream) { + if (stream.eat("{")) { + return ["operator", "interpolation"]; + } else { + stream.eatWhile(/[\w\\\-]/); + return ["atom", "hash"]; + } + } + }, + name: "css-base" + }); +})(); diff --git a/admin/view/javascript/shopunity/colorpicker/images/bar-alpha.png b/admin/view/javascript/shopunity/colorpicker/images/bar-alpha.png new file mode 100755 index 0000000..2950dae Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/bar-alpha.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/bar-opacity.png b/admin/view/javascript/shopunity/colorpicker/images/bar-opacity.png new file mode 100755 index 0000000..e42ad08 Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/bar-opacity.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/bar-pointer.png b/admin/view/javascript/shopunity/colorpicker/images/bar-pointer.png new file mode 100755 index 0000000..6e980cf Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/bar-pointer.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/bar.png b/admin/view/javascript/shopunity/colorpicker/images/bar.png new file mode 100755 index 0000000..80eb2bb Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/bar.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/map-opacity.png b/admin/view/javascript/shopunity/colorpicker/images/map-opacity.png new file mode 100755 index 0000000..6756cee Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/map-opacity.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/map-pointer.png b/admin/view/javascript/shopunity/colorpicker/images/map-pointer.png new file mode 100755 index 0000000..6499296 Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/map-pointer.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/map.png b/admin/view/javascript/shopunity/colorpicker/images/map.png new file mode 100755 index 0000000..853d38c Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/map.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/preview-opacity.png b/admin/view/javascript/shopunity/colorpicker/images/preview-opacity.png new file mode 100755 index 0000000..0dd9a2f Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/preview-opacity.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker-old.png b/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker-old.png new file mode 100755 index 0000000..e244c68 Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker-old.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker.png b/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker.png new file mode 100755 index 0000000..44bf332 Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker_old.png b/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker_old.png new file mode 100755 index 0000000..2cd2cab Binary files /dev/null and b/admin/view/javascript/shopunity/colorpicker/images/ui-colorpicker_old.png differ diff --git a/admin/view/javascript/shopunity/colorpicker/jquery.colorpicker.css b/admin/view/javascript/shopunity/colorpicker/jquery.colorpicker.css new file mode 100755 index 0000000..f9e0a68 --- /dev/null +++ b/admin/view/javascript/shopunity/colorpicker/jquery.colorpicker.css @@ -0,0 +1,198 @@ +.ui-colorpicker, +.ui-dialog.ui-colorpicker { + width: auto; + white-space: nowrap; + + -webkit-touch-callout: none; + -webkit-user-select: none; + -khtml-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.ui-colorpicker-inline { + position: static; +} + +.ui-colorpicker-buttonset { + float: left; + margin-left: .4em; +} + +.ui-colorpicker-buttonset .ui-button { + margin: .5em 0 .5em 0; + cursor: pointer; +} + +.ui-colorpicker-buttonpane { + background-image: none; + margin: .7em 0 0 0; + padding: 0 .2em; + border-left: 0; + border-right: 0; + border-bottom: 0; +} + +.ui-colorpicker-buttonpane button { + float: right; + margin: .5em .2em .4em; + cursor: pointer; + padding: .2em .6em .3em .6em; + width: auto; + overflow: visible; +} + +.ui-colorpicker-buttonpane button.ui-colorpicker-current { + float: left; +} + +.ui-colorpicker table { + width: 100%; + font-size: 100%; /* Reset browser table font-size */ + margin: 0; +} + +.ui-colorpicker table td { + vertical-align: top; +} + +.ui-colorpicker-padding-left { + padding-left: 10px; +} +.ui-colorpicker-padding-top { + padding-top: 10px; +} + +.ui-colorpicker-border { + border: 1px inset; + display: inline-block; +} + +/* Bar & map */ +.ui-colorpicker-map > *, +.ui-colorpicker-bar > * { + position: absolute; + cursor: crosshair; +} + +.ui-colorpicker-map-pointer, +.ui-colorpicker-bar-pointer { + position: absolute; +} +/* Map */ +.ui-colorpicker-map, +.ui-colorpicker-map > * { + display: block; + width: 256px; + height: 256px; + overflow: hidden; +} + +.ui-colorpicker-map-layer-1, +.ui-colorpicker-map-layer-2 { + background: url(images/map.png) no-repeat; +} + +.ui-colorpicker-map-layer-alpha { + background: url(images/map-opacity.png); +} + +.ui-colorpicker-map-pointer { + display: inline-block; + width: 15px; + height: 15px; + background: url(images/map-pointer.png) no-repeat; +} + +/* Bar */ +.ui-colorpicker-bar, +.ui-colorpicker-bar > * { + display: block; + width: 20px; + height: 256px; + overflow: hidden; + background-repeat: repeat-x; +} + +.ui-colorpicker-bar-layer-1, +.ui-colorpicker-bar-layer-2, +.ui-colorpicker-bar-layer-3, +.ui-colorpicker-bar-layer-4 { + background: url(images/bar.png) repeat-x; +} + +.ui-colorpicker-bar-layer-alpha { + background: url(images/bar-opacity.png); +} + +.ui-colorpicker-bar-layer-alphabar { + background: url(images/bar-alpha.png); +} + +.ui-colorpicker-bar-pointer { + display: inline-block; + width: 20px; + height: 7px; + background: url(images/bar-pointer.png) no-repeat; +} + +/* Preview */ +.ui-colorpicker-preview { + text-align: center; +} + +.ui-colorpicker-preview-initial { + cursor: pointer; +} + +.ui-colorpicker-preview-initial, +.ui-colorpicker-preview-current { + width: 50px; + height: 20px; + display: inline-block; +} + +.ui-colorpicker-preview-initial-alpha, +.ui-colorpicker-preview-current-alpha { + width: 50px; + height: 20px; + display: inline-block; + background: url(images/preview-opacity.png) repeat; +} + +/* Inputs */ +.ui-colorpicker-rgb label, +.ui-colorpicker-hsv label, +.ui-colorpicker-hsl label, +.ui-colorpicker-lab label, +.ui-colorpicker-cmyk label, +.ui-colorpicker-alpha label { + width: 1.5em; + display: inline-block; +} + +.ui-colorpicker-number { + margin: .1em; + width: 4em; +} + +/* Hex */ +.ui-colorpicker-hex { + text-align: center; +} + +/* Swatches */ +.ui-colorpicker-swatches { + height: 256px; + overflow: auto; + background-color: #f8f8f8; +} + +.ui-colorpicker-swatch { + cursor: pointer; + float: left; + width: 11px; + height: 11px; + border-right: 1px solid black; + border-bottom: 1px solid black; +} \ No newline at end of file diff --git a/admin/view/javascript/shopunity/colorpicker/jquery.colorpicker.js b/admin/view/javascript/shopunity/colorpicker/jquery.colorpicker.js new file mode 100755 index 0000000..fe9e4b4 --- /dev/null +++ b/admin/view/javascript/shopunity/colorpicker/jquery.colorpicker.js @@ -0,0 +1,2699 @@ +/*jslint devel: true, bitwise: true, regexp: true, browser: true, confusion: true, unparam: true, eqeq: true, white: true, nomen: true, plusplus: true, maxerr: 50, indent: 4 */ +/*globals jQuery,Color */ + +/*! + * ColorPicker + * + * Copyright (c) 2011-2013 Martijn W. van der Lee + * Licensed under the MIT. + */ +/* Full-featured colorpicker for jQueryUI with full theming support. + * Most images from jPicker by Christopher T. Tillman. + * Sourcecode created from scratch by Martijn W. van der Lee. + */ + +;(function ($) { + "use strict"; + + var _colorpicker_index = 0, + + _container_popup = '', + _container_inlineFrame = '
    ', + _container_inline = '
    ', + + _intToHex = function (dec) { + var result = Math.floor(dec).toString(16); + if (result.length === 1) { + result = ('0' + result); + } + return result.toLowerCase(); + }, + + _parseHex = function(color) { + var c, + m; + + // {#}rrggbb + m = /^#?([a-fA-F0-9]{1,6})$/.exec(color); + if (m) { + c = parseInt(m[1], 16); + return new $.colorpicker.Color( + ((c >> 16) & 0xFF) / 255, + ((c >> 8) & 0xFF) / 255, + (c & 0xFF) / 255 + ); + } + + return new $.colorpicker.Color(); + }, + + _layoutTable = function(layout, callback) { + var bitmap, + x, y, + width, height, + columns, rows, + index, + cell, + html, + w, h, + colspan, + walked; + + layout.sort(function(a, b) { + if (a.pos[1] === b.pos[1]) { + return a.pos[0] - b.pos[0]; + } + return a.pos[1] - b.pos[1]; + }); + + // Determine dimensions of the table + width = 0; + height = 0; + $.each (layout, function(index, part) { + width = Math.max(width, part.pos[0] + part.pos[2]); + height = Math.max(height, part.pos[1] + part.pos[3]); + }); + + // Initialize bitmap + bitmap = []; + for (x = 0; x < width; ++x) { + bitmap.push([]); + } + + // Mark rows and columns which have layout assigned + rows = []; + columns = []; + $.each(layout, function(index, part) { + // mark columns + for (x = 0; x < part.pos[2]; x += 1) { + columns[part.pos[0] + x] = true; + } + for (y = 0; y < part.pos[3]; y += 1) { + rows[part.pos[1] + y] = true; + } + }); + + // Generate the table + html = ''; + cell = layout[index = 0]; + for (y = 0; y < height; ++y) { + html += ''; + x = 0; + while (x < width) { + if (typeof cell !== 'undefined' && x === cell.pos[0] && y === cell.pos[1]) { + // Create a "real" cell + html += callback(cell, x, y); + + for (h = 0; h < cell.pos[3]; h +=1) { + for (w = 0; w < cell.pos[2]; w +=1) { + bitmap[x + w][y + h] = true; + } + } + + x += cell.pos[2]; + cell = layout[++index]; + } else { + // Fill in the gaps + colspan = 0; + walked = false; + + while (x < width && bitmap[x][y] === undefined && (cell === undefined || y < cell.pos[1] || (y === cell.pos[1] && x < cell.pos[0]))) { + if (columns[x] === true) { + colspan += 1; + } + walked = true; + x += 1; + } + + if (colspan > 0) { + html += ''; + } else if (!walked) { + x += 1; + } + } + } + html += ''; + } + + return '' + html + '
    '; + }; + + $.colorpicker = new function() { + this.regional = { + '': { + ok: 'OK', + cancel: 'Cancel', + none: 'None', + button: 'Color', + title: 'Pick a color', + transparent: 'Transparent', + hsvH: 'H', + hsvS: 'S', + hsvV: 'V', + rgbR: 'R', + rgbG: 'G', + rgbB: 'B', + labL: 'L', + labA: 'a', + labB: 'b', + hslH: 'H', + hslS: 'S', + hslL: 'L', + cmykC: 'C', + cmykM: 'M', + cmykY: 'Y', + cmykK: 'K', + alphaA: 'A' + } + }; + + this.swatches = { + 'html': { + 'black': {r: 0, g: 0, b: 0}, + 'dimgray': {r: 0.4117647058823529, g: 0.4117647058823529, b: 0.4117647058823529}, + 'gray': {r: 0.5019607843137255, g: 0.5019607843137255, b: 0.5019607843137255}, + 'darkgray': {r: 0.6627450980392157, g: 0.6627450980392157, b: 0.6627450980392157}, + 'silver': {r: 0.7529411764705882, g: 0.7529411764705882, b: 0.7529411764705882}, + 'lightgrey': {r: 0.8274509803921568, g: 0.8274509803921568, b: 0.8274509803921568}, + 'gainsboro': {r: 0.8627450980392157, g: 0.8627450980392157, b: 0.8627450980392157}, + 'whitesmoke': {r: 0.9607843137254902, g: 0.9607843137254902, b: 0.9607843137254902}, + 'white': {r: 1, g: 1, b: 1}, + 'rosybrown': {r: 0.7372549019607844, g: 0.5607843137254902, b: 0.5607843137254902}, + 'indianred': {r: 0.803921568627451, g: 0.3607843137254902, b: 0.3607843137254902}, + 'brown': {r: 0.6470588235294118, g: 0.16470588235294117, b: 0.16470588235294117}, + 'firebrick': {r: 0.6980392156862745, g: 0.13333333333333333, b: 0.13333333333333333}, + 'lightcoral': {r: 0.9411764705882353, g: 0.5019607843137255, b: 0.5019607843137255}, + 'maroon': {r: 0.5019607843137255, g: 0, b: 0}, + 'darkred': {r: 0.5450980392156862, g: 0, b: 0}, + 'red': {r: 1, g: 0, b: 0}, + 'snow': {r: 1, g: 0.9803921568627451, b: 0.9803921568627451}, + 'salmon': {r: 0.9803921568627451, g: 0.5019607843137255, b: 0.4470588235294118}, + 'mistyrose': {r: 1, g: 0.8941176470588236, b: 0.8823529411764706}, + 'tomato': {r: 1, g: 0.38823529411764707, b: 0.2784313725490196}, + 'darksalmon': {r: 0.9137254901960784, g: 0.5882352941176471, b: 0.47843137254901963}, + 'orangered': {r: 1, g: 0.27058823529411763, b: 0}, + 'coral': {r: 1, g: 0.4980392156862745, b: 0.3137254901960784}, + 'lightsalmon': {r: 1, g: 0.6274509803921569, b: 0.47843137254901963}, + 'sienna': {r: 0.6274509803921569, g: 0.3215686274509804, b: 0.17647058823529413}, + 'seashell': {r: 1, g: 0.9607843137254902, b: 0.9333333333333333}, + 'chocolate': {r: 0.8235294117647058, g: 0.4117647058823529, b: 0.11764705882352941}, + 'saddlebrown': {r: 0.5450980392156862, g: 0.27058823529411763, b: 0.07450980392156863}, + 'sandybrown': {r: 0.9568627450980393, g: 0.6431372549019608, b: 0.3764705882352941}, + 'peachpuff': {r: 1, g: 0.8549019607843137, b: 0.7254901960784313}, + 'peru': {r: 0.803921568627451, g: 0.5215686274509804, b: 0.24705882352941178}, + 'linen': {r: 0.9803921568627451, g: 0.9411764705882353, b: 0.9019607843137255}, + 'darkorange': {r: 1, g: 0.5490196078431373, b: 0}, + 'bisque': {r: 1, g: 0.8941176470588236, b: 0.7686274509803922}, + 'burlywood': {r: 0.8705882352941177, g: 0.7215686274509804, b: 0.5294117647058824}, + 'tan': {r: 0.8235294117647058, g: 0.7058823529411765, b: 0.5490196078431373}, + 'antiquewhite': {r: 0.9803921568627451, g: 0.9215686274509803, b: 0.8431372549019608}, + 'navajowhite': {r: 1, g: 0.8705882352941177, b: 0.6784313725490196}, + 'blanchedalmond': {r: 1, g: 0.9215686274509803, b: 0.803921568627451}, + 'papayawhip': {r: 1, g: 0.9372549019607843, b: 0.8352941176470589}, + 'orange': {r: 1, g: 0.6470588235294118, b: 0}, + 'moccasin': {r: 1, g: 0.8941176470588236, b: 0.7098039215686275}, + 'wheat': {r: 0.9607843137254902, g: 0.8705882352941177, b: 0.7019607843137254}, + 'oldlace': {r: 0.9921568627450981, g: 0.9607843137254902, b: 0.9019607843137255}, + 'floralwhite': {r: 1, g: 0.9803921568627451, b: 0.9411764705882353}, + 'goldenrod': {r: 0.8549019607843137, g: 0.6470588235294118, b: 0.12549019607843137}, + 'darkgoldenrod': {r: 0.7215686274509804, g: 0.5254901960784314, b: 0.043137254901960784}, + 'cornsilk': {r: 1, g: 0.9725490196078431, b: 0.8627450980392157}, + 'gold': {r: 1, g: 0.8431372549019608, b: 0}, + 'palegoldenrod': {r: 0.9333333333333333, g: 0.9098039215686274, b: 0.6666666666666666}, + 'khaki': {r: 0.9411764705882353, g: 0.9019607843137255, b: 0.5490196078431373}, + 'lemonchiffon': {r: 1, g: 0.9803921568627451, b: 0.803921568627451}, + 'darkkhaki': {r: 0.7411764705882353, g: 0.7176470588235294, b: 0.4196078431372549}, + 'beige': {r: 0.9607843137254902, g: 0.9607843137254902, b: 0.8627450980392157}, + 'lightgoldenrodyellow': {r: 0.9803921568627451, g: 0.9803921568627451, b: 0.8235294117647058}, + 'olive': {r: 0.5019607843137255, g: 0.5019607843137255, b: 0}, + 'yellow': {r: 1, g: 1, b: 0}, + 'lightyellow': {r: 1, g: 1, b: 0.8784313725490196}, + 'ivory': {r: 1, g: 1, b: 0.9411764705882353}, + 'olivedrab': {r: 0.4196078431372549, g: 0.5568627450980392, b: 0.13725490196078433}, + 'yellowgreen': {r: 0.6039215686274509, g: 0.803921568627451, b: 0.19607843137254902}, + 'darkolivegreen': {r: 0.3333333333333333, g: 0.4196078431372549, b: 0.1843137254901961}, + 'greenyellow': {r: 0.6784313725490196, g: 1, b: 0.1843137254901961}, + 'lawngreen': {r: 0.48627450980392156, g: 0.9882352941176471, b: 0}, + 'chartreuse': {r: 0.4980392156862745, g: 1, b: 0}, + 'darkseagreen': {r: 0.5607843137254902, g: 0.7372549019607844, b: 0.5607843137254902}, + 'forestgreen': {r: 0.13333333333333333, g: 0.5450980392156862, b: 0.13333333333333333}, + 'limegreen': {r: 0.19607843137254902, g: 0.803921568627451, b: 0.19607843137254902}, + 'lightgreen': {r: 0.5647058823529412, g: 0.9333333333333333, b: 0.5647058823529412}, + 'palegreen': {r: 0.596078431372549, g: 0.984313725490196, b: 0.596078431372549}, + 'darkgreen': {r: 0, g: 0.39215686274509803, b: 0}, + 'green': {r: 0, g: 0.5019607843137255, b: 0}, + 'lime': {r: 0, g: 1, b: 0}, + 'honeydew': {r: 0.9411764705882353, g: 1, b: 0.9411764705882353}, + 'mediumseagreen': {r: 0.23529411764705882, g: 0.7019607843137254, b: 0.44313725490196076}, + 'seagreen': {r: 0.1803921568627451, g: 0.5450980392156862, b: 0.3411764705882353}, + 'springgreen': {r: 0, g: 1, b: 0.4980392156862745}, + 'mintcream': {r: 0.9607843137254902, g: 1, b: 0.9803921568627451}, + 'mediumspringgreen': {r: 0, g: 0.9803921568627451, b: 0.6039215686274509}, + 'mediumaquamarine': {r: 0.4, g: 0.803921568627451, b: 0.6666666666666666}, + 'aquamarine': {r: 0.4980392156862745, g: 1, b: 0.8313725490196079}, + 'turquoise': {r: 0.25098039215686274, g: 0.8784313725490196, b: 0.8156862745098039}, + 'lightseagreen': {r: 0.12549019607843137, g: 0.6980392156862745, b: 0.6666666666666666}, + 'mediumturquoise': {r: 0.2823529411764706, g: 0.8196078431372549, b: 0.8}, + 'darkslategray': {r: 0.1843137254901961, g: 0.30980392156862746, b: 0.30980392156862746}, + 'paleturquoise': {r: 0.6862745098039216, g: 0.9333333333333333, b: 0.9333333333333333}, + 'teal': {r: 0, g: 0.5019607843137255, b: 0.5019607843137255}, + 'darkcyan': {r: 0, g: 0.5450980392156862, b: 0.5450980392156862}, + 'darkturquoise': {r: 0, g: 0.807843137254902, b: 0.8196078431372549}, + 'aqua': {r: 0, g: 1, b: 1}, + 'cyan': {r: 0, g: 1, b: 1}, + 'lightcyan': {r: 0.8784313725490196, g: 1, b: 1}, + 'azure': {r: 0.9411764705882353, g: 1, b: 1}, + 'cadetblue': {r: 0.37254901960784315, g: 0.6196078431372549, b: 0.6274509803921569}, + 'powderblue': {r: 0.6901960784313725, g: 0.8784313725490196, b: 0.9019607843137255}, + 'lightblue': {r: 0.6784313725490196, g: 0.8470588235294118, b: 0.9019607843137255}, + 'deepskyblue': {r: 0, g: 0.7490196078431373, b: 1}, + 'skyblue': {r: 0.5294117647058824, g: 0.807843137254902, b: 0.9215686274509803}, + 'lightskyblue': {r: 0.5294117647058824, g: 0.807843137254902, b: 0.9803921568627451}, + 'steelblue': {r: 0.27450980392156865, g: 0.5098039215686274, b: 0.7058823529411765}, + 'aliceblue': {r: 0.9411764705882353, g: 0.9725490196078431, b: 1}, + 'dodgerblue': {r: 0.11764705882352941, g: 0.5647058823529412, b: 1}, + 'slategray': {r: 0.4392156862745098, g: 0.5019607843137255, b: 0.5647058823529412}, + 'lightslategray': {r: 0.4666666666666667, g: 0.5333333333333333, b: 0.6}, + 'lightsteelblue': {r: 0.6901960784313725, g: 0.7686274509803922, b: 0.8705882352941177}, + 'cornflowerblue': {r: 0.39215686274509803, g: 0.5843137254901961, b: 0.9294117647058824}, + 'royalblue': {r: 0.2549019607843137, g: 0.4117647058823529, b: 0.8823529411764706}, + 'midnightblue': {r: 0.09803921568627451, g: 0.09803921568627451, b: 0.4392156862745098}, + 'lavender': {r: 0.9019607843137255, g: 0.9019607843137255, b: 0.9803921568627451}, + 'navy': {r: 0, g: 0, b: 0.5019607843137255}, + 'darkblue': {r: 0, g: 0, b: 0.5450980392156862}, + 'mediumblue': {r: 0, g: 0, b: 0.803921568627451}, + 'blue': {r: 0, g: 0, b: 1}, + 'ghostwhite': {r: 0.9725490196078431, g: 0.9725490196078431, b: 1}, + 'darkslateblue': {r: 0.2823529411764706, g: 0.23921568627450981, b: 0.5450980392156862}, + 'slateblue': {r: 0.41568627450980394, g: 0.35294117647058826, b: 0.803921568627451}, + 'mediumslateblue': {r: 0.4823529411764706, g: 0.40784313725490196, b: 0.9333333333333333}, + 'mediumpurple': {r: 0.5764705882352941, g: 0.4392156862745098, b: 0.8588235294117647}, + 'blueviolet': {r: 0.5411764705882353, g: 0.16862745098039217, b: 0.8862745098039215}, + 'indigo': {r: 0.29411764705882354, g: 0, b: 0.5098039215686274}, + 'darkorchid': {r: 0.6, g: 0.19607843137254902, b: 0.8}, + 'darkviolet': {r: 0.5803921568627451, g: 0, b: 0.8274509803921568}, + 'mediumorchid': {r: 0.7294117647058823, g: 0.3333333333333333, b: 0.8274509803921568}, + 'thistle': {r: 0.8470588235294118, g: 0.7490196078431373, b: 0.8470588235294118}, + 'plum': {r: 0.8666666666666667, g: 0.6274509803921569, b: 0.8666666666666667}, + 'violet': {r: 0.9333333333333333, g: 0.5098039215686274, b: 0.9333333333333333}, + 'purple': {r: 0.5019607843137255, g: 0, b: 0.5019607843137255}, + 'darkmagenta': {r: 0.5450980392156862, g: 0, b: 0.5450980392156862}, + 'magenta': {r: 1, g: 0, b: 1}, + 'fuchsia': {r: 1, g: 0, b: 1}, + 'orchid': {r: 0.8549019607843137, g: 0.4392156862745098, b: 0.8392156862745098}, + 'mediumvioletred': {r: 0.7803921568627451, g: 0.08235294117647059, b: 0.5215686274509804}, + 'deeppink': {r: 1, g: 0.0784313725490196, b: 0.5764705882352941}, + 'hotpink': {r: 1, g: 0.4117647058823529, b: 0.7058823529411765}, + 'palevioletred': {r: 0.8588235294117647, g: 0.4392156862745098, b: 0.5764705882352941}, + 'lavenderblush': {r: 1, g: 0.9411764705882353, b: 0.9607843137254902}, + 'crimson': {r: 0.8627450980392157, g: 0.0784313725490196, b: 0.23529411764705882}, + 'pink': {r: 1, g: 0.7529411764705882, b: 0.796078431372549}, + 'lightpink': {r: 1, g: 0.7137254901960784, b: 0.7568627450980392} + } + }; + + this.writers = { + '#HEX': function(color, that) { + return that._formatColor('#rxgxbx', color); + } + , '#HEX3': function(color, that) { + var hex3 = $.colorpicker.writers.HEX3(color); + return hex3 === false? false : '#'+hex3; + } + , 'HEX': function(color, that) { + return that._formatColor('rxgxbx', color); + } + , 'HEX3': function(color, that) { + var rgb = color.getRGB(), + r = Math.floor(rgb.r * 255), + g = Math.floor(rgb.g * 255), + b = Math.floor(rgb.b * 255); + + if (((r >>> 4) === (r &= 0xf)) + && ((g >>> 4) === (g &= 0xf)) + && ((b >>> 4) === (b &= 0xf))) { + return r.toString(16)+g.toString(16)+b.toString(16); + } + return false; + } + , 'RGB': function(color, that) { + return color.getAlpha() >= 1 + ? that._formatColor('rgb(rd,gd,bd)', color) + : false; + } + , 'RGBA': function(color, that) { + return that._formatColor('rgba(rd,gd,bd,af)', color); + } + , 'RGB%': function(color, that) { + return color.getAlpha() >= 1 + ? that._formatColor('rgb(rp%,gp%,bp%)', color) + : false; + } + , 'RGBA%': function(color, that) { + return that._formatColor('rgba(rp%,gp%,bp%,af)', color); + } + , 'HSL': function(color, that) { + return color.getAlpha() >= 1 + ? that._formatColor('hsl(hd,sd,vd)', color) + : false; + } + , 'HSLA': function(color, that) { + return that._formatColor('hsla(hd,sd,vd,af)', color); + } + , 'HSL%': function(color, that) { + return color.getAlpha() >= 1 + ? that._formatColor('hsl(hp%,sp%,vp%)', color) + : false; + } + , 'HSLA%': function(color, that) { + return that._formatColor('hsla(hp%,sp%,vp%,af)', color); + } + , 'NAME': function(color, that) { + return that._closestName(color); + } + , 'EXACT': function(color, that) { //@todo experimental. Implement a good fallback list + return that._exactName(color); + } + }; + + this.parsers = { + '': function(color) { + if (color === '') { + return new $.colorpicker.Color(); + } + } + , 'NAME': function(color, that) { + var c = that._getSwatch($.trim(color)); + if (c) { + return new $.colorpicker.Color(c.r, c.g, c.b); + } + } + , 'RGBA': function(color) { + var m = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)$/.exec(color); + if (m) { + return new $.colorpicker.Color( + m[1] / 255, + m[2] / 255, + m[3] / 255, + parseFloat(m[4]) + ); + } + } + , 'RGBA%': function(color) { + var m = /^rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)$/.exec(color); + if (m) { + return new $.colorpicker.Color( + m[1] / 100, + m[2] / 100, + m[3] / 100, + m[4] / 100 + ); + } + } + , 'HSLA': function(color) { + var m = /^hsla?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)$/.exec(color); + if (m) { + return (new $.colorpicker.Color()).setHSL( + m[1] / 255, + m[2] / 255, + m[3] / 255).setAlpha(parseFloat(m[4])); + } + } + , 'HSLA%': function(color) { + var m = /^hsla?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)$/.exec(color); + if (m) { + return (new $.colorpicker.Color()).setHSL( + m[1] / 100, + m[2] / 100, + m[3] / 100).setAlpha(m[4] / 100); + } + } + , '#HEX': function(color) { + var m = /^#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})$/.exec(color); + if (m) { + return new $.colorpicker.Color( + parseInt(m[1], 16) / 255, + parseInt(m[2], 16) / 255, + parseInt(m[3], 16) / 255 + ); + } + } + , '#HEX3': function(color) { + var m = /^#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])$/.exec(color); + if (m) { + return new $.colorpicker.Color( + parseInt(String(m[1]) + m[1], 16) / 255, + parseInt(String(m[2]) + m[2], 16) / 255, + parseInt(String(m[3]) + m[3], 16) / 255 + ); + } + } + , 'HEX': function(color) { + var m = /^([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})$/.exec(color); + if (m) { + return new $.colorpicker.Color( + parseInt(m[1], 16) / 255, + parseInt(m[2], 16) / 255, + parseInt(m[3], 16) / 255 + ); + } + } + , 'HEX3': function(color) { + var m = /^([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])$/.exec(color); + if (m) { + return new $.colorpicker.Color( + parseInt(String(m[1]) + m[1], 16) / 255, + parseInt(String(m[2]) + m[2], 16) / 255, + parseInt(String(m[3]) + m[3], 16) / 255 + ); + } + } + }; + + this.partslists = { + 'full': ['header', 'map', 'bar', 'hex', 'hsv', 'rgb', 'alpha', 'lab', 'cmyk', 'preview', 'swatches', 'footer'], + 'popup': ['map', 'bar', 'hex', 'hsv', 'rgb', 'alpha', 'preview', 'footer'], + 'draggable': ['header', 'map', 'bar', 'hex', 'hsv', 'rgb', 'alpha', 'preview', 'footer'], + 'inline': ['map', 'bar', 'hex', 'hsv', 'rgb', 'alpha', 'preview'], + 'custom': ['map','bar', 'hex', 'hsv', 'rgb', 'preview'], + 'simple': ['map','bar'] + }; + + this.limits = { + 'websafe': function(color) { + color.limit(6); + }, + 'nibble': function(color) { + color.limit(16); + }, + 'binary': function(color) { + color.limit(2); + }, + 'name': function(color, that) { + var swatch = that._getSwatch(that._closestName(color)); + color.setRGB(swatch.r, swatch.g, swatch.b); + } + }; + + this.parts = { + header: function (inst) { + var that = this, + e = null, + _html =function() { + var title = inst.options.title || inst._getRegional('title'), + html = '' + title + ''; + + if (!inst.inline && inst.options.showCloseButton) { + html += '' + + 'close'; + } + + return '
    ' + html + '
    '; + }; + + this.init = function() { + e = $(_html()).prependTo(inst.dialog); + + var close = $('.ui-dialog-titlebar-close', e); + inst._hoverable(close); + inst._focusable(close); + close.click(function(event) { + event.preventDefault(); + inst.close(inst.options.revert); + }); + + if (!inst.inline && inst.options.draggable) { + inst.dialog.draggable({ + handle: e + }); + } + }; + }, + + map: function (inst) { + var that = this, + e = null, + mousemove_timeout = null, + _mousedown, _mouseup, _mousemove, _html; + + _mousedown = function (event) { + if (!inst.opened) { + return; + } + + var div = $('.ui-colorpicker-map-layer-pointer', e), + offset = div.offset(), + width = div.width(), + height = div.height(), + x = event.pageX - offset.left, + y = event.pageY - offset.top; + + if (x >= 0 && x < width && y >= 0 && y < height) { + event.stopImmediatePropagation(); + event.preventDefault(); + e.unbind('mousedown', _mousedown); + $(document).bind('mouseup', _mouseup); + $(document).bind('mousemove', _mousemove); + _mousemove(event); + } + }; + + _mouseup = function (event) { + event.stopImmediatePropagation(); + event.preventDefault(); + $(document).unbind('mouseup', _mouseup); + $(document).unbind('mousemove', _mousemove); + e.bind('mousedown', _mousedown); + }; + + _mousemove = function (event) { + event.stopImmediatePropagation(); + event.preventDefault(); + + if (event.pageX === that.x && event.pageY === that.y) { + return; + } + that.x = event.pageX; + that.y = event.pageY; + + var div = $('.ui-colorpicker-map-layer-pointer', e), + offset = div.offset(), + width = div.width(), + height = div.height(), + x = event.pageX - offset.left, + y = event.pageY - offset.top; + + x = Math.max(0, Math.min(x / width, 1)); + y = Math.max(0, Math.min(y / height, 1)); + + // interpret values + switch (inst.mode) { + case 'h': + inst.color.setHSV(null, x, 1 - y); + break; + + case 's': + case 'a': + inst.color.setHSV(x, null, 1 - y); + break; + + case 'v': + inst.color.setHSV(x, 1 - y, null); + break; + + case 'r': + inst.color.setRGB(null, 1 - y, x); + break; + + case 'g': + inst.color.setRGB(1 - y, null, x); + break; + + case 'b': + inst.color.setRGB(x, 1 - y, null); + break; + } + + inst._change(); + }; + + _html = function () { + var html = '
    ' + + ' ' + + ' ' + + (inst.options.alpha ? ' ' : '') + + '
    '; + return html; + }; + + this.update = function () { + switch (inst.mode) { + case 'h': + $('.ui-colorpicker-map-layer-1', e).css({'background-position': '0 0', 'opacity': ''}).show(); + $('.ui-colorpicker-map-layer-2', e).hide(); + break; + + case 's': + case 'a': + $('.ui-colorpicker-map-layer-1', e).css({'background-position': '0 -260px', 'opacity': ''}).show(); + $('.ui-colorpicker-map-layer-2', e).css({'background-position': '0 -520px', 'opacity': ''}).show(); + break; + + case 'v': + $(e).css('background-color', 'black'); + $('.ui-colorpicker-map-layer-1', e).css({'background-position': '0 -780px', 'opacity': ''}).show(); + $('.ui-colorpicker-map-layer-2', e).hide(); + break; + + case 'r': + $('.ui-colorpicker-map-layer-1', e).css({'background-position': '0 -1040px', 'opacity': ''}).show(); + $('.ui-colorpicker-map-layer-2', e).css({'background-position': '0 -1300px', 'opacity': ''}).show(); + break; + + case 'g': + $('.ui-colorpicker-map-layer-1', e).css({'background-position': '0 -1560px', 'opacity': ''}).show(); + $('.ui-colorpicker-map-layer-2', e).css({'background-position': '0 -1820px', 'opacity': ''}).show(); + break; + + case 'b': + $('.ui-colorpicker-map-layer-1', e).css({'background-position': '0 -2080px', 'opacity': ''}).show(); + $('.ui-colorpicker-map-layer-2', e).css({'background-position': '0 -2340px', 'opacity': ''}).show(); + break; + } + that.repaint(); + }; + + this.repaint = function () { + var div = $('.ui-colorpicker-map-layer-pointer', e), + x = 0, + y = 0; + + switch (inst.mode) { + case 'h': + x = inst.color.getHSV().s * div.width(); + y = (1 - inst.color.getHSV().v) * div.width(); + $(e).css('background-color', inst.color.copy().setHSV(null, 1, 1).toCSS()); + break; + + case 's': + case 'a': + x = inst.color.getHSV().h * div.width(); + y = (1 - inst.color.getHSV().v) * div.width(); + $('.ui-colorpicker-map-layer-2', e).css('opacity', 1 - inst.color.getHSV().s); + break; + + case 'v': + x = inst.color.getHSV().h * div.width(); + y = (1 - inst.color.getHSV().s) * div.width(); + $('.ui-colorpicker-map-layer-1', e).css('opacity', inst.color.getHSV().v); + break; + + case 'r': + x = inst.color.getRGB().b * div.width(); + y = (1 - inst.color.getRGB().g) * div.width(); + $('.ui-colorpicker-map-layer-2', e).css('opacity', inst.color.getRGB().r); + break; + + case 'g': + x = inst.color.getRGB().b * div.width(); + y = (1 - inst.color.getRGB().r) * div.width(); + $('.ui-colorpicker-map-layer-2', e).css('opacity', inst.color.getRGB().g); + break; + + case 'b': + x = inst.color.getRGB().r * div.width(); + y = (1 - inst.color.getRGB().g) * div.width(); + $('.ui-colorpicker-map-layer-2', e).css('opacity', inst.color.getRGB().b); + break; + } + + if (inst.options.alpha) { + $('.ui-colorpicker-map-layer-alpha', e).css('opacity', 1 - inst.color.getAlpha()); + } + + $('.ui-colorpicker-map-pointer', e).css({ + 'left': x - 7, + 'top': y - 7 + }); + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-map-container', inst.dialog)); + + e.bind('mousedown', _mousedown); + }; + }, + + bar: function (inst) { + var that = this, + e = null, + _mousedown, _mouseup, _mousemove, _html; + + _mousedown = function (event) { + if (!inst.opened) { + return; + } + + var div = $('.ui-colorpicker-bar-layer-pointer', e), + offset = div.offset(), + width = div.width(), + height = div.height(), + x = event.pageX - offset.left, + y = event.pageY - offset.top; + + if (x >= 0 && x < width && y >= 0 && y < height) { + event.stopImmediatePropagation(); + event.preventDefault(); + e.unbind('mousedown', _mousedown); + $(document).bind('mouseup', _mouseup); + $(document).bind('mousemove', _mousemove); + _mousemove(event); + } + }; + + _mouseup = function (event) { + event.stopImmediatePropagation(); + event.preventDefault(); + $(document).unbind('mouseup', _mouseup); + $(document).unbind('mousemove', _mousemove); + e.bind('mousedown', _mousedown); + }; + + _mousemove = function (event) { + event.stopImmediatePropagation(); + event.preventDefault(); + + if (event.pageY === that.y) { + return; + } + that.y = event.pageY; + + var div = $('.ui-colorpicker-bar-layer-pointer', e), + offset = div.offset(), + height = div.height(), + y = event.pageY - offset.top; + + y = Math.max(0, Math.min(y / height, 1)); + + // interpret values + switch (inst.mode) { + case 'h': + inst.color.setHSV(1 - y, null, null); + break; + + case 's': + inst.color.setHSV(null, 1 - y, null); + break; + + case 'v': + inst.color.setHSV(null, null, 1 - y); + break; + + case 'r': + inst.color.setRGB(1 - y, null, null); + break; + + case 'g': + inst.color.setRGB(null, 1 - y, null); + break; + + case 'b': + inst.color.setRGB(null, null, 1 - y); + break; + + case 'a': + inst.color.setAlpha(1 - y); + break; + } + + inst._change(); + }; + + _html = function () { + var html = '
    ' + + ' ' + + ' ' + + ' ' + + ' '; + + if (inst.options.alpha) { + html += ' ' + + ' '; + } + + html += '
    '; + + return html; + }; + + this.update = function () { + switch (inst.mode) { + case 'h': + case 's': + case 'v': + case 'r': + case 'g': + case 'b': + $('.ui-colorpicker-bar-layer-alpha', e).show(); + $('.ui-colorpicker-bar-layer-alphabar', e).hide(); + break; + + case 'a': + $('.ui-colorpicker-bar-layer-alpha', e).hide(); + $('.ui-colorpicker-bar-layer-alphabar', e).show(); + break; + } + + switch (inst.mode) { + case 'h': + $('.ui-colorpicker-bar-layer-1', e).css({'background-position': '0 0', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-2', e).hide(); + $('.ui-colorpicker-bar-layer-3', e).hide(); + $('.ui-colorpicker-bar-layer-4', e).hide(); + break; + + case 's': + $('.ui-colorpicker-bar-layer-1', e).css({'background-position': '0 -260px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-2', e).css({'background-position': '0 -520px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-3', e).hide(); + $('.ui-colorpicker-bar-layer-4', e).hide(); + break; + + case 'v': + $('.ui-colorpicker-bar-layer-1', e).css({'background-position': '0 -520px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-2', e).hide(); + $('.ui-colorpicker-bar-layer-3', e).hide(); + $('.ui-colorpicker-bar-layer-4', e).hide(); + break; + + case 'r': + $('.ui-colorpicker-bar-layer-1', e).css({'background-position': '0 -1560px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-2', e).css({'background-position': '0 -1300px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-3', e).css({'background-position': '0 -780px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-4', e).css({'background-position': '0 -1040px', 'opacity': ''}).show(); + break; + + case 'g': + $('.ui-colorpicker-bar-layer-1', e).css({'background-position': '0 -2600px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-2', e).css({'background-position': '0 -2340px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-3', e).css({'background-position': '0 -1820px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-4', e).css({'background-position': '0 -2080px', 'opacity': ''}).show(); + break; + + case 'b': + $('.ui-colorpicker-bar-layer-1', e).css({'background-position': '0 -3640px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-2', e).css({'background-position': '0 -3380px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-3', e).css({'background-position': '0 -2860px', 'opacity': ''}).show(); + $('.ui-colorpicker-bar-layer-4', e).css({'background-position': '0 -3120px', 'opacity': ''}).show(); + break; + + case 'a': + $('.ui-colorpicker-bar-layer-1', e).hide(); + $('.ui-colorpicker-bar-layer-2', e).hide(); + $('.ui-colorpicker-bar-layer-3', e).hide(); + $('.ui-colorpicker-bar-layer-4', e).hide(); + break; + } + that.repaint(); + }; + + this.repaint = function () { + var div = $('.ui-colorpicker-bar-layer-pointer', e), + y = 0; + + switch (inst.mode) { + case 'h': + y = (1 - inst.color.getHSV().h) * div.height(); + break; + + case 's': + y = (1 - inst.color.getHSV().s) * div.height(); + $('.ui-colorpicker-bar-layer-2', e).css('opacity', 1 - inst.color.getHSV().v); + $(e).css('background-color', inst.color.copy().setHSV(null, 1, null).toCSS()); + break; + + case 'v': + y = (1 - inst.color.getHSV().v) * div.height(); + $(e).css('background-color', inst.color.copy().setHSV(null, null, 1).toCSS()); + break; + + case 'r': + y = (1 - inst.color.getRGB().r) * div.height(); + $('.ui-colorpicker-bar-layer-2', e).css('opacity', Math.max(0, (inst.color.getRGB().b - inst.color.getRGB().g))); + $('.ui-colorpicker-bar-layer-3', e).css('opacity', Math.max(0, (inst.color.getRGB().g - inst.color.getRGB().b))); + $('.ui-colorpicker-bar-layer-4', e).css('opacity', Math.min(inst.color.getRGB().b, inst.color.getRGB().g)); + break; + + case 'g': + y = (1 - inst.color.getRGB().g) * div.height(); + $('.ui-colorpicker-bar-layer-2', e).css('opacity', Math.max(0, (inst.color.getRGB().b - inst.color.getRGB().r))); + $('.ui-colorpicker-bar-layer-3', e).css('opacity', Math.max(0, (inst.color.getRGB().r - inst.color.getRGB().b))); + $('.ui-colorpicker-bar-layer-4', e).css('opacity', Math.min(inst.color.getRGB().r, inst.color.getRGB().b)); + break; + + case 'b': + y = (1 - inst.color.getRGB().b) * div.height(); + $('.ui-colorpicker-bar-layer-2', e).css('opacity', Math.max(0, (inst.color.getRGB().r - inst.color.getRGB().g))); + $('.ui-colorpicker-bar-layer-3', e).css('opacity', Math.max(0, (inst.color.getRGB().g - inst.color.getRGB().r))); + $('.ui-colorpicker-bar-layer-4', e).css('opacity', Math.min(inst.color.getRGB().r, inst.color.getRGB().g)); + break; + + case 'a': + y = (1 - inst.color.getAlpha()) * div.height(); + $(e).css('background-color', inst.color.copy().toCSS()); + break; + } + + if (inst.mode !== 'a') { + $('.ui-colorpicker-bar-layer-alpha', e).css('opacity', 1 - inst.color.getAlpha()); + } + + $('.ui-colorpicker-bar-pointer', e).css('top', y - 3); + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-bar-container', inst.dialog)); + + e.bind('mousedown', _mousedown); + }; + }, + + preview: function (inst) { + var that = this, + e = null, + _html; + + _html = function () { + return '
    ' + + '
    ' + + '
    ' + + '
    '; + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-preview-container', inst.dialog)); + + $('.ui-colorpicker-preview-initial', e).click(function () { + inst.color = inst.currentColor.copy(); + inst._change(inst.color.set); + }); + }; + + this.update = function () { + if (inst.options.alpha) { + $('.ui-colorpicker-preview-initial-alpha, .ui-colorpicker-preview-current-alpha', e).show(); + } else { + $('.ui-colorpicker-preview-initial-alpha, .ui-colorpicker-preview-current-alpha', e).hide(); + } + + this.repaint(); + }; + + this.repaint = function () { + $('.ui-colorpicker-preview-initial', e).css('background-color', inst.currentColor.set ? inst.currentColor.toCSS() : '').attr('title', inst.currentColor.set ? inst.currentColor.toCSS() : ''); + $('.ui-colorpicker-preview-initial-alpha', e).css('opacity', 1 - inst.currentColor.getAlpha()); + $('.ui-colorpicker-preview-current', e).css('background-color', inst.color.set ? inst.color.toCSS() : '').attr('title', inst.color.set ? inst.color.toCSS() : ''); + $('.ui-colorpicker-preview-current-alpha', e).css('opacity', 1 - inst.color.getAlpha()); + }; + }, + + hsv: function (inst) { + var that = this, + e = null, + _html; + + _html = function () { + var html = ''; + + if (inst.options.hsv) { + html += '
    °
    ' + + '
    %
    ' + + '
    %
    '; + } + + return '
    ' + html + '
    '; + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-hsv-container', inst.dialog)); + + $('.ui-colorpicker-mode', e).click(function () { + inst.mode = $(this).val(); + inst._updateAllParts(); + }); + + $('.ui-colorpicker-number', e).bind('change keyup', function () { + inst.color.setHSV( + $('.ui-colorpicker-hsv-h .ui-colorpicker-number', e).val() / 360, + $('.ui-colorpicker-hsv-s .ui-colorpicker-number', e).val() / 100, + $('.ui-colorpicker-hsv-v .ui-colorpicker-number', e).val() / 100 + ); + inst._change(); + }); + }; + + this.repaint = function () { + var hsv = inst.color.getHSV(); + hsv.h *= 360; + hsv.s *= 100; + hsv.v *= 100; + + $.each(hsv, function (index, value) { + var input = $('.ui-colorpicker-hsv-' + index + ' .ui-colorpicker-number', e); + value = Math.round(value); + if (parseInt(input.val(), 10) !== value) { + input.val(value); + } + }); + }; + + this.update = function () { + $('.ui-colorpicker-mode', e).each(function () { + $(this).attr('checked', $(this).val() === inst.mode); + }); + this.repaint(); + }; + }, + + rgb: function (inst) { + var that = this, + e = null, + _html; + + _html = function () { + var html = ''; + + if (inst.options.rgb) { + html += '
    ' + + '
    ' + + '
    '; + } + + return '
    ' + html + '
    '; + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-rgb-container', inst.dialog)); + + $('.ui-colorpicker-mode', e).click(function () { + inst.mode = $(this).val(); + inst._updateAllParts(); + }); + + $('.ui-colorpicker-number', e).bind('change keyup', function () { + var r = $('.ui-colorpicker-rgb-r .ui-colorpicker-number', e).val(); + inst.color.setRGB( + $('.ui-colorpicker-rgb-r .ui-colorpicker-number', e).val() / 255, + $('.ui-colorpicker-rgb-g .ui-colorpicker-number', e).val() / 255, + $('.ui-colorpicker-rgb-b .ui-colorpicker-number', e).val() / 255 + ); + + inst._change(); + }); + }; + + this.repaint = function () { + $.each(inst.color.getRGB(), function (index, value) { + var input = $('.ui-colorpicker-rgb-' + index + ' .ui-colorpicker-number', e); + value = Math.floor(value * 255); + if (parseInt(input.val(), 10) !== value) { + input.val(value); + } + }); + }; + + this.update = function () { + $('.ui-colorpicker-mode', e).each(function () { + $(this).attr('checked', $(this).val() === inst.mode); + }); + this.repaint(); + }; + }, + + lab: function (inst) { + var that = this, + part = null, + html = function () { + var html = ''; + + if (inst.options.hsv) { + html += '
    ' + + '
    ' + + '
    '; + } + + return '
    ' + html + '
    '; + }; + + this.init = function () { + var data = 0; + + part = $(html()).appendTo($('.ui-colorpicker-lab-container', inst.dialog)); + + $('.ui-colorpicker-number', part).bind('change keyup', function (event) { + inst.color.setLAB( + parseInt($('.ui-colorpicker-lab-l .ui-colorpicker-number', part).val(), 10) / 100, + (parseInt($('.ui-colorpicker-lab-a .ui-colorpicker-number', part).val(), 10) + 128) / 255, + (parseInt($('.ui-colorpicker-lab-b .ui-colorpicker-number', part).val(), 10) + 128) / 255 + ); + inst._change(); + }); + }; + + this.repaint = function () { + var lab = inst.color.getLAB(); + lab.l *= 100; + lab.a = (lab.a * 255) - 128; + lab.b = (lab.b * 255) - 128; + + $.each(lab, function (index, value) { + var input = $('.ui-colorpicker-lab-' + index + ' .ui-colorpicker-number', part); + value = Math.round(value); + if (parseInt(input.val(), 10) !== value) { + input.val(value); + } + }); + }; + + this.update = function () { + this.repaint(); + }; + }, + + cmyk: function (inst) { + var that = this, + part = null, + html = function () { + var html = ''; + + if (inst.options.hsv) { + html += '
    %
    ' + + '
    %
    ' + + '
    %
    ' + + '
    %
    '; + } + + return '
    ' + html + '
    '; + }; + + this.init = function () { + part = $(html()).appendTo($('.ui-colorpicker-cmyk-container', inst.dialog)); + + $('.ui-colorpicker-number', part).bind('change keyup', function (event) { + inst.color.setCMYK( + parseInt($('.ui-colorpicker-cmyk-c .ui-colorpicker-number', part).val(), 10) / 100, + parseInt($('.ui-colorpicker-cmyk-m .ui-colorpicker-number', part).val(), 10) / 100, + parseInt($('.ui-colorpicker-cmyk-y .ui-colorpicker-number', part).val(), 10) / 100, + parseInt($('.ui-colorpicker-cmyk-k .ui-colorpicker-number', part).val(), 10) / 100 + ); + inst._change(); + }); + }; + + this.repaint = function () { + $.each(inst.color.getCMYK(), function (index, value) { + var input = $('.ui-colorpicker-cmyk-' + index + ' .ui-colorpicker-number', part); + value = Math.round(value * 100); + if (parseInt(input.val(), 10, 10) !== value) { + input.val(value); + } + }); + }; + + this.update = function () { + this.repaint(); + }; + }, + + alpha: function (inst) { + var that = this, + e = null, + _html; + + _html = function () { + var html = ''; + + if (inst.options.alpha) { + html += '
    %
    '; + } + + return '
    ' + html + '
    '; + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-alpha-container', inst.dialog)); + + $('.ui-colorpicker-mode', e).click(function () { + inst.mode = $(this).val(); + inst._updateAllParts(); + }); + + $('.ui-colorpicker-number', e).bind('change keyup', function () { + inst.color.setAlpha($('.ui-colorpicker-a .ui-colorpicker-number', e).val() / 100); + inst._change(); + }); + }; + + this.update = function () { + $('.ui-colorpicker-mode', e).each(function () { + $(this).attr('checked', $(this).val() === inst.mode); + }); + this.repaint(); + }; + + this.repaint = function () { + var input = $('.ui-colorpicker-a .ui-colorpicker-number', e), + value = Math.round(inst.color.getAlpha() * 100); + if (parseInt(input.val(), 10) !== value) { + input.val(value); + } + }; + }, + + hex: function (inst) { + var that = this, + e = null, + _html; + + _html = function () { + var html = ''; + + if (inst.options.alpha) { + html += ''; + } + + html += ''; + + return '
    ' + html + '
    '; + }; + + this.init = function () { + e = $(_html()).appendTo($('.ui-colorpicker-hex-container', inst.dialog)); + + // repeat here makes the invalid input disappear faster + $('.ui-colorpicker-hex-input', e).bind('change keydown keyup', function (a, b, c) { + if (/[^a-fA-F0-9]/.test($(this).val())) { + $(this).val($(this).val().replace(/[^a-fA-F0-9]/, '')); + } + }); + + $('.ui-colorpicker-hex-input', e).bind('change keyup', function () { + // repeat here makes sure that the invalid input doesn't get parsed + inst.color = _parseHex($(this).val()).setAlpha(inst.color.getAlpha()); + inst._change(); + }); + + $('.ui-colorpicker-hex-alpha', e).bind('change keydown keyup', function () { + if (/[^a-fA-F0-9]/.test($(this).val())) { + $(this).val($(this).val().replace(/[^a-fA-F0-9]/, '')); + } + }); + + $('.ui-colorpicker-hex-alpha', e).bind('change keyup', function () { + inst.color.setAlpha(parseInt($('.ui-colorpicker-hex-alpha', e).val(), 16) / 255); + inst._change(); + }); + }; + + this.update = function () { + this.repaint(); + }; + + this.repaint = function () { + if (!$('.ui-colorpicker-hex-input', e).is(':focus')) { + $('.ui-colorpicker-hex-input', e).val(inst.color.toHex(true)); + } + + if (!$('.ui-colorpicker-hex-alpha', e).is(':focus')) { + $('.ui-colorpicker-hex-alpha', e).val(_intToHex(inst.color.getAlpha() * 255)); + } + }; + }, + + swatches: function (inst) { + var that = this, + part = null, + html = function () { + var html = ''; + + $.each(inst._getSwatches(), function (name, color) { + var c = new $.colorpicker.Color(color.r, color.g, color.b), + css = c.toCSS(); + html += '
    '; + }); + + return '
    ' + html + '
    '; + }; + + this.init = function () { + part = $(html()).appendTo($('.ui-colorpicker-swatches-container', inst.dialog)); + + $('.ui-colorpicker-swatch', part).click(function () { + inst.color = inst._parseColor($(this).css('background-color')); + inst._change(); + }); + }; + }, + + footer: function (inst) { + var that = this, + part = null, + id_transparent = 'ui-colorpicker-special-transparent-'+_colorpicker_index, + id_none = 'ui-colorpicker-special-none-'+_colorpicker_index, + html = function () { + var html = ''; + + if (inst.options.alpha || (!inst.inline && inst.options.showNoneButton)) { + html += '
    '; + + if (inst.options.alpha) { + html += ''; + } + if (!inst.inline && inst.options.showNoneButton) { + html += ''; + } + html += '
    '; + } + + if (!inst.inline) { + html += '
    '; + if (inst.options.showCancelButton) { + html += ''; + } + html += ''; + html += '
    '; + } + + return '
    ' + html + '
    '; + }; + + this.init = function () { + part = $(html()).appendTo(inst.dialog); + + $('.ui-colorpicker-ok', part).button().click(function () { + inst.close(); + }); + + $('.ui-colorpicker-cancel', part).button().click(function () { + inst.close(true); //cancel + }); + + //inst._getRegional('transparent') + $('.ui-colorpicker-buttonset', part).buttonset(); + + $('.ui-colorpicker-special-color', part).click(function () { + inst._change(); + }); + + $('#'+id_none, part).click(function () { + inst._change(false); + }); + + $('#'+id_transparent, part).click(function () { + inst.color.setAlpha(0); + inst._change(); + }); + }; + + this.repaint = function () { + if (!inst.color.set) { + $('.ui-colorpicker-special-none', part).attr('checked', true).button( "refresh" ); + } else if (inst.color.getAlpha() === 0) { + $('.ui-colorpicker-special-transparent', part).attr('checked', true).button( "refresh" ); + } else { + $('input', part).attr('checked', false).button( "refresh" ); + } + + $('.ui-colorpicker-cancel', part).button(inst.changed ? 'enable' : 'disable'); + }; + + this.update = function () {}; + } + }; + + this.Color = function () { + var spaces = { rgb: {r: 0, g: 0, b: 0}, + hsv: {h: 0, s: 0, v: 0}, + hsl: {h: 0, s: 0, l: 0}, + lab: {l: 0, a: 0, b: 0}, + cmyk: {c: 0, m: 0, y: 0, k: 1} + }, + a = 1, + illuminant = [0.9504285, 1, 1.0889], // CIE-L*ab D65/2' 1931 + args = arguments, + _clip = function(v) { + if (isNaN(v) || v === null) { + return 0; + } + if (typeof v == 'string') { + v = parseInt(v, 10); + } + return Math.max(0, Math.min(v, 1)); + }, + _hexify = function (number) { + var digits = '0123456789abcdef', + lsd = number % 16, + msd = (number - lsd) / 16, + hexified = digits.charAt(msd) + digits.charAt(lsd); + return hexified; + }, + _rgb_to_xyz = function(rgb) { + var r = (rgb.r > 0.04045) ? Math.pow((rgb.r + 0.055) / 1.055, 2.4) : rgb.r / 12.92, + g = (rgb.g > 0.04045) ? Math.pow((rgb.g + 0.055) / 1.055, 2.4) : rgb.g / 12.92, + b = (rgb.b > 0.04045) ? Math.pow((rgb.b + 0.055) / 1.055, 2.4) : rgb.b / 12.92; + + return { + x: r * 0.4124 + g * 0.3576 + b * 0.1805, + y: r * 0.2126 + g * 0.7152 + b * 0.0722, + z: r * 0.0193 + g * 0.1192 + b * 0.9505 + }; + }, + _xyz_to_rgb = function(xyz) { + var rgb = { + r: xyz.x * 3.2406 + xyz.y * -1.5372 + xyz.z * -0.4986, + g: xyz.x * -0.9689 + xyz.y * 1.8758 + xyz.z * 0.0415, + b: xyz.x * 0.0557 + xyz.y * -0.2040 + xyz.z * 1.0570 + }; + + rgb.r = (rgb.r > 0.0031308) ? 1.055 * Math.pow(rgb.r, (1 / 2.4)) - 0.055 : 12.92 * rgb.r; + rgb.g = (rgb.g > 0.0031308) ? 1.055 * Math.pow(rgb.g, (1 / 2.4)) - 0.055 : 12.92 * rgb.g; + rgb.b = (rgb.b > 0.0031308) ? 1.055 * Math.pow(rgb.b, (1 / 2.4)) - 0.055 : 12.92 * rgb.b; + + return rgb; + }, + _rgb_to_hsv = function(rgb) { + var minVal = Math.min(rgb.r, rgb.g, rgb.b), + maxVal = Math.max(rgb.r, rgb.g, rgb.b), + delta = maxVal - minVal, + del_R, del_G, del_B, + hsv = { + h: 0, + s: 0, + v: maxVal + }; + + if (delta === 0) { + hsv.h = 0; + hsv.s = 0; + } else { + hsv.s = delta / maxVal; + + del_R = (((maxVal - rgb.r) / 6) + (delta / 2)) / delta; + del_G = (((maxVal - rgb.g) / 6) + (delta / 2)) / delta; + del_B = (((maxVal - rgb.b) / 6) + (delta / 2)) / delta; + + if (rgb.r === maxVal) { + hsv.h = del_B - del_G; + } else if (rgb.g === maxVal) { + hsv.h = (1 / 3) + del_R - del_B; + } else if (rgb.b === maxVal) { + hsv.h = (2 / 3) + del_G - del_R; + } + + if (hsv.h < 0) { + hsv.h += 1; + } else if (hsv.h > 1) { + hsv.h -= 1; + } + } + + return hsv; + }, + _hsv_to_rgb = function(hsv) { + var rgb = { + r: 0, + g: 0, + b: 0 + }, + var_h, + var_i, + var_1, + var_2, + var_3; + + if (hsv.s === 0) { + rgb.r = rgb.g = rgb.b = hsv.v; + } else { + var_h = hsv.h === 1 ? 0 : hsv.h * 6; + var_i = Math.floor(var_h); + var_1 = hsv.v * (1 - hsv.s); + var_2 = hsv.v * (1 - hsv.s * (var_h - var_i)); + var_3 = hsv.v * (1 - hsv.s * (1 - (var_h - var_i))); + + if (var_i === 0) { + rgb.r = hsv.v; + rgb.g = var_3; + rgb.b = var_1; + } else if (var_i === 1) { + rgb.r = var_2; + rgb.g = hsv.v; + rgb.b = var_1; + } else if (var_i === 2) { + rgb.r = var_1; + rgb.g = hsv.v; + rgb.b = var_3; + } else if (var_i === 3) { + rgb.r = var_1; + rgb.g = var_2; + rgb.b = hsv.v; + } else if (var_i === 4) { + rgb.r = var_3; + rgb.g = var_1; + rgb.b = hsv.v; + } else { + rgb.r = hsv.v; + rgb.g = var_1; + rgb.b = var_2; + } + } + + return rgb; + }, + _rgb_to_hsl = function(rgb) { + var minVal = Math.min(rgb.r, rgb.g, rgb.b), + maxVal = Math.max(rgb.r, rgb.g, rgb.b), + delta = maxVal - minVal, + del_R, del_G, del_B, + hsl = { + h: 0, + s: 0, + l: (maxVal + minVal) / 2 + }; + + if (delta === 0) { + hsl.h = 0; + hsl.s = 0; + } else { + hsl.s = hsl.l < 0.5 ? delta / (maxVal + minVal) : delta / (2 - maxVal - minVal); + + del_R = (((maxVal - rgb.r) / 6) + (delta / 2)) / delta; + del_G = (((maxVal - rgb.g) / 6) + (delta / 2)) / delta; + del_B = (((maxVal - rgb.b) / 6) + (delta / 2)) / delta; + + if (rgb.r === maxVal) { + hsl.h = del_B - del_G; + } else if (rgb.g === maxVal) { + hsl.h = (1 / 3) + del_R - del_B; + } else if (rgb.b === maxVal) { + hsl.h = (2 / 3) + del_G - del_R; + } + + if (hsl.h < 0) { + hsl.h += 1; + } else if (hsl.h > 1) { + hsl.h -= 1; + } + } + + return hsl; + }, + _hsl_to_rgb = function(hsl) { + var var_1, + var_2, + hue_to_rgb = function(v1, v2, vH) { + if (vH < 0) { + vH += 1; + } + if (vH > 1) { + vH -= 1; + } + if ((6 * vH) < 1) { + return v1 + (v2 - v1) * 6 * vH; + } + if ((2 * vH) < 1) { + return v2; + } + if ((3 * vH) < 2) { + return v1 + (v2 - v1) * ((2 / 3) - vH) * 6; + } + return v1; + }; + + if (hsl.s === 0) { + return { + r: hsl.l, + g: hsl.l, + b: hsl.l + }; + } + + var_2 = (hsl.l < 0.5) ? hsl.l * (1 + hsl.s) : (hsl.l + hsl.s) - (hsl.s * hsl.l); + var_1 = 2 * hsl.l - var_2; + + return { + r: hue_to_rgb(var_1, var_2, hsl.h + (1 / 3)), + g: hue_to_rgb(var_1, var_2, hsl.h), + b: hue_to_rgb(var_1, var_2, hsl.h - (1 / 3)) + }; + }, + _xyz_to_lab = function(xyz) { + var x = xyz.x / illuminant[0], + y = xyz.y / illuminant[1], + z = xyz.z / illuminant[2]; + + x = (x > 0.008856) ? Math.pow(x, (1/3)) : (7.787 * x) + (16/116); + y = (y > 0.008856) ? Math.pow(y, (1/3)) : (7.787 * y) + (16/116); + z = (z > 0.008856) ? Math.pow(z, (1/3)) : (7.787 * z) + (16/116); + + return { + l: ((116 * y) - 16) / 100, // [0,100] + a: ((500 * (x - y)) + 128) / 255, // [-128,127] + b: ((200 * (y - z)) + 128) / 255 // [-128,127] + }; + }, + _lab_to_xyz = function(lab) { + var lab2 = { + l: lab.l * 100, + a: (lab.a * 255) - 128, + b: (lab.b * 255) - 128 + }, + xyz = { + x: 0, + y: (lab2.l + 16) / 116, + z: 0 + }; + + xyz.x = lab2.a / 500 + xyz.y; + xyz.z = xyz.y - lab2.b / 200; + + xyz.x = (Math.pow(xyz.x, 3) > 0.008856) ? Math.pow(xyz.x, 3) : (xyz.x - 16 / 116) / 7.787; + xyz.y = (Math.pow(xyz.y, 3) > 0.008856) ? Math.pow(xyz.y, 3) : (xyz.y - 16 / 116) / 7.787; + xyz.z = (Math.pow(xyz.z, 3) > 0.008856) ? Math.pow(xyz.z, 3) : (xyz.z - 16 / 116) / 7.787; + + xyz.x *= illuminant[0]; + xyz.y *= illuminant[1]; + xyz.z *= illuminant[2]; + + return xyz; + }, + _rgb_to_cmy = function(rgb) { + return { + c: 1 - (rgb.r), + m: 1 - (rgb.g), + y: 1 - (rgb.b) + }; + }, + _cmy_to_rgb = function(cmy) { + return { + r: 1 - (cmy.c), + g: 1 - (cmy.m), + b: 1 - (cmy.y) + }; + }, + _cmy_to_cmyk = function(cmy) { + var K = 1; + + if (cmy.c < K) { + K = cmy.c; + } + if (cmy.m < K) { + K = cmy.m; + } + if (cmy.y < K) { + K = cmy.y; + } + + if (K === 1) { + return { + c: 0, + m: 0, + y: 0, + k: 1 + }; + } + + return { + c: (cmy.c - K) / (1 - K), + m: (cmy.m - K) / (1 - K), + y: (cmy.y - K) / (1 - K), + k: K + }; + }, + _cmyk_to_cmy = function(cmyk) { + return { + c: cmyk.c * (1 - cmyk.k) + cmyk.k, + m: cmyk.m * (1 - cmyk.k) + cmyk.k, + y: cmyk.y * (1 - cmyk.k) + cmyk.k + }; + }; + + this.set = false; + + this.setAlpha = function(_a) { + if (_a !== null) { + a = _clip(_a); + } + + return this; + }; + + this.getAlpha = function() { + return a; + }; + + this.setRGB = function(r, g, b) { + spaces = { rgb: this.getRGB() }; + if (r !== null) { + spaces.rgb.r = _clip(r); + } + if (g !== null) { + spaces.rgb.g = _clip(g); + } + if (b !== null) { + spaces.rgb.b = _clip(b); + } + + return this; + }; + + this.setHSV = function(h, s, v) { + spaces = {hsv: this.getHSV()}; + if (h !== null) { + spaces.hsv.h = _clip(h); + } + if (s !== null) { + spaces.hsv.s = _clip(s); + } + if (v !== null) { + spaces.hsv.v = _clip(v); + } + + return this; + }; + + this.setHSL = function(h, s, l) { + spaces = {hsl: this.getHSL()}; + if (h !== null) { + spaces.hsl.h = _clip(h); + } + if (s !== null) { + spaces.hsl.s = _clip(s); + } + if (l !== null) { + spaces.hsl.l = _clip(l); + } + + return this; + }; + + this.setLAB = function(l, a, b) { + spaces = {lab: this.getLAB()}; + if (l !== null) { + spaces.lab.l = _clip(l); + } + if (a !== null) { + spaces.lab.a = _clip(a); + } + if (b !== null) { + spaces.lab.b = _clip(b); + } + + return this; + }; + + this.setCMYK = function(c, m, y, k) { + spaces = {cmyk: this.getCMYK()}; + if (c !== null) { + spaces.cmyk.c = _clip(c); + } + if (m !== null) { + spaces.cmyk.m = _clip(m); + } + if (y !== null) { + spaces.cmyk.y = _clip(y); + } + if (k !== null) { + spaces.cmyk.k = _clip(k); + } + + return this; + }; + + this.getRGB = function() { + if (!spaces.rgb) { + spaces.rgb = spaces.lab ? _xyz_to_rgb(_lab_to_xyz(spaces.lab)) + : spaces.hsv ? _hsv_to_rgb(spaces.hsv) + : spaces.hsl ? _hsl_to_rgb(spaces.hsl) + : spaces.cmyk ? _cmy_to_rgb(_cmyk_to_cmy(spaces.cmyk)) + : {r: 0, g: 0, b: 0}; + spaces.rgb.r = _clip(spaces.rgb.r); + spaces.rgb.g = _clip(spaces.rgb.g); + spaces.rgb.b = _clip(spaces.rgb.b); + } + return $.extend({}, spaces.rgb); + }; + + this.getHSV = function() { + if (!spaces.hsv) { + spaces.hsv = spaces.lab ? _rgb_to_hsv(this.getRGB()) + : spaces.rgb ? _rgb_to_hsv(spaces.rgb) + : spaces.hsl ? _rgb_to_hsv(this.getRGB()) + : spaces.cmyk ? _rgb_to_hsv(this.getRGB()) + : {h: 0, s: 0, v: 0}; + spaces.hsv.h = _clip(spaces.hsv.h); + spaces.hsv.s = _clip(spaces.hsv.s); + spaces.hsv.v = _clip(spaces.hsv.v); + } + return $.extend({}, spaces.hsv); + }; + + this.getHSL = function() { + if (!spaces.hsl) { + spaces.hsl = spaces.rgb ? _rgb_to_hsl(spaces.rgb) + : spaces.hsv ? _rgb_to_hsl(this.getRGB()) + : spaces.cmyk ? _rgb_to_hsl(this.getRGB()) + : spaces.hsv ? _rgb_to_hsl(this.getRGB()) + : {h: 0, s: 0, l: 0}; + spaces.hsl.h = _clip(spaces.hsl.h); + spaces.hsl.s = _clip(spaces.hsl.s); + spaces.hsl.l = _clip(spaces.hsl.l); + } + return $.extend({}, spaces.hsl); + }; + + this.getCMYK = function() { + if (!spaces.cmyk) { + spaces.cmyk = spaces.rgb ? _cmy_to_cmyk(_rgb_to_cmy(spaces.rgb)) + : spaces.hsv ? _cmy_to_cmyk(_rgb_to_cmy(this.getRGB())) + : spaces.hsl ? _cmy_to_cmyk(_rgb_to_cmy(this.getRGB())) + : spaces.lab ? _cmy_to_cmyk(_rgb_to_cmy(this.getRGB())) + : {c: 0, m: 0, y: 0, k: 1}; + spaces.cmyk.c = _clip(spaces.cmyk.c); + spaces.cmyk.m = _clip(spaces.cmyk.m); + spaces.cmyk.y = _clip(spaces.cmyk.y); + spaces.cmyk.k = _clip(spaces.cmyk.k); + } + return $.extend({}, spaces.cmyk); + }; + + this.getLAB = function() { + if (!spaces.lab) { + spaces.lab = spaces.rgb ? _xyz_to_lab(_rgb_to_xyz(spaces.rgb)) + : spaces.hsv ? _xyz_to_lab(_rgb_to_xyz(this.getRGB())) + : spaces.hsl ? _xyz_to_lab(_rgb_to_xyz(this.getRGB())) + : spaces.cmyk ? _xyz_to_lab(_rgb_to_xyz(this.getRGB())) + : {l: 0, a: 0, b: 0}; + spaces.lab.l = _clip(spaces.lab.l); + spaces.lab.a = _clip(spaces.lab.a); + spaces.lab.b = _clip(spaces.lab.b); + } + return $.extend({}, spaces.lab); + }; + + this.getChannels = function() { + return { + r: this.getRGB().r, + g: this.getRGB().g, + b: this.getRGB().b, + a: this.getAlpha(), + h: this.getHSV().h, + s: this.getHSV().s, + v: this.getHSV().v, + c: this.getCMYK().c, + m: this.getCMYK().m, + y: this.getCMYK().y, + k: this.getCMYK().k, + L: this.getLAB().l, + A: this.getLAB().a, + B: this.getLAB().b + }; + }; + + this.getSpaces = function() { + return $.extend(true, {}, spaces); + }; + + this.setSpaces = function(new_spaces) { + spaces = new_spaces; + return this; + }; + + this.distance = function(color) { + var space = 'lab', + getter = 'get'+space.toUpperCase(), + a = this[getter](), + b = color[getter](), + distance = 0, + channel; + + for (channel in a) { + distance += Math.pow(a[channel] - b[channel], 2); + } + + return distance; + }; + + this.equals = function(color) { + var a = this.getRGB(), + b = color.getRGB(); + + return this.getAlpha() === color.getAlpha() + && a.r === b.r + && a.g === b.g + && a.b === b.b; + }; + + this.limit = function(steps) { + steps -= 1; + var rgb = this.getRGB(); + this.setRGB( + Math.round(rgb.r * steps) / steps, + Math.round(rgb.g * steps) / steps, + Math.round(rgb.b * steps) / steps + ); + }; + + this.toHex = function() { + var rgb = this.getRGB(); + return _hexify(rgb.r * 255) + _hexify(rgb.g * 255) + _hexify(rgb.b * 255); + }; + + this.toCSS = function() { + return '#' + this.toHex(); + }; + + this.copy = function() { + var color = new $.colorpicker.Color(this.getSpaces(), this.getAlpha()); + color.set = this.set; + return color; + }; + + // Construct + if (args.length === 2) { + this.setSpaces(args[0]); + this.setAlpha(args[1] === 0 ? 0 : args[1] || 1); + this.set = true; + } + if (args.length > 2) { + this.setRGB(args[0], args[1], args[2]); + this.setAlpha(args[3] === 0 ? 0 : args[3] || 1); + this.set = true; + } + }; + }(); + + $.widget("vanderlee.colorpicker", { + options: { + alpha: false, // Show alpha controls and mode + altAlpha: true, // change opacity of altField as well? + altField: '', // selector for DOM elements which change background color on change. + altOnChange: true, // true to update on each change, false to update only on close. + altProperties: 'background-color', // comma separated list of any of 'background-color', 'color', 'border-color', 'outline-color' + autoOpen: false, // Open dialog automatically upon creation + buttonClass: null, // If set, the button will get this/these classname(s). + buttonColorize: false, + buttonImage: 'view/javascript/shopunity/colorpicker/images/ui-colorpicker.png', + buttonImageOnly: false, + buttonText: null, // Text on the button and/or title of button image. + closeOnEscape: true, // Close the dialog when the escape key is pressed. + closeOnOutside: true, // Close the dialog when clicking outside the dialog (not for inline) + color: '#00FF00', // Initial color (for inline only) + colorFormat: 'HEX', // Format string for output color format + draggable: true, // Make popup dialog draggable if header is visible. + duration: 'fast', + hsv: true, // Show HSV controls and modes + inline: true, // Show any divs as inline by default + inlineFrame: true, // Show a border and background when inline. + layout: { + map: [0, 0, 1, 5], // Left, Top, Width, Height (in table cells). + bar: [1, 0, 1, 5], + preview: [2, 0, 1, 1], + hsv: [2, 1, 1, 1], + rgb: [2, 2, 1, 1], + alpha: [2, 3, 1, 1], + hex: [2, 4, 1, 1], + lab: [3, 1, 1, 1], + cmyk: [3, 2, 1, 2], + swatches: [4, 0, 1, 5] + }, + limit: '', // Limit color "resolution": '', 'websafe', 'nibble', 'binary', 'name' + modal: false, // Modal dialog? + mode: 'h', // Initial editing mode, h, s, v, r, g, b or a + okOnEnter: false, // Close (with OK) when pressing the enter key + parts: '', // leave empty for automatic selection + regional: '', + revert: false, // Revert color upon non + rgb: true, // Show RGB controls and modes + showAnim: 'fadeIn', + showCancelButton: true, + showNoneButton: false, + showCloseButton: true, + showOn: 'focus click alt', // 'focus', 'click', 'button', 'alt', 'both' + showOptions: {}, + swatches: null, // null for default or kv-object or names swatches set + swatchesWidth: 84, // width (in number of pixels) of swatches box. + title: null, + + cancel: null, + close: null, + init: null, + select: null, + ok: null, + open: null + }, + + _create: function () { + var that = this, + text; + + ++_colorpicker_index; + + that.widgetEventPrefix = 'colorpicker'; + + that.opened = false; + that.generated = false; + that.inline = false; + that.changed = false; + + that.dialog = null; + that.button = null; + that.image = null; + that.overlay = null; + + that.mode = that.options.mode; + + if (that.element.is('input') || that.options.inline === false) { + // Initial color + that._setColor(that.element.is('input') ? that.element.val() : that.options.color); + that._callback('init'); + + // showOn focus + if (/\bfocus|both\b/.test(that.options.showOn)) { + that.element.bind('focus', function () { + that.open(); + }); + } + + // showOn click + if (/\bclick|both\b/.test(that.options.showOn)) { + that.element.bind('click', function () { + that.open(); + }); + } + + // showOn button + if (/\bbutton|both\b/.test(that.options.showOn)) { + if (that.options.buttonImage !== '') { + text = that.options.buttonText || that._getRegional('button'); + + that.image = $('').attr({ + 'src': that.options.buttonImage, + 'alt': text, + 'title': text + }); + if (that.options.buttonClass) { + that.image.attr('class', that.options.buttonClass); + } + + that._setImageBackground(); + } + + if (that.options.buttonImageOnly && that.image) { + that.button = that.image; + } else { + that.button = $('').html(that.image || that.options.buttonText).button(); + that.image = that.image ? $('img', that.button).first() : null; + } + that.button.insertAfter(that.element).click(function () { + that[that.opened ? 'close' : 'open'](); + }); + } + + // showOn alt + if (/\balt|both\b/.test(that.options.showOn)) { + $(that.options.altField).bind('click', function () { + that.open(); + }); + } + + if (that.options.autoOpen) { + that.open(); + } + } else { + that.inline = true; + + that._generate(); + that.opened = true; + } + + return this; + }, + + _setOption: function(key, value){ + var that = this; + + switch (key) { + case "disabled": + if (value) { + that.dialog.addClass('ui-colorpicker-disabled'); + } else { + that.dialog.removeClass('ui-colorpicker-disabled'); + } + break; + } + + $.Widget.prototype._setOption.apply(that, arguments); + }, + + _setImageBackground: function() { + if (this.image && this.options.buttonColorize) { + this.image.css('background-color', this.color.set? this._formatColor('RGBA', this.color) : ''); + } + }, + + /** + * If an alternate field is specified, set it according to the current color. + */ + _setAltField: function () { + if (this.options.altOnChange && this.options.altField && this.options.altProperties) { + var index, + property, + properties = this.options.altProperties.split(','); + + for (index = 0; index <= properties.length; ++index) { + property = $.trim(properties[index]); + switch (property) { + case 'color': + case 'background-color': + case 'backgroundColor': + case 'outline-color': + case 'border-color': + $(this.options.altField).css(property, this.color.set? this.color.toCSS() : ''); + break; + } + } + + if (this.options.altAlpha) { + $(this.options.altField).css('opacity', this.color.set? this.color.getAlpha() : ''); + } + } + }, + + _setColor: function(text) { + this.color = this._parseColor(text); + this.currentColor = this.color.copy(); + + this._setImageBackground(); + this._setAltField(); + }, + + setColor: function(text) { + this._setColor(text); + this._change(this.color.set); + }, + + _generateInline: function() { + var that = this; + + $(that.element).html(that.options.inlineFrame ? _container_inlineFrame : _container_inline); + + that.dialog = $('.ui-colorpicker', that.element); + }, + + _generatePopup: function() { + var that = this; + + $('body').append(_container_popup); + that.dialog = $('.ui-colorpicker:last'); + + // Close on clicking outside window and controls + $(document).delegate('html', 'touchstart click', function (event) { + if (!that.opened || event.target === that.element[0] || that.overlay) { + return; + } + + // Check if clicked on any part of dialog + if (that.dialog.is(event.target) || that.dialog.has(event.target).length > 0) { + that.element.blur(); // inside window! + return; + } + + // Check if clicked on known external elements + var p, + parents = $(event.target).parents(); + // add the event.target in case of buttonImageOnly and closeOnOutside both are set to true + parents.push(event.target); + for (p = 0; p <= parents.length; ++p) { + // button + if (that.button !== null && parents[p] === that.button[0]) { + return; + } + // showOn alt + if (/\balt|both\b/.test(that.options.showOn) && $(that.options.altField).is(parents[p])) { + return; + } + } + + // no closeOnOutside + if (!that.options.closeOnOutside) { + return; + } + + that.close(that.options.revert); + }); + + $(document).keydown(function (event) { + // close on ESC key + if (that.opened && event.keyCode === 27 && that.options.closeOnEscape) { + that.close(that.options.revert); + } + + // OK on Enter key + if (that.opened && event.keyCode === 13 && that.options.okOnEnter) { + that.close(); + } + }); + + // Close (with OK) on tab key in element + that.element.keydown(function (event) { + if (event.keyCode === 9) { + that.close(); + } + }).keyup(function (event) { + var color = that._parseColor(that.element.val()); + if (!that.color.equals(color)) { + that.color = color; + that._change(); + } + }); + }, + + _generate: function () { + var that = this, + index, + part, + parts_list, + layout_parts, + table, + classes; + + that._setColor(that.inline || !that.element.is('input') ? that.options.color : that.element.val()); + + that[that.inline ? '_generateInline' : '_generatePopup'](); + + // Determine the parts to include in this colorpicker + if (typeof that.options.parts === 'string') { + if ($.colorpicker.partslists[that.options.parts]) { + parts_list = $.colorpicker.partslists[that.options.parts]; + } else { + // automatic + parts_list = $.colorpicker.partslists[that.inline ? 'inline' : 'popup']; + } + } else { + parts_list = that.options.parts; + } + + // Add any parts to the internal parts list + that.parts = {}; + $.each(parts_list, function(index, part) { + if ($.colorpicker.parts[part]) { + that.parts[part] = new $.colorpicker.parts[part](that); + } + }); + + if (!that.generated) { + layout_parts = []; + + $.each(that.options.layout, function(part, pos) { + if (that.parts[part]) { + layout_parts.push({ + 'part': part, + 'pos': pos + }); + } + }); + + table = $(_layoutTable(layout_parts, function(cell, x, y) { + classes = ['ui-colorpicker-' + cell.part + '-container']; + + if (x > 0) { + classes.push('ui-colorpicker-padding-left'); + } + + if (y > 0) { + classes.push('ui-colorpicker-padding-top'); + } + + return ' 1 ? ' colspan="' + cell.pos[2] + '"' : '') + + (cell.pos[3] > 1 ? ' rowspan="' + cell.pos[3] + '"' : '') + + ' valign="top">'; + })).appendTo(that.dialog); + if (that.options.inlineFrame) { + table.addClass('ui-dialog-content ui-widget-content'); + } + + that._initAllParts(); + that._updateAllParts(); + that.generated = true; + } + }, + + _effectGeneric: function (element, show, slide, fade, callback) { + var that = this; + + if ($.effects && $.effects[that.options.showAnim]) { + element[show](that.options.showAnim, that.options.showOptions, that.options.duration, callback); + } else { + element[(that.options.showAnim === 'slideDown' ? + slide + : (that.options.showAnim === 'fadeIn' ? + fade + : show))]((that.options.showAnim ? that.options.duration : null), callback); + if (!that.options.showAnim || !that.options.duration) { + callback(); + } + } + }, + + _effectShow: function(element, callback) { + this._effectGeneric(element, 'show', 'slideDown', 'fadeIn', callback); + }, + + _effectHide: function(element, callback) { + this._effectGeneric(element, 'hide', 'slideUp', 'fadeOut', callback); + }, + + open: function() { + var that = this, + offset, + bottom, right, + height, width, + x, y, + zIndex, + hiddenPlaceholder; + + if (!that.opened) { + that._generate(); + + if (that.element.is(':hidden')) { + hiddenPlaceholder = $('
    ').insertBefore(that.element); + offset = hiddenPlaceholder.offset(); + hiddenPlaceholder.remove(); + } else { + offset = that.element.offset(); + } + bottom = $(window).height() + $(window).scrollTop(); + right = $(window).width() + $(window).scrollLeft(); + height = that.dialog.outerHeight(false); + width = that.dialog.outerWidth(); + x = offset.left; + y = offset.top + that.element.outerHeight(false); + + if (x + width > right) { + x = Math.max(0, right - width); + } + + if (y + height > bottom) { + if (offset.top - height >= $(window).scrollTop()) { + y = offset.top - height; + } else { + y = Math.max(0, bottom - height); + } + } + + that.dialog.css({'left': x, 'top': y}); + + // Automatically find highest z-index. + zIndex = 0; + $(that.element[0]).parents().each(function() { + var z = $(this).css('z-index'); + if ((typeof(z) === 'number' || typeof(z) === 'string') && z !== '' && !isNaN(z)) { + zIndex = parseInt(z, 10); + return false; + } + }); + + //@todo zIndexOffset option, to raise above other elements? + that.dialog.css('z-index', zIndex += 2); + + that.overlay = that.options.modal ? new $.ui.dialog.overlay(that) : null; + + that._effectShow(this.dialog); + that.opened = true; + that._callback('open', true); + + // Without waiting for domready the width of the map is 0 and we + // wind up with the cursor stuck in the upper left corner + $(function() { + that._repaintAllParts(); + }); + } + }, + + close: function (cancel) { + var that = this; + + if (cancel) { + that.color = that.currentColor.copy(); + that._change(that.color.set); + that._callback('cancel', true); + } else { + that.currentColor = that.color.copy(); + that._callback('ok', true); + } + that.changed = false; + + // tear down the interface + that._effectHide(that.dialog, function () { + that.dialog.remove(); + that.dialog = null; + that.generated = false; + + that.opened = false; + that._callback('close', true); + }); + + if (that.overlay) { + that.overlay.destroy(); + } + }, + + destroy: function() { + this.element.unbind(); + + if (this.image !== null) { + this.image.remove(); + } + + if (this.button !== null) { + this.button.remove(); + } + + if (this.dialog !== null) { + this.dialog.remove(); + } + + if (this.overlay) { + this.overlay.destroy(); + } + }, + + _callback: function (callback, spaces) { + var that = this, + data, + lab; + + if (that.color.set) { + data = { + formatted: that._formatColor(that.options.colorFormat, that.color) + }; + + lab = that.color.getLAB(); + lab.a = (lab.a * 2) - 1; + lab.b = (lab.b * 2) - 1; + + if (spaces === true) { + data.a = that.color.getAlpha(); + data.rgb = that.color.getRGB(); + data.hsv = that.color.getHSV(); + data.cmyk = that.color.getCMYK(); + data.hsl = that.color.getHSL(); + data.lab = lab; + } + + return that._trigger(callback, null, data); + } else { + return that._trigger(callback, null, { + formatted: '' + }); + } + }, + + _initAllParts: function () { + $.each(this.parts, function (index, part) { + if (part.init) { + part.init(); + } + }); + }, + + _updateAllParts: function () { + $.each(this.parts, function (index, part) { + if (part.update) { + part.update(); + } + }); + }, + + _repaintAllParts: function () { + $.each(this.parts, function (index, part) { + if (part.repaint) { + part.repaint(); + } + }); + }, + + _change: function (set /* = true */) { + this.color.set = (set !== false); + + this.changed = true; + + // Limit color palette + if (this.options.limit && $.colorpicker.limits[this.options.limit]) { + $.colorpicker.limits[this.options.limit](this.color, this); + } + + // update input element content + if (!this.inline) { + if (!this.color.set) { + this.element.val(''); + } else if (!this.color.equals(this._parseColor(this.element.val()))) { + this.element.val(this._formatColor(this.options.colorFormat, this.color)); + } + + this._setImageBackground(); + this._setAltField(); + } + + // update color option + this.options.color = this.color.set ? this.color.toCSS() : ''; + + if (this.opened) { + this._repaintAllParts(); + } + + // callback + this._callback('select'); + }, + + // This will be deprecated by jQueryUI 1.9 widget + _hoverable: function (e) { + e.hover(function () { + e.addClass("ui-state-hover"); + }, function () { + e.removeClass("ui-state-hover"); + }); + }, + + // This will be deprecated by jQueryUI 1.9 widget + _focusable: function (e) { + e.focus(function () { + e.addClass("ui-state-focus"); + }).blur(function () { + e.removeClass("ui-state-focus"); + }); + }, + + _getRegional: function(name) { + return $.colorpicker.regional[this.options.regional][name] !== undefined ? + $.colorpicker.regional[this.options.regional][name] : $.colorpicker.regional[''][name]; + }, + + _getSwatches: function() { + if (typeof(this.options.swatches) === 'string') { + return $.colorpicker.swatches[this.options.swatches]; + } + + if ($.isPlainObject(this.options.swatches)) { + return $.colorpicker.swatches; + } + + return $.colorpicker.swatches.html; + }, + + _getSwatch: function(name) { + var swatches = this._getSwatches(), + swatch = false; + + if (swatches[name] !== undefined) { + return swatches[name]; + } + + $.each(swatches, function(swatchName, current) { + if (swatchName.toLowerCase() == name.toLowerCase()) { + swatch = current; + return false; + } + return true; + }); + + return swatch; + }, + + _parseColor: function(color) { + var that = this, + c; + + $.each($.colorpicker.parsers, function(name, parser) { + c = parser(color, that); + if (c) { + return false; + } + }); + + if (c) { + return c; + } + + return new $.colorpicker.Color(); + }, + + _exactName: function(color) { + var name = false; + + $.each(this._getSwatches(), function(n, swatch) { + if (color.equals(new $.colorpicker.Color(swatch.r, swatch.g, swatch.b))) { + name = n; + return false; + } + return true; + }); + + return name; + }, + + _closestName: function(color) { + var rgb = color.getRGB(), + distance = null, + name = false, + d; + + $.each(this._getSwatches(), function(n, swatch) { + d = color.distance(new $.colorpicker.Color(swatch.r, swatch.g, swatch.b)); + if (d < distance || distance === null) { + name = n; + if (d === 0) { + return false; // can't get much closer than 0 + } + distance = d; + } + return true; + }); + + return name; + }, + + _formatColor: function (formats, color) { + var that = this, + text = null, + types = { 'x': function(v) {return _intToHex(v * 255);} + , 'd': function(v) {return Math.floor(v * 255);} + , 'f': function(v) {return v;} + , 'p': function(v) {return v * 100;} + }, + channels = color.getChannels(); + + if (!$.isArray(formats)) { + formats = [formats]; + } + + $.each(formats, function(index, format) { + if ($.colorpicker.writers[format]) { + text = $.colorpicker.writers[format](color, that); + return (text === false); + } else { + text = format.replace(/\\?[argbhsvcmykLAB][xdfp]/g, function(m) { + if (m.match(/^\\/)) { + return m.slice(1); + } + return types[m.charAt(1)](channels[m.charAt(0)]); + }); + return false; + } + }); + + return text; + } + }); +}(jQuery)); diff --git a/admin/view/javascript/shopunity/colorpicker/parts/jquery.ui.colorpicker-memory.js b/admin/view/javascript/shopunity/colorpicker/parts/jquery.ui.colorpicker-memory.js new file mode 100755 index 0000000..6ef647c --- /dev/null +++ b/admin/view/javascript/shopunity/colorpicker/parts/jquery.ui.colorpicker-memory.js @@ -0,0 +1,64 @@ +;jQuery(function($) { + $.colorpicker.parts.memory = function (inst) { + var that = this, + container, + selectNode = function(node) { + inst._setColor($(node).css('backgroundColor')); + inst._change(); + }, + deleteNode = function(node) { + node.remove(); + }, + addNode = function(color) { + var $node = $('
    ').addClass('ui-colorpicker-swatch').css('backgroundColor', color); + $node.mousedown(function(e) { + e.stopPropagation(); + switch (e.which) { + case 1: + selectNode(this); + break; + case 3: + deleteNode($node); + setMemory(); + break; + } + }).bind('contextmenu', function(e) { + e.preventDefault(); + }); + + container.append($node); + }, + getMemory = function() { + return (document.cookie.match(/\bcolorpicker-memory=([^;]*)/) || [0, ''])[1].split(','); + }; + setMemory = function() { + var colors = []; + $('> *', container).each(function() { + colors.push(escape($(this).css('backgroundColor'))); + }); + var expdate=new Date(); + expdate.setDate(expdate.getDate() + (365 * 10)); + document.cookie = 'colorpicker-memory='+colors.join()+";expires="+expdate.toUTCString(); + }; + + this.init = function () { + container = $('
    ') + .addClass('ui-colorpicker-memory ui-colorpicker-border ui-colorpicker-swatches') + .css({ + width: 84, + height: 84, + cursor: 'crosshair' + }) + .appendTo($('.ui-colorpicker-memory-container', inst.dialog)); + + $.each(getMemory(), function() { + addNode(unescape(this)); + }); + + container.mousedown(function(e) { + addNode(inst.color.toCSS()); + setMemory(); + }); + }; + }; +}); \ No newline at end of file diff --git a/admin/view/javascript/shopunity/colorpicker/parts/jquery.ui.colorpicker-rgbslider.js b/admin/view/javascript/shopunity/colorpicker/parts/jquery.ui.colorpicker-rgbslider.js new file mode 100755 index 0000000..0055d1b --- /dev/null +++ b/admin/view/javascript/shopunity/colorpicker/parts/jquery.ui.colorpicker-rgbslider.js @@ -0,0 +1,81 @@ +;jQuery(function($) { + /** + * Set a horizontal gradient background image on an element. + * Uses the now-deprecated $.browser + * @param $ element + * @param $.colorpicker.Color startColor + * @param $.colorpicker.Color endColor + * @returns {undefined} + */ + function setGradient(element, startColor, endColor) { + var start = startColor.toCSS(), + end = endColor.toCSS(), + prefixes = { + mozilla: '-moz-', + webkit: '-webkit-', + msie: '-ms-', + opera: '-o-' + }, + prefix = ''; + + $.each(prefixes, function(key, p) { + if ($.browser[key]) { + prefix = p; + return false; + } + }); + + element.css('background-image', prefix+'linear-gradient(left, '+start+' 0%, '+end+' 100%)'); + } + + $.colorpicker.parts.rgbslider = function (inst) { + var that = this, + sliders = { r: $('
    '), + g: $('
    '), + b: $('
    ') + }; + + this.init = function () { + $('
    ').append(sliders.r, sliders.g, sliders.b) + .appendTo($('.ui-colorpicker-rgbslider-container', inst.dialog)); + + function refresh() { + var min, + max, + r = sliders.r.slider('value') / 255, + g = sliders.g.slider('value') / 255, + b = sliders.b.slider('value') / 255; + + inst.color.setRGB(r, g, b); + + setGradient(sliders.r, new $.colorpicker.Color(0, g, b), new $.colorpicker.Color(1, g, b)); + setGradient(sliders.g, new $.colorpicker.Color(r, 0, b), new $.colorpicker.Color(r, 1, b)); + setGradient(sliders.b, new $.colorpicker.Color(r, g, 0), new $.colorpicker.Color(r, g, 1)); + + inst._change(); + } + + $(sliders.r).add(sliders.g).add(sliders.b).slider({ + min: 0, + max: 255, + step: 1, + slide: refresh, + change: refresh + }); + }; + + this.repaint = function () { + $.each(inst.color.getRGB(), function (index, value) { + var input = sliders[index]; + value = Math.round(value * 255); + if (input.slider('value') !== value) { + input.slider('value', value); + } + }); + }; + + this.update = function () { + this.repaint(); + }; + }; +}); \ No newline at end of file diff --git a/admin/view/javascript/shopunity/jquery.autosize.min.js b/admin/view/javascript/shopunity/jquery.autosize.min.js new file mode 100755 index 0000000..8d8cccb --- /dev/null +++ b/admin/view/javascript/shopunity/jquery.autosize.min.js @@ -0,0 +1,4 @@ +// Autosize 1.15.2 - jQuery plugin for textareas +// (c) 2013 Jack Moore - jacklmoore.com +// license: www.opensource.org/licenses/mit-license.php +(function(a){var j,b={className:"autosizejs",append:"",callback:!1},c="hidden",d="border-box",e="lineHeight",f=' +
    +
    + + + +
    +
    + +
    +
    + +
    +
    + + + +
    \ No newline at end of file diff --git a/catalog/view/theme/default/template/d_quickcheckout/login.tpl b/catalog/view/theme/default/template/d_quickcheckout/login.tpl new file mode 100755 index 0000000..ad58968 --- /dev/null +++ b/catalog/view/theme/default/template/d_quickcheckout/login.tpl @@ -0,0 +1,250 @@ + + + +
    + + +
    + + + + + +
    + + + + + + +
    + + +
    + +
    + + + + + + + + +
    +
    +
    +
    + + + + +
    +
    +
    + +
    + +
    + +
    +
    +
    +
    + + +
    +
    + +
    + + + +
    + + +
    + +
    +
    +
    +
    +
    +
    + + + + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    + + + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + +
    + + + \ No newline at end of file diff --git a/catalog/view/theme/default/template/d_quickcheckout/payment.tpl b/catalog/view/theme/default/template/d_quickcheckout/payment.tpl new file mode 100755 index 0000000..2cd2ede --- /dev/null +++ b/catalog/view/theme/default/template/d_quickcheckout/payment.tpl @@ -0,0 +1,15 @@ + + +
    +
    +
    +
    +
    +
    +
    +
    +
    + diff --git a/catalog/view/theme/default/template/d_quickcheckout/payment_address.tpl b/catalog/view/theme/default/template/d_quickcheckout/payment_address.tpl new file mode 100755 index 0000000..fe9e822 --- /dev/null +++ b/catalog/view/theme/default/template/d_quickcheckout/payment_address.tpl @@ -0,0 +1,200 @@ + + +
    > +
    +
    + + +
    +
    +
    + + registry->get('customer')->isLogged()) { ?> + + +
    + +
    + class="styled" data-refresh="2" autocomplete='off' /> + +
    + +
    + class="styled" data-refresh="2" autocomplete='off' /> + +
    +
    + +
    +
    + class="styled" data-refresh="1" autocomplete='off' /> + +
    +
    +
    + +
    +
    +
    + class="styled" data-refresh="1" autocomplete='off' /> + +
    +
    + + +
    + +
    +
    +
    +
    +'; +// print_r($this->session->data['payment_address']); +// echo ''; +?> + diff --git a/catalog/view/theme/default/template/d_quickcheckout/payment_method.tpl b/catalog/view/theme/default/template/d_quickcheckout/payment_method.tpl new file mode 100755 index 0000000..493e7a1 --- /dev/null +++ b/catalog/view/theme/default/template/d_quickcheckout/payment_method.tpl @@ -0,0 +1,82 @@ + +
    > + +
    + + +
    +
    + + +
    +
    +

    +
    + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + +
    +'; +// print_r($this->session->data['payment_methods']); +// echo ''; +?> +'; +// print_r($this->session->data['payment_method']); +// echo ''; +?> + diff --git a/catalog/view/theme/default/template/d_quickcheckout/shipping_address.tpl b/catalog/view/theme/default/template/d_quickcheckout/shipping_address.tpl new file mode 100755 index 0000000..98ef46a --- /dev/null +++ b/catalog/view/theme/default/template/d_quickcheckout/shipping_address.tpl @@ -0,0 +1,134 @@ + +
    > +
    +
    + + +
    +
    +
    + + registry->get('customer')->isLogged()) { ?> + +
    + +
    + class="styled" data-refresh="2" autocomplete='off' /> + +
    + +
    + class="styled" data-refresh="2" autocomplete='off' /> + +
    +
    + +
    +
    + class="styled" data-refresh="3" autocomplete='off' /> + +
    +
    + +
    + +
    +
    +
    + class="styled" data-refresh="3" autocomplete='off' /> + +
    +
    + + +
    + +
    + +
    +
    +
    +'; +// print_r($this->session->data['shipping_address']); +// echo ''; +?> + \ No newline at end of file diff --git a/catalog/view/theme/default/template/d_quickcheckout/shipping_method.tpl b/catalog/view/theme/default/template/d_quickcheckout/shipping_method.tpl new file mode 100755 index 0000000..4fa83a1 --- /dev/null +++ b/catalog/view/theme/default/template/d_quickcheckout/shipping_method.tpl @@ -0,0 +1,105 @@ + +
    > + +
    + + + + +
    +
    + + + + +
    +
    +

    + +
    + + +
    + +
    + + + + + +
    + + + +
    + +
    + + +
    + + + + + + +
    +
    +
    +
    + + +
    +'; +// print_r($this->session->data['shipping_methods']); +// echo ''; +?> +'; +// print_r($this->session->data['shipping_address']); +// echo ''; +?> + + + + + + + diff --git a/catalog/view/theme/default/template/module/d_quickcheckout.tpl b/catalog/view/theme/default/template/module/d_quickcheckout.tpl new file mode 100755 index 0000000..8711c9a --- /dev/null +++ b/catalog/view/theme/default/template/module/d_quickcheckout.tpl @@ -0,0 +1,743 @@ + + + + + +
    +
    + +
    +
    + + Processing payment... Please wait +
    +
    + + + +
    +
    + +
    + $step){ ?> +
    + +
    + +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    + diff --git a/image/data/payment/authorizenet_aim.png b/image/data/payment/authorizenet_aim.png new file mode 100755 index 0000000..69d232d Binary files /dev/null and b/image/data/payment/authorizenet_aim.png differ diff --git a/image/data/payment/bank_transfer.png b/image/data/payment/bank_transfer.png new file mode 100755 index 0000000..e7b37dd Binary files /dev/null and b/image/data/payment/bank_transfer.png differ diff --git a/image/data/payment/cheque.png b/image/data/payment/cheque.png new file mode 100755 index 0000000..2a5012c Binary files /dev/null and b/image/data/payment/cheque.png differ diff --git a/image/data/payment/cod.png b/image/data/payment/cod.png new file mode 100755 index 0000000..18d792d Binary files /dev/null and b/image/data/payment/cod.png differ diff --git a/image/data/payment/liqpay.png b/image/data/payment/liqpay.png new file mode 100755 index 0000000..fc3d05e Binary files /dev/null and b/image/data/payment/liqpay.png differ diff --git a/image/data/payment/moneybookers.png b/image/data/payment/moneybookers.png new file mode 100755 index 0000000..6c8828a Binary files /dev/null and b/image/data/payment/moneybookers.png differ diff --git a/image/data/payment/nochex.png b/image/data/payment/nochex.png new file mode 100755 index 0000000..88eb9fe Binary files /dev/null and b/image/data/payment/nochex.png differ diff --git a/image/data/payment/paymate.png b/image/data/payment/paymate.png new file mode 100755 index 0000000..4caf4c8 Binary files /dev/null and b/image/data/payment/paymate.png differ diff --git a/image/data/payment/paypoint.png b/image/data/payment/paypoint.png new file mode 100755 index 0000000..522e997 Binary files /dev/null and b/image/data/payment/paypoint.png differ diff --git a/image/data/payment/payza.png b/image/data/payment/payza.png new file mode 100755 index 0000000..210a299 Binary files /dev/null and b/image/data/payment/payza.png differ diff --git a/image/data/payment/pp_express.png b/image/data/payment/pp_express.png new file mode 100755 index 0000000..5ea9a02 Binary files /dev/null and b/image/data/payment/pp_express.png differ diff --git a/image/data/payment/pp_pro.png b/image/data/payment/pp_pro.png new file mode 100755 index 0000000..5ea9a02 Binary files /dev/null and b/image/data/payment/pp_pro.png differ diff --git a/image/data/payment/pp_pro_uk.png b/image/data/payment/pp_pro_uk.png new file mode 100755 index 0000000..dff01a4 Binary files /dev/null and b/image/data/payment/pp_pro_uk.png differ diff --git a/image/data/payment/pp_standard.png b/image/data/payment/pp_standard.png new file mode 100755 index 0000000..5ea9a02 Binary files /dev/null and b/image/data/payment/pp_standard.png differ diff --git a/image/data/payment/sagepay.png b/image/data/payment/sagepay.png new file mode 100755 index 0000000..5c4e5ae Binary files /dev/null and b/image/data/payment/sagepay.png differ diff --git a/image/data/payment/sagepay_direct.png b/image/data/payment/sagepay_direct.png new file mode 100755 index 0000000..5c4e5ae Binary files /dev/null and b/image/data/payment/sagepay_direct.png differ diff --git a/image/data/payment/sagepay_us.png b/image/data/payment/sagepay_us.png new file mode 100755 index 0000000..5c4e5ae Binary files /dev/null and b/image/data/payment/sagepay_us.png differ diff --git a/image/data/payment/twocheckout.png b/image/data/payment/twocheckout.png new file mode 100755 index 0000000..96c246e Binary files /dev/null and b/image/data/payment/twocheckout.png differ diff --git a/image/data/payment/web_payment_software.png b/image/data/payment/web_payment_software.png new file mode 100755 index 0000000..5d6cd6d Binary files /dev/null and b/image/data/payment/web_payment_software.png differ diff --git a/image/data/payment/worldpay.png b/image/data/payment/worldpay.png new file mode 100755 index 0000000..47fbf49 Binary files /dev/null and b/image/data/payment/worldpay.png differ diff --git a/system/config/d_quickcheckout.php b/system/config/d_quickcheckout.php new file mode 100755 index 0000000..353d313 --- /dev/null +++ b/system/config/d_quickcheckout.php @@ -0,0 +1,1188 @@ + array( + 'enable' => 0, + 'min_order' => array('value' => 0, 'text' => array(1 => 'You must have a sum more then %s to make an order ')), + 'min_quantity' => array('value' => 0, 'text' => array(1 => 'You must have a quantity more then %s to make an order ')), + 'main_checkout' => 1, + //'default_email' => $this->config->get('config_email'), + 'default_option' => 'guest', + 'socila_login_style' => 'icons', + 'debug' => 0, + 'store_id' => 0, + 'clear_session' => 0, + 'login_refresh' => 0, + 'settings' => array('value' => 0, 'bulk' => ''), + 'social_login' => array( + 'size' => '', + 'providers' => array() + ), + 'trigger' => '#confirm_payment .button, #confirm_payment .btn, #confirm_payment .button_oc, #confirm_payment input[type=submit]' + ), + 'design' => array( + 'theme' => 'default', + 'column_width' => array(1 => '40', 2 => '30', 3 => '30', 4 => '60'), + 'login_style' => 'popup', + 'address_style' => 'radio', + 'block_style' => 'row', + 'uniform' => 0, + 'max_width' => '', + 'only_quickcheckout' => 0, + 'cart_image_size' => array('width' => 150, 'height' => 150), + 'custom_style' => '', + ), + 'step' => array( + 'login' => array( + 'sort_order' => 1, + 'column' => 0, + 'row' => 0, + 'width' => '50', + 'option' => array('register' => array('title' => 'text_register', + 'description' => 'text_register_account', + 'display' => 1 + ), + 'guest' => array('title' => 'text_guest', + 'description' => 'step_option_guest_desciption', + 'display' => 1 + ), + 'login' => array('display' => 1 + ) + ) + + ), + 'payment_address' => array( + 'sort_order' => '2', + 'column' => 1, + 'row' => 1, + 'width' => '50', + 'fields' => array( + 'firstname' => array( + 'id' => 'firstname', + 'title' => 'entry_firstname', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'max_length' => 32, + 'text' => 'error_firstname')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 1, + 'class' => '' + ), + 'lastname' => array( + 'id' => 'lastname', + 'title' => 'entry_lastname', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'max_length' => 32, + 'text' => 'error_lastname')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 2, + 'class' => '' + ), + 'email' => array( + 'id' => 'email', + 'title' => 'entry_email', + 'tooltip' => '', + + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 3, + 'class' => '' + ), + 'email_confirm' => array( + 'id' => 'email_confirm', + 'title' => 'entry_email_confirm', + 'tooltip' => '', + 'error' => array(0 => array('compare_to' => 'payment_address[email]', + 'text' => 'error_email_confirm')), + + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 3, + 'class' => '' + ), + 'telephone' => array( + 'id' => 'telephone', + 'title' => 'entry_telephone', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 32, + 'text' => 'error_telephone')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + + 'display' => 0, + 'require' => 0, + 'sort_order' => 4, + 'class' => '' + ), + 'fax' => array( + 'id' => 'fax', + 'title' => 'entry_fax', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 32, + 'text' => 'error_telephone')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 5, + 'class' => '' + ), + 'password' => array( + 'id' => 'password', + 'title' => 'entry_password', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 20, + 'text' => 'error_password')), + 'type' => 'password', + 'refresh' => '3', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 6, + 'class' => '' + ), + 'confirm' => array( + 'id' => 'confirm', + 'title' => 'entry_confirm', + 'tooltip' => '', + 'error' => array(0 => array('compare_to' => 'payment_address[password]', + 'text' => 'error_confirm'), + 1 => array('min_length' => '1', + 'text' => 'error_confirm')), + 'type' => 'password', + 'refresh' => '3', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 7, + 'class' => '' + ), + 'heading' => array( + 'id' => 'heading', + 'title' => 'text_your_address', + 'type' => 'heading', + 'display' => 0, + 'sort_order' => 8, + 'class' => '' + ), + 'company' => array( + 'id' => 'company', + 'title' => 'entry_company', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 34, + 'text' => 'error_step_payment_address_fields_company')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 9, + 'class' => '' + ), + 'customer_group_id' => array( + 'id' => 'customer_group_id', + 'title' => 'entry_customer_group', + 'tooltip' => '', + 'type' => 'radio', + 'refresh' => '2', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 12, + 'class' => '' + ), + 'address_1' => array( + 'id' => 'address_1', + 'title' => 'entry_address_1', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 128, + 'text' => 'error_address_1')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 13, + 'class' => '' + ), + 'address_2' => array( + 'id' => 'address_2', + 'title' => 'entry_address_2', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 128, + 'text' => 'error_address_1')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 14, + 'class' => '' + ), + 'city' => array( + 'id' => 'city', + 'title' => 'entry_city', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 128, + 'text' => 'error_city')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 15, + 'class' => '' + ), + 'postcode' => array( + 'id' => 'postcode', + 'title' => 'entry_postcode', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 2, + 'max_length' => 10, + 'text' => 'error_postcode')), + 'type' => 'text', + 'refresh' => '3', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 16, + 'class' => '' + ), + 'country_id' => array( + 'id' => 'country_id', + 'title' => 'entry_country', + 'tooltip' => '', + 'error' => array(0 => array('not_empty' => true, + 'text' => 'error_country')), + 'type' => 'select', + 'refresh' => '3', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 17, + 'class' => '' + ), + 'zone_id' => array( + 'id' => 'zone_id', + 'title' => 'entry_zone', + 'tooltip' => '', + 'error' => array(0 => array('not_empty' => true, 'text' => 'error_zone')), + 'type' => 'select', + 'refresh' => '3', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 18, + 'class' => '' + ), + 'newsletter' => array( + 'id' => 'newsletter', + 'title' => 'entry_newsletter', + 'tooltip' => '', + 'error' => array(0 => array('checked' => true, + 'text' => array(1 => 'You must subsribe to our newsletter to make the order'))), + 'type' => 'checkbox', + 'custom' => 0, + 'class' => '', + 'refresh' => '0', + 'display' => 0, + 'require' => 0, + 'sort_order' => 19, + 'value' => '1' + ), + 'shipping' => array( + 'id' => 'shipping', + 'title' => 'entry_shipping', + 'tooltip' => '', + 'error' => array(0 => array('checked' => true, + 'text' => 'error_step_payment_address_fields_shipping')), + 'type' => 'checkbox', + 'refresh' => '3', + 'custom' => 0, + 'display' => 0, + 'sort_order' => 20, + 'class' => '', + 'value' => 1, + ), + 'agree' => array( + 'id' => 'agree', + 'title' => 'text_agree', + //'information_id' => $this->config->get('config_account_id'), + 'tooltip' => '', + 'error' => array(0 => array('checked' => true, + 'text' => 'error_agree', + //'information_id' => $this->config->get('config_account_id') + )), + 'type' => 'checkbox', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 21, + 'class' => '' + ) + + ) + ), + 'shipping_address' => array( + 'sort_order' => '3', + 'column' => 1, + 'row' => 2, + 'width' => '30', + 'fields' => array( + 'firstname' => array( + 'id' => 'firstname', + 'title' => 'entry_firstname', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'max_length' => 32, + 'text' => 'error_firstname')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 1, + 'class' => '' + ), + 'lastname' => array( + 'id' => 'lastname', + 'title' => 'entry_lastname', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'max_length' => 32, + 'text' => 'error_lastname')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 2, + 'class' => '' + ), + 'company' => array( + 'id' => 'company', + 'title' => 'entry_company', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 32, + 'text' => 'error_step_shipping_address_fields_company')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 3, + 'class' => '' + ), + 'address_1' => array( + 'id' => 'address_1', + 'title' => 'entry_address_1', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 128, + 'text' => 'error_address_1')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 4, + 'class' => '' + ), + 'address_2' => array( + 'id' => 'address_2', + 'title' => 'entry_address_2', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 128, + 'text' => 'error_address_1')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 5, + 'class' => '' + ), + 'city' => array( + 'id' => 'city', + 'title' => 'entry_city', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 128, + 'text' => 'error_city')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 6, + 'class' => '' + ), + 'postcode' => array( + 'id' => 'postcode', + 'title' => 'entry_postcode', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 2, + 'max_length' => 10, + 'text' => 'error_postcode')), + 'type' => 'text', + 'refresh' => '0', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 7, + 'class' => '' + ), + 'country_id' => array( + 'id' => 'country_id', + 'title' => 'entry_country', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'text' => 'error_country')), + 'type' => 'select', + 'refresh' => '4', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 8, + 'class' => '' + ), + 'zone_id' => array( + 'id' => 'zone_id', + 'title' => 'entry_zone', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'text' => 'error_zone')), + 'type' => 'select', + 'refresh' => '4', + 'custom' => 0, + 'display' => 0, + 'require' => 0, + 'sort_order' => 9, + 'class' => '' + ) + ) + ), + 'shipping_method' => array( + 'sort_order' => 4, + 'column' => 2, + 'row' => 1, + 'display' => 1, + 'input_style' => 'radio', + 'display_title' => 1, + 'display_desciption' => 1, + 'display_options' => 1, + 'width' => '30', + 'default_option' => '' + + ), + 'payment_method' =>array( + 'sort_order' => 5, + 'column' => 3, + 'row' => 1, + 'display' => 1, + 'display_options' => 1, + 'display_images' => 1, + 'input_style' => 'radio', + 'display_logos' => 1, + 'width' => '30', + 'default_option' => '' + ), + 'cart' => array( + 'sort_order' => 6, + 'column' => 4, + 'row' => 2, + 'display_title' => 1, + 'display_description' => 1, + 'width' => '50', + 'option' => array( + 'voucher' => array( + 'id' => 'voucher', + 'title' => array(1 => 'voucher'), + 'tooltip' => array(1 => 'voucher'), + 'type' => 'text', + 'refresh' => '3', + 'custom' => 0, + 'class' => '' + ), + 'coupon' => array( + 'id' => 'coupon', + 'title' => array(1 => 'coupon'), + 'tooltip' => array(1 => 'coupon'), + 'type' => 'text', + 'refresh' => '3', + 'custom' => 0, + 'class' => '' + ), + 'reward' => array( + 'id' => 'reward', + 'title' => array(1 => 'reward'), + 'tooltip' => array(1 => 'reward'), + 'type' => 'text', + 'refresh' => '3', + 'custom' => 0, + 'class' => '' + ) + ), + ), + 'payment' => array( + 'sort_order' => 7, + 'column' => 4, + 'row' => 2, + 'width' => '50' + ), + 'confirm' => array( + 'sort_order' => 8, + 'column' => 4, + 'row' => 2, + 'width' => '50', + 'fields' => array( + 'comment' => array( + 'id' => 'comment', + 'title' => 'text_comments', + 'tooltip' => '', + 'error' => array(0 => array('min_length' => 1, + 'text' => 'error_step_confirm_fields_comment')), + 'type' => 'textarea', + 'refresh' => '0', + 'custom' => 0, + 'class' => '' + ), + 'agree' => array( + 'id' => 'agree', + 'title' => 'text_agree', + //'information_id' => $this->config->get('config_checkout_id'), + 'tooltip' => '', + 'error' => array(0 => array('checked' => true, + 'text' => 'error_agree', + //'information_id' => $this->config->get('config_checkout_id') + )), + 'type' => 'checkbox', + 'refresh' => '0', + 'value' => 0, + 'custom' => 0, + 'class' => '' + ) + + + ) + ) + ), + 'option' => array( + 'register' => array( + 'display' => 1, + 'login' => array(), + 'payment_address' => array( + 'display' => 1, + 'title' => 'text_your_details', + 'description' => 'option_register_payment_address_description', + 'fields' => array( + 'firstname' => array('display' => 1, + 'require' => 1, + 'value' => '' + ), + 'lastname' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'email' => array( 'display' => 1, + 'require' => 1, + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 96, + 'text' => array(1 => 'Sorry, but you need to have the length of the text more then 3 and less then 96 ')), + 1 => array('regex' => '/^[^\@]+@.*\.[a-z]{2,6}$/i', + 'text' => 'error_email'), + 2 => array('email_exists' => true, + 'text' => 'error_exists'), + 3 => array('not_empty' => true, + 'text' => 'error_email') + ), + 'value' => '' + ), + 'email_confirm' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'heading' => array( + 'display' => 1, + 'value' => '' + ), + 'telephone' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'fax' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'password' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'confirm' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'company' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'customer_group_id' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'address_1' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'address_2' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'city' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'postcode' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'country_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'zone_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'newsletter' => array( + 'display' => 1, + 'require' => 0, + 'value' => '0' + ), + 'shipping' => array( + 'display' => 1, + 'value' => 1 + ), + 'agree' => array( + 'display' => 1, + 'require' => 0, + 'value' => '0' + ) + + ) + ), + 'shipping_address' => array( + 'display' => 1, + 'require' => 0, + 'title' => 'option_register_shipping_address_title', + 'description' => 'option_register_shipping_address_description', + 'fields' => array( + 'firstname' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'lastname' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'company' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'address_1' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'address_2' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'city' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'postcode' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'country_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'zone_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ) + ) + ), + 'shipping_method' => array( + 'title' => 'option_register_shipping_method_title', + 'description' => 'text_shipping_method', + ), + 'payment_method' =>array( + 'title' => 'option_register_payment_method_title', + 'description' => 'text_payment_method', + ), + 'cart' => array( + 'display' => 1, + 'title' => 'text_cart', + 'description' => 'option_register_cart_description', + 'option' => array( + 'voucher' => array( + 'display' => 1, + 'value' => '' + ), + 'coupon' => array( + 'display' => 1, + 'value' => '' + ), + 'reward' => array( + 'display' => 1, + 'value' => '' + ) + ), + 'columns' => array( + 'image' => 1, + 'name' => 1, + 'model' => 0, + 'quantity' => 1, + 'price' => 1, + 'total' => 1 + ) + ), + 'confirm' => array( + 'display' => 1, + 'fields' => array( + 'comment' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'agree' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ) + ) + ) + ), + 'guest' => array( + 'display' => 1, + 'login' => array(), + 'payment_address' => array( + 'title' => 'text_your_details', + 'description' => 'option_guest_payment_address_description', + 'display' => 1, + 'fields' => array( + 'firstname' => array('display' => 1, + 'require' => 1, + 'value' => '' + ), + 'lastname' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'email' => array( 'display' => 1, + 'require' => 1, + 'error' => array(0 => array('min_length' => 3, + 'max_length' => 96, + 'text' => array(1 => 'Sorry, but you need to have the length of the text more then 3 and less then 96 ')), + 1 => array('regex' => '/^[^\@]+@.*\.[a-z]{2,6}$/i', + 'text' => 'error_email'), + 2 => array('not_empty' => true, + 'text' => 'error_email') + ), + 'value' => '' + ), + 'email_confirm' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'heading' => array( + 'display' => 1, + 'value' => '' + ), + 'telephone' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'fax' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'company' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'customer_group_id' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'address_1' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'address_2' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'city' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'postcode' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'country_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'zone_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'shipping' => array( + 'display' => 1, + 'value' => 1 + ), + 'agree' => array( + 'display' => 1, + 'require' => 0, + 'value' => '0' + ) + ) + ), + 'shipping_address' => array( + 'display' => 1, + 'require' => 0, + 'title' => 'option_guest_shipping_address_title', + 'description' => 'option_guest_shipping_address_description', + 'fields' => array( + 'firstname' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'lastname' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'company' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'address_1' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'address_2' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'city' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'postcode' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'country_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'zone_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ) + ) + ), + 'shipping_method' =>array( + 'title' => 'option_guest_shipping_method_title', + 'description' => 'text_shipping_method', + + + ), + 'payment_method' =>array( + 'title' => 'option_guest_payment_method_title', + 'description' => 'text_payment_method', + ), + 'cart' => array( + 'display' => 1, + 'title' => 'text_cart', + 'description' => 'option_guest_cart_description', + 'option' => array( + 'voucher' => array( + 'display' => 1, + 'value' => '' + ), + 'coupon' => array( + 'display' => 1, + 'value' => '' + ), + 'reward' => array( + 'display' => 1, + 'value' => '' + ) + ), + 'columns' => array( + 'image' => 1, + 'name' => 1, + 'model' => 0, + 'quantity' => 1, + 'price' => 1, + 'total' => 1 + ) + ), + 'confirm' => array( + 'display' => 1, + 'fields' => array( + 'comment' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'agree' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ) + ) + ) + ), + 'logged'=> array( + 'login' => array(), + 'payment_address' => array( + 'display' => 1, + 'title' => 'option_logged_payment_address_title', + 'description' => 'option_logged_payment_address_description', + 'fields' => array( + 'firstname' => array('display' => 1, + 'require' => 1, + 'value' => '' + ), + 'lastname' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'company' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'address_1' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'address_2' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'city' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'postcode' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'country_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'zone_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'shipping' => array( + 'display' => 1, + 'value' => 1 + ), + 'address_id' => array() + ) + ), + 'shipping_address' => array( + 'display' => 1, + 'require' => 0, + 'title' => 'option_logged_shipping_address_title', + 'description' => 'option_logged_shipping_address_description', + 'fields' => array( + 'firstname' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'lastname' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'company' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'address_1' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'address_2' => array( + 'display' => 0, + 'require' => 0, + 'value' => '' + ), + 'city' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'postcode' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'country_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ), + 'zone_id' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ) + ) + ), + 'shipping_method' =>array( + 'title' => 'option_logged_shipping_method_title', + 'description' => 'text_shipping_method', + ), + 'payment_method' =>array( + 'title' => 'option_logged_payment_method_title', + 'description' => 'text_payment_method', + ), + 'cart' => array( + 'display' => 1, + 'title' => 'text_cart', + 'description' => 'option_logged_cart_description', + 'option' => array( + 'voucher' => array( + 'display' => 1, + 'value' => '' + ), + 'coupon' => array( + 'display' => 1, + 'value' => '' + ), + 'reward' => array( + 'display' => 1, + 'value' => '' + ) + ), + 'columns' => array( + 'image' => 1, + 'name' => 1, + 'model' => 0, + 'quantity' => 1, + 'price' => 1, + 'total' => 1 + ) + ), + 'confirm' => array( + 'display' => 1, + 'fields' => array( + 'comment' => array( + 'display' => 1, + 'require' => 0, + 'value' => '' + ), + 'agree' => array( + 'display' => 1, + 'require' => 1, + 'value' => '' + ) + ) + ) + ) + ) + ); +$cfg = $_; +?> \ No newline at end of file diff --git a/system/library/Ubench.php b/system/library/Ubench.php new file mode 100755 index 0000000..b2a25ac --- /dev/null +++ b/system/library/Ubench.php @@ -0,0 +1,148 @@ +start_time = microtime(true); + } + + /** + * Sets end microtime + * + * @return void + */ + public function end() + { + $this->end_time = microtime(true); + $this->memory_usage = memory_get_usage(true); + } + + /** + * Returns the elapsed time, readable or not + * + * @param boolean $readable Whether the result must be human readable + * @param string $format The format to display (printf format) + * @return string|float + */ + public function getTime($raw = false, $format = null) + { + $elapsed = $this->end_time - $this->start_time; + + return $raw ? $elapsed : self::readableElapsedTime($elapsed, $format); + } + + /** + * Returns the memory usage at the end checkpoint + * + * @param boolean $readable Whether the result must be human readable + * @param string $format The format to display (printf format) + * @return string|float + */ + public function getMemoryUsage($raw = false, $format = null) + { + return $raw ? $this->memory_usage : self::readableSize($this->memory_usage, $format); + } + + /** + * Returns the memory peak, readable or not + * + * @param boolean $readable Whether the result must be human readable + * @param string $format The format to display (printf format) + * @return string|float + */ + public function getMemoryPeak($raw = false, $format = null) + { + $memory = memory_get_peak_usage(true); + + return $raw ? $memory : self::readableSize($memory, $format); + } + + /** + * Returns a human readable memory size + * + * @param int $size + * @param string $format The format to display (printf format) + * @param int $round + * @return string + */ + public static function readableSize($size, $format = null, $round = 3) + { + $mod = 1024; + + if (is_null($format)) { + $format = '%.2f%s'; + } + + $units = explode(' ','B Kb Mb Gb Tb'); + + for ($i = 0; $size > $mod; $i++) { + $size /= $mod; + } + + if (0 === $i) { + $format = preg_replace('/(%.[\d]+f)/', '%d', $format); + } + + return sprintf($format, round($size, $round), $units[$i]); + } + + /** + * Returns a human readable elapsed time + * + * @param float $microtime + * @param string $format The format to display (printf format) + * @return string + */ + public static function readableElapsedTime($microtime, $format = null, $round = 3) + { + if (is_null($format)) { + $format = '%.3f%s'; + } + + if ($microtime >= 1) { + $unit = 's'; + $time = round($microtime, $round); + } else { + $unit = 'ms'; + $time = round($microtime*1000); + + $format = preg_replace('/(%.[\d]+f)/', '%d', $format); + } + + return sprintf($format, $time, $unit); + } +} diff --git a/system/mbooth/xml/mbooth_d_quickcheckout_lite.xml b/system/mbooth/xml/mbooth_d_quickcheckout_lite.xml new file mode 100755 index 0000000..f8e4172 --- /dev/null +++ b/system/mbooth/xml/mbooth_d_quickcheckout_lite.xml @@ -0,0 +1,112 @@ + + d_quickcheckout_lite + Ajax Quick Checkout + Ajax Quick Checkout is a sophisticated checkout solution for Opencart, that allows the user to setup the checkout process in the most user-friendly possible way to increase the sales. It removes 6 steps leaving 1 step, creating only one button for all cases. The only solution you will ever need. + module + 5.0.0.0 + 1.5.3x-5x + 1.0 + Dreamvention + + + system/mbooth/xml/mbooth_d_quickcheckout_lite.xml + + admin/controller/module/d_quickcheckout.php + admin/language/english/module/d_quickcheckout.php + admin/view/template/module/d_quickcheckout.tpl + admin/view/stylesheet/d_quickcheckout.css + + catalog/model/d_quickcheckout/order.php + + catalog/controller/module/d_quickcheckout.php + catalog/language/english/module/d_quickcheckout.php + + catalog/view/theme/default/template/checkout/d_quickcheckout.tpl + catalog/view/theme/default/template/module/d_quickcheckout.tpl + + vqmod/xml/a_vqmod_d_quickcheckout.xml + + system/config/d_quickcheckout.php + system/library/Ubench.php + + + + system/library/Monolog + system/library/Psr + admin/view/javascript/shopunity + admin/view/stylesheet/shopunity + catalog/view/javascript/d_quickcheckout + catalog/view/theme/default/image/d_quickcheckout + catalog/view/theme/default/stylesheet/d_quickcheckout + catalog/view/theme/default/template/d_quickcheckout + image/data/payment + + + vqmod + shopunity + + + + + 2. Added new funtion - clear session data + ]]> + + + 2. New iOS theme. + ]]> + + 2. Added new style option for addresses for logged in users + ]]> + + 2. Fixed the Zone_id bug
    + 3. Fixed the Uniform bug
    + 4. Fixed the cart clear styling bug.
    + 5. Removed the first install error.
    + 6. Email empty fix.
    + 7. Comment fix
    + 8. Customer group support
    + 9. Double click of confirm button fix]]>
    + + + + 2. Added Klarna support; ]]> + + 2. Updated the Shopunity admin design. + 3. Added the option of a 4-th column which is a combination of 2 and 3 column. ]]> + + + 2. Update: when logging in with another method, AQC will show avalible addresses.
    + 3. Update: The tigger can now be edited in admin (usefull for special payment methods, that have different class or id's for the payment button. + 4. Bug fix: https fix, admin folder change fix.
    + 5. Bug fix: sending admin emails with email field turned off.]]>
    + + 2. Bug fix: Tax calculation based on the address
    + 3. Email for Guest does not go through exist check]]>
    + + + New Features:
    + 1. Responsive. Mobile friendly.
    + 2. Full module ability - can be placed into a position and layout.
    + 3. Update version control
    + 4. Better compatibility - compatible with opencart 1.5.1.3 and up
    + 5. Extensible. Now you can create and install plugins to extend the functionality of the module using hooks.
    + 6. Works with Shoppica and all major themes.

    + New Design:
    + 1. New admin design.
    + 2. 4 design choices for frontend.

    + Upgrade:
    + If you are upgrading from 3x to 4x, please follow the next instructions.
    + 1. Uninstall v3.5
    + 2. Delete all vqmod from v3.5
    + 3. Upload v4.0
    + 4. Run install from admin. Edit and save new settings.]]>
    + +
    +
    \ No newline at end of file diff --git a/vqmod/xml/a_vqmod_d_quickcheckout.xml b/vqmod/xml/a_vqmod_d_quickcheckout.xml new file mode 100755 index 0000000..edeed43 --- /dev/null +++ b/vqmod/xml/a_vqmod_d_quickcheckout.xml @@ -0,0 +1,66 @@ + + + AJAX QUICK CHECKOUT LITE V5.0 BY DREAMVENTION + 2.0.0.0 + 2.2.1 + dreamvention.com + + + config->get('config_template') . '/template/checkout/checkout.tpl')) {]]> + load->model('setting/setting'); + $quickcheckout = $this->model_setting_setting->getSetting('d_quickcheckout', $this->config->get('config_store_id')); + if(isset($quickcheckout['d_quickcheckout']['general']['main_checkout'])){ + $template = ($quickcheckout['d_quickcheckout']['general']['main_checkout']) ? 'd_quickcheckout' : 'checkout'; + }else{ + $template = 'checkout'; + } + if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/'.$template.'.tpl')) { + $this->template = $this->config->get('config_template') . '/template/checkout/'.$template.'.tpl'; + } else { + $this->template = 'default/template/checkout/'.$template.'.tpl'; + } + $this->response->setOutput($this->load->view($this->template, $data));]]> + + + load->controller('common/header');]]> + load->controller('module/d_quickcheckout');]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +