my-calendar-core.php 80.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly

function my_calendar_add_feed() {
	add_feed( 'my-calendar-rss', 'my_calendar_rss' );
	add_feed( 'my-calendar-ics', 'my_calendar_ical' );
	//add_feed( 'my-calendar-print', 'my_calendar_print' );
}

add_action( 'template_redirect', 'my_calendar_print_view' );
function my_calendar_print_view() {
	if ( isset( $_GET['cid'] ) && $_GET['cid'] == 'mc-print-view' ) {
		echo my_calendar_print();
		exit;
	}
}

if ( ! function_exists( 'is_ssl' ) ) {
	function is_ssl() {
		if ( isset( $_SERVER['HTTPS'] ) ) {
			if ( 'on' == strtolower( $_SERVER['HTTPS'] ) ) {
				return true;
			}
			if ( '1' == $_SERVER['HTTPS'] ) {
				return true;
			}
		} elseif ( isset( $_SERVER['SERVER_PORT'] ) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
			return true;
		}

		return false;
	}
}

function my_calendar_getUsers() {
	return mc_get_users();
}

// mod from Mike T
function mc_get_users() {
	global $blog_id;
	$count = count_users( 'time' );
	$args  = array(
		'blog_id' => $blog_id,
		'orderby' => 'display_name',
		'fields'  => array( 'ID', 'user_nicename', 'display_name' )
	);
	$args  = apply_filters( 'mc_filter_user_arguments', $args, $count );
	$users = new WP_User_Query( $args );

	return $users->get_results();
}

function mc_selected_users( $selected ) {
	$selected = explode( ',', $selected );
	$users    = mc_get_users();
	$options  = '';
	foreach ( $users as $u ) {
		if ( in_array( $u->ID, $selected ) ) {
			$checked = ' checked="checked"';
		} else {
			$checked = '';
		}
		$display_name = ( $u->display_name == '' ) ? $u->user_nicename : $u->display_name;
		$options     .= '<option value="' . $u->ID . '"' . $checked . ">$display_name</option>\n";
	}

	return $options;
}

function mc_plugin_action( $links, $file ) {
	if ( $file == plugin_basename( dirname( __FILE__ ) . '/my-calendar.php' ) ) {
		$links[] = "<a href='admin.php?page=my-calendar-config'>" . __( 'Settings', 'my-calendar' ) . "</a>";
		$links[] = "<a href='admin.php?page=my-calendar-help'>" . __( 'Help', 'my-calendar' ) . "</a>";
	}

	return $links;
}

function mc_inverse_color( $color ) {
	$color = str_replace( '#', '', $color );
	if ( strlen( $color ) != 6 ) {
		return '#000000';
	}
	$rgb       = '';
	$total     = 0;
	$red       = 0.299 * ( 255 - hexdec( substr( $color, 0, 2 ) ) );
	$green     = 0.587 * ( 255 - hexdec( substr( $color, 2, 2 ) ) );
	$blue      = 0.114 * ( 255 - hexdec( substr( $color, 4, 2 ) ) );
	$luminance = 1 - ( ( $red + $green + $blue ) / 255 );
	if ( $luminance < 0.5 ) {
		return '#ffffff';
	} else {
		return '#000000';
	}
}

function mc_shift_color( $color ) {
	$color   = str_replace( '#', '', $color );
	$rgb     = ''; // Empty variable
	$percent = ( mc_inverse_color( $color ) == '#ffffff' ) ? - 20 : 20;
	$per     = $percent / 100 * 255; // Creates a percentage to work with. Change the middle figure to control colour temperature
	if ( $per < 0 ) {
		// DARKER
		$per = abs( $per ); // Turns Neg Number to Pos Number
		for ( $x = 0; $x < 3; $x ++ ) {
			$c = hexdec( substr( $color, ( 2 * $x ), 2 ) ) - $per;
			$c = ( $c < 0 ) ? 0 : dechex( $c );
			$rgb .= ( strlen( $c ) < 2 ) ? '0' . $c : $c;
		}
	} else {
		// LIGHTER        
		for ( $x = 0; $x < 3; $x ++ ) {
			$c = hexdec( substr( $color, ( 2 * $x ), 2 ) ) + $per;
			$c = ( $c > 255 ) ? 'ff' : dechex( $c );
			$rgb .= ( strlen( $c ) < 2 ) ? '0' . $c : $c;
		}
	}

	return '#' . $rgb;
}

function mc_file_exists( $file ) {
	$dir    = plugin_dir_path( __FILE__ );
	$base   = basename( $dir );
	$return = apply_filters( 'mc_file_exists', false, $file );
	if ( $return ) {
		return true;
	}
	if ( file_exists( get_stylesheet_directory() . '/' . $file ) ) {
		return true;
	}
	if ( file_exists( str_replace( $base, 'my-calendar-custom', $dir ) . $file ) ) {
		return true;
	}

	return false;
}

function mc_get_file( $file, $type = 'path' ) {
	$dir  = plugin_dir_path( __FILE__ );
	$url  = plugin_dir_url( __FILE__ );
	$base = basename( $dir );
	$path = ( $type == 'path' ) ? $dir . $file : $url . $file;
	if ( file_exists( get_stylesheet_directory() . '/' . $file ) ) {
		$path = ( $type == 'path' ) ? get_stylesheet_directory() . '/' . $file : get_stylesheet_directory_uri() . '/' . $file;
	}
	if ( file_exists( str_replace( $base, 'my-calendar-custom', $dir ) . $file ) ) {
		$path = ( $type == 'path' ) ? str_replace( $base, 'my-calendar-custom', $dir ) . $file : str_replace( $base, 'my-calendar-custom', $url ) . $file;
	}
	$path = apply_filters( 'mc_get_file', $path, $file );

	return $path;
}

add_action( 'wp_enqueue_scripts', 'mc_register_styles' );
function mc_register_styles() {
	global $wp_query;
	$stylesheet = apply_filters( 'mc_registered_stylesheet', mc_get_style_path( get_option( 'mc_css_file' ), 'url' ) );
	wp_register_style( 'my-calendar-reset', plugins_url( 'css/reset.css', __FILE__ ) );
	wp_register_style( 'my-calendar-style', $stylesheet, array( 'dashicons', 'my-calendar-reset' ) );
	$admin_stylesheet = plugins_url( 'css/mc-admin.css', __FILE__ );
	wp_register_style( 'my-calendar-admin-style', $admin_stylesheet );
	if ( current_user_can( 'mc_manage_events' ) ) {
		wp_enqueue_style( 'my-calendar-admin-style' );
	}
	$this_post = $wp_query->get_queried_object();
	$id        = ( is_object( $this_post ) && isset( $this_post->ID ) ) ? $this_post->ID : false;
	$js_array  = ( get_option( 'mc_show_js' ) != '' ) ? explode( ",", get_option( 'mc_show_js' ) ) : array();
	$css_array = ( get_option( 'mc_show_css' ) != '' ) ? explode( ",", get_option( 'mc_show_css' ) ) : array();
	// check whether any scripts are actually enabled.
	if ( get_option( 'mc_calendar_javascript' ) != 1 || get_option( 'mc_list_javascript' ) != 1 || get_option( 'mc_mini_javascript' ) != 1 || get_option( 'mc_ajax_javascript' ) != 1 ) {
		if ( @in_array( $id, $js_array ) || get_option( 'mc_show_js' ) == '' || is_singular( 'mc-events' ) ) {
			wp_enqueue_script( 'jquery' );
			if ( get_option( 'mc_gmap' ) == 'true' ) {
				$api_key = get_option( 'mc_gmap_api_key' );
				if ( $api_key ) {
					wp_enqueue_script( 'gmaps', "https://maps.googleapis.com/maps/api/js?key=$api_key" );
					wp_enqueue_script( 'gmap3', plugins_url( 'js/gmap3.min.js', __FILE__ ), array( 'jquery' ) );
				}
			}
		}
	}
	if ( get_option( 'mc_use_styles' ) != 'true' ) {
		if ( @in_array( $id, $css_array ) || get_option( 'mc_show_css' ) == '' ) {
			wp_enqueue_style( 'my-calendar-style' );
		}
	}
	if ( mc_is_tablet() && mc_file_exists( 'mc-tablet.css' ) ) {
		$tablet = mc_get_file( 'mc-tablet.css' );
		wp_register_style( 'my-calendar-tablet-style', $tablet );
		wp_enqueue_style( 'my-calendar-tablet-style' );
	}
	if ( mc_is_mobile() && mc_file_exists( 'mc-mobile.css' ) ) {
		$mobile = mc_get_file( 'mc-mobile.css' );
		wp_register_style( 'my-calendar-mobile-style', $mobile );
		wp_enqueue_style( 'my-calendar-mobile-style' );
	}
}

// Function to add the calendar style into the header
function my_calendar_wp_head() {
	global $wpdb, $wp_query;
	$mcdb  = $wpdb;
	$array = array();

	if ( get_option( 'mc_use_styles' ) != 'true' ) {
		$this_post = $wp_query->get_queried_object();
		$id        = ( is_object( $this_post ) && isset( $this_post->ID ) ) ? $this_post->ID : false;
		$array     = ( get_option( 'mc_show_css' ) != '' ) ? explode( ",", get_option( 'mc_show_css' ) ) : $array;
		if ( @in_array( $id, $array ) || get_option( 'mc_show_css' ) == '' ) {
			// generate category colors
			$category_styles = $inv = $type = $alt = '';
			$categories      = $mcdb->get_results( "SELECT * FROM " . my_calendar_categories_table() . " ORDER BY category_id ASC" );
			foreach ( $categories as $category ) {
				$class = "mc_" . sanitize_title( $category->category_name );
				$hex   = ( strpos( $category->category_color, '#' ) !== 0 ) ? '#' : '';
				$color = $hex . $category->category_color;
				if ( $color != '#' ) {
					$hcolor = mc_shift_color( $category->category_color );
					if ( get_option( 'mc_apply_color' ) == 'font' ) {
						$type = 'color';
						$alt  = 'background';
					} else if ( get_option( 'mc_apply_color' ) == 'background' ) {
						$type = 'background';
						$alt  = 'color';
					}
					if ( get_option( 'mc_inverse_color' ) == 'true' ) {
						$inverse = mc_inverse_color( $color );
						$inv     = "$alt: $inverse;";
					}
					if ( get_option( 'mc_apply_color' ) == 'font' || get_option( 'mc_apply_color' ) == 'background' ) {
						// always an anchor as of 1.11.0, apply also to title
						$category_styles .= "\n.mc-main .$class .event-title, .mc-main .$class .event-title a { $type: $color; $inv }";
						$category_styles .= "\n.mc-main .$class .event-title a:hover, .mc-main .$class .event-title a:focus { $type: $hcolor;}";
					}
				}
			}
			$all_styles = "
<style type=\"text/css\">
<!--
/* Styles by My Calendar - Joseph C Dolson http://www.joedolson.com/ */
$category_styles
.mc-event-visible {
display: block!important;
}
-->
</style>";
			echo $all_styles;
		}
	}
}

// Function to deal with events posted by a user when that user is deleted
function mc_deal_with_deleted_user( $id ) {
	global $wpdb;
	$mcdb = $wpdb;
	// Do the queries
	// This may not work quite right in multi-site. Need to explore further when I have time.
	$mcdb->get_results( "UPDATE " . my_calendar_table() . " SET event_author=" . esc_sql( apply_filters( 'mc_deleted_author', $mcdb->get_var( "SELECT MIN(ID) FROM " . $mcdb->prefix . "users", 0, 0 ) ) ) . " WHERE event_author=" . $id );
	$mcdb->get_results( "UPDATE " . my_calendar_table() . " SET event_host=" . esc_sql( apply_filters( 'mc_deleted_host', $mcdb->get_var( "SELECT MIN(ID) FROM " . $mcdb->prefix . "users", 0, 0 ) ) ) . " WHERE event_host=" . $id );
}

