Jump to content

sfraise

Members
  • Posts

    48
  • Joined

  • Last visited

    Never

Profile Information

  • Gender
    Not Telling

sfraise's Achievements

Member

Member (2/5)

0

Reputation

  1. Here is a brief description of what I'm doing... I have a very large complex social networking site built on the Joomla CMS with many one off components and modules and many heavily modified ones. One thing I'm doing is using a module called mod_component built by jomexperts (their website forum doesn't work so no help there) which allows you to load a component within a module, in this case it's loading the wall component within a module position called in a tab on the community builder profiles. This module is modified a bit in order to include the user id in the internal url it creates in order to determine if you are viewing your own profile or someone else's and to determine who's wall it is. This all worked like a champ until a couple of weeks ago when for whatever reason the server was unresponsive for a few minutes. When it came back up the wall no longer would load, so basically the mod_component module simply stopped working. I racked my brain for a couple of days trying to figure out what was causing it when it just suddenly started working again on it's own. It worked fine again until last night, according to my host there was a large scale ddos attack causing the server to be unresponsive again for a few minutes, when it came back up the wall no longer loaded again. I'm using a dual dedicated server set up with the web files on one server and the other server strictly dedicated to the database, don't think this matters in this case but figured I'd mention it. On to the heart of the problem... So I began going through the module code and doing an echo of each variable starting at the top of the file. It works fine until I get to a little bit of curl code that writes the session id to a cookie. Doing a die("curl"); call right before that code causes the page to break and respond with curl. I tweaked the code a bit to specify the path to cookiejar and the code creates the file, but is unable to write to it. Now I created an exact mirror instance of this site on a separate server and it works fine, on that server it can both create the file and write to it without any problem. So... Since this worked on this server fine until it went down briefly last night, then stopped working when it came back up, something changed somewhere somehow either with permissions or something else that would cause curl to not be able to write. What baffles me is it's able to create the file, just not write to it?????? Does anyone have any idea on what could be happening here? I thought maybe it was a case of a curl session not being closed when the server went down locking it up, but I cleared the php sessions, joomla sessions, cache, and rebooted the machine and it still didn't work so I'm not sure on that theory. I really really really need a genius here to point me the right direction lol. Here's a copy of the modules main file, commented out parts of the curl code are what I was using to determine if it could both create and write a file: <?php /** * Component Loader * @version : 1.0.1 * @package : Component Loader 1.0.1 * @author : JomExperts * @Copyright : Copyright © 2009 by Jomexperts.com * @license : Component Loader 1.0.1 is Free Software released under the GNU/GPL License. */ // no direct access defined('_JEXEC') or die ('Restricted access'); /* Getting Parameters */ $component= $params->get('component',''); $view= $params->get('views',''); $custom=$params->get('custom',''); $auto=$params->get('autojscss','0'); $js=$params->get('customjs',''); $css=$params->get('customcss',''); $head_js=$params->get('custombodyjs',''); $head_css=$params->get('custombodycss',''); /* End of Parameters */ $type=array(); $layout=array(); if($component!=''){ /* Getting components parameters like task, view, layout, etc. */ $re1='.*?'; $re2='(?:[a-z][a-z0-9_]*)'; $re3='.*?'; $re4='((?:[a-z][a-z0-9_]*))'; $re5='.*?'; $re6='((?:[a-z][a-z0-9_]*))'; if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5.$re6."/is", $view, $matches)){ $type=$matches[1]; $layout=$matches[2]; } /* end */ /* Creating URL */ $user_id = $_GET['user']; $url=JURI::root().'index.php?'.$component.'&tmpl=component&print=1&wuid='.$user_id.''; for($i=1;$i<count($type);$i++){ $url.='&'.$type[$i].'='.$layout[$i]; } $url.=$custom; /* End */ /* Getting current joomla Session ID */ $session=&JFactory::getSession(); $session_id=$session->getId(); /* End */ /* Starting curl session */ /* $ckfile = tempnam ("/tmp", session_name().'='.$session_id ); */ $c_open=curl_init(); /* curl_setopt($c_open, CURLOPT_COOKIEJAR, $ckfile); */ curl_setopt($c_open, CURLOPT_URL , $url); curl_setopt($c_open, CURLOPT_HEADER, 1); curl_setopt($c_open, CURLOPT_RETURNTRANSFER, 1); /* curl_setopt ($c_open, CURLOPT_COOKIEFILE, $ckfile); */ curl_setopt ($c_open, CURLOPT_COOKIE, session_name().'='.$session_id ); // Passing session ID. /* session_write_close($c_open); */ $result=curl_exec($c_open); curl_close($c_open); /* End of curl session */ $document=&JFactory::getDocument(); $matches=array(); if($auto=='0'){ $jsarray=explode(',',$js); $cssarray=explode(',',$css); for($i=0;$i<count($jsarray);$i++){ $document->addScript($jsarray[$i]); } for($i=0;$i<count($cssarray);$i++){ $document->addStyleSheet($cssarray[$i]); } if($head_js!=''){ $document->addScriptDeclaration($head_js); } if($head_css!=''){ $document->addStyleDeclaration($head_css); } } else { /* Using regular expression to match and extract contents between <head> and </head> tag */ $pattern = "/(<HEAD[^>]*>)(.*?)(<\/HEAD>)(.*)/si"; $count = preg_match_all($pattern,$result,$matches); if ($count>0) { $head=$matches[2][0]; } else { $head=''; } /* Using regular expression to match and extract contents between <script> and </script> tag with source */ $pattern = '/<script.*src=[\'\"](.*?)[\'\"][^>]*[^<]*(<\/script>)?/i'; $count = preg_match_all($pattern,$head,$scripts); if ($count>0) foreach ($scripts[1] as $script) { $document->addScript($script); } /* Using regular expression to match and extract contents between <script> and </script> tag without source */ $pattern = '/<script[^>]*>(.*?)<\/script>/si'; $scripts= array(); $count = preg_match_all($pattern,$head,$scripts); if ($count>0) foreach ($scripts[1] as $script) { if (trim($script)!='') $document->addScriptDeclaration($script); } /* Using regular expression to match and extract contents link tag */ $pattern = '/<link.*href=[\'\"](.*?)[\'\"][^>]*[^<]*(<\/link>)?/i'; $count = preg_match_all($pattern,$head,$styles); if ($count>0) for ($x=0;$x<$count;$x++) { if ((preg_match('/type=[\'"]text\/css[\'"]/i', $styles[0][$x])>0)||(preg_match('/rel=[\'"]stylesheet[\'"]/i', $styles[0][$x])>0)) $document->addStyleSheet($styles[1][$x]); } /* Using regular expression to match and extract contents between <style> and </style> */ $pattern = '/<style[^>]*>(.*?)<\/style>/si'; $styles = array(); $count = preg_match_all($pattern,$head,$styles); if ($count>0) foreach ($styles[1] as $style) { if (trim($style)!='') $document->addStyleDeclaration($style); } } /* Using regular expression to match and extract contents between <body> and </body> tag */ $pattern='~<body[^>]*>(.*?)</body>~si'; if(preg_match_all($pattern,$result,$matches)){ echo ($matches[1][0]); } else { echo "We're working on the wall, please check back later."; } }
  2. My head's a bit more clear today and was able to think of the best way to do this. I decided the best way to go about it was to do a query for the item's address, then do a second query pulling all of the rows that match the item's address and then count the number of rows returned. If the number = 1 then echo a td, else echo a div. Now I just have to be able to handle the 1st listing with multiple addresses differently than all of the other ones in order for that one to be in a td while the rest fall under divs. Any good ideas on how to go about that? Here's what I have so far that's working as I want: $myquery = "SELECT data_txt FROM jos_sobi2_fields_data WHERE fieldid = 76 AND itemid = $mySobi->id"; $myresult = mysql_query($myquery) or die(mysql_error()); while($row = mysql_fetch_array($myresult)){ $myaddress = $row['data_txt']; } $query = "SELECT data_txt FROM jos_sobi2_fields_data WHERE data_txt = '$myaddress'"; $result = mysql_query($query) or die(mysql_error()); $numrows = mysql_num_rows($result); while($row = mysql_fetch_array($result)) { if($numrows == 1) { echo "<td $style>"; } elseif($numrows > 1) { echo "<div id=\"jquerydiv\">"; } }
  3. Excellent Jaysonic, I'll give it a shot and see what I come up with.
  4. Well it's actually a bit more complex than that. The query I listed there for $myaddress was just a query to pull that item's address in order to check against the results. The actual listing results are popped by a pretty extensive set of code spread across several files to incorporate the regular search, radius search, and google map and fired through ajax. What I'm hoping to do is figure out a way to set an if/else statement to show the <td> if it's unique or the first result of multiple addresses, else if it's the 2nd or subsequent listing with the same address to echo the <div id="jquerydiv">. But the key here is to try and somehow accomplish this without having to rewrite the actual search code because man that thing is a complex beast.
  5. No joy, still just pops the first result. If you want to get a better idea of what I'm talking about you can go to the dev site at http://www.erecoverydev.com, log in with user test and password test123. Click the resource center link in the top menu, then click on the service directory link on the left menu. We just have test data in there right now so just do a search for within 500 miles of 90210, this should pop some results. You'll see what I'm talking about with the tags only showing one result in the list, but if you click on it to view the details you'll see all of the tags output.
  6. I can't just limit it to 1 as I need all of the other listings with the same address to show as well, they're not duplicate listings, they just have the same address. What this is is a directory of AA and NA meetings and many times there are multiple meetings for different things at different times at the same location which is why we have the issue of the duplicate addresses. I'm not sure the sql section is the best place for this as this is more of a way to handle the sql with php and perhaps regex as opposed on how to do the actual query. If you want to get a better idea of what I'm talking about you can go to the dev site at http://www.erecoverydev.com, log in with user test and password test123. Click the resource center link in the top menu, then click on the find a meeting link on the left menu. Do a search for within 200 miles of 55403, this should pop some results. You'll see what I'm talking about with multiple listings with the same address.
  7. Thanks, I'll change the $result to something else and see if that helps.
  8. 110% positive, I can look at the item listing and see if there are multiple values selected, plus I'm using this same query in the item details page and when I view that it will display all of the results there instead of just the first one like it does in the list view.
  9. I'm working on a directory component and have kind of a tricky thing I need to do. The list of results pop through ajax on the left side along with it's google map number tag, and the google map pops on the right side. To make it even trickier the results are popped through a radius search by proximity. The problem is if there are multiple results with the same address you end up having all of the number tags on the map buried under the last tag with that address, plus it makes for kind of a long list. What I need to do is run a check to see if the previous result is the same address, and if yes not pop that result in a new table cell, rather stick it in a jquery drop down div so that all of the following results with the same address are stuffed in the jquery drop down in the same table cell under the first result with that address. In a perfect world all of the listings with the same addresses would be submitted in order so I could just do a check for the previous itemid's address, but of course that's not the case. I thought about running a query to grab ALL of the addresses and then check the item's address against it to see if it matches and if yes echo the jquery div instead of the <td>, but obviously that won't work because that will cause the first item with that address to be put in the div also. Plus I don't know if that's a very efficient way to go about it anyway. Here's kind of the basic thing I'm working with: $query = "SELECT data_txt FROM jos_sobi2_fields_data WHERE fieldid = 76 AND itemid = $mySobi->id"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $myaddress = $row['data_txt']; } echo "<td $style>"; Any ideas?
  10. I'm having trouble getting all of the results out of a query array, as it is I only get the first result and nothing else. Here's the basic code I'm working with: $query = "SELECT data_txt FROM jos_servicedirectory_fields_data WHERE fieldid = 19 AND itemid = $item->itemid"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ $listtags = $row['data_txt']; $tags = "$listtags, "; $title = "<div class='servicedirectoryItemTitle'><table class=\"sdlistingitemtitle\" cellspacing=\"5\"><tbody><tr>$listingimage<td style=\"vertical-align:top;width:690px;\">$listingbasicicon<span class=\"$listingtitleclass\">$listinglogo<a href=\"{$href}\" {$onClick} title=\"{$item->title}\">{$item->title}</a></span><br /><span class=\"listingdescription\">$listingdescription</span></td><td style=\"vertical-align:top;\">$featuredribbon$moreinfobasic</td></tr></tbody></table><div class=\"listingbottom\">Tags:<span class=\"listingtags\"> $tags </span></div></div>"; } I've also tried using a foreach loop thinking that would pop all of the results but I end up not getting anything at all then. I'm guessing I'm setting the foreach loop up wrong. Here's how I'm trying to do it: foreach($listtags as $value) { $tags = $value; } Does it have something to do with sticking the $tags variable in the $title variable? I wouldn't think that would matter, but the strange thing is I use this exact same query in a different part of this component and just echo it directly and it works fine.
  11. I'm not exactly sure how to go about this, but I have an IM & online friends script that shows the online friends both in a module position as well as in a jquery box. Currently it's set to link the results to the IM function for both positions, however I want the module position to link to their profile and the jquery box to link to the IM function. Here is the bit of code where this is done: <!-- I added this as the second option to link to the profile... $text2.="<div onmousedown=\"createChatBoxmesg('".$res[$show_name]."','".$res['id']."')\"><a class=\"texts\" href='index.php?option=com_comprofiler'><img style='padding:0px 5px 0px 0px;' src='".$res['avatar']."' height='25' width='25' />".$res[$show_name]."</a></div><hr/>"; --> $text.="<div onmousedown=\"createChatBoxmesg('".$res[$show_name]."','".$res['id']."')\"><a class=\"texts\" href='javascript:void(0)'><img style='padding:0px 5px 0px 0px;' src='".$res['avatar']."' height='25' width='25' />".$res[$show_name]."</a></div><hr/>"; } } $query="SELECT * FROM frei_chat WHERE frei_chat.to=$usr_id AND recd=0 ORDER BY sent"; $db->setQuery($query); $jon->messages=$db->loadAssocList(); <!-- I need to add this here but obviously so far u can just have one or the other.. $jon->userdata=$text2; --> $jon->userdata=$text; $jon->result=$exec; $jon->count=$onlcnt; It would be simple if I could do an if else depending on the div id or class it sits in but as far as I know there is no real way to do that. Anyone have any ideas on how to do this?
  12. I need to separate multiple field values with commas but I can't seem to get it to work, I've been trying to use .split(',') but maybe I can't do it this way. Here's the part of the script I think this should go in: // Do the actual search function run_search(query) { var cached_results = cache.get(query); if(cached_results) { populate_dropdown(query, cached_results); } else { var queryStringDelimiter = settings.url.indexOf("?") < 0 ? "?" : "&"; var callback = function(results) { if($.isFunction(settings.onResult)) { results = settings.onResult.call(this, results); } cache.add(query, settings.jsonContainer ? results[settings.jsonContainer] : results); populate_dropdown(query, settings.jsonContainer ? results[settings.jsonContainer] : results); }; if(settings.method == "POST") { $.post(settings.url, settings.queryParam + "=" + query, callback, settings.contentType); } else { $.get(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType); } } } }; // Really basic cache for the results $.TokenList.Cache = function (options) { var settings = $.extend({ max_size: 50 }, options); var data = {}; var size = 0; var flush = function () { data = {}; size = 0; }; this.add = function (query, results) { if(size > settings.max_size) { flush(); } if(!data[query]) { size++; } data[query] = results; }; this.get = function (query) { return data[query]; }; }; The full script is at www.erecoverydev.com/autocomplete2/js/jquery.tokeninput.js My php code is: <? mysql_pconnect("localhost", "myuser", "mypass") or die("Could not connect"); mysql_select_db("mydb") or die("Could not select database"); $param = mysql_real_escape_string ($_GET["q"]); $query = sprintf("SELECT DISTINCT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'"); $arr = array(); $rs = mysql_query($query); while($obj = mysql_fetch_object($rs)) { $arr[] = $obj; } echo json_encode($arr); ?>
  13. I need to run this autocomplete script on multiple fields in a form. I created separate js and php files for each field and it seems to pull the values from the php file ok, when you don't have a match it correctly displays no results, however when you do have a match the suggestion box disappears in the first field. The last field works correctly. I'm assuming there is a var conflict between the script instances here and need to find a way around it. I've tried playing around with if else statements in both the php file and the js file to try and just use one but I can't get anything to work. You can view the script at www.erecoverydev.com/autocomplete2/js/jquery.tokeninput.js My php file is: <? mysql_pconnect("localhost", "username", "password") or die("Could not connect"); mysql_select_db("mydb") or die("Could not select database"); $param = mysql_real_escape_string ($_GET["q"]); $query = sprintf("SELECT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'"); $arr = array(); $rs = mysql_query($query); while($obj = mysql_fetch_object($rs)) { $arr[] = $obj; } echo json_encode($arr); ?> There has to be a simple way to use multiple instances of this.
  14. This is solved, not sure why this got posted here.
  15. I'm working on an autocomplete script and have it working close to what I need, however I have an issues. I need to be able to pass a new value to the hidden field input, as it is now only selected values from the auto suggestions get's passed. I'm guessing I need to create some type of onchange or onclick event to do it but I'm not 100% sure how to go about it correctly. My first thought here is I should add a small + icon when clicked will add the new value. Here's the script I'm using: /* * jQuery Plugin: Tokenizing Autocomplete Text Entry * Version 1.1 * * Copyright (c) 2009 James Smith (http://loopj.com) * Licensed jointly under the GPL and MIT licenses, * choose which one suits your project best! * */ (function($) { $.fn.tokenInput = function (url, options) { var settings = $.extend({ url: url, hintText: "Type in a search term", noResultsText: "No results", searchingText: "Searching...", searchDelay: 300, minChars: 1, tokenLimit: null, jsonContainer: null, method: "GET", contentType: "json", queryParam: "q", onResult: null }, options); settings.classes = $.extend({ tokenList: "token-input-list", token: "token-input-token", tokenDelete: "token-input-delete-token", selectedToken: "token-input-selected-token", highlightedToken: "token-input-highlighted-token", dropdown: "token-input-dropdown", dropdownItem: "token-input-dropdown-item", dropdownItem2: "token-input-dropdown-item2", selectedDropdownItem: "token-input-selected-dropdown-item", inputToken: "token-input-input-token" }, options.classes); return this.each(function () { var list = new $.TokenList(this, settings); }); }; $.TokenList = function (input, settings) { // // Variables // // Input box position "enum" var POSITION = { BEFORE: 0, AFTER: 1, END: 2 }; // Keys "enum" var KEY = { BACKSPACE: 8, TAB: 9, RETURN: 13, ESC: 27, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, COMMA: 188 }; // Save the tokens var saved_tokens = []; // Keep track of the number of tokens in the list var token_count = 0; // Basic cache to save on db hits var cache = new $.TokenList.Cache(); // Keep track of the timeout var timeout; // Create a new text input an attach keyup events var input_box = $("<input type=\"text\">") .css({ outline: "none" }) .focus(function () { if (settings.tokenLimit == null || settings.tokenLimit != token_count) { show_dropdown_hint(); } }) .blur(function () { hide_dropdown(); }) .keydown(function (event) { var previous_token; var next_token; switch(event.keyCode) { case KEY.LEFT: case KEY.RIGHT: case KEY.UP: case KEY.DOWN: if(!$(this).val()) { previous_token = input_token.prev(); next_token = input_token.next(); if((previous_token.length && previous_token.get(0) === selected_token) || (next_token.length && next_token.get(0) === selected_token)) { // Check if there is a previous/next token and it is selected if(event.keyCode == KEY.LEFT || event.keyCode == KEY.UP) { deselect_token($(selected_token), POSITION.BEFORE); } else { deselect_token($(selected_token), POSITION.AFTER); } } else if((event.keyCode == KEY.LEFT || event.keyCode == KEY.UP) && previous_token.length) { // We are moving left, select the previous token if it exists select_token($(previous_token.get(0))); } else if((event.keyCode == KEY.RIGHT || event.keyCode == KEY.DOWN) && next_token.length) { // We are moving right, select the next token if it exists select_token($(next_token.get(0))); } } else { var dropdown_item = null; if(event.keyCode == KEY.DOWN || event.keyCode == KEY.RIGHT) { dropdown_item = $(selected_dropdown_item).next(); } else { dropdown_item = $(selected_dropdown_item).prev(); } if(dropdown_item.length) { select_dropdown_item(dropdown_item); } return false; } break; case KEY.BACKSPACE: previous_token = input_token.prev(); if(!$(this).val().length) { if(selected_token) { delete_token($(selected_token)); } else if(previous_token.length) { select_token($(previous_token.get(0))); } return false; } else if($(this).val().length == 1) { hide_dropdown(); } else { // set a timeout just long enough to let this function finish. setTimeout(function(){do_search(false);}, 5); } break; case KEY.TAB: case KEY.RETURN: case KEY.COMMA: if(selected_dropdown_item) { add_token($(selected_dropdown_item)); return false; } break; case KEY.ESC: hide_dropdown(); return true; default: if(is_printable_character(event.keyCode)) { // set a timeout just long enough to let this function finish. setTimeout(function(){do_search(false);}, 5); } break; } }); // Keep a reference to the original input box var hidden_input = $(input) .hide() .focus(function () { input_box.focus(); }) .blur(function () { input_box.blur(); }); // Keep a reference to the selected token and dropdown item var selected_token = null; var selected_dropdown_item = null; // The list to store the token items in var token_list = $("<ul />") .addClass(settings.classes.tokenList) .insertAfter(hidden_input) .click(function (event) { var li = get_element_from_event(event, "li"); if(li && li.get(0) != input_token.get(0)) { toggle_select_token(li); return false; } else { input_box.focus(); if(selected_token) { deselect_token($(selected_token), POSITION.END); } } }) .mouseover(function (event) { var li = get_element_from_event(event, "li"); if(li && selected_token !== this) { li.addClass(settings.classes.highlightedToken); } }) .mouseout(function (event) { var li = get_element_from_event(event, "li"); if(li && selected_token !== this) { li.removeClass(settings.classes.highlightedToken); } }) .mousedown(function (event) { // Stop user selecting text on tokens var li = get_element_from_event(event, "li"); if(li){ return false; } }); // The list to store the dropdown items in var dropdown = $("<div>") .addClass(settings.classes.dropdown) .insertAfter(token_list) .hide(); // The token holding the input box var input_token = $("<li />") .addClass(settings.classes.inputToken) .appendTo(token_list) .append(input_box); init_list(); // // Functions // // Pre-populate list if items exist function init_list () { li_data = settings.prePopulate; if(li_data && li_data.length) { for(var i in li_data) { var this_token = $("<li><p>"+li_data[i].cb_activities+"</p> </li>") .addClass(settings.classes.token) .insertBefore(input_token); $("<span>x</span>") .addClass(settings.classes.tokenDelete) .appendTo(this_token) .click(function () { delete_token($(this).parent()); return false; }); $.data(this_token.get(0), "tokeninput", {"cb_activities": li_data[i].cb_activities}); // Clear input box and make sure it keeps focus input_box .val("") .focus(); // Don't show the help dropdown, they've got the idea hide_dropdown(); // Save this token id var id_string = li_data[i].cb_activities + "," hidden_input.val(hidden_input.val() + id_string); } } } function is_printable_character(keycode) { if((keycode >= 48 && keycode <= 90) || // 0-1a-z (keycode >= 96 && keycode <= 111) || // numpad 0-9 + - / * . (keycode >= 186 && keycode <= 192) || // ; = , - . / ^ (keycode >= 219 && keycode <= 222) // ( \ ) ' ) { return true; } else { return false; } } // Get an element of a particular type from an event (click/mouseover etc) function get_element_from_event (event, element_type) { var target = $(event.target); var element = null; if(target.is(element_type)) { element = target; } else if(target.parent(element_type).length) { element = target.parent(element_type+":first"); } return element; } // Inner function to a token to the list function insert_token(value) { var this_token = $("<li><p>"+ value +"</p> </li>") .addClass(settings.classes.token) .insertBefore(input_token); // The 'delete token' button $("<span>x</span>") .addClass(settings.classes.tokenDelete) .appendTo(this_token) .click(function () { delete_token($(this).parent()); return false; }); $.data(this_token.get(0), "tokeninput", {"cb_activities": value}); return this_token; } // Add a token to the token list based on user input function add_token (item) { var li_data = $.data(item.get(0), "tokeninput"); var this_token = insert_token(li_data.cb_activities); // Clear input box and make sure it keeps focus input_box .val("") .focus(); // Don't show the help dropdown, they've got the idea hide_dropdown(); // Save this token id var id_string = li_data.cb_activities + "," hidden_input.val(hidden_input.val() + id_string); token_count++; if(settings.tokenLimit != null && settings.tokenLimit >= token_count) { input_box.hide(); hide_dropdown(); } } // Select a token in the token list function select_token (token) { token.addClass(settings.classes.selectedToken); selected_token = token.get(0); // Hide input box input_box.val(""); // Hide dropdown if it is visible (eg if we clicked to select token) hide_dropdown(); } // Deselect a token in the token list function deselect_token (token, position) { token.removeClass(settings.classes.selectedToken); selected_token = null; if(position == POSITION.BEFORE) { input_token.insertBefore(token); } else if(position == POSITION.AFTER) { input_token.insertAfter(token); } else { input_token.appendTo(token_list); } // Show the input box and give it focus again input_box.focus(); } // Toggle selection of a token in the token list function toggle_select_token (token) { if(selected_token == token.get(0)) { deselect_token(token, POSITION.END); } else { if(selected_token) { deselect_token($(selected_token), POSITION.END); } select_token(token); } } // Delete a token from the token list function delete_token (token) { // Remove the id from the saved list var token_data = $.data(token.get(0), "tokeninput"); // Delete the token token.remove(); selected_token = null; // Show the input box and give it focus again input_box.focus(); // Delete this token's id from hidden input var str = hidden_input.val() var start = str.indexOf(token_data.cb_activities+","); var end = str.indexOf(",", start) + 1; if(end >= str.length) { hidden_input.val(str.slice(0, start)); } else { hidden_input.val(str.slice(0, start) + str.slice(end, str.length)); } token_count--; if (settings.tokenLimit != null) { input_box .show() .val("") .focus(); } } // Hide and clear the results dropdown function hide_dropdown () { dropdown.hide().empty(); selected_dropdown_item = null; } function show_dropdown_searching () { dropdown .html("<p>"+settings.searchingText+"</p>") .show(); } function show_dropdown_hint () { dropdown .html("<p>"+settings.hintText+"</p>") .show(); } // Highlight the query part of the search term function highlight_term(value, term) { return value.replace(new RegExp("(?![^&;]+(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+", "gi"), "<b>$1</b>"); } // Populate the results dropdown with some results function populate_dropdown (query, results) { if(results.length) { dropdown.empty(); var dropdown_ul = $("<ul>") .appendTo(dropdown) .mouseover(function (event) { select_dropdown_item(get_element_from_event(event, "li")); }) .mousedown(function (event) { add_token(get_element_from_event(event, "li")); return false; }) .hide(); for(var i in results) { if (results.hasOwnProperty(i)) { var this_li = $("<li>"+highlight_term(results[i].cb_activities, query)+"</li>") .appendTo(dropdown_ul); if(i%2) { this_li.addClass(settings.classes.dropdownItem); } else { this_li.addClass(settings.classes.dropdownItem2); } if(i == 0) { select_dropdown_item(this_li); } $.data(this_li.get(0), "tokeninput", {"cb_activities": results[i].cb_activities}); } } dropdown.show(); dropdown_ul.slideDown("fast"); } else { dropdown .html("<p>"+settings.noResultsText+"</p>") .show(); } } // Highlight an item in the results dropdown function select_dropdown_item (item) { if(item) { if(selected_dropdown_item) { deselect_dropdown_item($(selected_dropdown_item)); } item.addClass(settings.classes.selectedDropdownItem); selected_dropdown_item = item.get(0); } } // Remove highlighting from an item in the results dropdown function deselect_dropdown_item (item) { item.removeClass(settings.classes.selectedDropdownItem); selected_dropdown_item = null; } // Do a search and show the "searching" dropdown if the input is longer // than settings.minChars function do_search(immediate) { var query = input_box.val().toLowerCase(); if (query && query.length) { if(selected_token) { deselect_token($(selected_token), POSITION.AFTER); } if (query.length >= settings.minChars) { show_dropdown_searching(); if (immediate) { run_search(query); } else { clearTimeout(timeout); timeout = setTimeout(function(){run_search(query);}, settings.searchDelay); } } else { hide_dropdown(); } } } // Do the actual search function run_search(query) { var cached_results = cache.get(query); if(cached_results) { populate_dropdown(query, cached_results); } else { var queryStringDelimiter = settings.url.indexOf("?") < 0 ? "?" : "&"; var callback = function(results) { if($.isFunction(settings.onResult)) { results = settings.onResult.call(this, results); } cache.add(query, settings.jsonContainer ? results[settings.jsonContainer] : results); populate_dropdown(query, settings.jsonContainer ? results[settings.jsonContainer] : results); }; if(settings.method == "POST") { $.post(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType); } else { $.get(settings.url + queryStringDelimiter + settings.queryParam + "=" + query, {}, callback, settings.contentType); } } } }; // Really basic cache for the results $.TokenList.Cache = function (options) { var settings = $.extend({ max_size: 50 }, options); var data = {}; var size = 0; var flush = function () { data = {}; size = 0; }; this.add = function (query, results) { if(size > settings.max_size) { flush(); } if(!data[query]) { size++; } data[query] = results; }; this.get = function (query) { return data[query]; }; }; })(jQuery);
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.