// Function to add the javascript to the admin header
function my_calendar_add_javascript() {
	wp_register_script( 'mc.tabs', plugins_url( 'js/tabs.js', __FILE__ ), array( 'jquery' ) );
	wp_register_script( 'mc.sortable', plugins_url( 'js/sortable.js', __FILE__ ), array(
			'jquery',
			'jquery-ui-sortable'
		) );
	wp_register_script( 'mc-upload', plugins_url( 'js/upload.js', __FILE__ ), array( 'jquery' ) );
	if ( isset( $_GET['page'] ) && ( $_GET['page'] == 'my-calendar' || $_GET['page'] == 'my-calendar-groups' || $_GET['page'] == 'my-calendar-locations' ) ) {
		wp_enqueue_script( 'jquery-ui-autocomplete' );
		wp_enqueue_script( 'jquery-ui-accordion' );
		wp_enqueue_script( 'pickadate', plugins_url( 'js/pickadate/picker.js', __FILE__ ), array( 'jquery' ) );
		wp_enqueue_script( 'pickadate.date', plugins_url( 'js/pickadate/picker.date.js', __FILE__ ), array( 'pickadate' ) );
		wp_enqueue_script( 'pickadate.time', plugins_url( 'js/pickadate/picker.time.js', __FILE__ ), array( 'pickadate' ) );
		wp_localize_script( 'pickadate.date', 'mc_months', array(
			date_i18n( 'F', strtotime( 'January 1' ) ),
			date_i18n( 'F', strtotime( 'February 1' ) ),
			date_i18n( 'F', strtotime( 'March 1' ) ),
			date_i18n( 'F', strtotime( 'April 1' ) ),
			date_i18n( 'F', strtotime( 'May 1' ) ),
			date_i18n( 'F', strtotime( 'June 1' ) ),
			date_i18n( 'F', strtotime( 'July 1' ) ),
			date_i18n( 'F', strtotime( 'August 1' ) ),
			date_i18n( 'F', strtotime( 'September 1' ) ),
			date_i18n( 'F', strtotime( 'October 1' ) ),
			date_i18n( 'F', strtotime( 'November 1' ) ),
			date_i18n( 'F', strtotime( 'December 1' ) )
		) );
		wp_localize_script( 'pickadate.date', 'mc_days', array(
			date_i18n( 'D', strtotime( 'Sunday' ) ),
			date_i18n( 'D', strtotime( 'Monday' ) ),
			date_i18n( 'D', strtotime( 'Tuesday' ) ),
			date_i18n( 'D', strtotime( 'Wednesday' ) ),
			date_i18n( 'D', strtotime( 'Thursday' ) ),
			date_i18n( 'D', strtotime( 'Friday' ) ),
			date_i18n( 'D', strtotime( 'Saturday' ) )
		) );
		wp_localize_script( 'pickadate.time', 'mc_time_format', apply_filters( 'mc_time_format', 'h:i A' ) );
		wp_localize_script( 'pickadate.time', 'mc_interval', apply_filters( 'mc_interval', '15' ) );
		
		wp_enqueue_script( 'jquery.addfields', plugins_url( 'js/jquery.addfields.js', __FILE__ ), array( 'jquery' ) );
		if ( function_exists( 'wp_enqueue_media' ) && ! did_action( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}
		wp_enqueue_script( 'mc-upload' );
		wp_localize_script( 'mc-upload', 'thumbHeight', get_option( 'thumbnail_size_h' ) );
	}
	if ( isset( $_GET['page'] ) && ( $_GET['page'] == 'my-calendar-config' || $_GET['page'] == 'my-calendar-help' ) ) {
		wp_enqueue_script( 'mc.tabs' );
		wp_enqueue_script( 'mc.sortable' );
	}
	
	if ( isset( $_GET['page'] ) && ( $_GET['page'] == 'my-calendar-groups' || $_GET['page'] == 'my-calendar-manage' ) ) {
		wp_enqueue_script( 'jquery.checkall', plugins_url( 'js/jquery.checkall.js', __FILE__ ), array( 'jquery' ) );
	}
}

function my_calendar_write_js() {
	if ( isset( $_GET['page'] ) && ( $_GET['page'] == 'my-calendar' || $_GET['page'] == 'my-calendar-locations' ) ) {
		?>
		<script type="text/javascript">
			//<![CDATA[
			jQuery(document).ready(function ($) {
				$( '.mc-datepicker' ).pickadate({
					monthsFull: mc_months,
					weekdaysShort: mc_days,
					format: 'yyyy-mm-dd',
					selectYears: true,
					selectMonths: true,
					editable: true
				});
				$( '.mc-timepicker' ).pickatime({
					interval: parseInt( mc_interval ),
					format: mc_time_format,
					editable: true		
				});
				$('#mc-accordion').accordion( { collapsible: true, active: false, heightStyle: 'content' } );
				<?php
				if ( function_exists( 'jd_doTwitterAPIPost' ) && isset( $_GET['page'] ) && $_GET['page'] == 'my-calendar' ) { 
				?>
				$('#mc_twitter').charCount({
					allowed: 140,
					counterText: '<?php _e('Characters left: ','my-calendar') ?>'
				});
				<?php 
				} 
				?>
			});
			//]]>
		</script><?php
	}
}

add_action( 'in_plugin_update_message-my-calendar/my-calendar.php', 'mc_plugin_update_message' );
function mc_plugin_update_message() {
	global $mc_version;
	define( 'MC_PLUGIN_README_URL', 'http://svn.wp-plugins.org/my-calendar/trunk/readme.txt' );
	$response = wp_remote_get( MC_PLUGIN_README_URL, array( 'user-agent' => 'WordPress/My Calendar' . $mc_version . '; ' . get_bloginfo( 'url' ) ) );
	if ( ! is_wp_error( $response ) || is_array( $response ) ) {
		$data = $response['body'];
		$bits = explode( '== Upgrade Notice ==', $data );
		echo '<div id="mc-upgrade"><p><strong style="color:#c22;">Upgrade Notes:</strong> ' . nl2br( trim( $bits[1] ) ) . '</p></div>';
	} else {
		printf( __( '<br /><strong>Note:</strong> Please review the <a class="thickbox" href="%1$s">changelog</a> before upgrading.', 'my-calendar' ), 'plugin-install.php?tab=plugin-information&amp;plugin=my-calendar&amp;TB_iframe=true&amp;width=640&amp;height=594' );
	}
}

function mc_footer_js() {
	global $wp_query;
	if ( mc_is_mobile() && apply_filters( 'mc_disable_mobile_js', false ) ) {
		return;
	} else {
		$pages = array();
		if ( get_option( 'mc_show_js' ) != '' ) {
			$pages = explode( ",", get_option( 'mc_show_js' ) );
		}
		if ( is_object( $wp_query ) && isset( $wp_query->post ) ) {
			$id = $wp_query->post->ID;
		} else {
			$id = false;
		}
		if ( get_option( 'mc_use_custom_js' ) == 1 ) {
			$top     = $bottom = $inner = '';
			$list_js = stripcslashes( get_option( 'mc_listjs' ) );
			$cal_js  = stripcslashes( get_option( 'mc_caljs' ) );
			if ( get_option( 'mc_open_uri' ) == 'true' ) { // remove sections of javascript if necessary.
				$replacements = array(
					'$(this).parent().children().not(".event-title").toggle();',
					'e.preventDefault();'
				);
				$cal_js       = str_replace( $replacements, '', $cal_js );
			}
			$mini_js = stripcslashes( get_option( 'mc_minijs' ) );
			if ( get_option( 'mc_open_day_uri' ) == 'true' || get_option( 'mc_open_day_uri' ) == 'listanchor' || get_option( 'mc_open_day_uri' ) == 'calendaranchor' ) {
				$mini_js = str_replace( 'e.preventDefault();', '', $mini_js );
			}
			$ajax_js = stripcslashes( get_option( 'mc_ajaxjs' ) );

			if ( @in_array( $id, $pages ) || get_option( 'mc_show_js' ) == '' ) {
				$inner = '';
				if ( get_option( 'mc_calendar_javascript' ) != 1 ) {
					$inner .= "\n" . $cal_js;
				}
				if ( get_option( 'mc_list_javascript' ) != 1 ) {
					$inner .= "\n" . $list_js;
				}
				if ( get_option( 'mc_mini_javascript' ) != 1 ) {
					$inner .= "\n" . $mini_js;
				}
				if ( get_option( 'mc_ajax_javascript' ) != 1 ) {
					$inner .= "\n" . $ajax_js;
				}
				$script = '
<script type="text/javascript">
(function( $ ) { \'use strict\';'.
	$inner
.'}(jQuery));
</script>';
			}
			$inner = apply_filters( 'mc_filter_javascript_footer', $inner );
			echo ( $inner != '' ) ? $script : '';
		} else {
			if ( @in_array( $id, $pages ) || get_option( 'mc_show_js' ) == '' ) {
				if ( get_option( 'mc_calendar_javascript' ) != 1 && get_option( 'mc_open_uri' ) != 'true' ) {
					$url = apply_filters( 'mc_grid_js', plugins_url( 'js/mc-grid.js', __FILE__ ) );
					wp_enqueue_script( 'mc.grid', $url, array( 'jquery' ) );
				}
				if ( get_option( 'mc_list_javascript' ) != 1 ) {
					$url = apply_filters( 'mc_list_js', plugins_url( 'js/mc-list.js', __FILE__ ) );
					wp_enqueue_script( 'mc.list', $url, array( 'jquery' ) );
				}
				if ( get_option( 'mc_mini_javascript' ) != 1 ) {
					$url = apply_filters( 'mc_mini_js', plugins_url( 'js/mc-mini.js', __FILE__ ) );
					wp_enqueue_script( 'mc.mini', $url, array( 'jquery' ) );
				}
				if ( get_option( 'mc_ajax_javascript' ) != 1 ) {
					$url = apply_filters( 'mc_ajax_js', plugins_url( 'js/mc-ajax.js', __FILE__ ) );
					wp_enqueue_script( 'mc.ajax', $url, array( 'jquery' ) );
				}
			}
		}
	}
}

function my_calendar_add_styles() {
	if ( isset( $_GET['page'] ) ) {
		$pages = array(
			'my-calendar',
			'my-calendar-manage',
			'my-calendar-groups',
			'my-calendar-categories',
			'my-calendar-locations',
			'my-calendar-config',
			'my-calendar-styles',
			'my-calendar-help',
			'my-calendar-behaviors',
			'my-calendar-templates'
		);
		if ( in_array( $_GET['page'], $pages ) ) {
			wp_enqueue_style( 'mc-styles', plugins_url( 'css/mc-styles.css', __FILE__ ) );
		}
		if ( $_GET['page'] == 'my-calendar' ) {
			wp_enqueue_style( 'mc-pickadate-default', plugins_url( 'js/pickadate/themes/default.css', __FILE__ ) );
			wp_enqueue_style( 'mc-pickadate-date', plugins_url( 'js/pickadate/themes/default.date.css', __FILE__ ) );
			wp_enqueue_style( 'mc-pickadate-time', plugins_url( 'js/pickadate/themes/default.time.css', __FILE__ ) );
		}
	}
}

function mc_get_current_url() {
	global $wp, $wp_rewrite;
	$args = array();
	if ( isset( $_GET['page_id'] ) ) {
		$args = array( 'page_id' => $_GET['page_id'] );
	}
	$current_url = home_url( add_query_arg( $args, $wp->request ) );
		
	if ( $wp_rewrite->using_index_permalinks() && strpos( $current_url, 'index.php' ) === false ) {
		$current_url = str_replace( home_url(), home_url( '/' ) . 'index.php', $home );
	}
	if ( $wp_rewrite->using_permalinks() ) {
		$current_url = trailingslashit( $current_url );
	}
	
	return esc_url( $current_url );
}

function mc_csv_to_array( $csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n" ) {
	$r    = array();
	$rows = explode( $terminator, trim( $csv ) );
	foreach ( $rows as $row ) {
		if ( trim( $row ) ) {
			$values          = explode( $delimiter, $row );
			$r[ $values[0] ] = ( isset( $values[1] ) ) ? str_replace( array( $enclosure, $escape ), '', $values[1] ) : $values[0] ;
		}
	}

	return $r;
}

function mc_if_needs_permissions() {
	// prevent administrators from losing privileges to edit my calendar
	$role = get_role( 'administrator' );
	if ( is_object( $role ) ) {
		$caps = $role->capabilities;
		if ( isset( $caps['mc_add_events'] ) ) {
			return;
		} else {
			$role->add_cap( 'mc_add_events' );
			$role->add_cap( 'mc_approve_events' );
			$role->add_cap( 'mc_manage_events' );
			$role->add_cap( 'mc_edit_cats' );
			$role->add_cap( 'mc_edit_styles' );
			$role->add_cap( 'mc_edit_behaviors' );
			$role->add_cap( 'mc_edit_templates' );
			$role->add_cap( 'mc_edit_settings' );
			$role->add_cap( 'mc_edit_locations' );
			$role->add_cap( 'mc_view_help' );
		}
	} else {
		return;
	}
}

function mc_add_roles( $add = false, $manage = false, $approve = false ) {
	// grant administrator role all event permissions
	$role = get_role( 'administrator' );
	$role->add_cap( 'mc_add_events' );
	$role->add_cap( 'mc_approve_events' );
	$role->add_cap( 'mc_manage_events' );
	$role->add_cap( 'mc_edit_cats' );
	$role->add_cap( 'mc_edit_styles' );
	$role->add_cap( 'mc_edit_behaviors' );
	$role->add_cap( 'mc_edit_templates' );
	$role->add_cap( 'mc_edit_settings' );
	$role->add_cap( 'mc_edit_locations' );
	$role->add_cap( 'mc_view_help' );

	// depending on permissions settings, grant other permissions
	if ( $add && $manage && $approve ) {
		// this is an upgrade;
		// Get Roles
		$subscriber  = get_role( 'subscriber' );
		$contributor = get_role( 'contributor' );
		$author      = get_role( 'author' );
		$editor      = get_role( 'editor' );
		$subscriber->add_cap( 'mc_view_help' );
		$contributor->add_cap( 'mc_view_help' );
		$author->add_cap( 'mc_view_help' );
		$editor->add_cap( 'mc_view_help' );
		switch ( $add ) {
			case 'read':
				$subscriber->add_cap( 'mc_add_events' );
				$contributor->add_cap( 'mc_add_events' );
				$author->add_cap( 'mc_add_events' );
				$editor->add_cap( 'mc_add_events' );
				break;
			case 'edit_posts':
				$contributor->add_cap( 'mc_add_events' );
				$author->add_cap( 'mc_add_events' );
				$editor->add_cap( 'mc_add_events' );
				break;
			case 'publish_posts':
				$author->add_cap( 'mc_add_events' );
				$editor->add_cap( 'mc_add_events' );
				break;
			case 'moderate_comments':
				$editor->add_cap( 'mc_add_events' );
				break;
		}
		switch ( $approve ) {
			case 'read':
				$subscriber->add_cap( 'mc_approve_events' );
				$contributor->add_cap( 'mc_approve_events' );
				$author->add_cap( 'mc_approve_events' );
				$editor->add_cap( 'mc_approve_events' );
				break;
			case 'edit_posts':
				$contributor->add_cap( 'mc_approve_events' );
				$author->add_cap( 'mc_approve_events' );
				$editor->add_cap( 'mc_approve_events' );
				break;
			case 'publish_posts':
				$author->add_cap( 'mc_approve_events' );
				$editor->add_cap( 'mc_approve_events' );
				break;
			case 'moderate_comments':
				$editor->add_cap( 'mc_approve_events' );
				break;
		}
		switch ( $manage ) {
			case 'read':
				$subscriber->add_cap( 'mc_manage_events' );
				$contributor->add_cap( 'mc_manage_events' );
				$author->add_cap( 'mc_manage_events' );
				$editor->add_cap( 'mc_manage_events' );
				break;
			case 'edit_posts':
				$contributor->add_cap( 'mc_manage_events' );
				$author->add_cap( 'mc_manage_events' );
				$editor->add_cap( 'mc_manage_events' );
				break;
			case 'publish_posts':
				$author->add_cap( 'mc_manage_events' );
				$editor->add_cap( 'mc_manage_events' );
				break;
			case 'moderate_comments':
				$editor->add_cap( 'mc_manage_events' );
				break;
		}
	}
}

function my_calendar_exists() {
	global $wpdb;
	$tables = $wpdb->get_results( "show tables;" );
	foreach ( $tables as $table ) {
		foreach ( $table as $value ) {
			if ( $value == my_calendar_table() ) {
				// if the table exists, then My Calendar was already installed.
				return true;
			}
		}
	}
	return false;
}

// Function to check what version of My Calendar is installed and install or upgrade if needed
function check_my_calendar() {
	global $wpdb, $mc_version;
	$mcdb = $wpdb;
	mc_if_needs_permissions();
	$current_version = ( get_option( 'mc_version' ) == '' ) ? get_option( 'my_calendar_version' ) : get_option( 'mc_version' );
	if ( version_compare( $current_version, '2.3.12', '>=' ) ) {
		// if current is a version higher than 2.3.11, they've already seen this notice and handled it.
		update_option( 'mc_update_notice', 1 );
	}
	// If current version matches, don't bother running this.
	if ( $current_version == $mc_version ) {
		return true;
	}
	// Assume this is not a new install until we prove otherwise
	$new_install        = false;
	$upgrade_path       = array();

	if ( my_calendar_exists() && $current_version == '' ) {
		// If the table exists, but I don't know what version it is, I have to run the full cycle of upgrades. 
		$current_version = '1.10.7';
	}

	if ( !my_calendar_exists() ) {
		$new_install = true;
	} else {
		// for each release requiring an upgrade path, add a version compare. 
		// Loop will run every relevant upgrade cycle.
		$valid_upgrades = array(
			'1.11.0',
			'1.11.1',
			'2.0.0',
			'2.0.4',
			'2.1.0',
			'2.2.0',
			'2.2.6',
			'2.2.10',
			'2.3.0',
			'2.3.11',
			'2.3.15',
			'2.5.0',
		);
		foreach ( $valid_upgrades as $upgrade ) {
			if ( version_compare( $current_version, $upgrade, "<" ) ) {
				$upgrade_path[] = $upgrade;
			}
		}
	}
	// having determined upgrade path, assign new version number
	update_option( 'mc_version', $mc_version );
	// Now we've determined what the current install is or isn't 
	if ( $new_install == true ) {
		//add default settings
		mc_default_settings();
		$sql = "INSERT INTO " . my_calendar_categories_table() . " SET category_id=1, category_name='General', category_color='#ffffcc', category_icon='event.png'";
		$mcdb->query( $sql );
		$term = wp_insert_term( 'General', 'mc-event-category' );
		
	} else {
		// clear cache so updates are immediately available
		mc_delete_cache();
	}
	mc_do_upgrades( $upgrade_path );
	/*
	if the user has fully uninstalled the plugin but kept the database of events, this will restore default 
	settings and upgrade db if needed.
	*/
	if ( get_option( 'mc_uninstalled' ) == 'true' ) {
		mc_default_settings();
		update_option( 'mc_db_version', $mc_version );
		delete_option( 'mc_uninstalled' );
	}
}

function mc_do_upgrades( $upgrade_path ) {
	global $mc_version;
	
	foreach ( $upgrade_path as $upgrade ) {
		switch ( $upgrade ) {
			case '2.5.0':
				update_option( 'mc_db_version', $mc_version );
				mc_upgrade_db();
				break;
			// only upgrade db on most recent version
			case '2.4.4':
				add_option( 'mc_display_more', 'true' );
				$input_options = get_option( 'mc_input_options' );
				$input_options['event_host'] = 'on';
				update_option( 'mc_input_options', $input_options );
				add_option( 'mc_default_direction', 'DESC' );
				break;
			case '2.3.15':
				delete_option( 'mc_event_groups' );
				delete_option( 'mc_details' );
				break;
			case '2.3.11':
				add_option( 'mc_use_custom_js', 0 );
				add_option( 'mc_update_notice', 0 );
				break;
			case '2.3.0':
				delete_option( 'mc_location_control' );
				$user_data              = get_option( 'mc_user_settings' );
				$loc_type               = ( get_option( 'mc_location_type' ) == '' ) ? 'event_state' : get_option( 'mc_location_type' );
				$locations[ $loc_type ] = $user_data['my_calendar_location_default']['values'];
				add_option( 'mc_use_permalinks', false );
				delete_option( 'mc_modified_feeds' );
				add_option( 'mc_location_controls', $locations );
				$mc_input_options                 = get_option( 'mc_input_options' );
				$mc_input_options['event_access'] = 'on';
				update_option( 'mc_input_options', $mc_input_options );
				mc_transition_db();
				break;
			case '2.2.10':
				delete_option( 'mc_show_print' );
				delete_option( 'mc_show_ical' );
				delete_option( 'mc_show_rss' );
				break;
			case '2.2.8':
				delete_option( 'mc_draggable' );
				break;
			case '2.2.6':
				delete_option( 'mc_caching_enabled' ); // remove caching support via options. Filter only.
				break;
			case '2.2.0':
				add_option( 'mc_inverse_color', 'true' );
				break;
			case '2.1.0':
				$templates = get_option( 'mc_templates' );
				global $rss_template;
				$templates['rss'] = $rss_template;
				update_option( 'mc_templates', $templates );
				break;
			case '2.0.4':
				update_option( 'mc_ical_utc', 'true' );
				break;
			case '2.0.0':
				mc_migrate_db();
				$mc_input = get_option( 'mc_input_options' );
				if ( ! isset( $mc_input['event_specials'] ) ) {
					$mc_input['event_specials'] = 'on';
					update_option( 'mc_input_options', $mc_input );
				}
				break;
			case '1.11.1':
				add_option( 'mc_event_link', 'true' );
				break;
			case '1.11.0':
				add_option( 'mc_convert', 'true' );
				add_option( 'mc_process_shortcodes', 'false' );
				$add     = get_option( 'mc_can_manage_events' ); // yes, this is correct.
				$manage  = get_option( 'mc_event_edit_perms' );
				$approve = get_option( 'mc_event_approve_perms' );
				mc_add_roles( $add, $manage, $approve );
				delete_option( 'mc_can_manage_events' );
				delete_option( 'mc_event_edit_perms' );
				delete_option( 'mc_event_approve_perms' );
				break;
			default:
				break;
		}
	}
}

// @data object with event_category value
function mc_category_select( $data = false, $option = true, $multiple = false ) {
	global $wpdb;
	$mcdb = $wpdb;
	if ( get_option( 'mc_remote' ) == 'true' && function_exists( 'mc_remote_db' ) ) {
		$mcdb = mc_remote_db();
	}
	// Grab all the categories and list them
	$list = $default = '';
	$sql  = "SELECT * FROM " . my_calendar_categories_table() . " ORDER BY category_name ASC";
	$cats = $mcdb->get_results( $sql );
	if ( empty( $cats ) ) {
		// need to have categories. Try to create again.
		$insert = "INSERT INTO " . my_calendar_categories_table() . " SET category_id=1, category_name='General', category_color='#ffffcc', category_icon='event.png'";
		$term = wp_insert_term( 'General', 'mc-event-category' );		
		$mcdb->query( $insert );
		$cats = $mcdb->get_results( $sql );
	}
	if ( ! empty( $cats ) ) {
		$cats = apply_filters( 'mc_category_list', $cats, $data, $option );
		foreach ( $cats as $cat ) {
			$c = '<option value="' . $cat->category_id . '"';
			if ( ! empty( $data ) ) {
				if ( ! is_object( $data ) ) {
					$category = $data;
				} else if ( is_array( $data ) && $multiple ) {
					$category = $data;
				} else {
					$category = $data->event_category;
				}
				if ( $multiple ) {
					if ( in_array( $cat->category_id, $category ) ) {
						$c .= ' selected="selected"';
					}
				} else {
					if ( $category == $cat->category_id ) {
						$c .= ' selected="selected"';
					}
				}
			}
			$c .= '>' . mc_kses_post( stripslashes( $cat->category_name ) ) . '</option>';
			if ( $cat->category_id != get_option( 'mc_default_category' ) ) {
				$list .= $c;
			} else {
				$default = $c;
			}
		}
	} else {
		$category_url = admin_url( 'admin.php?page=my-calendar-categories' );
		echo "<div class='updated error'><p>" . sprintf( __( 'You do not have any categories created. Please <a href="%s">create at least one category!</a>', 'my-calendar' ), $category_url ) . "</p></div>";
	}
	if ( ! $option ) {
		$default = ( get_option( 'mc_default_category' ) ) ? get_option( 'mc_default_category' ) : 1;

		return ( is_object( $data ) ) ? $data->event_category : $default;
	}

	return $default . $list;
}

// @data object with event_location value
function mc_location_select( $location = false ) {
	global $wpdb;
	$mcdb = $wpdb;
	if ( get_option( 'mc_remote' ) == 'true' && function_exists( 'mc_remote_db' ) ) {
		$mcdb = mc_remote_db();
	}
	// Grab all locations and list them
	$list = '';
	$sql  = "SELECT location_id, location_label FROM " . my_calendar_locations_table() . " ORDER BY location_label ASC";
	$locs = $mcdb->get_results( $sql );
	foreach ( $locs as $loc ) {
		$l = '<option value="' . $loc->location_id . '"';
		if ( $location ) {
			if ( $location == $loc->location_id ) {
				$l .= ' selected="selected"';
			}
		}
		$l .= '>' . mc_kses_post( stripslashes( $loc->location_label ) ) . '</option>';
		$list .= $l;
	}

	return $list;
}

function mc_is_checked( $theFieldname, $theValue, $theArray = '', $return = false ) {
	if ( ! is_array( get_option( $theFieldname ) ) ) {
		if ( get_option( $theFieldname ) == $theValue ) {
			if ( $return ) {
				return 'checked="checked"';
			} else {
				echo 'checked="checked"';
			}
		}
	} else {
		$theSetting = get_option( $theFieldname );
		if ( ! empty( $theSetting[ $theArray ]['enabled'] ) && $theSetting[ $theArray ]['enabled'] == $theValue ) {
			if ( $return ) {
				return 'checked="checked"';
			} else {
				echo 'checked="checked"';
			}
		}
	}
}

function mc_is_selected( $theFieldname, $theValue, $theArray = '' ) {
	if ( ! is_array( get_option( $theFieldname ) ) ) {
		if ( get_option( $theFieldname ) == $theValue ) {
			return 'selected="selected"';
		}
	} else {
		$theSetting = get_option( $theFieldname );
		if ( $theSetting[ $theArray ]['enabled'] == $theValue ) {
			return 'selected="selected"';
		}
	}

	return '';
}

function my_calendar_fouc() {
	global $wp_query;
	$array = array();
	if ( get_option( 'mc_calendar_javascript' ) != 1 || get_option( 'mc_list_javascript' ) != 1 || get_option( 'mc_mini_javascript' ) != 1 ) {
		$scripting = "\n<script type='text/javascript'>\n";
		$scripting .= "	jQuery('html').addClass('mcjs');\n";
		$scripting .= "	jQuery(document).ready( function($) { \$('html').removeClass('mcjs') } );\n";
		$scripting .= "</script>\n";

		if ( ! is_404() ) {
			if ( is_object( $wp_query ) && isset( $wp_query->post ) ) {
				$id = $wp_query->post->ID;
			} else {
				$id = '';
			}
			if ( get_option( 'mc_show_js' ) != '' ) {
				$array = explode( ",", get_option( 'mc_show_js' ) );
			}
			if ( @in_array( $id, $array ) || trim( get_option( 'mc_show_js' ) ) == '' ) {
				echo $scripting;
			}
		}
	}
}

function mc_month_comparison( $month ) {
	$current_month = date( "n", current_time( 'timestamp' ) );
	if ( isset( $_GET['yr'] ) && isset( $_GET['month'] ) ) {
		if ( $month == $_GET['month'] ) {
			return ' selected="selected"';
		}
	} elseif ( $month == $current_month ) {
		return ' selected="selected"';
	}

	return '';
}

function mc_day_comparison( $day ) {
	$current_day = date( "j", current_time( 'timestamp' ) );
	if ( isset( $_GET['yr'] ) && isset( $_GET['month'] ) && isset( $_GET['dy'] ) ) {
		if ( $day == $_GET['dy'] ) {
			return ' selected="selected"';
		}
	} else if ( $day == $current_day ) {
		return ' selected="selected"';
	}

	return '';
}

function mc_year_comparison( $year ) {
	$current_year = date( "Y", current_time( 'timestamp' ) );
	if ( isset( $_GET['yr'] ) && isset( $_GET['month'] ) ) {
		if ( $year == $_GET['yr'] ) {
			return ' selected="selected"';
		}
	} else if ( $year == $current_year ) {
		return ' selected="selected"';
	}

	return '';
}

function mc_event_repeats_forever( $recur, $repeats ) {
	if ( $recur != 'S' && $repeats == 0 ) {
		return true;
	}
	switch ( $recur ) {
		case "S": // single
			return false;
			break;
		case "D": // daily
			return ( $repeats == 500 ) ? true : false;
			break;
		case "W": // weekly
			return ( $repeats == 240 ) ? true : false;
			break;
		case "B": // biweekly
			return ( $repeats == 120 ) ? true : false;
			break;
		case "M": // monthly
		case "U":
			return ( $repeats == 60 ) ? true : false;
			break;
		case "Y":
			return ( $repeats == 5 ) ? true : false;
			break;
		default:
			return false;
	}
}

function my_calendar_is_odd( $int ) {
	return ( $int & 1 );
}

/* Unless an admin, authors can only edit their own events if they don't have mc_manage_events capabilities. */
function mc_can_edit_event( $event = false ) {
	if ( ! is_user_logged_in() ) {
		return false;
	}
	
	if ( !$event ) {
		return false;
	}
	
	if ( is_object( $event ) ) {
		$event_id = $event->event_id;
		$event_author = $event->event_author;
	} else {
		$event_id = $event;
		$event = mc_get_event_core( $event );
		$event_author = $event->event_author;
	}
	
	
	$current_user = wp_get_current_user();
	$user = $current_user->ID;
	$has_permissions = mc_can_edit_category( $event->event_category, $user );
	
	if ( !is_object( $event ) ) {
		$event_author = 0;
	} else {
		$event_author = $event->event_author;
	}
	
	if ( current_user_can( 'mc_manage_events' ) && $has_permissions ) {
		$return = true;
	} else if ( $user == $event_author ) {
		$return = true;
	} else {
		$return = false;
	}

	return apply_filters( 'mc_can_edit_event', $return, $event_id );
}

function mc_can_edit_category( $category, $user ) {
	$permissions = get_user_meta( $user, 'mc_user_permissions', true );
	
	if ( empty( $permissions ) || in_array( 'all', $permissions ) || in_array( $category, $permissions ) ) {
		return true;
	}
	
	return false;
}

function jd_option_selected( $field, $value, $type = 'checkbox' ) {
	switch ( $type ) {
		case 'radio':
		case 'checkbox':
			$result = ' checked="checked"';
			break;
		case 'option':
			$result = ' selected="selected"';
			break;
		default:
			$result = '';
			break;
	}
	if ( $field == $value ) {
		$output = $result;
	} else {
		$output = '';
	}

	return $output;
}

// compatibility of clone keyword between PHP 5 and 4
if ( version_compare( phpversion(), '5.0' ) < 0 ) {
	eval( '
	function clone($object) {
	  return $object;
	}
	' );
}

add_action( 'admin_bar_menu', 'my_calendar_admin_bar', 200 );
function my_calendar_admin_bar() {
	global $wp_admin_bar;
	if ( current_user_can( 'mc_add_events' ) ) {
		$url  = apply_filters( 'mc_add_events_url', admin_url( 'admin.php?page=my-calendar' ) );
		$args = array( 'id' => 'mc-add-event', 'title' => __( 'Add Event', 'my-calendar' ), 'href' => $url );
		$wp_admin_bar->add_node( $args );
	}
	if ( _mc_is_url( get_option( 'mc_uri' ) ) ) {
		$url  = esc_url( apply_filters( 'mc_adminbar_uri', get_option( 'mc_uri' ) ) );
		$args = array( 'id' => 'mc-my-calendar', 'title' => __( 'View Calendar', 'my-calendar' ), 'href' => $url );
		$wp_admin_bar->add_node( $args );
	} else {
		$url  = admin_url( 'admin.php?page=my-calendar-config#mc-output' );
		$args = array( 'id' => 'mc-my-calendar', 'title' => __( 'Set Calendar URL', 'my-calendar' ), 'href' => $url );
		$wp_admin_bar->add_node( $args );		
	}
	if ( current_user_can( 'mc_manage_events' ) && current_user_can( 'mc_add_events' ) ) {
		$url  = admin_url( 'admin.php?page=my-calendar-manage' );
		$args = array(
			'id'     => 'mc-manage-events',
			'title'  => __( 'Events', 'my-calendar' ),
			'href'   => $url,
			'parent' => 'mc-add-event'
		);
		$wp_admin_bar->add_node( $args );
	}
	if ( current_user_can( 'mc_edit_cats' ) && current_user_can( 'mc_add_events' ) ) {
		$url  = admin_url( 'admin.php?page=my-calendar-categories' );
		$args = array(
			'id'     => 'mc-manage-categories',
			'title'  => __( 'Categories', 'my-calendar' ),
			'href'   => $url,
			'parent' => 'mc-add-event'
		);
		$wp_admin_bar->add_node( $args );
	}
	if ( current_user_can( 'mc_edit_locations' ) && current_user_can( 'mc_add_events' ) ) {
		$url  = admin_url( 'admin.php?page=my-calendar-locations' );
		$args = array(
			'id'     => 'mc-manage-locations',
			'title'  => __( 'Locations', 'my-calendar' ),
			'href'   => $url,
			'parent' => 'mc-add-event'
		);
		$wp_admin_bar->add_node( $args );
	}
}

// Mail functions (originally by Roland)
function my_calendar_send_email( $event ) {
	$details = mc_create_tags( $event );
	$headers = array();
	// shift to boolean
	$send_email_option = ( get_option( 'mc_event_mail' ) == 'true' ) ? true : false;
	$send_email        = apply_filters( 'mc_send_notification', $send_email_option, $details );
	if ( $send_email == true ) {
		add_filter( 'wp_mail_content_type', create_function( '', 'return "text/html";' ) );
	}
	if ( get_option( 'mc_event_mail' ) == 'true' ) {
		$to        = apply_filters( 'mc_event_mail_to', get_option( 'mc_event_mail_to' ), $details );
		$from      = ( get_option( 'mc_event_mail_from' ) == '' ) ? get_bloginfo( 'admin_email' ) : get_option( 'mc_event_mail_from' );
		$from      = apply_filters( 'mc_event_mail_from', $from, $details );
		$headers[] = "From: " . __( 'Event Notifications', 'my-calendar' ) . " <$from>";
		$bcc       = apply_filters( 'mc_event_mail_bcc', get_option( 'mc_event_mail_bcc' ), $details );
		if ( $bcc ) {
			$bcc = explode( PHP_EOL, $bcc );
			foreach ( $bcc as $b ) {
				$b = trim( $b );
				if ( is_email( $b ) ) {
					$headers[] = "Bcc: $b";
				}
			}
		}
		$headers = apply_filters( 'mc_customize_email_headers', $headers, $event );
		$subject = jd_draw_template( $details, get_option( 'mc_event_mail_subject' ) );
		$message = jd_draw_template( $details, get_option( 'mc_event_mail_message' ) );
		wp_mail( $to, $subject, $message, $headers );
	}
	if ( get_option( 'mc_html_email' ) == 'true' ) {
		remove_filter( 'wp_mail_content_type', create_function( '', 'return "text/html";' ) );
	}
}

// checks submitted events against akismet or botsmasher, if available, otherwise just returns false 
function mc_spam( $event_url = '', $description = '', $post = array() ) {
	global $akismet_api_host, $akismet_api_port, $current_user;
	$wpcom_api_key = defined( 'WPCOM_API_KEY' ) ? WPCOM_API_KEY : false;
	$current_user = wp_get_current_user();
	if ( current_user_can( 'mc_manage_events' ) ) { // is a privileged user
		return 0;
	}
	$bs = $akismet = false;
	$c  = array();
	// check for Akismet
	if ( ! function_exists( 'akismet_http_post' ) || ! ( get_option( 'wordpress_api_key' ) || $wpcom_api_key ) ) {
		// check for BotSmasher
		$bs = get_option( 'bs_options' );
		if ( is_array( $bs ) ) {
			$bskey = $bs['bs_api_key'];
		} else {
			$bskey = '';
		}
		if ( ! function_exists( 'bs_checker' ) || $bskey == '' ) {
			return 0; // if neither exist
		} else {
			$bs = true;
		}
	} else {
		$akismet = true;
	}
	if ( $akismet ) {
		$c['blog']         = get_option( 'home' );
		$c['user_ip']      = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] );
		$c['user_agent']   = $_SERVER['HTTP_USER_AGENT'];
		$c['referrer']     = $_SERVER['HTTP_REFERER'];
		$c['comment_type'] = 'my_calendar_event';
		if ( $permalink = get_permalink() ) {
			$c['permalink'] = $permalink;
		}
		if ( '' != $event_url ) {
			$c['comment_author_url'] = $event_url;
		}
		if ( '' != $description ) {
			$c['comment_content'] = $description;
		}
		$ignore = array( 'HTTP_COOKIE' );

		foreach ( $_SERVER as $key => $value ) {
			if ( ! in_array( $key, (array) $ignore ) ) {
				$c["$key"] = $value;
			}
		}
		$query_string = '';
		foreach ( $c as $key => $data ) {
			$query_string .= $key . '=' . urlencode( stripslashes( (string) $data ) ) . '&';
		}
		$response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
		if ( 'true' == $response[1] ) {
			return 1;
		} else {
			return 0;
		}
	}
	if ( $bs ) {
		if ( is_user_logged_in() ) {
			$name  = $current_user->user_login;
			$email = $current_user->user_email;
		} else {
			$name  = $post['mcs_name'];
			$email = $post['mcs_email'];
		}
		$args       = array(
			'ip'     => preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] ),
			'email'  => $email,
			'name'   => $name,
			'action' => 'check'
		);
		$args['ip'] = "216.152.251.41";
		$response   = bs_checker( $args );
		if ( $response ) {
			return 1;
		} else {
			return 0;
		}
	}

	return 0;
}

// duplicate of mc_is_url, which really should have been in this file. Bugger.
function _mc_is_url( $url ) {
	return preg_match( '|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url );
}

function mc_external_link( $link ) {
	if ( ! _mc_is_url( $link ) ) {
		return "class='error-link'";
	}

	$url   = parse_url( $link );
	$host  = $url['host'];
	$site  = parse_url( get_option( 'siteurl' ) );
	$known = $site['host'];
	if ( strpos( $host, $known ) === false ) {
		return true;
	}

	return false;
}

add_action( 'admin_enqueue_scripts', 'mc_scripts' );
function mc_scripts() {
	global $current_screen;
	if ( $current_screen->id == 'toplevel_page_my-calendar' && function_exists( 'jd_doTwitterAPIPost' ) ) {
		wp_enqueue_script( 'charCount', plugins_url( 'wp-to-twitter/js/jquery.charcount.js' ), array( 'jquery' ) );
	}
	if ( $current_screen->id == 'toplevel_page_my-calendar' ) {
		if ( current_user_can( 'mc_manage_events' ) ) {
			wp_enqueue_script( 'mc.ajax', plugins_url( 'js/ajax.js', __FILE__ ), array( 'jquery' ) );
			wp_localize_script( 'mc.ajax', 'mc_data', array(
				'action'   => 'delete_occurrence',
				'recur'    => 'add_date',
				'security' => wp_create_nonce( 'mc-delete-nonce' )
			) );
		}
	}
	
	if ( $current_screen->id == 'my-calendar_page_my-calendar-categories' ) {
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'mc-color-picker', plugins_url( 'js/color-picker.js', __FILE__ ), array( 'wp-color-picker' ), false, true );
	}
}

add_action( 'wp_ajax_delete_occurrence', 'mc_ajax_delete_occurrence' );
/**
 * Delete a single occurrence of an event from the event manager.
 *
 * @return string Confirmation message indicating success or failure.
 */
function mc_ajax_delete_occurrence() {
	if ( ! check_ajax_referer( 'mc-delete-nonce', 'security', false ) ) {
		wp_send_json( array( 'success'=>0, 'response' => __( "Invalid Security Check", 'my-calendar' ) ) );
	}

	if ( current_user_can( 'mc_manage_events' ) ) {
		
		global $wpdb;
		$mcdb    = $wpdb;		
		$occur_id = (int) $_REQUEST['occur_id'];
				
		$delete = "DELETE FROM " . my_calendar_event_table() . " WHERE occur_id = $occur_id";
		$result = $mcdb->query( $delete );
				
		if ( $result ) {
			wp_send_json( array( 'success'=>1, 'response' => __( 'Event instance has been deleted.', 'my-calendar' ) ) );
		} else {
			wp_send_json( array( 'success'=>0, 'response' => __( 'Event instance was not deleted.', 'my-calendar' ) ) );
		}

	} else {
		wp_send_json( array( 'success'=>0, 'response' => __( 'You are not authorized to perform this action', 'my-calendar' ) ) );
	}
}


add_action( 'wp_ajax_add_date', 'mc_ajax_add_date' );
/**
 * Add a single additional date for an event from the event manager.
 *
 * @return string Confirmation message indicating success or failure.
 */
function mc_ajax_add_date() {
	if ( ! check_ajax_referer( 'mc-delete-nonce', 'security', false ) ) {
		wp_send_json( array( 'success'=>0, 'response' => __( "Invalid Security Check", 'my-calendar' ) ) );
	}

	if ( current_user_can( 'mc_manage_events' ) ) {
		
		global $wpdb;
		$mcdb     = $wpdb;		
		$event_id = (int) $_REQUEST['event_id'];
		
		if ( $event_id === 0 ) {
			wp_send_json( array( 'success' => 0, 'response' => __( 'No event ID in that request.', 'my-calendar' ) ) );
		}
		
		$event_date = $_REQUEST['event_date'];
		$event_end   = isset( $_REQUEST['event_end'] ) ? $_REQUEST['event_end'] : $event_date;
		$event_time  = $_REQUEST['event_time'];
		$event_endtime = isset( $_REQUEST['event_endtime'] ) ? $_REQUEST['event_endtime'] : '';
		$group_id = (int) $_REQUEST['group_id'];
		
		// event end can not be earlier than event start
		if ( ! $event_end || strtotime( $event_end ) < strtotime( $event_date ) ) {
			$event_end = $event_date;
		}
		
		$begin = strtotime( $event_date . ' ' . $event_time );
		$end   = ( $event_endtime != '' ) ? strtotime( $event_end . ' ' . $event_endtime ) : strtotime( $event_end . ' ' . $event_time ) + HOUR_IN_SECONDS;
		
		$format   = array( '%d', '%s', '%s', '%d' );
		$data = array(
				'occur_event_id' => $event_id,
				'occur_begin'    => date( 'Y-m-d  H:i:s', $begin ),
				'occur_end'      => date( 'Y-m-d  H:i:s', $end ),
				'occur_group_id' => $group_id
			);
		$result = $wpdb->insert( my_calendar_event_table(), $data, $format );
		
		if ( $result ) {
			wp_send_json( array( 'success'=>1, 'response' => __( 'Thanks! I added your new date.', 'my-calendar' ) ) );
		} else {
			wp_send_json( array( 'success'=>0, 'response' => __( 'Sorry! I failed to add that date.', 'my-calendar' ) ) );
		}

	} else {
		wp_send_json( array( 'success'=>0, 'response' => __( 'You are not authorized to perform this action', 'my-calendar' ) ) );
	}
}

function mc_newline_replace( $string ) {
	return (string) str_replace( array( "\r", "\r\n", "\n" ), '', $string );
}

function reverse_array( $array, $boolean, $order ) {
	if ( $order == 'desc' ) {
		return array_reverse( $array, $boolean );
	} else {
		return $array;
	}
}

// in multi-site, wp_is_mobile() won't be defined yet if plug-in is network activated. 
if ( ! function_exists( 'is_plugin_active_for_network' ) ) {
	require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
}

if ( ! function_exists( 'wp_is_mobile' ) ) {
	if ( ! is_plugin_active_for_network( 'my-calendar/my-calendar.php' ) ) {
		function wp_is_mobile() {
			return false;
		}
	}
}

function mc_is_mobile() {
	return apply_filters( 'mc_is_mobile', wp_is_mobile() );
}

/* this function only provides a filter for custom dev. */
function mc_is_tablet() {
	return apply_filters( 'mc_is_tablet', false );
}

function mc_guess_calendar() {
	global $wpdb;
	$mcdb = $wpdb;
	/* If you're looking at this, and have suggestions for other slugs I could be looking at, feel  to let me know. I didn't feel a need to be overly thorough. */
	$my_guesses = array(
		'calendar',
		'events',
		'activities',
		'classes',
		'courses',
		'rehearsals',
		'schedule',
		'calendario',
		'actividades',
		'eventos',
		'kalender',
		'veranstaltungen',
		'unterrichten',
		'eventi',
		'classi'
	);
	$current_uri = get_option( 'mc_uri' );
	// check whether calendar page is a valid URL.
	if ( $current_uri ) {
		$response = wp_remote_head( $current_uri );
		if ( !is_wp_error( $response ) ) {
			$http = $response['response']['code'];
			// Only modify the value if it's explicitly missing. Redirects or secured pages are fine.
			if ( $http == 404 ) {
				$current_uri = '';
			}
		}
	}
	if ( $current_uri == '' ) {
		foreach ( $my_guesses as $guess ) {
			$post_ID = $mcdb->get_var( "SELECT id FROM $mcdb->posts WHERE post_title LIKE '%$guess%' AND post_status = 'publish'" );
			if ( $post_ID ) {
				$link = get_permalink( $post_ID );
				update_option( 'mc_uri', $link );
				update_option( 'mc_uri_id', $post_ID );
				$return = array( 'response' => true, 'message'=> __( 'Is this your calendar page?', 'my-calendar' ) . ' <code>' . $link . '</code>' );

				return $return;
			} else {
				update_option( 'mc_uri', '' );
				update_option( 'mc_uri_id', '' );
				$return = array( 'response' => false, 'message' => __( 'No valid calendar detected. Please provide a URL!', 'my-calendar' ) );
				return $return;
			}
		}
	}
	return;
}

function mc_get_support_form() {
	global $current_user;
	$current_user = wp_get_current_user();
	// send fields for My Calendar
	$version       = get_option( 'mc_version' );
	$mc_db_version = get_option( 'mc_db_version' );
	$mc_uri        = get_option( 'mc_uri' );
	$mc_css        = get_option( 'mc_css_file' );

	$license         = ( get_option( 'mcs_license_key' ) != '' ) ? get_option( 'mcs_license_key' ) : 'none';
	$tickets_license = ( get_option( 'mt_license_key' ) != '' ) ? get_option( 'mt_license_key' ) : 'none';
	// send fields for all plugins
	$wp_version = get_bloginfo( 'version' );
	$home_url   = home_url();
	$wp_url     = site_url();
	$language   = get_bloginfo( 'language' );
	$charset    = get_bloginfo( 'charset' );
	// server
	$php_version = phpversion();

	$admin_email = get_option( 'admin_email' );
	// theme data
	$theme         = wp_get_theme();
	$theme_name    = $theme->Name;
	$theme_uri     = $theme->ThemeURI;
	$theme_parent  = $theme->Template;
	$theme_version = $theme->Version;

	// plugin data
	$plugins        = get_plugins();
	$plugins_string = '';

	foreach ( array_keys( $plugins ) as $key ) {
		if ( is_plugin_active( $key ) ) {
			$plugin         =& $plugins[ $key ];
			$plugin_name    = $plugin['Name'];
			$plugin_uri     = $plugin['PluginURI'];
			$plugin_version = $plugin['Version'];
			$plugins_string .= "$plugin_name: $plugin_version; $plugin_uri\n";
		}
	}
	$data    = "
================ Installation Data ====================
==My Calendar:==
Version: $version
DB Version: $mc_db_version
URI: $mc_uri
CSS: $mc_css
Licenses: Pro - $license; Ticketing - $tickets_license
Requester Email: $current_user->user_email
Admin Email: $admin_email

==WordPress:==
Version: $wp_version
URL: $home_url
Install: $wp_url
Language: $language
Charset: $charset

==Extra info:==
PHP Version: $php_version
Server Software: $_SERVER[SERVER_SOFTWARE]
User Agent: $_SERVER[HTTP_USER_AGENT]

==Theme:==
Name: $theme_name
URI: $theme_uri
Parent: $theme_parent
Version: $theme_version

==Active Plugins:==
$plugins_string
";
	$request = '';
	if ( isset( $_POST['mc_support'] ) ) {
		$nonce = $_REQUEST['_wpnonce'];
		if ( ! wp_verify_nonce( $nonce, 'my-calendar-nonce' ) ) {
			die( "Security check failed" );
		}
		$request       = ( ! empty( $_POST['support_request'] ) ) ? stripslashes( $_POST['support_request'] ) : false;
		$has_donated   = ( $_POST['has_donated'] == 'on' ) ? "Donor" : "No donation";
		$has_purchased = ( $_POST['has_purchased'] == 'on' ) ? "Purchaser" : "No purchase";
		$has_read_faq  = ( $_POST['has_read_faq'] == 'on' ) ? "Read FAQ" : false;
		$subject       = "My Calendar support request. $has_donated; $has_purchased";
		$message       = $request . "\n\n" . $data;
		// Get the site domain and get rid of www. from pluggable.php
		$sitename = strtolower( $_SERVER['SERVER_NAME'] );
		if ( substr( $sitename, 0, 4 ) == 'www.' ) {
			$sitename = substr( $sitename, 4 );
		}
		$from_email = 'wordpress@' . $sitename;
		$from       = "From: \"$current_user->display_name\" <$from_email>\r\nReply-to: \"$current_user->display_name\" <$current_user->user_email>\r\n";

		if ( ! $has_read_faq ) {
			echo "<div class='message error'><p>" . __( 'Please read the FAQ and other Help documents before making a support request.', 'my-calendar' ) . "</p></div>";
		} else if ( ! $request ) {
			echo "<div class='message error'><p>" . __( 'Please describe your problem in detail. I\'m not psychic.', 'my-calendar' ) . "</p></div>";
		} else {
			$sent = wp_mail( "plugins@joedolson.com", $subject, $message, $from );
			if ( $sent ) {
				if ( $has_donated == 'Donor' || $has_purchased == 'Purchaser' ) {
					echo "<div class='message updated'><p>" . __( 'Thank you for supporting the continuing development of this plug-in! I\'ll get back to you as soon as I can.', 'my-calendar' ) . "</p></div>";
				} else {
					echo "<div class='message updated'><p>" . __( 'I\'ll get back to you as soon as I can, after dealing with any support requests from plug-in supporters.', 'my-calendar' ) . "</p></div>";
				}
			} else {
				echo "<div class='message error'><p>" . __( "Sorry! I couldn't send that message. Here's the text of your request:", 'my-calendar' ) . "</p><p>" . sprintf( __( '<a href="%s">Contact me here</a>, instead</p>', 'my-calendar' ), 'https://www.joedolson.com/contact/' ) . "<pre>$request</pre></div>";
			}
		}
	}

	echo "
	<form method='post' action='" . admin_url( 'admin.php?page=my-calendar-help' ) . "'>
		<div><input type='hidden' name='_wpnonce' value='" . wp_create_nonce( 'my-calendar-nonce' ) . "' /></div>
		<div>
		<p>" .
	     __( '<strong>Note</strong>: I keep records of donations, but if your donation came from <em>somebody other than your account at this web site</em>, please note this in your message.', 'my-calendar' )
	     . "<p>
		<code>" . __( 'From:', 'my-calendar' ) . " \"$current_user->display_name\" &lt;$current_user->user_email&gt;</code>
		</p>
		<p>
			<input type='checkbox' name='has_read_faq' id='has_read_faq' value='on' required='required' aria-required='true' /> <label for='has_read_faq'>" . __( 'I have read <a href="http://www.joedolson.com/my-calendar/faq/">the FAQ for this plug-in</a>.', 'my-calendar' ) . " <span>(required)</span></label>
		</p>
		<p>
			<input type='checkbox' name='has_donated' id='has_donated' value='on' /> <label for='has_donated'>" . sprintf( __( 'I <a href="%s">made a donation to help support this plug-in</a>.', 'my-calendar' ), 'https://www.joedolson.com/donate/' ) . "</label>
		</p>
		<p>
			<input type='checkbox' name='has_purchased' id='has_purchased' value='on' /> <label for='has_purchased'>" . __( 'I have <a href="http://www.joedolson.com/my-calendar/users-guide/">purchased the User\'s Guide</a>, but could not find an answer to this question.', 'my-calendar' ) . "</label>
		</p>
		<p>
			<label for='support_request'>Support Request:</label><br /><textarea name='support_request' id='support_request' required aria-required='true' cols='80' rows='10' class='widefat'>" . stripslashes( $request ) . "</textarea>
		</p>
		<p>
			<input type='submit' value='" . __( 'Send Support Request', 'my-calendar' ) . "' name='mc_support' class='button-primary' />
		</p>
		<p>" .
	     __( 'The following additional information will be sent with your support request:', 'my-calendar' )
	     . "</p>
		<div class='mc_support'>
		" . wpautop( $data ) . "
		</div>
		</div>
	</form>";
}


function mc_recur_options( $value ) {
	$s = ( $value == 'S' ) ? " selected='selected'" : '';
	$d = ( $value == 'D' ) ? " selected='selected'" : '';
	$e = ( $value == 'E' ) ? " selected='selected'" : '';
	$w = ( $value == 'W' || $value == 'B' ) ? " selected='selected'" : '';
	$m = ( $value == 'M' ) ? " selected='selected'" : '';
	$u = ( $value == 'U' ) ? " selected='selected'" : '';
	$y = ( $value == 'Y' ) ? " selected='selected'" : '';

	$return = "
				<option class='input' value='S' $s>" . __( 'Does not recur', 'my-calendar' ) . "</option>
				<option class='input' value='D' $d>" . __( 'Days', 'my-calendar' ) . "</option>
				<option class='input' value='E' $e>" . __( 'Days, weekdays only', 'my-calendar' ) . "</option>
				<option class='input' value='W' $w>" . __( 'Weeks', 'my-calendar' ) . "</option>
				<option class='input' value='M' $m>" . __( 'Months by date (e.g., the 24th of each month)', 'my-calendar' ) . "</option>
				<option class='input' value='U' $u>" . __( 'Month by day (e.g., the 3rd Monday of each month)', 'my-calendar' ) . "</option>
				<option class='input' value='Y' $y>" . __( 'Year', 'my-calendar' ) . "</option>
	";

	return $return;
}

//".$select = ( $value == 'D' )?$selected:''."

function _mc_increment_values( $recur ) {
	switch ( $recur ) {
		case "S": // single
			return 0;
			break;
		case "D": // daily
			return 500;
			break;
		case "E": // weekdays
			return 400;
			break;
		case "W": // weekly
			return 240;
			break;
		case "B": // biweekly
			return 120;
			break;
		case "M": // monthly
		case "U":
			return 60;
			break;
		case "Y":
			return 10;
			break;
		default:
			false;
	}
}

/*
* @param event_id, number of repetitions
* @return true/false
*/
function mc_change_instances( $id, $repeats, $begin = false ) {
	global $wpdb;
	$mcdb   = $wpdb;
	$events = $mcdb->get_results( $mcdb->prepare( "SELECT * FROM " . my_calendar_event_table() . " WHERE occur_event_id = %d ORDER BY occur_begin DESC", $id ) );
	$count  = count( $events );
	$last   = $count - 1;
	if ( $begin == false ) {
		if ( $count > $repeats ) {
			// if higher than previous: delete
			$diff = $count - $repeats;
			for ( $i = 0; $i < $diff; $i ++ ) {
				$oid = $events[ $i ]->occur_id;
				$sql = "DELETE FROM " . my_calendar_event_table() . " WHERE occur_id = $oid";
				$mcdb->query( $sql );
			}
		} else if ( $count < $repeats ) {
			// if lower: add more by incrementing from the last date available.
			$dates = array(
				'event_begin'   => date( 'Y-m-d', strtotime( $events[0]->occur_begin ) ),
				'event_time'    => date( 'H:i:s', strtotime( $events[0]->occur_begin ) ),
				'event_end'     => date( 'Y-m-d', strtotime( $events[0]->occur_end ) ),
				'event_endtime' => date( 'H:i:s', strtotime( $events[0]->occur_end ) )
			);
			mc_increment_event( $id, $dates );
		} else {
			return false;
		}
	} else {
		$sql = "DELETE FROM " . my_calendar_event_table() . " WHERE occur_event_id = $id";
		$mcdb->query( $sql );
		$dates = array(
			'event_begin'   => date( 'Y-m-d', strtotime( $events[ $last ]->occur_begin ) ),
			'event_time'    => date( 'H:i:s', strtotime( $events[ $last ]->occur_begin ) ),
			'event_end'     => date( 'Y-m-d', strtotime( $events[ $last ]->occur_end ) ),
			'event_endtime' => date( 'H:i:s', strtotime( $events[ $last ]->occur_end ) )
		);
		mc_increment_event( $id, $dates );
	}

	return true;
}

/* deletes all instances of an event without deleting the event details. Sets stage for rebuilding event instances. */
function mc_delete_instances( $id ) {
	global $wpdb;
	$id  = (int) $id;
	$sql = "DELETE FROM " . my_calendar_event_table() . " WHERE occur_event_id = $id";
	$wpdb->query( $sql );

	return;
}

/* 
 * @param integer $id Event ID in my_calendar db
 * @param array $post an array of POST data (or array containing dates)
 * @param boolean $test true if testing
 *
 * @return null by default; data array if testing
*/
function mc_increment_event( $id, $post = array(), $test = false ) {
	global $wpdb;
	$event  = mc_get_event_core( $id );
	$data   = array();
	$return = array();
	if ( empty( $post ) ) {
		$orig_begin = $event->event_begin . ' ' . $event->event_time;
		$orig_end   = $event->event_end . ' ' . $event->event_endtime;
	} else {
		$orig_begin = @$post['event_begin'] . ' ' . @$post['event_time'];
		$orig_end   = @$post['event_end'] . ' ' . @$post['event_endtime'];
	}
	$group_id = $event->event_group_id;
	$format   = array( '%d', '%s', '%s', '%d' );
	$recurs   = str_split( $event->event_recur, 1 );
	$recur    = $recurs[0];
	$every    = ( isset( $recurs[1] ) ) ? $recurs[1] : 1;
	if ( $recur != "S" ) {
		// if this event had a rep of 0, translate that.
		$event_repetition = ( $event->event_repeats != 0 ) ? $event->event_repeats : _mc_increment_values( $recur );
		$numforward       = (int) $event_repetition;
		if ( $recur != 'S' ) {
			switch ( $recur ) {
				case "D":
				case "E":
					for ( $i = 0; $i <= $numforward; $i ++ ) {
						$begin = my_calendar_add_date( $orig_begin, $i * $every, 0, 0 );
						$end   = my_calendar_add_date( $orig_end, $i * $every, 0, 0 );
						if ( ( $recur == 'E' && ( date( 'w', $begin ) != 0 && date( 'w', $begin ) != 6 ) ) || $recur == 'D' ) {
							$data = array(
								'occur_event_id' => $id,
								'occur_begin'    => date( 'Y-m-d  H:i:s', $begin ),
								'occur_end'      => date( 'Y-m-d  H:i:s', $end ),
								'occur_group_id' => $group_id
							);
							if ( $test == 'test' && $i > 0 ) {
								return $data;
							}
							if ( $test == true ) {
								$return[] = $data;
							}
							if ( ! $test ) {
								$wpdb->insert( my_calendar_event_table(), $data, $format );
							}
						} else {
							$numforward ++;
						}
					}
					break;
				case "W":
					for ( $i = 0; $i <= $numforward; $i ++ ) {
						$begin = my_calendar_add_date( $orig_begin, ( $i * 7 ) * $every, 0, 0 );
						$end   = my_calendar_add_date( $orig_end, ( $i * 7 ) * $every, 0, 0 );
						$data  = array(
							'occur_event_id' => $id,
							'occur_begin'    => date( 'Y-m-d  H:i:s', $begin ),
							'occur_end'      => date( 'Y-m-d  H:i:s', $end ),
							'occur_group_id' => $group_id
						);
						if ( $test == 'test' && $i > 0 ) {
							return $data;
						}
						if ( $test == true ) {
							$return[] = $data;
						}						
						if ( ! $test ) {
							$sql = $wpdb->insert( my_calendar_event_table(), $data, $format );
						}
					}
					break;
				case "B":
					for ( $i = 0; $i <= $numforward; $i ++ ) {
						$begin = my_calendar_add_date( $orig_begin, ( $i * 14 ), 0, 0 );
						$end   = my_calendar_add_date( $orig_end, ( $i * 14 ), 0, 0 );
						$data  = array(
							'occur_event_id' => $id,
							'occur_begin'    => date( 'Y-m-d  H:i:s', $begin ),
							'occur_end'      => date( 'Y-m-d  H:i:s', $end ),
							'occur_group_id' => $group_id
						);
						if ( $test == 'test' && $i > 0 ) {
							return $data;
						}
						if ( $test == true ) {
							$return[] = $data;
						}
						if ( ! $test ) {
							$wpdb->insert( my_calendar_event_table(), $data, $format );
						}
					}
					break;
				case "M":
					for ( $i = 0; $i <= $numforward; $i ++ ) {
						$begin = my_calendar_add_date( $orig_begin, 0, $i * $every, 0 );
						$end   = my_calendar_add_date( $orig_end, 0, $i * $every, 0 );
						$data  = array(
							'occur_event_id' => $id,
							'occur_begin'    => date( 'Y-m-d  H:i:s', $begin ),
							'occur_end'      => date( 'Y-m-d  H:i:s', $end ),
							'occur_group_id' => $group_id
						);
						if ( $test == 'test' && $i > 0 ) {
							return $data;
						}
						if ( $test == true ) {
							$return[] = $data;
						}
						if ( ! $test ) {
							$wpdb->insert( my_calendar_event_table(), $data, $format );
						}
					}
					break;
				case "U": 
					// important to keep track of which date variables are strings and which are timestamps
					$week_of_event = week_of_month( date( 'd', strtotime( $event->event_begin ) ) );
					$newbegin      = my_calendar_add_date( $orig_begin, 28, 0, 0 );
					$newend        = my_calendar_add_date( $orig_end, 28, 0, 0 );
					$fifth_week    = $event->event_fifth_week;
					$data          = array(
						'occur_event_id' => $id,
						'occur_begin'    => date( 'Y-m-d  H:i:s', strtotime( $orig_begin ) ),
						'occur_end'      => date( 'Y-m-d  H:i:s', strtotime( $orig_end ) ),
						'occur_group_id' => $group_id
					);

					if ( ! $test ) {
						$wpdb->insert( my_calendar_event_table(), $data, $format );
					}
					$numforward = $numforward - 1;
					for ( $i = 0; $i <= $numforward; $i ++ ) {
						$next_week_diff = ( date( 'm', $newbegin ) == date( 'm', my_calendar_add_date( date( 'Y-m-d', $newbegin ), 7, 0, 0 ) ) ) ? false : true;
						$move_event     = ( ( $fifth_week == 1 ) && ( $week_of_event == ( week_of_month( date( 'd', $newbegin ) ) + 1 ) ) && $next_week_diff == true ) ? true : false;
						if ( $week_of_event == week_of_month( date( 'd', $newbegin ) ) || $move_event == true ) {
							// continue;
						} else {
							$newbegin   = my_calendar_add_date( date( 'Y-m-d  H:i:s', $newbegin ), 7, 0, 0 );
							$newend     = my_calendar_add_date( date( 'Y-m-d  H:i:s', $newend ), 7, 0, 0 );
							$move_event = ( $fifth_week == 1 && $week_of_event == week_of_month( date( 'd', $newbegin ) ) + 1 ) ? true : false;
							if ( $week_of_event == week_of_month( date( 'd', $newbegin ) ) || $move_event == true ) {
								// continue;
							} else {
								$newbegin = my_calendar_add_date( date( 'Y-m-d  H:i:s', $newbegin ), 14, 0, 0 );
								$newend   = my_calendar_add_date( date( 'Y-m-d  H:i:s', $newend ), 14, 0, 0 );
							}
						}
						$data = array(
							'occur_event_id' => $id,
							'occur_begin'    => date( 'Y-m-d  H:i:s', $newbegin ),
							'occur_end'      => date( 'Y-m-d  H:i:s', $newend ),
							'occur_group_id' => $group_id
						);
						if ( $test == 'test' && $i > 0 ) {
							return $data;
						}
						if ( ! $test ) {
							$wpdb->insert( my_calendar_event_table(), $data, $format );
						}
						$newbegin = my_calendar_add_date( date( 'Y-m-d  H:i:s', $newbegin ), 28, 0, 0 );
						$newend   = my_calendar_add_date( date( 'Y-m-d  H:i:s', $newend ), 28, 0, 0 );
					}
					break;
				case "Y":
					for ( $i = 0; $i <= $numforward; $i ++ ) {
						$begin = my_calendar_add_date( $orig_begin, 0, 0, $i * $every );
						$end   = my_calendar_add_date( $orig_end, 0, 0, $i * $every );
						$data  = array(
							'occur_event_id' => $id,
							'occur_begin'    => date( 'Y-m-d  H:i:s', $begin ),
							'occur_end'      => date( 'Y-m-d  H:i:s', $end ),
							'occur_group_id' => $group_id
						);
						if ( $test == 'test' && $i > 0 ) {
							return $data;
						}
						if ( $test == true ) {
							$return[] = $data;
						}
						if ( ! $test ) {
							$wpdb->insert( my_calendar_event_table(), $data, $format );
						}
					}
					break;
			}
		}
	} else {
		$begin = strtotime( $orig_begin );
		$end   = strtotime( $orig_end );
		$data  = array(
			'occur_event_id' => $id,
			'occur_begin'    => date( 'Y-m-d H:i:s', $begin ),
			'occur_end'      => date( 'Y-m-d H:i:s', $end ),
			'occur_group_id' => $group_id
		);
		if ( ! $test ) {
			$wpdb->insert( my_calendar_event_table(), $data, $format );
		}
	}

	if ( $test == true ) {
		return $return;
	}
	
	return $data;
}

function mc_get_details_link( $event ) {
	if ( is_numeric( $event ) ) {
		$event = mc_get_event( $event );
	}
	// if available, and not querying remotely, use permalink.
	$permalinks   = apply_filters( 'mc_use_permalinks', get_option( 'mc_use_permalinks' ) );
	$permalinks   = ( $permalinks === 1 || $permalinks === true || $permalinks === 'true' ) ? true : false;
	$details_link = mc_event_link( $event );
	if ( $event->event_post != 0 && get_option( 'mc_remote' ) != 'true' && $permalinks ) {
		$details_link = add_query_arg( 'mc_id', $event->occur_id, get_permalink( $event->event_post ) );
	} else {
		if ( get_option( 'mc_uri' ) != '' && _mc_is_url( get_option( 'mc_uri' ) ) ) {
			$details_link = mc_build_url( array( 'mc_id' => $event->occur_id ), array(
					'month',
					'dy',
					'yr',
					'ltype',
					'loc',
					'mcat',
					'format',
					'feed',
					'page_id',
					'p',
					'mcs',
					'time',
					'page'
				), get_option( 'mc_uri' ) );
		}
	}

	return apply_filters( 'mc_customize_details_link', $details_link, $event );
}

// Actions -- these are action hooks attached to My Calendar events, usable to add additional actions during those events.
add_action( 'init', 'mc_register_actions' );
function mc_register_actions() {
	add_filter( 'mc_event_registration', 'mc_standard_event_registration', 10, 4 );
	add_filter( 'mc_datetime_inputs', 'mc_standard_datetime_input', 10, 4 );
	add_action( 'mc_transition_event', 'mc_tweet_approval', 10, 2 );
	add_action( 'mc_save_event', 'mc_event_post', 10, 3 );
	add_action( 'mc_delete_event', 'mc_event_delete_post', 10, 2 );
	add_action( 'mc_mass_delete_events', 'mc_event_delete_posts', 10, 1 );
	add_action( 'parse_request', 'my_calendar_api' );
}

// Filters
add_filter( 'post_updated_messages', 'mc_posttypes_messages' );

// Actions
add_action( 'init', 'mc_taxonomies', 0 );
add_action( 'init', 'mc_posttypes' );

function mc_event_delete_posts( $deleted ) {
	foreach ( $deleted as $delete ) {
		$posts = get_posts( array(
				'post_type'  => 'mc-events',
				'meta_key'   => '_mc_event_id',
				'meta_value' => $delete
		) );
		if ( isset( $posts[0] ) && is_object( $posts[0] ) ) {	
			$post_id = $posts[0]->ID;
			wp_delete_post( $post_id, true );
		}
	}
}

add_action( 'load-options-permalink.php', 'mc_load_permalinks' );
function mc_load_permalinks() {
	if( isset( $_POST['mc_cpt_base'] ) )	{
		update_option( 'mc_cpt_base', sanitize_text_field( $_POST['mc_cpt_base'] ) );
	}
	
	// Add a settings field to the permalink page
	add_settings_field( 'mc_cpt_base', __( 'My Calendar Events base' ), 'mc_field_callback', 'permalink', 'optional', array( 'label_for'=>'mc_cpt_base' ) );
}

function mc_field_callback() {
	$value = ( get_option( 'mc_cpt_base' ) != '' ) ? get_option( 'mc_cpt_base' ) : 'mc-events';	
	echo '<input type="text" value="' . esc_attr( $value ) . '" name="mc_cpt_base" id="mc_cpt_base" class="regular-text" />';
}

function mc_posttypes() {
	$arguments = array(
		'public'              => apply_filters( 'mc_event_posts_public', true ),
		'publicly_queryable'  => true,
		'exclude_from_search' => true,
		'show_ui'             => true,
		'show_in_menu'        => apply_filters( 'mc_show_custom_posts_in_menu', false ),
		'menu_icon'           => null,
		'supports'            => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'custom-fields' )
	);

	$types   = array(
		'mc-events' => array(
			__( 'event', 'my-calendar' ),
			__( 'events', 'my-calendar' ),
			__( 'Event', 'my-calendar' ),
			__( 'Events', 'my-calendar' ),
			$arguments
		),
	);
	$enabled = array( 'mc-events' );
	$slug = ( get_option( 'mc_cpt_base' ) != '' ) ? get_option( 'mc_cpt_base' ) : 'mc-events';
	if ( is_array( $enabled ) ) {
		foreach ( $enabled as $key ) {
			$value  =& $types[ $key ];
			$labels = array(
				'name'               => _x( $value[3], 'post type general name' ),
				'singular_name'      => _x( $value[2], 'post type singular name' ),
				'add_new'            => _x( 'Add New', $key, 'my-calendar' ),
				'add_new_item'       => sprintf( __( 'Create New %s', 'my-calendar' ), $value[2] ),
				'edit_item'          => sprintf( __( 'Modify %s', 'my-calendar' ), $value[2] ),
				'new_item'           => sprintf( __( 'New %s', 'my-calendar' ), $value[2] ),
				'view_item'          => sprintf( __( 'View %s', 'my-calendar' ), $value[2] ),
				'search_items'       => sprintf( __( 'Search %s', 'my-calendar' ), $value[3] ),
				'not_found'          => sprintf( __( 'No %s found', 'my-calendar' ), $value[1] ),
				'not_found_in_trash' => sprintf( __( 'No %s found in Trash', 'my-calendar' ), $value[1] ),
				'parent_item_colon'  => ''
			);
			$raw    = $value[4];
			$args   = array(
				'labels'              => $labels,
				'public'              => $raw['public'],
				'publicly_queryable'  => $raw['publicly_queryable'],
				'exclude_from_search' => $raw['exclude_from_search'],
				'show_ui'             => $raw['show_ui'],
				'show_in_menu'        => $raw['show_in_menu'],
				'menu_icon'           => ( $raw['menu_icon'] == null ) ? plugins_url( 'images', __FILE__ ) . "/icon.png" : $raw['menu_icon'],
				'query_var'           => true,
				'rewrite'             => array(
					'with_front' => false,
					'slug'       => apply_filters( 'mc_event_slug', $slug )
				),
				'hierarchical'        => false,
				'menu_position'       => 20,
				'supports'            => $raw['supports']
			);
			register_post_type( $key, $args );
		}
	}
}

/**
 * Most people don't want comments open on events. This will automatically close them. 
 */
function mc_close_comments( $posts ) {
	if ( !is_single() || empty( $posts ) ) { return $posts; }
	
	if ( 'mc-events' == get_post_type($posts[0]->ID) ) {
		if ( apply_filters( 'mc_autoclose_comments', true ) && $posts[0]->comment_status != 'closed' ) {
			$posts[0]->comment_status = 'closed';
			$posts[0]->ping_status    = 'closed';
			wp_update_post( $posts[0] );
		}
	}
	
	return $posts;
}
add_filter( 'the_posts', 'mc_close_comments' );


function mc_taxonomies() {
	global $mc_types;
	$types   = $mc_types;
	$enabled = array( 'mc-events' );
	if ( is_array( $enabled ) ) {
		foreach ( $enabled as $key ) {
			$value = $types[ $key ];
			register_taxonomy(
				"mc-event-category",    // internal name = machine-readable taxonomy name
				array( $key ),    // object type = post, page, link, or custom post-type
				array(
					'hierarchical' => true,
					'label'        => sprintf( __( '%s Categories', 'my-calendar' ), $value[2] ),
					// the human-readable taxonomy name
					'query_var'    => true,
					// enable taxonomy-specific querying
					'rewrite'      => array( 'slug' => apply_filters( 'mc_event_category_slug', 'mc-event-category' ) ),
					// pretty permalinks for your taxonomy?
				)
			);
		}
	}
}

function mc_posttypes_messages( $messages ) {
	global $post, $post_ID, $mc_types;
	$types   = $mc_types;
	$enabled = array( 'mc-events' );
	if ( is_array( $enabled ) ) {
		foreach ( $enabled as $key ) {
			$value            = $types[ $key ];
			$messages[ $key ] = array(
				0  => '', // Unused. Messages start at index 1.
				1  => sprintf( __( '%1$s updated. <a href="%2$s">View %1$s</a>' ), $value[2], esc_url( get_permalink( $post_ID ) ) ),
				2  => __( 'Custom field updated.' ),
				3  => __( 'Custom field deleted.' ),
				4  => sprintf( __( '%s updated.' ), $value[2] ),
				/* translators: %s: date and time of the revision */
				5  => isset( $_GET['revision'] ) ? sprintf( __( '%1$s restored to revision from %2$ss' ), $value[2], wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
				6  => sprintf( __( '%1$s published. <a href="%2$s">View %3$s</a>' ), $value[2], esc_url( get_permalink( $post_ID ) ), $value[0] ),
				7  => sprintf( __( '%s saved.' ), $value[2] ),
				8  => sprintf( __( '%1$s submitted. <a target="_blank" href="%2$s">Preview %3$s</a>' ), $value[2], esc_url( add_query_arg( 'preview', 'true', get_permalink( $post_ID ) ) ), $value[0] ),
				9  => sprintf( __( '%1$s scheduled for: <strong>%2$s</strong>. <a target="_blank" href="%3$s">Preview %4$s</a>' ),
					$value[2], date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink( $post_ID ) ), $value[0] ),
				10 => sprintf( __( '%1$s draft updated. <a target="_blank" href="%2$s">Preview %3$s</a>' ), $value[2], esc_url( add_query_arg( 'preview', 'true', get_permalink( $post_ID ) ) ), $value[0] ),
			);
		}
	}

	return $messages;
}

/* By default, disable comments on event posts */
add_filter( 'default_content', 'mc_posttypes_defaults', 10, 2 );
function mc_posttypes_defaults( $post_content, $post ) {
	if ( $post->post_type ) {
		switch ( $post->post_type ) {
			case 'mc-events':
				$post->comment_status = 'closed';
				break;
		}
	}

	return $post_content;
}

function mc_dismiss_notice() {
	if ( isset( $_GET['dismiss'] ) && $_GET['dismiss'] == 'update' ) {
		update_option( 'mc_update_notice', 1 );
	}
}

mc_dismiss_notice();

add_action( 'admin_notices', 'mc_update_notice' );
function mc_update_notice() {
	if ( current_user_can( 'activate_plugins' ) && get_option( 'mc_update_notice' ) == 0 || ! get_option( 'mc_update_notice' ) ) {
		$dismiss = admin_url( 'admin.php?page=my-calendar-behaviors&dismiss=update' );
		echo "<div class='updated fade'><p>" . sprintf( __( "<strong>Update notice:</strong> if you use custom JS with My Calendar, you need to activate your custom scripts following this update. <a href='%s'>Dismiss Notice</a>", 'wp-to-twitter' ), $dismiss ) . "</p></div>";
	}
}

// Actions are only performed after their respective My Calendar events have been successfully completed.
// If there are errors in the My Calendar event, the action hook will not fire.
/*
mc_save_event
Performed when an event is added, updated, or copied. Arguments are the action taken ('edit','copy','add') and 
and an array of the processed event data

mc_delete_event
Performed when an event is deleted. Argument is the event_id.

mc_mass_delete_events
Performed when events are deleted en masse. Argument is an array of event_ids deleted.

*/

// Filters -- these are filters applied on My Calendar elements, which you can use to modify output. 
// Base values are empty unless otherwise specified.
// The actual filters are in the places they belong, but these are here for documentation.
/*
mc_before_calendar
	- inserts information before the calendar is output to the page. 
	- received arguments: calendar setup variables
	
mc_after_calendar
	- inserts information after the calendar is output to the page.
	- received arguments: calendar setup variables
	
mc_before_event_title
	- insert information at beginning of event title.
	- received arguments: event object
	
mc_after_event_title
	- insert information after event title.
	- received arguments: event object
	
mc_before_event
	- insert information before event details
	- received arguments: event object
	
mc_after_event
	- insert information after event details
	- received arguments: event object
	
mc_event_content
	- base value: event content output.
	- received arguments: event details as string, event object
	- runs for all event output formats.
	
	mc_event_content_mini
		- same as above, only runs in mini output
	mc_event_content_list
		- same as above, only runs in list output
	mc_event_content_single
		- same as above, only runs in single output
	mc_event_content_grid
		- same as above, only runs in grid output

mc_event_upcoming
	- base value: upcoming event output
	- received arguments: event object
	
mc_event_today
	- base value: today's event output
	- received arguments: event object

mc_category_selector
	- base value: category selector output
	- received arguments: categories object

mc_location_selector
	- base value: location selector output
	- received arguments: locations object

mc_location_list
	-base value: location list output
	-received arguments: locations object
	
mc_category_key
	- base value: category key output
	- received arguments: categories object

mc_previous_link
	- base value: previous link output
	- received arguments: array of previous link parameters

mc_next_link
	- base value: next link output
	- received arguments: array of previous link parameters

mc_jumpbox
	- base value: jumpbox output
	- received arguments: none
	
mc_filter_styles
	- base value: styles head block (string)
	- received arguments: URL for your selected My Calendar stylesheet
	
mc_filter_javascript_footer
	- base value: javascript footer block
	- received arguments: none
	
mc_filter_shortcodes
	- base value: array of shortcodes and values
	- received arguments: event object
	
mc_search_template
	- base value: default search template (<strong>{date}</strong> {title} {details})
	- no arguments
	
mc_event_mail_to
	- base value: stored "to" email address from options
	- arguments: event template tag array
	
apply_filters( 'mc_display_format', $format, $args )

*/