Drupal.locale = { 'pluralFormula': function ($n) { return Number((((($n%10)==1)&&(($n%100)!=11))?(0):((((($n%10)>=2)&&(($n%10)<=4))&&((($n%100)<10)||(($n%100)>=20)))?(1):2))); }, 'strings': {"An AJAX HTTP error occurred.":"\u0412\u043e\u0437\u043d\u0438\u043a\u043b\u0430 AJAX HTTP \u043e\u0448\u0438\u0431\u043a\u0430.","HTTP Result Code: !status":"\u041f\u043e\u043b\u0443\u0447\u0435\u043d\u043d\u044b\u0439 \u043a\u043e\u0434 HTTP: !status","An AJAX HTTP request terminated abnormally.":"HTTP \u0437\u0430\u043f\u0440\u043e\u0441 AJAX \u0437\u0430\u0432\u0435\u0440\u0448\u0435\u043d \u043d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e.","Debugging information follows.":"\u0421\u043b\u0435\u0434\u0443\u0435\u0442 \u043e\u0442\u043b\u0430\u0434\u043e\u0447\u043d\u0430\u044f \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f.","Path: !uri":"\u041f\u0443\u0442\u044c: !uri","StatusText: !statusText":"\u0421\u0442\u0430\u0442\u0443\u0441\u0422\u0435\u043a\u0441\u0442: !statusText","ResponseText: !responseText":"ResponseText: !responseText","ReadyState: !readyState":"ReadyState: !readyState","Yes":"\u0414\u0430","No":"\u041d\u0435\u0442","Edit":"\u0418\u0437\u043c\u0435\u043d\u0438\u0442\u044c","Message":"\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435","Configure":"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0438","Done":"\u0421\u0434\u0435\u043b\u0430\u043d\u043e!","Warning":"\u041f\u0440\u0435\u0434\u0443\u043f\u0440\u0435\u0436\u0434\u0435\u043d\u0438\u0435","Show":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c","Select all rows in this table":"\u041e\u0442\u043c\u0435\u0442\u0438\u0442\u044c \u0432\u0441\u0435 \u0441\u0442\u0440\u043e\u043a\u0438 \u0442\u0430\u0431\u043b\u0438\u0446\u044b","Deselect all rows in this table":"\u0421\u043d\u044f\u0442\u044c \u043e\u0442\u043c\u0435\u0442\u043a\u0443 \u0441\u043e \u0432\u0441\u0435\u0445 \u043a\u043e\u043b\u043e\u043d\u043e\u043a \u0442\u0430\u0431\u043b\u0438\u0446\u044b","Not published":"\u041d\u0435 \u043e\u043f\u0443\u0431\u043b\u0438\u043a\u043e\u0432\u0430\u043d\u043e","Please wait...":"\u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430...","Hide":"\u0423\u0431\u0440\u0430\u0442\u044c","Loading":"\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430","By @name on @date":"@name. @date","By @name":"\u0410\u0432\u0442\u043e\u0440: @name","Not in menu":"\u041d\u0435 \u0432 \u043c\u0435\u043d\u044e","Alias: @alias":"\u0410\u0434\u0440\u0435\u0441: @alias","No alias":"\u0410\u043b\u044c\u0442\u0435\u0440\u043d\u0430\u0442\u0438\u0432\u043d\u043e\u0433\u043e \u0430\u0434\u0440\u0435\u0441\u0430 \u043d\u0435\u0442","New revision":"\u041d\u043e\u0432\u0430\u044f \u043f\u0440\u0430\u0432\u043a\u0430","Drag to re-order":"\u0418\u0437\u043c\u0435\u043d\u0438\u0442\u044c \u043f\u043e\u0440\u044f\u0434\u043e\u043a \u043c\u043e\u0436\u043d\u043e \u043f\u0435\u0440\u0435\u0442\u0430\u0449\u0438\u0432 \u043f\u0443\u043d\u043a\u0442 \u043c\u044b\u0448\u043a\u043e\u0439.","Changes made in this table will not be saved until the form is submitted.":"\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f \u0432\u0441\u0442\u0443\u043f\u044f\u0442 \u0432 \u0441\u0438\u043b\u0443 \u043f\u043e\u0441\u043b\u0435 \u0441\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u044f \u0444\u043e\u0440\u043c\u044b.","The changes to these blocks will not be saved until the \u003cem\u003eSave blocks\u003c\/em\u003e button is clicked.":"\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f \u0432\u0441\u0442\u0443\u043f\u044f\u0442 \u0432 \u0441\u0438\u043b\u0443 \u043f\u043e\u0441\u043b\u0435 \u0441\u043e\u0445\u0440\u0430\u043d\u0435\u043d\u0438\u044f \u0444\u043e\u0440\u043c\u044b.","Show shortcuts":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f \u043a\u043b\u0430\u0432\u0438\u0448","This permission is inherited from the authenticated user role.":"\u042d\u0442\u043e \u043f\u0440\u0430\u0432\u043e \u043d\u0430\u0441\u043b\u0435\u0434\u0443\u0435\u0442\u0441\u044f \u043e\u0442 \u0440\u043e\u043b\u0438 \u00ab\u0417\u0430\u0440\u0435\u0433\u0438\u0441\u0442\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u043d\u044b\u0439 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044c\u00bb.","No revision":"\u0412\u0435\u0440\u0441\u0438\u0439 \u043d\u0435\u0442","Requires a title":"\u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044f \u0437\u0430\u0433\u043e\u043b\u043e\u0432\u043e\u043a","Not restricted":"\u0411\u0435\u0437 \u043e\u0433\u0440\u0430\u043d\u0438\u0447\u0435\u043d\u0438\u0439","(active tab)":"(\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0432\u043a\u043b\u0430\u0434\u043a\u0430)","Not customizable":"\u041f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0438 \u043d\u0435 \u043c\u043e\u0433\u0443\u0442 \u0443\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c \u0432\u0438\u0434\u0438\u043c\u043e\u0441\u0442\u044c\u044e","Restricted to certain pages":"\u0417\u0430\u043f\u0440\u0435\u0449\u0435\u043d\u043e \u0434\u043b\u044f \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u043d\u044b\u0445 \u0441\u0442\u0440\u0430\u043d\u0438\u0446","The block cannot be placed in this region.":"\u0411\u043b\u043e\u043a \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u0440\u0430\u0437\u043c\u0435\u0449\u0451\u043d \u0432 \u044d\u0442\u043e\u043c \u0440\u0435\u0433\u0438\u043e\u043d\u0435.","Customize dashboard":"\u041d\u0430\u0441\u0442\u0440\u043e\u0439\u043a\u0430 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u043e\u043d\u043d\u043e\u0439 \u043f\u0430\u043d\u0435\u043b\u0438","Hide summary":"\u041d\u0435 \u0432\u0432\u043e\u0434\u0438\u0442\u044c \u043a\u0440\u0430\u0442\u043a\u043e\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u0435","Edit summary":"\u0412\u0432\u0435\u0441\u0442\u0438 \u043a\u0440\u0430\u0442\u043a\u043e\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u0435","Don't display post information":"\u041d\u0435 \u043f\u043e\u043a\u0430\u0437\u044b\u0432\u0430\u0442\u044c \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044e \u043c\u0430\u0442\u0435\u0440\u0438\u0430\u043b\u0430","@title dialog":"@title \u0434\u0438\u0430\u043b\u043e\u0433","Re-order rows by numerical weight instead of dragging.":"\u0423\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0438\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0438 \u043f\u043e \u0432\u0435\u0441\u0443 \u0432\u043c\u0435\u0441\u0442\u043e \u043f\u0435\u0440\u0435\u0442\u0430\u0441\u043a\u0438\u0432\u0430\u043d\u0438\u044f.","Show row weights":"\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u0432\u0435\u0441 \u0441\u0442\u0440\u043e\u043a","Hide row weights":"\u0421\u043a\u0440\u044b\u0442\u044c \u0432\u0435\u0441 \u0441\u0442\u0440\u043e\u043a","Autocomplete popup":"\u0412\u0441\u043f\u043b\u044b\u0432\u0430\u044e\u0449\u0435\u0435 \u0430\u0432\u0442\u043e\u0437\u0430\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u0435","Searching for matches...":"\u041f\u043e\u0438\u0441\u043a \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u0439...","No Items":"\u041d\u0435\u0442 \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u0439","Are you sure that you want to delete this logic entry?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u044d\u0442\u0443 \u0437\u0430\u043f\u0438\u0441\u044c?","Are you sure that you want to delete all selected logic entries?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0437\u0430\u043f\u0438\u0441\u0438?","Are you sure you want to delete selected rubrics?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b, \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0440\u0443\u0431\u0440\u0438\u043a\u0438?","Are you sure that you want to add this new logic?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u044d\u0442\u0443 \u043d\u043e\u0432\u0443\u044e \u0437\u0430\u043f\u0438\u0441\u044c?","Are you sure that you want to delete all logic entries?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0437\u0430\u043f\u0438\u0441\u0438?","Are you sure you want to delete all rubrics?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b, \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0440\u0443\u0431\u0440\u0438\u043a\u0438?","Rubric edit":"\u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u0442\u044c","Are you sure that you want to delete all firms entries?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0437\u0430\u043f\u0438\u0441\u0438?","Are you sure that you want to delete this firm?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u044d\u0442\u0443 \u0437\u0430\u043f\u0438\u0441\u044c?","Are you sure that you want to delete all selected firms?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0437\u0430\u043f\u0438\u0441\u0438?","Are you sure that you want to add this new firm?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0434\u043e\u0431\u0430\u0432\u0438\u0442\u044c \u044d\u0442\u0443 \u043d\u043e\u0432\u0443\u044e \u0437\u0430\u043f\u0438\u0441\u044c?","Are you sure that you want to delete all firms?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0437\u0430\u043f\u0438\u0441\u0438?","Are you sure you want to delete all strings?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b, \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0441\u0442\u0440\u043e\u043a\u0438?","Save rubric":"\u0421\u043e\u0445\u0440\u0430\u043d\u0438\u0442\u044c","Please enter rubric name":"\u0418\u043c\u044f \u0440\u0443\u0431\u0440\u0438\u043a\u0438 \u043d\u0435 \u043c\u043e\u0436\u0435\u0442 \u0431\u044b\u0442\u044c \u043f\u0443\u0441\u0442\u044b\u043c","Are you sure you want to delete selected banners?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b, \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u044b\u0431\u0440\u0430\u043d\u043d\u044b\u0435 \u0431\u0430\u043d\u043d\u0435\u0440\u044b?","Are you sure you want to delete all banners?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b, \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0432\u0441\u0435 \u0431\u0430\u043d\u043d\u0435\u0440\u044b?","Banner preview":"\u041f\u0440\u043e\u0441\u043c\u043e\u0442\u0440\u0435\u0442\u044c","Click on picture or press esc for close":"\u041d\u0430\u0436\u043c\u0438\u0442\u0435 \u043d\u0430 \u0438\u0437\u043e\u0431\u0440\u0430\u0436\u0435\u043d\u0438\u0435 \u0438\u043b\u0438 Esc, \u0447\u0442\u043e\u0431\u044b \u0437\u0430\u043a\u0440\u044b\u0442\u044c \u0435\u0433\u043e","Close":"\u0417\u0430\u043a\u0440\u044b\u0442\u044c","Click to unblock":"\u041d\u0430\u0436\u043c\u0438\u0442\u0435, \u0447\u0442\u043e\u0431\u044b \u0437\u0430\u043a\u0440\u044b\u0442\u044c","All logic deleted":"\u0412\u0441\u044f \u043b\u043e\u0433\u0438\u043a\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e \u0443\u0434\u0430\u043b\u0435\u043d\u0430","Selected logic deleted":"\u0423\u043a\u0430\u0437\u0430\u043d\u043d\u0430\u044f \u0441\u0442\u0440\u043e\u043a\u0430 \u043b\u043e\u0433\u0438\u043a\u0438 \u0431\u044b\u043b\u0430 \u0443\u0441\u043f\u0435\u0448\u043d\u043e \u0443\u0434\u0430\u043b\u0435\u043d\u0430","Cancel edit":"\u041e\u0442\u043c\u0435\u043d\u0438\u0442\u044c","Are you sure you want to delete current string?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b, \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u0441\u0442\u0440\u043e\u043a\u0443?","Create group":"\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0435 \u0433\u0440\u0443\u043f\u043f\u044b","Edit group":"\u0420\u0435\u0434\u0430\u043a\u0442\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435 \u0433\u0440\u0443\u043f\u043f\u044b","Are you sure you want to delete this group?":"\u0412\u044b \u0443\u0432\u0435\u0440\u0435\u043d\u044b \u0447\u0442\u043e \u0445\u043e\u0442\u0438\u0442\u0435 \u0443\u0434\u0430\u043b\u0438\u0442\u044c \u044d\u0442\u0443 \u0433\u0440\u0443\u043f\u043f\u0443?","Delete group":"\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u0433\u0440\u0443\u043f\u043f\u044b"} };;
jQuery(document).ready(function() {
	var table = jQuery('#banners-overview-table');
	var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') };
	var updateSelectAll = function (state) {
		jQuery('th.select-all input:checkbox', table).each(function () {
			jQuery(this).attr('title', state ? strings.selectNone : strings.selectAll);
			this.checked = state;
		});
	};	
	
	jQuery('th.select-all input:checkbox', table).click(function (event) {
		if (jQuery(event.target).is('input:checkbox')) {
			/** Loop through all checkboxes and set their state to the select all checkbox' state. **/
			jQuery('input:checkbox').each(function () {
		        this.checked = event.target.checked;
		        /** Either add or remove the selected class based on the state of the check all checkbox. **/
		        jQuery(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected');
			});
			/** Update the title and the state of the check all box. **/
			updateSelectAll(event.target.checked);
	    }
	});

	/** Loop through all checkboxes and set their state to the select all checkbox' state. **/
	bind_checkboxes = function() {
		jQuery('input:checkbox', table).each(function () {
		    jQuery(this).click(function (e) {
		    	jQuery(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected');
			    if (e.shiftKey && lastChecked && lastChecked != e.target) {
			    	/** We use the checkbox's parent TR to do our range searching. **/
			    	Drupal.tableSelectRange(jQuery(e.target).parents('tr')[0], jQuery(lastChecked).parents('tr')[0], e.target.checked);
			    }
			    updateSelectAll(jQuery('td input:checked', table).length == jQuery('td input:checkbox').length);
		    });
		});
	}
	bind_checkboxes();
	jQuery('th.select-all input:checkbox', table).attr('checked', false);	
	
	/** Get popup window for banners deleting confirmation **/
	var deleteBanner = jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete selected banners?') +'</div>').dialog({
		title: Drupal.t('Warning'),
		autoOpen: false,
		resizable: false,
		buttons: {
			'Нет': function() {
				jQuery(this).dialog('close');
			},
			'Да': function() {
				jQuery(this).dialog("close");
				jQuery('#edit-delete').unbind('click');
				jQuery('#edit-delete').click();
			}
		}
	});	

	/** Confirm banners deleting **/
	confirm_delete_banners = function () {
		if (jQuery('td input:checked', table).length > 0)
			deleteBanner.dialog('open');
		
		return false;
	}
	jQuery('#edit-delete').bind('click', confirm_delete_banners);	
	
	/** Get popup window for banners clearing confirmation **/
	var clearBanner = jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete all banners?') +'</div>').dialog({
		title: Drupal.t('Warning'),
		autoOpen: false,
		resizable: false,
		buttons: {
			'Нет': function() {
				jQuery(this).dialog('close');
			},
			'Да': function() {
				jQuery(this).dialog("close");
				jQuery('#edit-delete-all').unbind('click');
				jQuery('#edit-delete-all').click();
			}
		}
	});	

	/** Confirm banners deleting **/
	confirm_clear_banners = function () {
		if (jQuery('td input:checkbox', table).length > 0)
			clearBanner.dialog('open');
		return false;
	}
	jQuery('#edit-delete-all').bind('click', confirm_clear_banners);
	
	/** Banners preview event **/
	jQuery('.banner-edit-link').click(function(e) {
		var image = jQuery(new Image());
		image.load(function() {
			jQuery('#banners-background').css({'opacity' : '0'}).fadeIn('slow');			
			jQuery('#banners-preview').html('<img src="' + jQuery(this).attr('src') + '" alt="' + Drupal.t('Banner preview') + '" /><div>' + Drupal.t('Click on picture or press esc for close') + '</div>').center().fadeIn('slow');			
		}).attr('src', jQuery(this).attr('href'));
		
		return false;
	});
});;
jQuery.fn.center = function () {
    this.css('position','absolute');
    this.css('top', (jQuery(window).height() - this.height()) / 2 + jQuery(window).scrollTop() + 'px');
    this.css('left', (jQuery(window).width() - this.width()) / 2 + jQuery(window).scrollLeft() + 'px');
    return this;
}

jQuery(document).ready(function() {
	jQuery('body').append('<div id="banners-preview"></div>');	
	jQuery('body').append('<div id="banners-background"></div>');	
	
	jQuery('#banners-background').click(function() {
		jQuery('#banners-background').fadeOut('slow');
		jQuery('#banners-preview').fadeOut('slow');
	});
	
	jQuery('#banners-preview').click(function() {
		jQuery('#banners-background').fadeOut('slow');
		jQuery('#banners-preview').fadeOut('slow');
	});	
	
	jQuery(document).keypress(function(e) {
		if (e.keyCode==27) {
			jQuery('#banners-background').fadeOut('slow');
			jQuery('#banners-preview').fadeOut('slow');
		}
	});
});;
;
jQuery(document).ready(function() {
	var table = jQuery('#rubrics-overview');
	var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') };
	var updateSelectAll = function (state) {
		jQuery('th.select-all input:checkbox', table).each(function () {
			jQuery(this).attr('title', state ? strings.selectNone : strings.selectAll);
			this.checked = state;
		});
	};	
	
	jQuery('th.select-all input:checkbox', table).click(function (event) {
		if (jQuery(event.target).is('input:checkbox')) {
			/** Loop through all checkboxes and set their state to the select all checkbox' state. **/
			jQuery('input:checkbox').each(function () {
		        this.checked = event.target.checked;
		        /** Either add or remove the selected class based on the state of the check all checkbox. **/
		        jQuery(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected');
			});
			/** Update the title and the state of the check all box. **/
			updateSelectAll(event.target.checked);
	    }
	});

	/** Loop through all checkboxes and set their state to the select all checkbox' state. **/
	bind_checkboxes = function() {
		jQuery('input:checkbox', table).each(function () {
		    jQuery(this).click(function (e) {
		    	jQuery(this).parents('tr:first')[ this.checked ? 'addClass' : 'removeClass' ]('selected');
			    if (e.shiftKey && lastChecked && lastChecked != e.target) {
			    	/** We use the checkbox's parent TR to do our range searching. **/
			    	Drupal.tableSelectRange(jQuery(e.target).parents('tr')[0], jQuery(lastChecked).parents('tr')[0], e.target.checked);
			    }
			    updateSelectAll(jQuery('td input:checked', table).length == jQuery('td input:checkbox').length);
		    });
		});
	}
	bind_checkboxes();
	jQuery('th.select-all input:checkbox', table).attr('checked', false);

	/** Get popup window for rubrics deleting confirmation **/
	var confirm = jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete selected rubrics?') +'</div>').dialog({
		title: Drupal.t('Warning'),
		autoOpen: false,
		resizable: false,
		buttons: {
			'Нет': function() {
				jQuery(this).dialog('close');
			},
			'Да': function() {
				jQuery(this).dialog("close");
				jQuery('#edit-delete').unbind('click');
				jQuery('#edit-delete').click();
			}
		}
	});	

	/** Confirm rubrics deleting **/
	confirm_delete_rubric = function () {
		if (jQuery('td input:checked', table).length > 0)
			confirm.dialog('open');
		
		return false;
	}
	jQuery('#edit-delete').bind('click', confirm_delete_rubric);

	/** Get popup window for rubrics clearing confirmation **/
	var clear = jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete all rubrics?') +'</div>').dialog({
		title: Drupal.t('Warning'),
		autoOpen: false,
		resizable: false,
		buttons: {
			'Нет': function() {
				jQuery(this).dialog('close');
			},
			'Да': function() {
				jQuery(this).dialog("close");
				jQuery('#edit-delete-all').unbind('click');
				jQuery('#edit-delete-all').click();
			}
		}
	});	

	/** Confirm rubrics deleting **/
	confirm_clear_rubric = function () {
		if (jQuery('td input:checkbox', table).length > 0)
			clear.dialog('open');
		return false;
	}
	jQuery('#edit-delete-all').bind('click', confirm_clear_rubric);
	
	/** Remove weight link **/
	jQuery('.tabledrag-toggle-weight-wrapper').remove();
	
	/** Ajax get rubrics child **/
	ajax_rubrics_get_child = function () {
		var oParent = jQuery(this).parent().parent();
		oParent.addClass('loading');
		jQuery.ajax({
			type: 'POST',
			url: this.href,
			success: function(data) {
				jQuery(data).insertAfter(jQuery(oParent));
				jQuery('.parent-level-link', oParent).each(function (index, item) {
					jQuery(item).unbind();
					jQuery(item).bind('click', {id: oParent.attr('id')}, parent_show_child);
					jQuery('.parent-level-close', oParent).attr('class', 'parent-level-open');
				});
				bind_checkboxes();
				jQuery('.parent-level-link', jQuery('.' + oParent.attr('id'))).bind('click', ajax_rubrics_get_child);
				jQuery('.rubric-lock-input', jQuery('.' + oParent.attr('id'))).bind('click', function () {set_autocomplete_status(this);});
				oParent.removeClass('loading');
				
				/** Bind group categories **/
				jQuery('.group-categories-inactive', jQuery('.' + oParent.attr('id'))).bind('click', function () {bind_group_categories(this);});
				jQuery('.group-item-edit').bind('click', function () {bind_group_categories_edit(this);});
				jQuery('.group-item-delete').bind('click', function () {bind_group_categories_delete(this);});
				
				/** Bind popup window **/
				bind_popup_window();
				
				/** Bind search input button **/
				jQuery('.group_categories_filter').bind('keyup', function () {search_group_categories(this);});
				
				/** Bind rubrics sorting **/
				jQuery('.rubric-sorting', jQuery('.' + oParent.attr('id'))).bind('click', function () {bind_rubric_sorting(this);});
				
				/** Bind rubrics sorting equal **/
				jQuery('.rubric-sorting-equal', jQuery('.' + oParent.attr('id'))).bind('click', function () {bind_rubric_sorting_equal(this);});
				
				/** Bind rubrics clear strings **/
				jQuery('.rubric-clear').bind('click', function () {clear_rubric_strings(this);});
				
				/** Set category autocomplete weight **/
				jQuery('.autocomplete-weight', jQuery('.' + oParent.attr('id'))).bind('click', function () {bind_category_autocomplete_weight(this);});
			},
			dataType: 'json',
			data: { 'class': oParent.attr('class') }
		});
		return false;
	}
	jQuery('.parent-level-link').bind('click', ajax_rubrics_get_child);
	
	/** Show/hide child of parent **/
	parent_show_child = function(event) {
		var id = event.data.id;
		var oParent = jQuery('#' + id);
		
		if (jQuery('div', jQuery('.parent-level-link', oParent)).attr('class') == 'parent-level-open'){
			jQuery('div', jQuery('.parent-level-link', oParent)).attr('class', 'parent-level-close');
			jQuery('.' + id).hide();
		} else {
			jQuery('div', jQuery('.parent-level-link', oParent)).attr('class', 'parent-level-open');
			jQuery('.' + id).show();
		}
		return false;
	}

	/** Get popup window for strings clearing confirmation **/
	var clear_strings = jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete all strings?') +'</div>').dialog({
		title: Drupal.t('Warning'),
		autoOpen: false,
		resizable: false,
		buttons: {
			'Нет': function() {
				jQuery(this).dialog('close');
			},
			'Да': function() {
				jQuery(this).dialog("close");
				jQuery('#import-strings-clear').unbind('click');
				jQuery('#import-strings-clear').click();
			}
		}
	});	
	
	/** Confirm strings deleting **/
	confirm_clear_strings = function () {
		if (jQuery('#import-strings-count').attr('value') > 0)
			clear_strings.dialog('open');
		return false;
	}
	jQuery('#import-strings-clear').bind('click', confirm_clear_strings);
	
	/** Rubric edit submit action **/
	rubric_edit_submit = function(id) {
		var parent = jQuery('#row-' + id);
		jQuery('.rubric-title-normal', parent).addClass('rubric-title-edit');
		var link = jQuery('.rubrics-edit-link', parent);
		jQuery('span', link).html(Drupal.t('Save rubric'));
		jQuery('img', link).attr('src', Drupal.settings.basePath + 'sites/all/modules/rubrics/images/save_icon.png');
		link.removeAttr('onclick');
		link.unbind('click');
		link.bind('click', function() {return rubric_save_submit(this.href, id);});
		
		/** Cancel edit button **/
		var previousValue = jQuery('.rubric-title-normal', parent).val();
		var cancelImg = document.createElement('img');
		jQuery(cancelImg).attr({
				src: Drupal.settings.basePath + 'sites/all/modules/rubrics/images/cancel_icon.png',
				alt: Drupal.t('Ccancel edit'),
				title: Drupal.t('Cancel edit')
		});
		var cancel = document.createElement('a');
		jQuery(cancel).append(jQuery(cancelImg))
				.attr('href', 'javascript:void(0);')
				.addClass('rubrics-cancel-edit')
				.bind('click', function() {
					jQuery('.rubric-title-normal', parent).val(previousValue);
					return rubric_save_submit(link.attr('href'), id);
				});
		link.parent().append(cancel);
		
		return false;
	}
	/** Rubric save submit action **/
	rubric_save_submit = function(url, id) {
		var parent = jQuery('#row-' + id);
		if (jQuery('.rubric-title-normal', parent).val()) {
			jQuery.ajax({
				type: 'POST',
				url: url,
				success: function() {
					jQuery('.rubric-title-normal', parent).removeClass('rubric-title-edit');
					var link = jQuery('.rubrics-edit-link', parent);
					jQuery('span', link).html(Drupal.t('Rubric edit'));
					jQuery('img', link).attr('src', Drupal.settings.basePath + 'sites/all/modules/rubrics/images/edit_icon.png');
					link.removeAttr('onclick');
					link.unbind('click');
					link.bind('click', function() {return rubric_edit_submit(id);});
					
					/** Remove edit cancel button **/
					jQuery('.rubrics-cancel-edit', parent).remove();
				},
				dataType: 'json',
				data: { rubric: jQuery('.rubric-title-normal', parent).val() }
			});
		} else
			alert(Drupal.t('Please enter rubric name'));
		
		return false;
	}
	
	/** Lift up/Drop down rubric by weight **/
	var sortRubricsList = new Array();
	jQuery('tr', 'table#taxonomy').each(function (i, item) {
		var rubricID = jQuery(item).attr('id').replace('row-', '');
		if (rubricID > 0)
			sortRubricsList.push(rubricID); 
	});
	
	function sort_array_search(needle, haystack, strict) { 
		var strict = !!strict;

		for (var key in haystack) {
			if ( (strict && haystack[key] === needle) || (!strict && haystack[key] == needle) ) {
				return key;
			}
		}
		return false;
	}	
	
	sort_rubric_by_weight = function(link)
	{
		var sort_info = jQuery(link).attr('class').split('-');
		var type = sort_info[1];
		var taxonomy_id = sort_info[0];
		
		jQuery(link).addClass('loading');
		jQuery.ajax({
			type: 'POST',
			url: Drupal.settings.basePath + 'admin/rubrics/weight',
			success: function(data) {
				if(data['success'] == 0)
					alert(Drupal.t('An unexpected error occurred'));
				else
				{
					switch(type)
					{
						case 'up':
							var currPosition = parseInt(sort_array_search(taxonomy_id, sortRubricsList));
							var prevPosition = currPosition - 1;
							var nextPosition = currPosition + 1;
							
							var prevClass = jQuery('#row-' + sortRubricsList[prevPosition]).attr('class');
							var currClass = jQuery('#row-' + sortRubricsList[currPosition]).attr('class');
							
							jQuery('#row-' + sortRubricsList[currPosition]).insertBefore(jQuery('#row-' + sortRubricsList[prevPosition]));
							jQuery('.row-' + sortRubricsList[currPosition]).insertAfter(jQuery('#row-' + sortRubricsList[currPosition]));

							jQuery('.' + sortRubricsList[currPosition] + '-down').show();
							jQuery('.' + sortRubricsList[prevPosition] + '-up').show();
							jQuery('.' + sortRubricsList[prevPosition] + '-down > img').removeAttr('align');
							
							if (prevPosition == 0) {
								jQuery('.' + sortRubricsList[currPosition] + '-up').hide();
								jQuery('.' + sortRubricsList[currPosition] + '-down > img').attr('align', 'right');
							}
							if (nextPosition == sortRubricsList.length)
								jQuery('.' + sortRubricsList[prevPosition] + '-down').hide();
							
							sortRubricsList[currPosition] = sortRubricsList[prevPosition];
							sortRubricsList[prevPosition] = taxonomy_id;
							jQuery('#row-' + sortRubricsList[currPosition]).attr('class', currClass);
							jQuery('#row-' + sortRubricsList[prevPosition]).attr('class', prevClass);
						break;
						case 'down':
							var currPosition = parseInt(sort_array_search(taxonomy_id, sortRubricsList));
							var prevPosition = currPosition - 1;
							var nextPosition = currPosition + 1;
							
							var nextClass = jQuery('#row-' + sortRubricsList[nextPosition]).attr('class');
							var currClass = jQuery('#row-' + sortRubricsList[currPosition]).attr('class');
							
							jQuery('#row-' + sortRubricsList[currPosition]).insertAfter(jQuery('#row-' + sortRubricsList[nextPosition]));
							jQuery('.row-' + sortRubricsList[currPosition]).insertAfter(jQuery('#row-' + sortRubricsList[currPosition]));
							jQuery('.row-' + sortRubricsList[nextPosition]).insertBefore(jQuery('#row-' + sortRubricsList[currPosition]));

							jQuery('.' + sortRubricsList[currPosition] + '-up').show();
							jQuery('.' + sortRubricsList[currPosition] + '-down > img').removeAttr('align');
							jQuery('.' + sortRubricsList[nextPosition] + '-down').show();

							if (nextPosition == sortRubricsList.length - 1)
								jQuery('.' + sortRubricsList[currPosition] + '-down').hide();
							if (prevPosition == -1) {
								jQuery('.' + sortRubricsList[nextPosition] + '-up').hide();
								jQuery('.' + sortRubricsList[nextPosition] + '-down > img').attr('align', 'right');
							}
							
							sortRubricsList[currPosition] = sortRubricsList[nextPosition];
							sortRubricsList[nextPosition] = taxonomy_id;
							jQuery('#row-' + sortRubricsList[currPosition]).attr('class', currClass);
							jQuery('#row-' + sortRubricsList[nextPosition]).attr('class', nextClass);
						break;
					}
				}
				jQuery(link).removeClass('loading');
			},
			dataType: 'json',
			data:
			{
				taxonomy_id: taxonomy_id,
				type: type
			}
		});
	}
		
	/** Unbind recalculate button if used strings count is 0 **/
	if (jQuery('#import-used-strings-count').attr('value') == 0)
		jQuery('#edit-recalculate').attr('disabled', 'disabled');
	else
		jQuery('#edit-recalculate').removeAttr('disabled');
	
	/** Set autocomplete status **/
	function set_autocomplete_status(checkbox) {
		jQuery.ajax({
			type: 'POST',
			url: Drupal.settings.basePath + 'admin/rubrics/autocomplete',
			success: function(status) {
				if (status == 1) {
					jQuery('#' + jQuery(checkbox).attr('id')).removeClass('rubric-unlock');
					jQuery('#' + jQuery(checkbox).attr('id')).addClass('rubric-lock');
				} else {
					jQuery('#' + jQuery(checkbox).attr('id')).removeClass('rubric-lock');
					jQuery('#' + jQuery(checkbox).attr('id')).addClass('rubric-unlock');
				}
			},
			dataType: 'json',
			data: { 
				rubric: jQuery(checkbox).attr('id')
			}
		});		
	}
	jQuery('.rubric-lock-input').bind('click', function () {set_autocomplete_status(this);});
	
	/** Set category sorting priority **/
	function bind_rubric_sorting(rubric) {
		var sorting = jQuery(rubric).clone(true);
		var parent = jQuery(rubric).parent();
		var rubricID = jQuery('input', sorting).attr('name').replace('rubric_sorting_', '');
		jQuery(rubric).unbind('click');
		
		jQuery(rubric).dialog({
			resizable: false,
			buttons: {
				'Сохранить': function() {
					jQuery('input', sorting).val(jQuery('input', this).val());

					if ( jQuery('input', this).val() ) {
						jQuery.ajax({
							type: 'POST',
							url: Drupal.settings.basePath + 'admin/rubrics/' + rubricID + '/sorting',
							success: function() {					
								sorting.removeClass('rubric-sorting-inactive');
								sorting.addClass('rubric-sorting-active');
							},
							dataType: 'json',
							data: {
								value: jQuery('input', this).val()
							} 
						});
						jQuery(this).dialog('close');
					}
				},
				'Очистить': function() {
					jQuery('input', sorting).val('');

					jQuery.ajax({
						type: 'POST',
						url: Drupal.settings.basePath + 'admin/rubrics/' + rubricID + '/sorting',
						success: function() {					
							sorting.removeClass('rubric-sorting-active');
							sorting.addClass('rubric-sorting-inactive');
						},
						dataType: 'json',
						data: {
							value: ''
						} 
					});
					jQuery(this).dialog('close');
				}
			}
		});
		parent.append(sorting);
	}
	jQuery('.rubric-sorting').bind('click', function () {bind_rubric_sorting(this);});
	
	/** Clear rubrics strings **/
	function clear_rubric_strings(children) {
		jQuery.ajax({
			type: 'POST',
			url: Drupal.settings.basePath + 'admin/rubrics/clear/strings',
			success: function(status) {
				jQuery(children).removeClass('rubric-clear');
				jQuery(children).addClass('rubric-clear-inactive');
				jQuery(children).unbind('click');
				var count = parseInt(jQuery('.placeholder:eq(2)', '#strings-import-form').html()) + 1;
				jQuery('.placeholder:eq(2)', '#strings-import-form').html(count);
				jQuery('.count-strings', jQuery(children).parent().parent()).html('');
			},
			dataType: 'json',
			data: { 
				rubric: jQuery(children).parent().parent().attr('id')
			}
		});		
	}
	jQuery('.rubric-clear').bind('click', function () {clear_rubric_strings(this);});
	
	/** Remove selected string **/
	function remove_selected_string(string) {
		var stringRow = jQuery(string).parent().parent();
		stringRow.addClass('selected');
		
		jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete current string?') +'</div>').dialog({
			title: Drupal.t('Warning'),
			resizable: false,
			buttons: {
				'Нет': function() {
					stringRow.removeClass('selected');
					jQuery(this).dialog('close');
				},
				'Да': function() {
					jQuery.ajax({
						type: 'POST',
						url: Drupal.settings.basePath + 'admin/rubrics/remove/string',
						success: function() {
							stringRow.remove();
						},
						dataType: 'json',
						data: { 
							string: stringRow.attr('id')
						}
					});					
					jQuery(this).dialog("close");
				}
			}
		});	
	}
	jQuery('.strings-remove-item').bind('click', function () {remove_selected_string(this);});
	
	/** Set category sorting equal priority **/
	function bind_rubric_sorting_equal(rubric) {
		var sorting = jQuery(rubric).clone(true);
		var parent = jQuery(rubric).parent();
		var rubricID = jQuery('input', sorting).attr('name').replace('rubric_sorting_equal_', '');
		jQuery(rubric).unbind('click');
		
		jQuery(rubric).dialog({
			resizable: false,
			buttons: {
				'Сохранить': function() {
					jQuery('input', sorting).val(jQuery('input', this).val());

					if ( jQuery('input', this).val() ) {
						jQuery.ajax({
							type: 'POST',
							url: Drupal.settings.basePath + 'admin/rubrics/' + rubricID + '/sorting-equal',
							success: function() {					
								sorting.removeClass('rubric-sorting-equal-inactive');
								sorting.addClass('rubric-sorting-equal-active');
							},
							dataType: 'json',
							data: {
								value: jQuery('input', this).val()
							} 
						});
						jQuery(this).dialog('close');
					}
				},
				'Очистить': function() {
					jQuery('input', sorting).val('');

					jQuery.ajax({
						type: 'POST',
						url: Drupal.settings.basePath + 'admin/rubrics/' + rubricID + '/sorting-equal',
						success: function() {					
							sorting.removeClass('rubric-sorting-equal-active');
							sorting.addClass('rubric-sorting-equal-inactive');
						},
						dataType: 'json',
						data: {
							value: ''
						} 
					});
					jQuery(this).dialog('close');
				}
			}
		});
		parent.append(sorting);
	}
	jQuery('.rubric-sorting-equal').bind('click', function () {bind_rubric_sorting_equal(this);});	
	
	/** Bind group categories **/
	bind_group_categories = function(oDiv)
	{
		var rubric = jQuery(oDiv).find('#cat-checkboxes-0');
		var group = jQuery(rubric).clone(true);
		var parent = jQuery(rubric).parent();
		var rubricID = jQuery(rubric).closest('tr').attr('id').replace('row-', '');
		
		jQuery(rubric).dialog(
		{
			title: Drupal.t('Create group'),
			resizable:  false,
			width: 450,
			buttons: {
				'Отменить': function()
				{
					jQuery(this).dialog('close');
				},
				'Сохранить': function()
				{
					var cat_ids = '';
					jQuery(rubric).find('.cat-group-item-checbox').each(function ()
					{
						if(jQuery(this).attr('checked'))
						{
							var cat_id = jQuery(this).attr('id').replace('cat-checkbox-', '');
							cat_ids += cat_id + ',';
						}
					});
					if(cat_ids)
					{
						jQuery.ajax(
						{
							type: 'POST',
							url: Drupal.settings.basePath + 'admin/rubrics/group/create',
							success: function(data)
							{					
								if(data.status)
								{
									var parent_row_id = jQuery('#row-' + rubricID).attr('class').replace('even', '').replace('odd', '').replace('row-', '').trim();
									jQuery('.row-' + parent_row_id).remove();
									jQuery('.parent-level-link', '#row-' + parent_row_id).unbind();
									jQuery('.parent-level-link', '#row-' + parent_row_id).bind('click', ajax_rubrics_get_child);
									jQuery('.parent-level-link', '#row-' + parent_row_id).click();
								}
								else
									alert(Drupal.t('An unexpected error occurred'));
							},
							dataType: 'json',
							data:
							{
								rubric_id:rubricID,
								categories_ids:cat_ids
							}
						});
						jQuery(this).dialog('close');
					}
				}
			}
		});
		parent.append(group); // set previos block content
		//jQuery('.ui-dialog-content > div').show();
	}
	jQuery('.group-categories-inactive').bind('click', function() {bind_group_categories(this);});
	
	/** Bind group categories **/
	bind_group_categories_edit = function(img)
	{
		var groupID = jQuery(img).attr('id').replace('img-group-edit-', '');
		var rubric = jQuery(img).closest('div').find('.group-categories').find('#cat-checkboxes-' + groupID);
		var group = jQuery(rubric).clone(true);
		var parent = jQuery(rubric).parent();
		var rubricID = jQuery(rubric).closest('tr').attr('id').replace('row-', '');
		
		jQuery(rubric).dialog(
		{
			title: Drupal.t('Edit group'),
			resizable: false,
			width: 450,
			buttons: {
				'Отменить': function()
				{
					jQuery(this).dialog('close');
				},
				'Сохранить': function()
				{
					var cat_ids = '';
					jQuery(rubric).find('.cat-group-item-checbox').each(function ()
					{
						if(jQuery(this).attr('checked'))
							cat_ids += jQuery(this).attr('id').replace('cat-checkbox-', '') + ',';
					});
					if(cat_ids)
					{
						jQuery.ajax({
							type: 'POST',
							url: Drupal.settings.basePath + 'admin/rubrics/group/edit',
							success: function(data)
							{					
								if(data.status)
								{
									var parent_row_id = jQuery('#row-' + rubricID).attr('class').replace('even', '').replace('odd', '').replace('row-', '').trim();
									jQuery('.row-' + parent_row_id).remove();
									jQuery('.parent-level-link', '#row-' + parent_row_id).unbind();
									jQuery('.parent-level-link', '#row-' + parent_row_id).bind('click', ajax_rubrics_get_child);
									jQuery('.parent-level-link', '#row-' + parent_row_id).click();
								}
								else
									alert(Drupal.t('An unexpected error occurred'));
							},
							dataType: 'json',
							data: {
								group_id:groupID,
								rubric_id:rubricID,
								categories_ids:cat_ids
							}
						});
					}
					jQuery(this).dialog('close');
				}
			}
		});
		parent.append(group); // set previos block content
		//jQuery('.ui-dialog-content > div').show();
	}
	jQuery('.group-item-edit').bind('click', function () {bind_group_categories_edit(this);});
	
	bind_group_categories_delete = function(img)
	{
		var groupID = jQuery(img).attr('id').replace('img-group-delete-', '');
		var rubricID = jQuery(img).closest('div').closest('tr').attr('id').replace('row-', '');
		
		jQuery('<div id="confirm">' + Drupal.t('Are you sure you want to delete this group?') +'</div>').dialog(
		{
			title: Drupal.t('Delete group'),
			resizable: false,
			buttons: {
				'Нет': function()
				{
					jQuery(this).dialog('close');
				},
				'Да': function()
				{
					jQuery.ajax({
						type: 'POST',
						url: Drupal.settings.basePath + 'admin/rubrics/group/delete',
						success: function(data)
						{					
							if(data.status)
							{
								var parent_row_id = jQuery('#row-' + rubricID).attr('class').replace('even', '').replace('odd', '').replace('row-', '').trim();
								jQuery('.row-' + parent_row_id).remove();
								jQuery('.parent-level-link', '#row-' + parent_row_id).unbind();
								jQuery('.parent-level-link', '#row-' + parent_row_id).bind('click', ajax_rubrics_get_child);
								jQuery('.parent-level-link', '#row-' + parent_row_id).click();
							}
							else
								alert(Drupal.t('An unexpected error occurred'));
						},
						dataType: 'json',
						data:
						{
							group_id:groupID
						}
					});
					jQuery(this).dialog('close');
				}
			}
		});
	}
	jQuery('.group-item-delete').bind('click', function () {bind_group_categories_delete(this);});
	
	bind_popup_window = function()
	{
		jQuery('.bubbleInfo').each(function ()
		{
	        var distance = 10;
	        var time = 250;
	        var hideDelay = 100;
	
	        var hideDelayTimer = null;
	
	        var beingShown = false;
	        var shown = false;
	        var trigger = jQuery('.trigger', this);
	        var info = jQuery('.popup', this).css('opacity', 0);
		
	        jQuery([trigger.get(0), info.get(0)]).mouseover(function ()
	        {
	            if (hideDelayTimer) clearTimeout(hideDelayTimer);
	            if (beingShown || shown)
	            {
	                // don't trigger the animation again
	                return;
	            }
	            else
	            {
	                // reset position of info box
	                beingShown = true;
	                info.css({
	                	top: - info.height(),
	                    left: -25,
	                    display: 'block'
	                }).animate({
	                    top: '-=' + distance + 'px',
	                    opacity: 1
	                }, time, 'swing', function() {
	                    beingShown = false;
	                    shown = true;
	                });
	            }
	
	            return false;
	        }).mouseout(function ()
	        {
	            if (hideDelayTimer) clearTimeout(hideDelayTimer);
	            hideDelayTimer = setTimeout(function ()
	            {
	                hideDelayTimer = null;
	                info.animate({
	                    top: '-=' + distance + 'px',
	                    opacity: 0
	                }, time, 'swing', function () {
	                    shown = false;
	                    info.css('display', 'none');
	                });
	
	            }, hideDelay);
	
	            return false;
	        });
	    });
	}
	
	search_group_categories = function(button)
	{
		var search_world = jQuery(button).val().trim();
		
		if(search_world.length >= 3)
		{
			var cat_ids_not_search = '';
			jQuery(button).closest('div').find('.cat-group-item-checbox').each(function ()
			{
				if(jQuery(this).attr('checked'))
					cat_ids_not_search += jQuery(this).attr('id').replace('cat-checkbox-', '') + ',';
			});
			jQuery.ajax({
				type: 'POST',
				url: Drupal.settings.basePath + 'admin/rubrics/group/categories',
				success: function(data)
				{					
					var exists_content = '';
					if(jQuery(button).closest('div').find('.cat-checkboxes').html())
					{
						jQuery(button).closest('div').find('.cat-group-item-checbox').each(function ()
						{
							if(jQuery(this).attr('checked'))
								exists_content += '<tr>' + jQuery(this).closest('tr').html().replace('type="checkbox"', 'type="checkbox" checked="checked"') + '</tr>';
						});
					}
					if(jQuery(button).closest('div').find('.cat-checkboxes').html().trim())
					{
						jQuery(button).closest('div').find('.cat-checkboxes').html('');
						jQuery(button).closest('div').find('.cat-checkboxes').append(exists_content + data.content);
					}
					else
						jQuery(button).closest('div').find('.cat-checkboxes').append(data.content);
						
				},
				dataType: 'json',
				data: {
					search_world:search_world,
					cat_ids_not_search:cat_ids_not_search
				}
			});
		}
	}
	jQuery('.group_categories_filter').bind('keyup', function () {search_group_categories(this);});
	
	/** Set category autocomplete weight **/
	function bind_category_autocomplete_weight(rubric) {
		var weight = jQuery('div.autocomplete-inner-block', rubric).clone(true);
		var rubricID = jQuery('input', weight).attr('name').replace('autocomplete_weight_', '');
		jQuery('div.autocomplete-inner-block', rubric).unbind('click');
		
		jQuery('div.autocomplete-inner-block', rubric).dialog({
			resizable: false,
			buttons: {
				'Сохранить': function() {
					var value = jQuery('input', weight).val(jQuery('input', this).val());

					if (jQuery('input', this).val()) {
						jQuery.ajax({
							type: 'POST',
							url: Drupal.settings.basePath + 'admin/rubrics/' + rubricID + '/set-autocomplete-weight',
							success: function() {					
								jQuery('span', jQuery(weight).parent()).html(value.val());
							},
							dataType: 'json',
							data: {
								value: jQuery('input', this).val()
							} 
						});
						jQuery(this).dialog('close');
					}
				},
				'Отменить': function() {
					jQuery(this).dialog('close');
				}
			}
		});
		jQuery(rubric).append(weight);
	}
});;
jQuery(document).ready(function() {
	/** Ajax get strings **/
	ajax_statistincs_get_strings = function () {
		var oParent = jQuery(this).parent().parent();
		var iRubricID = jQuery(this).attr('rel');
		oParent.addClass('loading');
		jQuery.ajax({
			type: 'POST',
			url: this.href,
			success: function(data) {
				jQuery(data).insertAfter(jQuery(oParent));
				jQuery('.statistics-parent-level-link', oParent).each(function (index, item) {
					jQuery(item).unbind();
					jQuery(item).bind('click', {id: oParent.attr('id')}, statistincs_parent_show_strings);
					jQuery('.statistics-parent-level-close', oParent).attr('class', 'statistics-parent-level-open');
				});
				oParent.removeClass('loading');
			},
			dataType: 'json',
			data: { 
				'class': oParent.attr('class'),
				'rubric': iRubricID
			}
		});
		return false;
	}
	jQuery('.statistics-parent-level-link').bind('click', ajax_statistincs_get_strings);
	
	/** Show/hide strings of parent **/
	statistincs_parent_show_strings = function(event) {
		var id = event.data.id;
		var oParent = jQuery('#' + id);
		
		if (jQuery('div', jQuery('.statistics-parent-level-link', oParent)).attr('class') == 'statistics-parent-level-open'){
			jQuery('div', jQuery('.statistics-parent-level-link', oParent)).attr('class', 'statistics-parent-level-close');
			jQuery('.' + id).hide();
		} else {
			jQuery('div', jQuery('.statistics-parent-level-link', oParent)).attr('class', 'statistics-parent-level-open');
			jQuery('.' + id).show();
		}
		return false;
	}	
});;
/*!
 * jScrollPane - v2.0.0beta10 - 2011-04-17
 * http://jscrollpane.kelvinluck.com/
 *
 * Copyright (c) 2010 Kelvin Luck
 * Dual licensed under the MIT and GPL licenses.
 */

// Script: jScrollPane - cross browser customisable scrollbars
//
// *Version: 2.0.0beta10, Last updated: 2011-04-17*
//
// Project Home - http://jscrollpane.kelvinluck.com/
// GitHub       - http://github.com/vitch/jScrollPane
// Source       - http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.js
// (Minified)   - http://github.com/vitch/jScrollPane/raw/master/script/jquery.jscrollpane.min.js
//
// About: License
//
// Copyright (c) 2011 Kelvin Luck
// Dual licensed under the MIT or GPL Version 2 licenses.
// http://jscrollpane.kelvinluck.com/MIT-LICENSE.txt
// http://jscrollpane.kelvinluck.com/GPL-LICENSE.txt
//
// About: Examples
//
// All examples and demos are available through the jScrollPane example site at:
// http://jscrollpane.kelvinluck.com/
//
// About: Support and Testing
//
// This plugin is tested on the browsers below and has been found to work reliably on them. If you run
// into a problem on one of the supported browsers then please visit the support section on the jScrollPane
// website (http://jscrollpane.kelvinluck.com/) for more information on getting support. You are also
// welcome to fork the project on GitHub if you can contribute a fix for a given issue. 
//
// jQuery Versions - tested in 1.4.2+ - reported to work in 1.3.x
// Browsers Tested - Firefox 3.6.8, Safari 5, Opera 10.6, Chrome 5.0, IE 6, 7, 8
//
// About: Release History
//
// 2.0.0beta10 - (2011-04-17) cleaner required size calculation, improved keyboard support, stickToBottom/Left, other small fixes
// 2.0.0beta9 - (2011-01-31) new API methods, bug fixes and correct keyboard support for FF/OSX
// 2.0.0beta8 - (2011-01-29) touchscreen support, improved keyboard support
// 2.0.0beta7 - (2011-01-23) scroll speed consistent (thanks Aivo Paas)
// 2.0.0beta6 - (2010-12-07) scrollToElement horizontal support
// 2.0.0beta5 - (2010-10-18) jQuery 1.4.3 support, various bug fixes
// 2.0.0beta4 - (2010-09-17) clickOnTrack support, bug fixes
// 2.0.0beta3 - (2010-08-27) Horizontal mousewheel, mwheelIntent, keyboard support, bug fixes
// 2.0.0beta2 - (2010-08-21) Bug fixes
// 2.0.0beta1 - (2010-08-17) Rewrite to follow modern best practices and enable horizontal scrolling, initially hidden
//							 elements and dynamically sized elements.
// 1.x - (2006-12-31 - 2010-07-31) Initial version, hosted at googlecode, deprecated

(function($,window,undefined){

	$.fn.jScrollPane = function(settings)
	{
		// JScrollPane "class" - public methods are available through $('selector').data('jsp')
		function JScrollPane(elem, s)
		{
			var settings, jsp = this, pane, paneWidth, paneHeight, container, contentWidth, contentHeight,
				percentInViewH, percentInViewV, isScrollableV, isScrollableH, verticalDrag, dragMaxY,
				verticalDragPosition, horizontalDrag, dragMaxX, horizontalDragPosition,
				verticalBar, verticalTrack, scrollbarWidth, verticalTrackHeight, verticalDragHeight, arrowUp, arrowDown,
				horizontalBar, horizontalTrack, horizontalTrackWidth, horizontalDragWidth, arrowLeft, arrowRight,
				reinitialiseInterval, originalPadding, originalPaddingTotalWidth, previousContentWidth,
				wasAtTop = true, wasAtLeft = true, wasAtBottom = false, wasAtRight = false,
				originalElement = elem.clone(false, false).empty(),
				mwEvent = $.fn.mwheelIntent ? 'mwheelIntent.jsp' : 'mousewheel.jsp';

			originalPadding = elem.css('paddingTop') + ' ' +
								elem.css('paddingRight') + ' ' +
								elem.css('paddingBottom') + ' ' +
								elem.css('paddingLeft');
			originalPaddingTotalWidth = (parseInt(elem.css('paddingLeft'), 10) || 0) +
										(parseInt(elem.css('paddingRight'), 10) || 0);

			function initialise(s)
			{

				var /*firstChild, lastChild, */isMaintainingPositon, lastContentX, lastContentY,
						hasContainingSpaceChanged, originalScrollTop, originalScrollLeft,
						maintainAtBottom = false, maintainAtRight = false;

				settings = s;

				if (pane === undefined) {
					originalScrollTop = elem.scrollTop();
					originalScrollLeft = elem.scrollLeft();

					elem.css(
						{
							overflow: 'hidden',
							padding: 0
						}
					);
					// TODO: Deal with where width/ height is 0 as it probably means the element is hidden and we should
					// come back to it later and check once it is unhidden...
					paneWidth = elem.innerWidth() + originalPaddingTotalWidth;
					paneHeight = elem.innerHeight();

					elem.width(paneWidth);
					
					pane = $('<div class="jspPane" />').css('padding', originalPadding).append(elem.children());
					container = $('<div class="jspContainer" />')
						.css({
							'width': paneWidth + 'px',
							'height': paneHeight + 'px'
						}
					).append(pane).appendTo(elem);

					/*
					// Move any margins from the first and last children up to the container so they can still
					// collapse with neighbouring elements as they would before jScrollPane 
					firstChild = pane.find(':first-child');
					lastChild = pane.find(':last-child');
					elem.css(
						{
							'margin-top': firstChild.css('margin-top'),
							'margin-bottom': lastChild.css('margin-bottom')
						}
					);
					firstChild.css('margin-top', 0);
					lastChild.css('margin-bottom', 0);
					*/
				} else {
					elem.css('width', '');

					maintainAtBottom = settings.stickToBottom && isCloseToBottom();
					maintainAtRight  = settings.stickToRight  && isCloseToRight();

					hasContainingSpaceChanged = elem.innerWidth() + originalPaddingTotalWidth != paneWidth || elem.outerHeight() != paneHeight;

					if (hasContainingSpaceChanged) {
						paneWidth = elem.innerWidth() + originalPaddingTotalWidth;
						paneHeight = elem.innerHeight();
						container.css({
							width: paneWidth + 'px',
							height: paneHeight + 'px'
						});
					}

					// If nothing changed since last check...
					if (!hasContainingSpaceChanged && previousContentWidth == contentWidth && pane.outerHeight() == contentHeight) {
						elem.width(paneWidth);
						return;
					}
					previousContentWidth = contentWidth;
					
					pane.css('width', '');
					elem.width(paneWidth);

					container.find('>.jspVerticalBar,>.jspHorizontalBar').remove().end();
				}

				pane.css('overflow', 'auto');
				if (s.contentWidth) {
					contentWidth = s.contentWidth;
				} else {
					contentWidth = pane[0].scrollWidth;
				}
				contentHeight = pane[0].scrollHeight;
				pane.css('overflow', '');
				
				percentInViewH = contentWidth / paneWidth;
				percentInViewV = contentHeight / paneHeight;
				
				isScrollableV = percentInViewV > 1;

				isScrollableH = percentInViewH > 1;

				//console.log(paneWidth, paneHeight, contentWidth, contentHeight, percentInViewH, percentInViewV, isScrollableH, isScrollableV);
				/** Increase content widhto to fill area [OG] **/
				originalPaddingTotalWidth = -3;
				
				if (!(isScrollableH || isScrollableV)) {
					elem.removeClass('jspScrollable');
					pane.css({
						top: 0,
						width: container.width() - originalPaddingTotalWidth
					});
					removeMousewheel();
					removeFocusHandler();
					removeKeyboardNav();
					removeClickOnTrack();
					unhijackInternalLinks();
				} else {
					elem.addClass('jspScrollable');

					isMaintainingPositon = settings.maintainPosition && (verticalDragPosition || horizontalDragPosition);
					if (isMaintainingPositon) {
						lastContentX = contentPositionX();
						lastContentY = contentPositionY();
					}

					initialiseVerticalScroll();
					initialiseHorizontalScroll();
					resizeScrollbars();

					if (isMaintainingPositon) {
						scrollToX(maintainAtRight  ? (contentWidth  - paneWidth ) : lastContentX, false);
						scrollToY(maintainAtBottom ? (contentHeight - paneHeight) : lastContentY, false);
					}

					initFocusHandler();
					initMousewheel();
					initTouch();
					
					if (settings.enableKeyboardNavigation) {
						initKeyboardNav();
					}
					if (settings.clickOnTrack) {
						initClickOnTrack();
					}
					
					observeHash();
					if (settings.hijackInternalLinks) {
						hijackInternalLinks();
					}
				}

				if (settings.autoReinitialise && !reinitialiseInterval) {
					reinitialiseInterval = setInterval(
						function()
						{
							initialise(settings);
						},
						settings.autoReinitialiseDelay
					);
				} else if (!settings.autoReinitialise && reinitialiseInterval) {
					clearInterval(reinitialiseInterval);
				}

				originalScrollTop && elem.scrollTop(0) && scrollToY(originalScrollTop, false);
				originalScrollLeft && elem.scrollLeft(0) && scrollToX(originalScrollLeft, false);

				elem.trigger('jsp-initialised', [isScrollableH || isScrollableV]);
			}

			function initialiseVerticalScroll()
			{
				if (isScrollableV) {

					container.append(
						$('<div class="jspVerticalBar" />').append(
							$('<div class="jspCap jspCapTop" />'),
							$('<div class="jspTrack" />').append(
								$('<div class="jspDrag" />').append(
									$('<div class="jspDragTop" />'),
									$('<div class="jspDragBottom" />')
								)
							),
							$('<div class="jspCap jspCapBottom" />')
						)
					);

					verticalBar = container.find('>.jspVerticalBar');
					verticalTrack = verticalBar.find('>.jspTrack');
					verticalDrag = verticalTrack.find('>.jspDrag');

					if (settings.showArrows) {
						arrowUp = $('<a class="jspArrow jspArrowUp" />').bind(
							'mousedown.jsp', getArrowScroll(0, -1)
						).bind('click.jsp', nil);
						arrowDown = $('<a class="jspArrow jspArrowDown" />').bind(
							'mousedown.jsp', getArrowScroll(0, 1)
						).bind('click.jsp', nil);
						if (settings.arrowScrollOnHover) {
							arrowUp.bind('mouseover.jsp', getArrowScroll(0, -1, arrowUp));
							arrowDown.bind('mouseover.jsp', getArrowScroll(0, 1, arrowDown));
						}

						appendArrows(verticalTrack, settings.verticalArrowPositions, arrowUp, arrowDown);
					}

					verticalTrackHeight = paneHeight - 2; /** Set bottom margin (2) to vertical scroll [OG] **/
					container.find('>.jspVerticalBar>.jspCap:visible,>.jspVerticalBar>.jspArrow').each(
						function()
						{
							verticalTrackHeight -= $(this).outerHeight();
						}
					);


					verticalDrag.hover(
						function()
						{
							verticalDrag.addClass('jspHover');
						},
						function()
						{
							verticalDrag.removeClass('jspHover');
						}
					).bind(
						'mousedown.jsp',
						function(e)
						{
							// Stop IE from allowing text selection
							$('html').bind('dragstart.jsp selectstart.jsp', nil);

							verticalDrag.addClass('jspActive');

							var startY = e.pageY - verticalDrag.position().top;

							$('html').bind(
								'mousemove.jsp',
								function(e)
								{
									positionDragY(e.pageY - startY, false);
								}
							).bind('mouseup.jsp mouseleave.jsp', cancelDrag);
							return false;
						}
					);
					sizeVerticalScrollbar();
				}
			}

			function sizeVerticalScrollbar()
			{
				verticalTrack.height(verticalTrackHeight + 'px');
				verticalDragPosition = 0;
				scrollbarWidth = settings.verticalGutter + verticalTrack.outerWidth();

				// Make the pane thinner to allow for the vertical scrollbar
				pane.width(paneWidth - scrollbarWidth - originalPaddingTotalWidth);

				// Add margin to the left of the pane if scrollbars are on that side (to position
				// the scrollbar on the left or right set it's left or right property in CSS)
				try {
					if (verticalBar.position().left === 0) {
						pane.css('margin-left', scrollbarWidth + 'px');
					}
				} catch (err) {
				}
			}

			function initialiseHorizontalScroll()
			{
				if (isScrollableH) {

					container.append(
						$('<div class="jspHorizontalBar" />').append(
							$('<div class="jspCap jspCapLeft" />'),
							$('<div class="jspTrack" />').append(
								$('<div class="jspDrag" />').append(
									$('<div class="jspDragLeft" />'),
									$('<div class="jspDragRight" />')
								)
							),
							$('<div class="jspCap jspCapRight" />')
						)
					);

					horizontalBar = container.find('>.jspHorizontalBar');
					horizontalTrack = horizontalBar.find('>.jspTrack');
					horizontalDrag = horizontalTrack.find('>.jspDrag');

					if (settings.showArrows) {
						arrowLeft = $('<a class="jspArrow jspArrowLeft" />').bind(
							'mousedown.jsp', getArrowScroll(-1, 0)
						).bind('click.jsp', nil);
						arrowRight = $('<a class="jspArrow jspArrowRight" />').bind(
							'mousedown.jsp', getArrowScroll(1, 0)
						).bind('click.jsp', nil);
						if (settings.arrowScrollOnHover) {
							arrowLeft.bind('mouseover.jsp', getArrowScroll(-1, 0, arrowLeft));
							arrowRight.bind('mouseover.jsp', getArrowScroll(1, 0, arrowRight));
						}
						appendArrows(horizontalTrack, settings.horizontalArrowPositions, arrowLeft, arrowRight);
					}

					horizontalDrag.hover(
						function()
						{
							horizontalDrag.addClass('jspHover');
						},
						function()
						{
							horizontalDrag.removeClass('jspHover');
						}
					).bind(
						'mousedown.jsp',
						function(e)
						{
							// Stop IE from allowing text selection
							$('html').bind('dragstart.jsp selectstart.jsp', nil);

							horizontalDrag.addClass('jspActive');

							var startX = e.pageX - (horizontalDrag.position().left);
							$('html').bind(
								'mousemove.jsp',
								function(e)
								{
									positionDragX(e.pageX - startX, false);
								}
							).bind('mouseup.jsp mouseleave.jsp', cancelDrag);
							return false;
						}
					);
					horizontalTrackWidth = container.innerWidth();
					sizeHorizontalScrollbar();
				}
			}

			function sizeHorizontalScrollbar()
			{
				container.find('>.jspHorizontalBar>.jspCap:visible,>.jspHorizontalBar>.jspArrow').each(
					function()
					{
						horizontalTrackWidth -= $(this).outerWidth();
					}
				);

				horizontalTrack.width(horizontalTrackWidth + 'px');
				horizontalDragPosition = 0;
			}

			function resizeScrollbars()
			{
				if (isScrollableH && isScrollableV) {
					var horizontalTrackHeight = horizontalTrack.outerHeight(),
						verticalTrackWidth = verticalTrack.outerWidth();
					verticalTrackHeight -= horizontalTrackHeight;
					$(horizontalBar).find('>.jspCap:visible,>.jspArrow').each(
						function()
						{
							horizontalTrackWidth += $(this).outerWidth();
						}
					);
					horizontalTrackWidth -= verticalTrackWidth;
					paneHeight -= verticalTrackWidth;
					paneWidth -= horizontalTrackHeight;
					
					horizontalTrack.parent().append(
						$('<div class="jspCorner" />').css('width', horizontalTrackHeight + 'px')
					);
					sizeVerticalScrollbar();
					sizeHorizontalScrollbar();
				}
				// reflow content
				if (isScrollableH) {
					pane.width((container.outerWidth() - originalPaddingTotalWidth) + 'px');
				}
				contentHeight = pane.outerHeight();
				percentInViewV = contentHeight / paneHeight;

				if (isScrollableH) {
					horizontalDragWidth = 32; /** Math.ceil(1 / percentInViewH * horizontalTrackWidth); Remove [OG] **/
					if (horizontalDragWidth > settings.horizontalDragMaxWidth) {
						horizontalDragWidth = settings.horizontalDragMaxWidth;
					} else if (horizontalDragWidth < settings.horizontalDragMinWidth) {
						horizontalDragWidth = settings.horizontalDragMinWidth;
					}
					horizontalDrag.width(horizontalDragWidth + 'px');
					dragMaxX = horizontalTrackWidth - horizontalDragWidth;
					_positionDragX(horizontalDragPosition); // To update the state for the arrow buttons
				}
				if (isScrollableV) {
					verticalDragHeight = 30; /** Math.ceil(1 / percentInViewV * verticalTrackHeight); Remove [OG] **/
					if (verticalDragHeight > settings.verticalDragMaxHeight) {
						verticalDragHeight = settings.verticalDragMaxHeight;
					} else if (verticalDragHeight < settings.verticalDragMinHeight) {
						verticalDragHeight = settings.verticalDragMinHeight;
					}
					verticalDrag.height(verticalDragHeight + 'px');
					dragMaxY = verticalTrackHeight - verticalDragHeight;
					_positionDragY(verticalDragPosition); // To update the state for the arrow buttons
				}
			}

			function appendArrows(ele, p, a1, a2)
			{
				var p1 = "before", p2 = "after", aTemp;
				
				// Sniff for mac... Is there a better way to determine whether the arrows would naturally appear
				// at the top or the bottom of the bar?
				if (p == "os") {
					p = /Mac/.test(navigator.platform) ? "after" : "split";
				}
				if (p == p1) {
					p2 = p;
				} else if (p == p2) {
					p1 = p;
					aTemp = a1;
					a1 = a2;
					a2 = aTemp;
				}

				ele[p1](a1)[p2](a2);
			}

			function getArrowScroll(dirX, dirY, ele)
			{
				return function()
				{
					arrowScroll(dirX, dirY, this, ele);
					this.blur();
					return false;
				};
			}

			function arrowScroll(dirX, dirY, arrow, ele)
			{
				arrow = $(arrow).addClass('jspActive');

				var eve,
					scrollTimeout,
					isFirst = true,
					doScroll = function()
					{
						if (dirX !== 0)
						{
							jsp.scrollByX(dirX * settings.arrowButtonSpeed);
						}
						if (dirY !== 0)
						{
							jsp.scrollByY(dirY * settings.arrowButtonSpeed);
						}
						scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.arrowRepeatFreq);
						isFirst = false;
					};

				doScroll();

				eve = ele ? 'mouseout.jsp' : 'mouseup.jsp';
				ele = ele || $('html');
				ele.bind(
					eve,
					function()
					{
						arrow.removeClass('jspActive');
						scrollTimeout && clearTimeout(scrollTimeout);
						scrollTimeout = null;
						ele.unbind(eve);
					}
				);
			}

			function initClickOnTrack()
			{
				removeClickOnTrack();
				if (isScrollableV) {
					verticalTrack.bind(
						'mousedown.jsp',
						function(e)
						{
							if (e.originalTarget === undefined || e.originalTarget == e.currentTarget) {
								var clickedTrack = $(this),
									offset = clickedTrack.offset(),
									direction = e.pageY - offset.top - verticalDragPosition,
									scrollTimeout,
									isFirst = true,
									doScroll = function()
									{
										var offset = clickedTrack.offset(),
											pos = e.pageY - offset.top - verticalDragHeight / 2,
											contentDragY = paneHeight * settings.scrollPagePercent,
											dragY = dragMaxY * contentDragY / (contentHeight - paneHeight);
										if (direction < 0) {
											if (verticalDragPosition - dragY > pos) {
												jsp.scrollByY(-contentDragY);
											} else {
												positionDragY(pos);
											}
										} else if (direction > 0) {
											if (verticalDragPosition + dragY < pos) {
												jsp.scrollByY(contentDragY);
											} else {
												positionDragY(pos);
											}
										} else {
											cancelClick();
											return;
										}
										scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.trackClickRepeatFreq);
										isFirst = false;
									},
									cancelClick = function()
									{
										scrollTimeout && clearTimeout(scrollTimeout);
										scrollTimeout = null;
										$(document).unbind('mouseup.jsp', cancelClick);
									};
								doScroll();
								$(document).bind('mouseup.jsp', cancelClick);
								return false;
							}
						}
					);
				}
				
				if (isScrollableH) {
					horizontalTrack.bind(
						'mousedown.jsp',
						function(e)
						{
							if (e.originalTarget === undefined || e.originalTarget == e.currentTarget) {
								var clickedTrack = $(this),
									offset = clickedTrack.offset(),
									direction = e.pageX - offset.left - horizontalDragPosition,
									scrollTimeout,
									isFirst = true,
									doScroll = function()
									{
										var offset = clickedTrack.offset(),
											pos = e.pageX - offset.left - horizontalDragWidth / 2,
											contentDragX = paneWidth * settings.scrollPagePercent,
											dragX = dragMaxX * contentDragX / (contentWidth - paneWidth);
										if (direction < 0) {
											if (horizontalDragPosition - dragX > pos) {
												jsp.scrollByX(-contentDragX);
											} else {
												positionDragX(pos);
											}
										} else if (direction > 0) {
											if (horizontalDragPosition + dragX < pos) {
												jsp.scrollByX(contentDragX);
											} else {
												positionDragX(pos);
											}
										} else {
											cancelClick();
											return;
										}
										scrollTimeout = setTimeout(doScroll, isFirst ? settings.initialDelay : settings.trackClickRepeatFreq);
										isFirst = false;
									},
									cancelClick = function()
									{
										scrollTimeout && clearTimeout(scrollTimeout);
										scrollTimeout = null;
										$(document).unbind('mouseup.jsp', cancelClick);
									};
								doScroll();
								$(document).bind('mouseup.jsp', cancelClick);
								return false;
							}
						}
					);
				}
			}

			function removeClickOnTrack()
			{
				if (horizontalTrack) {
					horizontalTrack.unbind('mousedown.jsp');
				}
				if (verticalTrack) {
					verticalTrack.unbind('mousedown.jsp');
				}
			}

			function cancelDrag()
			{
				$('html').unbind('dragstart.jsp selectstart.jsp mousemove.jsp mouseup.jsp mouseleave.jsp');

				if (verticalDrag) {
					verticalDrag.removeClass('jspActive');
				}
				if (horizontalDrag) {
					horizontalDrag.removeClass('jspActive');
				}
			}

			function positionDragY(destY, animate)
			{
				if (!isScrollableV) {
					return;
				}
				if (destY < 0) {
					destY = 0;
				} else if (destY > dragMaxY) {
					destY = dragMaxY;
				}

				// can't just check if(animate) because false is a valid value that could be passed in...
				if (animate === undefined) {
					animate = settings.animateScroll;
				}
				if (animate) {
					jsp.animate(verticalDrag, 'top', destY,	_positionDragY);
				} else {
					verticalDrag.css('top', destY);
					_positionDragY(destY);
				}

			}

			function _positionDragY(destY)
			{
				if (destY === undefined) {
					destY = verticalDrag.position().top;
				}

				container.scrollTop(0);
				verticalDragPosition = destY;

				var isAtTop = verticalDragPosition === 0,
					isAtBottom = verticalDragPosition == dragMaxY,
					percentScrolled = destY/ dragMaxY,
					destTop = -percentScrolled * (contentHeight - paneHeight);

				if (wasAtTop != isAtTop || wasAtBottom != isAtBottom) {
					wasAtTop = isAtTop;
					wasAtBottom = isAtBottom;
					elem.trigger('jsp-arrow-change', [wasAtTop, wasAtBottom, wasAtLeft, wasAtRight]);
				}
				
				updateVerticalArrows(isAtTop, isAtBottom);
				pane.css('top', destTop);
				elem.trigger('jsp-scroll-y', [-destTop, isAtTop, isAtBottom]).trigger('scroll');
			}

			function positionDragX(destX, animate)
			{
				if (!isScrollableH) {
					return;
				}
				if (destX < 0) {
					destX = 0;
				} else if (destX > dragMaxX) {
					destX = dragMaxX;
				}

				if (animate === undefined) {
					animate = settings.animateScroll;
				}
				if (animate) {
					jsp.animate(horizontalDrag, 'left', destX,	_positionDragX);
				} else {
					horizontalDrag.css('left', destX);
					_positionDragX(destX);
				}
			}

			/** Changes for scroll by column [SD][Start] **/
			function _positionDragX(destX)
			{
				var iColumnWidth = 300;
				var iColumns = Math.floor(contentWidth / iColumnWidth);
				var iUnvisibleCol = iColumns - 4;
				var iScrollColumnWidth = paneWidth / (iUnvisibleCol + 1);
				var iK = (iColumns >= 0 && iColumns <= 10) ? 0.01 : ((iColumns > 10 && iColumns <= 20) ? 0.2 : 0.25);
				
				var iCurScrollCol = (Math.round(destX / iScrollColumnWidth) - (destX / iScrollColumnWidth)) > 0 && (Math.round(destX / iScrollColumnWidth) - (destX / iScrollColumnWidth)) < iK ? Math.round(destX / iScrollColumnWidth) : Math.floor(destX / iScrollColumnWidth);
				
				var iLimitdestX = iCurScrollCol * iScrollColumnWidth;
				
				if (destX === undefined)
				{
					destX = horizontalDrag.position().left;
				}
				
				container.scrollTop(0);
				horizontalDragPosition = destX;

				var isAtLeft = horizontalDragPosition === 0,
					isAtRight = horizontalDragPosition == dragMaxX,
					percentScrolled = destX / dragMaxX,
					destLeft = -percentScrolled * (contentWidth - paneWidth);
				
				if (wasAtLeft != isAtLeft || wasAtRight != isAtRight)
				{
					wasAtLeft = isAtLeft;
					wasAtRight = isAtRight;
					elem.trigger('jsp-arrow-change', [wasAtTop, wasAtBottom, wasAtLeft, wasAtRight]);
				}
				
				updateHorizontalArrows(isAtLeft, isAtRight);
				
				if(iLimitdestX && (destX >= iLimitdestX))
					destLeft = -iColumnWidth * (Math.floor(destX / iScrollColumnWidth));
				else if(!iLimitdestX)
					destLeft = 0;
				
				//if(iLimitdestX && (destX >= iLimitdestX))
				//	pane.css('left', -iColumnWidth * (Math.floor(destX / iScrollColumnWidth)));
				//else if(!iLimitdestX)
				//	pane.css('left', 0);
				pane.css('left', destLeft);
				
				elem.trigger('jsp-scroll-x', [-destLeft, isAtLeft, isAtRight]).trigger('scroll');
			}
			/** Changes for scroll by column [SD][End] **/

			function updateVerticalArrows(isAtTop, isAtBottom)
			{
				if (settings.showArrows) {
					arrowUp[isAtTop ? 'addClass' : 'removeClass']('jspDisabled');
					arrowDown[isAtBottom ? 'addClass' : 'removeClass']('jspDisabled');
				}
			}

			function updateHorizontalArrows(isAtLeft, isAtRight)
			{
				if (settings.showArrows) {
					arrowLeft[isAtLeft ? 'addClass' : 'removeClass']('jspDisabled');
					arrowRight[isAtRight ? 'addClass' : 'removeClass']('jspDisabled');
				}
			}

			function scrollToY(destY, animate)
			{
				var percentScrolled = destY / (contentHeight - paneHeight);
				positionDragY(percentScrolled * dragMaxY, animate);
			}

			function scrollToX(destX, animate)
			{
				var percentScrolled = destX / (contentWidth - paneWidth);
				positionDragX(percentScrolled * dragMaxX, animate);
			}

			function scrollToElement(ele, stickToTop, animate)
			{
				var e, eleHeight, eleWidth, eleTop = 0, eleLeft = 0, viewportTop, viewportLeft, maxVisibleEleTop, maxVisibleEleLeft, destY, destX;

				// Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
				// errors from the lookup...
				try {
					e = $(ele);
				} catch (err) {
					return;
				}
				eleHeight = e.outerHeight();
				eleWidth= e.outerWidth();

				container.scrollTop(0);
				container.scrollLeft(0);
				
				// loop through parents adding the offset top of any elements that are relatively positioned between
				// the focused element and the jspPane so we can get the true distance from the top
				// of the focused element to the top of the scrollpane...
				while (!e.is('.jspPane')) {
					eleTop += e.position().top;
					eleLeft += e.position().left;
					e = e.offsetParent();
					if (/^body|html$/i.test(e[0].nodeName)) {
						// we ended up too high in the document structure. Quit!
						return;
					}
				}

				viewportTop = contentPositionY();
				maxVisibleEleTop = viewportTop + paneHeight;
				if (eleTop < viewportTop || stickToTop) { // element is above viewport
					destY = eleTop - settings.verticalGutter;
				} else if (eleTop + eleHeight > maxVisibleEleTop) { // element is below viewport
					destY = eleTop - paneHeight + eleHeight + settings.verticalGutter;
				}
				if (destY) {
					scrollToY(destY, animate);
				}
				
				viewportLeft = contentPositionX();
	            maxVisibleEleLeft = viewportLeft + paneWidth;
	            if (eleLeft < viewportLeft || stickToTop) { // element is to the left of viewport
	                destX = eleLeft - settings.horizontalGutter;
	            } else if (eleLeft + eleWidth > maxVisibleEleLeft) { // element is to the right viewport
	                destX = eleLeft - paneWidth + eleWidth + settings.horizontalGutter;
	            }
	            if (destX) {
	                scrollToX(destX, animate);
	            }

			}

			function contentPositionX()
			{
				return -pane.position().left;
			}

			function contentPositionY()
			{
				return -pane.position().top;
			}

			function isCloseToBottom()
			{
				var scrollableHeight = contentHeight - paneHeight;
				return (scrollableHeight > 20) && (scrollableHeight - contentPositionY() < 10);
			}

			function isCloseToRight()
			{
				var scrollableWidth = contentWidth - paneWidth;
				return (scrollableWidth > 20) && (scrollableWidth - contentPositionX() < 10);
			}

			function initMousewheel()
			{
				container.unbind(mwEvent).bind(
					mwEvent,
					function (event, delta, deltaX, deltaY) {
						var dX = horizontalDragPosition, dY = verticalDragPosition;
						jsp.scrollBy(deltaX * settings.mouseWheelSpeed, -deltaY * settings.mouseWheelSpeed, false);
						// return true if there was no movement so rest of screen can scroll
						return dX == horizontalDragPosition && dY == verticalDragPosition;
					}
				);
			}

			function removeMousewheel()
			{
				container.unbind(mwEvent);
			}

			function nil()
			{
				return false;
			}

			function initFocusHandler()
			{
				pane.find(':input,a').unbind('focus.jsp').bind(
					'focus.jsp',
					function(e)
					{
						scrollToElement(e.target, false);
					}
				);
			}

			function removeFocusHandler()
			{
				pane.find(':input,a').unbind('focus.jsp');
			}
			
			function initKeyboardNav()
			{
				var keyDown, elementHasScrolled, validParents = [];
				isScrollableH && validParents.push(horizontalBar[0]);
				isScrollableV && validParents.push(verticalBar[0]);
				
				// IE also focuses elements that don't have tabindex set.
				pane.focus(
					function()
					{
						elem.focus();
					}
				);
				
				elem.attr('tabindex', 0)
					.unbind('keydown.jsp keypress.jsp')
					.bind(
						'keydown.jsp',
						function(e)
						{
							if (e.target !== this && !(validParents.length && $(e.target).closest(validParents).length)){
								return;
							}
							var dX = horizontalDragPosition, dY = verticalDragPosition;
							switch(e.keyCode) {
								case 40: // down
								case 38: // up
								case 34: // page down
								case 32: // space
								case 33: // page up
								case 39: // right
								case 37: // left
									keyDown = e.keyCode;
									keyDownHandler();
									break;
								case 35: // end
									scrollToY(contentHeight - paneHeight);
									keyDown = null;
									break;
								case 36: // home
									scrollToY(0);
									keyDown = null;
									break;
							}

							elementHasScrolled = e.keyCode == keyDown && dX != horizontalDragPosition || dY != verticalDragPosition;
							return !elementHasScrolled;
						}
					).bind(
						'keypress.jsp', // For FF/ OSX so that we can cancel the repeat key presses if the JSP scrolls...
						function(e)
						{
							if (e.keyCode == keyDown) {
								keyDownHandler();
							}
							return !elementHasScrolled;
						}
					);
				
				if (settings.hideFocus) {
					elem.css('outline', 'none');
					if ('hideFocus' in container[0]){
						elem.attr('hideFocus', true);
					}
				} else {
					elem.css('outline', '');
					if ('hideFocus' in container[0]){
						elem.attr('hideFocus', false);
					}
				}
				
				function keyDownHandler()
				{
					var dX = horizontalDragPosition, dY = verticalDragPosition;
					switch(keyDown) {
						case 40: // down
							jsp.scrollByY(settings.keyboardSpeed, false);
							break;
						case 38: // up
							jsp.scrollByY(-settings.keyboardSpeed, false);
							break;
						case 34: // page down
						case 32: // space
							jsp.scrollByY(paneHeight * settings.scrollPagePercent, false);
							break;
						case 33: // page up
							jsp.scrollByY(-paneHeight * settings.scrollPagePercent, false);
							break;
						case 39: // right
							jsp.scrollByX(settings.keyboardSpeed, false);
							break;
						case 37: // left
							jsp.scrollByX(-settings.keyboardSpeed, false);
							break;
					}

					elementHasScrolled = dX != horizontalDragPosition || dY != verticalDragPosition;
					return elementHasScrolled;
				}
			}
			
			function removeKeyboardNav()
			{
				elem.attr('tabindex', '-1')
					.removeAttr('tabindex')
					.unbind('keydown.jsp keypress.jsp');
			}

			function observeHash()
			{
				if (location.hash && location.hash.length > 1) {
					var e, retryInt;
					try {
						e = $(location.hash);
					} catch (err) {
						return;
					}

					if (e.length && pane.find(location.hash)) {
						// nasty workaround but it appears to take a little while before the hash has done its thing
						// to the rendered page so we just wait until the container's scrollTop has been messed up.
						if (container.scrollTop() === 0) {
							retryInt = setInterval(
								function()
								{
									if (container.scrollTop() > 0) {
										scrollToElement(location.hash, true);
										$(document).scrollTop(container.position().top);
										clearInterval(retryInt);
									}
								},
								50
							);
						} else {
							scrollToElement(location.hash, true);
							$(document).scrollTop(container.position().top);
						}
					}
				}
			}

			function unhijackInternalLinks()
			{
				$('a.jspHijack').unbind('click.jsp-hijack').removeClass('jspHijack');
			}

			function hijackInternalLinks()
			{
				unhijackInternalLinks();
				$('a[href^=#]').addClass('jspHijack').bind(
					'click.jsp-hijack',
					function()
					{
						var uriParts = this.href.split('#'), hash;
						if (uriParts.length > 1) {
							hash = uriParts[1];
							if (hash.length > 0 && pane.find('#' + hash).length > 0) {
								scrollToElement('#' + hash, true);
								// Need to return false otherwise things mess up... Would be nice to maybe also scroll
								// the window to the top of the scrollpane?
								return false;
							}
						}
					}
				);
			}
			
			// Init touch on iPad, iPhone, iPod, Android
			function initTouch()
			{
				var startX,
					startY,
					touchStartX,
					touchStartY,
					moved,
					moving = false;
  
				container.unbind('touchstart.jsp touchmove.jsp touchend.jsp click.jsp-touchclick').bind(
					'touchstart.jsp',
					function(e)
					{
						var touch = e.originalEvent.touches[0];
						startX = contentPositionX();
						startY = contentPositionY();
						touchStartX = touch.pageX;
						touchStartY = touch.pageY;
						moved = false;
						moving = true;
					}
				).bind(
					'touchmove.jsp',
					function(ev)
					{
						if(!moving) {
							return;
						}
						
						var touchPos = ev.originalEvent.touches[0],
							dX = horizontalDragPosition, dY = verticalDragPosition;
						
						jsp.scrollTo(startX + touchStartX - touchPos.pageX, startY + touchStartY - touchPos.pageY);
						
						moved = moved || Math.abs(touchStartX - touchPos.pageX) > 5 || Math.abs(touchStartY - touchPos.pageY) > 5;
						
						// return true if there was no movement so rest of screen can scroll
						return dX == horizontalDragPosition && dY == verticalDragPosition;
					}
				).bind(
					'touchend.jsp',
					function(e)
					{
						moving = false;
						/*if(moved) {
							return false;
						}*/
					}
				).bind(
					'click.jsp-touchclick',
					function(e)
					{
						if(moved) {
							moved = false;
							return false;
						}
					}
				);
			}
			
			function destroy(){
				var currentY = contentPositionY(),
					currentX = contentPositionX();
				elem.removeClass('jspScrollable').unbind('.jsp');
				elem.replaceWith(originalElement.append(pane.children()));
				originalElement.scrollTop(currentY);
				originalElement.scrollLeft(currentX);
			}

			// Public API
			$.extend(
				jsp,
				{
					// Reinitialises the scroll pane (if it's internal dimensions have changed since the last time it
					// was initialised). The settings object which is passed in will override any settings from the
					// previous time it was initialised - if you don't pass any settings then the ones from the previous
					// initialisation will be used.
					reinitialise: function(s)
					{
						s = $.extend({}, settings, s);
						initialise(s);
					},
					// Scrolls the specified element (a jQuery object, DOM node or jQuery selector string) into view so
					// that it can be seen within the viewport. If stickToTop is true then the element will appear at
					// the top of the viewport, if it is false then the viewport will scroll as little as possible to
					// show the element. You can also specify if you want animation to occur. If you don't provide this
					// argument then the animateScroll value from the settings object is used instead.
					scrollToElement: function(ele, stickToTop, animate)
					{
						scrollToElement(ele, stickToTop, animate);
					},
					// Scrolls the pane so that the specified co-ordinates within the content are at the top left
					// of the viewport. animate is optional and if not passed then the value of animateScroll from
					// the settings object this jScrollPane was initialised with is used.
					scrollTo: function(destX, destY, animate)
					{
						scrollToX(destX, animate);
						scrollToY(destY, animate);
					},
					// Scrolls the pane so that the specified co-ordinate within the content is at the left of the
					// viewport. animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					scrollToX: function(destX, animate)
					{
						scrollToX(destX, animate);
					},
					// Scrolls the pane so that the specified co-ordinate within the content is at the top of the
					// viewport. animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					scrollToY: function(destY, animate)
					{
						scrollToY(destY, animate);
					},
					// Scrolls the pane to the specified percentage of its maximum horizontal scroll position. animate
					// is optional and if not passed then the value of animateScroll from the settings object this
					// jScrollPane was initialised with is used.
					scrollToPercentX: function(destPercentX, animate)
					{
						scrollToX(destPercentX * (contentWidth - paneWidth), animate);
					},
					// Scrolls the pane to the specified percentage of its maximum vertical scroll position. animate
					// is optional and if not passed then the value of animateScroll from the settings object this
					// jScrollPane was initialised with is used.
					scrollToPercentY: function(destPercentY, animate)
					{
						scrollToY(destPercentY * (contentHeight - paneHeight), animate);
					},
					// Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then
					// the value of animateScroll from the settings object this jScrollPane was initialised with is used.
					scrollBy: function(deltaX, deltaY, animate)
					{
						jsp.scrollByX(deltaX, animate);
						jsp.scrollByY(deltaY, animate);
					},
					// Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then
					// the value of animateScroll from the settings object this jScrollPane was initialised with is used.
					scrollByX: function(deltaX, animate)
					{
						var destX = contentPositionX() + deltaX,
							percentScrolled = destX / (contentWidth - paneWidth);
						positionDragX(percentScrolled * dragMaxX, animate);
					},
					// Scrolls the pane by the specified amount of pixels. animate is optional and if not passed then
					// the value of animateScroll from the settings object this jScrollPane was initialised with is used.
					scrollByY: function(deltaY, animate)
					{
						var destY = contentPositionY() + deltaY,
							percentScrolled = destY / (contentHeight - paneHeight);
						positionDragY(percentScrolled * dragMaxY, animate);
					},
					// Positions the horizontal drag at the specified x position (and updates the viewport to reflect
					// this). animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					positionDragX: function(x, animate)
					{
						positionDragX(x, animate);
					},
					// Positions the vertical drag at the specified y position (and updates the viewport to reflect
					// this). animate is optional and if not passed then the value of animateScroll from the settings
					// object this jScrollPane was initialised with is used.
					positionDragY: function(y, animate)
					{
						positionDragY(y, animate);
					},
					// This method is called when jScrollPane is trying to animate to a new position. You can override
					// it if you want to provide advanced animation functionality. It is passed the following arguments:
					//  * ele          - the element whose position is being animated
					//  * prop         - the property that is being animated
					//  * value        - the value it's being animated to
					//  * stepCallback - a function that you must execute each time you update the value of the property
					// You can use the default implementation (below) as a starting point for your own implementation.
					animate: function(ele, prop, value, stepCallback)
					{
						var params = {};
						params[prop] = value;
						ele.animate(
							params,
							{
								'duration'	: settings.animateDuration,
								'ease'		: settings.animateEase,
								'queue'		: false,
								'step'		: stepCallback
							}
						);
					},
					// Returns the current x position of the viewport with regards to the content pane.
					getContentPositionX: function()
					{
						return contentPositionX();
					},
					// Returns the current y position of the viewport with regards to the content pane.
					getContentPositionY: function()
					{
						return contentPositionY();
					},
					// Returns the width of the content within the scroll pane.
					getContentWidth: function()
					{
						return contentWidth;
					},
					// Returns the height of the content within the scroll pane.
					getContentHeight: function()
					{
						return contentHeight;
					},
					// Returns the horizontal position of the viewport within the pane content.
					getPercentScrolledX: function()
					{
						return contentPositionX() / (contentWidth - paneWidth);
					},
					// Returns the vertical position of the viewport within the pane content.
					getPercentScrolledY: function()
					{
						return contentPositionY() / (contentHeight - paneHeight);
					},
					// Returns whether or not this scrollpane has a horizontal scrollbar.
					getIsScrollableH: function()
					{
						return isScrollableH;
					},
					// Returns whether or not this scrollpane has a vertical scrollbar.
					getIsScrollableV: function()
					{
						return isScrollableV;
					},
					// Gets a reference to the content pane. It is important that you use this method if you want to
					// edit the content of your jScrollPane as if you access the element directly then you may have some
					// problems (as your original element has had additional elements for the scrollbars etc added into
					// it).
					getContentPane: function()
					{
						return pane;
					},
					// Scrolls this jScrollPane down as far as it can currently scroll. If animate isn't passed then the
					// animateScroll value from settings is used instead.
					scrollToBottom: function(animate)
					{
						positionDragY(dragMaxY, animate);
					},
					// Hijacks the links on the page which link to content inside the scrollpane. If you have changed
					// the content of your page (e.g. via AJAX) and want to make sure any new anchor links to the
					// contents of your scroll pane will work then call this function.
					hijackInternalLinks: function()
					{
						hijackInternalLinks();
					},
					// Removes the jScrollPane and returns the page to the state it was in before jScrollPane was
					// initialised.
					destroy: function()
					{
							destroy();
					}
				}
			);
			
			initialise(s);
		}

		// Pluginifying code...
		settings = $.extend({}, $.fn.jScrollPane.defaults, settings);
		
		// Apply default speed
		$.each(['mouseWheelSpeed', 'arrowButtonSpeed', 'trackClickSpeed', 'keyboardSpeed'], function() {
			settings[this] = settings[this] || settings.speed;
		});

		var ret;
		this.each(
			function()
			{
				var elem = $(this), jspApi = elem.data('jsp');
				if (jspApi) {
					jspApi.reinitialise(settings);
				} else {
					jspApi = new JScrollPane(elem, settings);
					elem.data('jsp', jspApi);
				}
				ret = ret ? ret.add(elem) : elem;
			}
		);
		return ret;
	};

	$.fn.jScrollPane.defaults = {
		showArrows					: false,
		maintainPosition			: true,
		stickToBottom				: false,
		stickToRight				: false,
		clickOnTrack				: true,
		autoReinitialise			: false,
		autoReinitialiseDelay		: 500,
		verticalDragMinHeight		: 0,
		verticalDragMaxHeight		: 99999,
		horizontalDragMinWidth		: 0,
		horizontalDragMaxWidth		: 99999,
		contentWidth				: undefined,
		animateScroll				: false,
		animateDuration				: 300,
		animateEase					: 'linear',
		hijackInternalLinks			: false,
		verticalGutter				: 4,
		horizontalGutter			: 4,
		mouseWheelSpeed				: 0,
		arrowButtonSpeed			: 300,
		arrowRepeatFreq				: 50,
		arrowScrollOnHover			: false,
		trackClickSpeed				: 0,
		trackClickRepeatFreq		: 70,
		verticalArrowPositions		: 'split',
		horizontalArrowPositions	: 'split',
		enableKeyboardNavigation	: true,
		hideFocus					: false,
		keyboardSpeed				: 0,
		initialDelay                : 300,        // Delay before starting repeating
		speed						: 30,		// Default speed when others falsey
		scrollPagePercent			: .8		// Percent of visible area scrolled when pageUp/Down or track area pressed
	};

})(jQuery,this);

;
/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.4
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    
    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }
    
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    
    return $.event.handle.apply(this, args);
}

})(jQuery);;
jQuery(document).ready(function() {
	jQuery('.sub-rubrics-link').bind('click', function() {
		jQuery.fn.nyroModalManual({
			content: jQuery('.subrubrics-list').html()
		});
	});

	/** Statistics search button click **/ 
	ajax_statistics_search_button = function() {
		jQuery.ajax({
			type: 'POST',
			url: Drupal.settings.basePath + 'statistics/type/button',
			success: function(data) {},
			dataType: 'json'
		});
		
		return false;
	}
	
	/** Click on also search **/
	function bind_also_search_link() {
		jQuery('a.search-info-also', '.search-bottom-info-row').click(function(){
			/** Set list position **/
			var position = jQuery('a.search-info-also', '.search-bottom-info-row').offset();
			var mainPosition = jQuery('div#main').offset();
			var positionShift = position.left - mainPosition.left - 13;
			if (jQuery('.categories-search-also').width() + positionShift < jQuery('div.result-main-area').width())
				jQuery('.categories-search-also').offset({left: positionShift});
			
			jQuery('.categories-search-also').slideToggle(function() {
				jQuery('a.search-info-also', '.search-bottom-info-row').unbind();
				jQuery('body').click(function() {
					jQuery('body').unbind();
					jQuery('.categories-search-also').slideToggle(function() {
						bind_also_search_link();
					});
				});
			});
			jQuery('li', '.categories-search-also').mouseover( function(event) {
				jQuery(this).addClass('item-active');
			});
			jQuery('li', '.categories-search-also').mouseout( function(event) {
				jQuery(this).removeClass('item-active');
			});
			jQuery('li', '.categories-search-also').click( function() {
				var iCategoryID = jQuery(this).attr('id').replace('category-also-', '');
				var sCategory = jQuery(this).html();
				
				jQuery.ajax({
					type: 'POST',
					url: Drupal.settings.basePath + 'statistics/search-also',
					success: function(data) {
						window.location = Drupal.settings.basePath + 'search/' + sCategory;
					},
					dataType: 'json',
					data: { 'id': iCategoryID } 
				});
			});
		});
	}
	bind_also_search_link();
	
	var tWidth = 930;
	var minHeight = 409;
	var heightShift = 18;
	var mainStringWidth = 460;
	var tHeight = jQuery(window).height() - (jQuery('#inner-block-strings-search-form').outerHeight() + jQuery('.records-count').outerHeight() + jQuery('.main-bottom-banner').outerHeight() + jQuery('.header').outerHeight() + jQuery('.region-page-top').outerHeight() + jQuery('#footer-wrapper').outerHeight()) - heightShift;
	
	/** Min size of window **/
	if (tHeight < minHeight)
		tHeight = minHeight;
	
	jQuery('.results-table-block').height(tHeight);
	
	if (jQuery('#middle-banner-block').height() == null) {
		jQuery('.result-content-area').width(tWidth);
		jQuery('#strings-search', '.result-content-area').width(763);
	} else
		jQuery('.main', '.search-result-item').width(mainStringWidth);
	
	jQuery('#strings-search').focus().select();
	jQuery('.results-table-block').jScrollPane({showArrows: true});
	
	/** Search categories link **/
	jQuery('.region-page-top').addClass('top-links-block');
	jQuery('.top-menu-link').last().addClass('search-categories-link');
	
	/** Center phones in the line **/
	jQuery('.search-result-item').each(function () {
		var detailsHeight = 33;
		if (jQuery('.site', this).height() == null)
			detailsHeight -= 19;
		
		jQuery('.details', this).css('padding-top', (jQuery(this).height() - detailsHeight) / 2);
		
		jQuery(this).mouseover(function(event) {
			jQuery(this).addClass('selected-item-active');
		});
		jQuery(this).mouseout(function(event) {
			jQuery(this).removeClass('selected-item-active');
		});
	});
	
	/** Submit search form after autocomplete **/
	jQuery('#strings-search-block-form').submit(function() {
		if (jQuery('#strings-search').val()) {
			if (jQuery('input[name="strings_search_rubric"]').val()) {
				jQuery.ajax({
					type: 'POST',
					url: Drupal.settings.basePath + 'search/autocomplete/add/statistic',
					success:function(data) {
						if (!data)
							data = Drupal.settings.basePath + 'search/' + jQuery('#strings-search').val();
						
						window.location.replace(data);
					},
					/**dataType: 'json',**/
					data: 'string_id=' + jQuery('input[name="strings_search_rubric"]').val()
				});
				return false;
			} else
				return true;
		} else
			return false;
	});
});;
/*
 * nyroModal - jQuery Plugin
 * http://nyromodal.nyrodev.com
 *
 * Copyright (c) 2010 Cedric Nirousset (nyrodev.com)
 * Licensed under the MIT license
 *
 * $Date: 2010-02-23 (Tue, 23 Feb 2010) $
 * $version: 1.6.2
 */
jQuery(function($){var userAgent=navigator.userAgent.toLowerCase();var browserVersion=(userAgent.match(/.+(?:rv|webkit|khtml|opera|msie)[\/: ]([\d.]+)/)||[0,'0'])[1];var isIE6=(/msie/.test(userAgent)&&!/opera/.test(userAgent)&&parseInt(browserVersion)<7&&(!window.XMLHttpRequest||typeof(XMLHttpRequest)==='function'));var body=$('body');var currentSettings;var callingSettings;var shouldResize=false;var gallery={};var fixFF=false;var contentElt;var contentEltLast;var modal={started:false,ready:false,dataReady:false,anim:false,animContent:false,loadingShown:false,transition:false,resizing:false,closing:false,error:false,blocker:null,blockerVars:null,full:null,bg:null,loading:null,tmp:null,content:null,wrapper:null,contentWrapper:null,scripts:new Array(),scriptsShown:new Array()};var resized={width:false,height:false,windowResizing:false};var initSettingsSize={width:null,height:null,windowResizing:true};var windowResizeTimeout;$.fn.nyroModal=function(settings){if(!this)return false;return this.each(function(){var me=$(this);if(this.nodeName.toLowerCase()=='form'){me.unbind('submit.nyroModal').bind('submit.nyroModal',function(e){if(e.isDefaultPrevented())return false;if(me.data('nyroModalprocessing'))return true;if(this.enctype=='multipart/form-data'){processModal($.extend(settings,{from:this}));return true}e.preventDefault();processModal($.extend(settings,{from:this}));return false})}else{me.unbind('click.nyroModal').bind('click.nyroModal',function(e){if(e.isDefaultPrevented())return false;e.preventDefault();processModal($.extend(settings,{from:this}));return false})}})};$.fn.nyroModalManual=function(settings){if(!this.length)processModal(settings);return this.each(function(){processModal($.extend(settings,{from:this}))})};$.nyroModalManual=function(settings){processModal(settings)};$.nyroModalSettings=function(settings,deep1,deep2){setCurrentSettings(settings,deep1,deep2);if(!deep1&&modal.started){if(modal.bg&&settings.bgColor)currentSettings.updateBgColor(modal,currentSettings,function(){});if(modal.contentWrapper&&settings.title)setTitle();if(!modal.error&&(settings.windowResizing||(!modal.resizing&&(('width'in settings&&settings.width==currentSettings.width)||('height'in settings&&settings.height==currentSettings.height))))){modal.resizing=true;if(modal.contentWrapper)calculateSize(true);if(modal.contentWrapper&&modal.contentWrapper.is(':visible')&&!modal.animContent){if(fixFF)modal.content.css({position:''});currentSettings.resize(modal,currentSettings,function(){currentSettings.windowResizing=false;modal.resizing=false;if(fixFF)modal.content.css({position:'fixed'});if($.isFunction(currentSettings.endResize))currentSettings.endResize(modal,currentSettings)})}}}};$.nyroModalRemove=function(){removeModal()};$.nyroModalNext=function(){var link=getGalleryLink(1);if(link)return link.nyroModalManual(getCurrentSettingsNew());return false};$.nyroModalPrev=function(){var link=getGalleryLink(-1);if(link)return link.nyroModalManual(getCurrentSettingsNew());return false};$.fn.nyroModal.settings={debug:false,blocker:false,windowResize:true,modal:false,type:'',forceType:null,from:'',hash:'',processHandler:null,selIndicator:'nyroModalSel',formIndicator:'nyroModal',content:null,bgColor:'#000000',ajax:{},swf:{wmode:'transparent'},width:null,height:null,minWidth:400,minHeight:300,resizable:true,autoSizable:true,padding:25,regexImg:'[^\.]\.(jpg|jpeg|png|tiff|gif|bmp)\s*$',addImageDivTitle:false,defaultImgAlt:'Image',setWidthImgTitle:true,ltr:true,gallery:null,galleryLinks:'<a href="#" class="nyroModalPrev">Prev</a><a href="#"  class="nyroModalNext">Next</a>',galleryCounts:galleryCounts,galleryLoop:false,zIndexStart:100,cssOpt:{bg:{position:'absolute',overflow:'hidden',top:0,left:0,height:'100%',width:'100%'},wrapper:{position:'absolute',top:'50%',left:'50%'},wrapper2:{},content:{},loading:{position:'absolute',top:'50%',left:'50%',marginTop:'-50px',marginLeft:'-50px'}},wrap:{div:'<div class="wrapper"></div>',ajax:'<div class="wrapper"></div>',form:'<div class="wrapper"></div>',formData:'<div class="wrapper"></div>',image:'<div class="wrapperImg"></div>',swf:'<div class="wrapperSwf"></div>',iframe:'<div class="wrapperIframe"></div>',iframeForm:'<div class="wrapperIframe"></div>',manual:'<div class="wrapper"></div>'},closeButton:'<a href="#" class="nyroModalClose" id="closeBut" title="Закрыть">Close</a>',title:null,titleFromIframe:true,openSelector:'.nyroModal',closeSelector:'.nyroModalClose',contentLoading:'<a href="#" class="nyroModalClose">Cancel</a>',errorClass:'error',contentError:'The requested content cannot be loaded.<br />Please try again later.<br /><a href="#" class="nyroModalClose">Close</a>',handleError:null,showBackground:showBackground,hideBackground:hideBackground,endFillContent:null,showContent:showContent,endShowContent:null,beforeHideContent:null,hideContent:hideContent,showTransition:showTransition,hideTransition:hideTransition,showLoading:showLoading,hideLoading:hideLoading,resize:resize,endResize:null,updateBgColor:updateBgColor,endRemove:null};function processModal(settings){if(modal.loadingShown||modal.transition||modal.anim)return;debug('processModal');modal.started=true;callingSettings=$.extend(true,settings);setDefaultCurrentSettings(settings);if(!modal.full)modal.blockerVars=modal.blocker=null;modal.error=false;modal.closing=false;modal.dataReady=false;modal.scripts=new Array();modal.scriptsShown=new Array();currentSettings.type=fileType();if(currentSettings.forceType){if(!currentSettings.content)currentSettings.from=true;currentSettings.type=currentSettings.forceType;currentSettings.forceType=null}if($.isFunction(currentSettings.processHandler))currentSettings.processHandler(currentSettings);var from=currentSettings.from;var url=currentSettings.url;initSettingsSize.width=currentSettings.width;initSettingsSize.height=currentSettings.height;if(currentSettings.type=='swf'){setCurrentSettings({overflow:'visible'},'cssOpt','content');currentSettings.content='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+currentSettings.width+'" height="'+currentSettings.height+'"><param name="movie" value="'+url+'"></param>';var tmp='';$.each(currentSettings.swf,function(name,val){currentSettings.content+='<param name="'+name+'" value="'+val+'"></param>';tmp+=' '+name+'="'+val+'"'});currentSettings.content+='<embed src="'+url+'" type="application/x-shockwave-flash" width="'+currentSettings.width+'" height="'+currentSettings.height+'"'+tmp+'></embed></object>'}if(from){var jFrom=$(from).blur();if(currentSettings.type=='form'){var data=$(from).serializeArray();data.push({name:currentSettings.formIndicator,value:1});if(currentSettings.selector)data.push({name:currentSettings.selIndicator,value:currentSettings.selector.substring(1)});showModal();$.ajax($.extend({},currentSettings.ajax,{url:url,data:data,type:jFrom.attr('method')?jFrom.attr('method'):'get',success:ajaxLoaded,error:loadingError}));debug('Form Ajax Load: '+jFrom.attr('action'))}else if(currentSettings.type=='formData'){initModal();jFrom.attr('target','nyroModalIframe');jFrom.attr('action',url);jFrom.prepend('<input type="hidden" name="'+currentSettings.formIndicator+'" value="1" />');if(currentSettings.selector)jFrom.prepend('<input type="hidden" name="'+currentSettings.selIndicator+'" value="'+currentSettings.selector.substring(1)+'" />');modal.tmp.html('<iframe frameborder="0" hspace="0" name="nyroModalIframe" src="javascript:\'\';"></iframe>');$('iframe',modal.tmp).css({width:currentSettings.width,height:currentSettings.height}).error(loadingError).load(formDataLoaded);debug('Form Data Load: '+jFrom.attr('action'));showModal();showContentOrLoading()}else if(currentSettings.type=='image'){debug('Image Load: '+url);var title=jFrom.attr('title')||currentSettings.defaultImgAlt;initModal();modal.tmp.html('<img id="nyroModalImg" />').find('img').attr('alt',title);modal.tmp.css({lineHeight:0});$('img',modal.tmp).error(loadingError).load(function(){debug('Image Loaded: '+this.src);$(this).unbind('load');var w=modal.tmp.width();var h=modal.tmp.height();modal.tmp.css({lineHeight:''});resized.width=w;resized.height=h;setCurrentSettings({width:w,height:h,imgWidth:w,imgHeight:h});initSettingsSize.width=w;initSettingsSize.height=h;setCurrentSettings({overflow:'visible'},'cssOpt','content');modal.dataReady=true;if(modal.loadingShown||modal.transition)showContentOrLoading()}).attr('src',url);showModal()}else if(currentSettings.type=='iframeForm'){initModal();modal.tmp.html('<iframe frameborder="0" hspace="0" src="javascript:\'\';" name="nyroModalIframe" id="nyroModalIframe"></iframe>');debug('Iframe Form Load: '+url);$('iframe',modal.tmp).eq(0).css({width:'100%',height:$.support.boxModel?'99%':'100%'}).load(iframeLoaded);modal.dataReady=true;showModal()}else if(currentSettings.type=='iframe'){initModal();modal.tmp.html('<iframe frameborder="0" hspace="0" src="javascript:\'\';" name="nyroModalIframe" id="nyroModalIframe"></iframe>');debug('Iframe Load: '+url);$('iframe',modal.tmp).eq(0).css({width:'100%',height:$.support.boxModel?'99%':'100%'}).load(iframeLoaded);modal.dataReady=true;showModal()}else if(currentSettings.type){debug('Content: '+currentSettings.type);initModal();modal.tmp.html(currentSettings.content);var w=modal.tmp.width();var h=modal.tmp.height();var div=$(currentSettings.type);if(div.length){setCurrentSettings({type:'div'});w=div.width();h=div.height();if(contentElt)contentEltLast=contentElt;contentElt=div;modal.tmp.append(div.contents())}initSettingsSize.width=w;initSettingsSize.height=h;setCurrentSettings({width:w,height:h});if(modal.tmp.html())modal.dataReady=true;else loadingError();if(!modal.ready)showModal();else endHideContent()}else{debug('Ajax Load: '+url);setCurrentSettings({type:'ajax'});var data=currentSettings.ajax.data||{};if(currentSettings.selector){if(typeof data=="string"){data+='&'+currentSettings.selIndicator+'='+currentSettings.selector.substring(1)}else{data[currentSettings.selIndicator]=currentSettings.selector.substring(1)}}showModal();$.ajax($.extend(true,currentSettings.ajax,{url:url,success:ajaxLoaded,error:loadingError,data:data}))}}else if(currentSettings.content){debug('Content: '+currentSettings.type);setCurrentSettings({type:'manual'});initModal();modal.tmp.html($('<div/>').html(currentSettings.content).contents());if(modal.tmp.html())modal.dataReady=true;else loadingError();showModal()}else{}}function setDefaultCurrentSettings(settings){debug('setDefaultCurrentSettings');currentSettings=$.extend(true,{},$.fn.nyroModal.settings,settings);setMargin()}function setCurrentSettings(settings,deep1,deep2){if(modal.started){if(deep1&&deep2){$.extend(true,currentSettings[deep1][deep2],settings)}else if(deep1){$.extend(true,currentSettings[deep1],settings)}else{if(modal.animContent){if('width'in settings){if(!modal.resizing){settings.setWidth=settings.width;shouldResize=true}delete settings['width']}if('height'in settings){if(!modal.resizing){settings.setHeight=settings.height;shouldResize=true}delete settings['height']}}$.extend(true,currentSettings,settings)}}else{if(deep1&&deep2){$.extend(true,$.fn.nyroModal.settings[deep1][deep2],settings)}else if(deep1){$.extend(true,$.fn.nyroModal.settings[deep1],settings)}else{$.extend(true,$.fn.nyroModal.settings,settings)}}}function setMarginScroll(){if(isIE6&&!modal.blocker){if(document.documentElement){currentSettings.marginScrollLeft=document.documentElement.scrollLeft;currentSettings.marginScrollTop=document.documentElement.scrollTop}else{currentSettings.marginScrollLeft=document.body.scrollLeft;currentSettings.marginScrollTop=document.body.scrollTop}}else{currentSettings.marginScrollLeft=0;currentSettings.marginScrollTop=0}}function setMargin(){setMarginScroll();currentSettings.marginLeft=-(currentSettings.width+currentSettings.borderW)/2;currentSettings.marginTop=-(currentSettings.height+currentSettings.borderH)/2;if(!modal.blocker){currentSettings.marginLeft+=currentSettings.marginScrollLeft;currentSettings.marginTop+=currentSettings.marginScrollTop}}function setMarginLoading(){setMarginScroll();var outer=getOuter(modal.loading);currentSettings.marginTopLoading=-(modal.loading.height()+outer.h.border+outer.h.padding)/2;currentSettings.marginLeftLoading=-(modal.loading.width()+outer.w.border+outer.w.padding)/2;if(!modal.blocker){currentSettings.marginLeftLoading+=currentSettings.marginScrollLeft;currentSettings.marginTopLoading+=currentSettings.marginScrollTop}}function setTitle(){var title=$('h1#nyroModalTitle',modal.contentWrapper);if(title.length)title.text(currentSettings.title);else modal.contentWrapper.prepend('<h1 id="nyroModalTitle">'+currentSettings.title+'</h1>')}function initModal(){debug('initModal');if(!modal.full){if(currentSettings.debug)setCurrentSettings({color:'white'},'cssOpt','bg');var full={zIndex:currentSettings.zIndexStart,position:'fixed',top:0,left:0,width:'100%',height:'100%'};var contain=body;var iframeHideIE='';if(currentSettings.blocker){modal.blocker=contain=$(currentSettings.blocker);var pos=modal.blocker.offset();var w=modal.blocker.outerWidth();var h=modal.blocker.outerHeight();if(isIE6){setCurrentSettings({height:'100%',width:'100%',top:0,left:0},'cssOpt','bg')}modal.blockerVars={top:pos.top,left:pos.left,width:w,height:h};var plusTop=(/msie/.test(userAgent)?0:getCurCSS(body.get(0),'borderTopWidth'));var plusLeft=(/msie/.test(userAgent)?0:getCurCSS(body.get(0),'borderLeftWidth'));full={position:'absolute',top:pos.top+plusTop,left:pos.left+plusLeft,width:w,height:h}}else if(isIE6){body.css({marginLeft:0,marginRight:0});var w=body.width();var h=$(window).height()+'px';if($(window).height()>=body.outerHeight()){h=body.outerHeight()+'px'}else w+=20;w+='px';body.css({width:w,height:h,position:'static',overflow:'hidden'});$('html').css({overflow:'hidden'});setCurrentSettings({cssOpt:{bg:{position:'absolute',zIndex:currentSettings.zIndexStart+1,height:'110%',width:'110%',top:currentSettings.marginScrollTop+'px',left:currentSettings.marginScrollLeft+'px'},wrapper:{zIndex:currentSettings.zIndexStart+2},loading:{zIndex:currentSettings.zIndexStart+3}}});iframeHideIE=$('<iframe id="nyroModalIframeHideIe" src="javascript:\'\';"></iframe>').css($.extend({},currentSettings.cssOpt.bg,{opacity:0,zIndex:50,border:'none'}))}contain.append($('<div id="nyroModalFull"><div id="nyroModalBg"></div><div id="nyroModalWrapper"><div id="nyroModalContent"></div></div><div id="nyrModalTmp"></div><div id="nyroModalLoading"></div></div>').hide());modal.full=$('#nyroModalFull').css(full).show();modal.bg=$('#nyroModalBg').css($.extend({backgroundColor:currentSettings.bgColor},currentSettings.cssOpt.bg)).before(iframeHideIE);modal.bg.bind('click.nyroModal',clickBg);modal.loading=$('#nyroModalLoading').css(currentSettings.cssOpt.loading).hide();modal.contentWrapper=$('#nyroModalWrapper').css(currentSettings.cssOpt.wrapper).hide();modal.content=$('#nyroModalContent');modal.tmp=$('#nyrModalTmp').hide();if($.isFunction($.fn.mousewheel)){modal.content.mousewheel(function(e,d){var elt=modal.content.get(0);if((d>0&&elt.scrollTop==0)||(d<0&&elt.scrollHeight-elt.scrollTop==elt.clientHeight)){e.preventDefault();e.stopPropagation()}})}$(document).bind('keydown.nyroModal',keyHandler);modal.content.css({width:'auto',height:'auto'});modal.contentWrapper.css({width:'auto',height:'auto'});if(!currentSettings.blocker&&currentSettings.windowResize){$(window).bind('resize.nyroModal',function(){window.clearTimeout(windowResizeTimeout);windowResizeTimeout=window.setTimeout(windowResizeHandler,200)})}}}function windowResizeHandler(){$.nyroModalSettings(initSettingsSize)}function showModal(){debug('showModal');if(!modal.ready){initModal();modal.anim=true;currentSettings.showBackground(modal,currentSettings,endBackground)}else{modal.anim=true;modal.transition=true;currentSettings.showTransition(modal,currentSettings,function(){endHideContent();modal.anim=false;showContentOrLoading()})}}function clickBg(e){if(!currentSettings.modal)removeModal()}function keyHandler(e){if(e.keyCode==27){if(!currentSettings.modal)removeModal()}else if(currentSettings.gallery&&modal.ready&&modal.dataReady&&!modal.anim&&!modal.transition){if(e.keyCode==39||e.keyCode==40){e.preventDefault();$.nyroModalNext();return false}else if(e.keyCode==37||e.keyCode==38){e.preventDefault();$.nyroModalPrev();return false}}}function fileType(){var from=currentSettings.from;var url;if(from&&from.nodeName){var jFrom=$(from);url=jFrom.attr(from.nodeName.toLowerCase()=='form'?'action':'href');if(!url)url=location.href.substring(window.location.host.length+7);currentSettings.url=url;if(jFrom.attr('rev')=='modal')currentSettings.modal=true;currentSettings.title=jFrom.attr('title');if(from&&from.rel&&from.rel.toLowerCase()!='nofollow'){var indexSpace=from.rel.indexOf(' ');currentSettings.gallery=indexSpace>0?from.rel.substr(0,indexSpace):from.rel}var imgType=imageType(url,from);if(imgType)return imgType;if(isSwf(url))return'swf';var iframe=false;if(from.target&&from.target.toLowerCase()=='_blank'||(from.hostname&&from.hostname.replace(/:\d*$/,'')!=window.location.hostname.replace(/:\d*$/,''))){iframe=true}if(from.nodeName.toLowerCase()=='form'){if(iframe)return'iframeForm';setCurrentSettings(extractUrlSel(url));if(jFrom.attr('enctype')=='multipart/form-data')return'formData';return'form'}if(iframe)return'iframe'}else{url=currentSettings.url;if(!currentSettings.content)currentSettings.from=true;if(!url)return null;if(isSwf(url))return'swf';var reg1=new RegExp("^http://|https://","g");if(url.match(reg1))return'iframe'}var imgType=imageType(url,from);if(imgType)return imgType;var tmp=extractUrlSel(url);setCurrentSettings(tmp);if(!tmp.url)return tmp.selector}function imageType(url,from){var image=new RegExp(currentSettings.regexImg,'i');if(image.test(url)){return'image'}}function isSwf(url){var swf=new RegExp('[^\.]\.(swf)\s*$','i');return swf.test(url)}function extractUrlSel(url){var ret={url:null,selector:null};if(url){var hash=getHash(url);var hashLoc=getHash(window.location.href);var curLoc=window.location.href.substring(0,window.location.href.length-hashLoc.length);var req=url.substring(0,url.length-hash.length);if(req==curLoc||req==$('base').attr('href')){ret.selector=hash}else{ret.url=req;ret.selector=hash}}return ret}function loadingError(){debug('loadingError');modal.error=true;if(!modal.ready)return;if($.isFunction(currentSettings.handleError))currentSettings.handleError(modal,currentSettings);modal.loading.addClass(currentSettings.errorClass).html(currentSettings.contentError);$(currentSettings.closeSelector,modal.loading).unbind('click.nyroModal').bind('click.nyroModal',removeModal);setMarginLoading();modal.loading.css({marginTop:currentSettings.marginTopLoading+'px',marginLeft:currentSettings.marginLeftLoading+'px'})}function fillContent(){debug('fillContent');if(!modal.tmp.html())return;modal.content.html(modal.tmp.contents());modal.tmp.empty();wrapContent();if(currentSettings.type=='iframeForm'){$(currentSettings.from).attr('target','nyroModalIframe').data('nyroModalprocessing',1).submit().attr('target','_blank').removeData('nyroModalprocessing')}if(!currentSettings.modal)modal.wrapper.prepend(currentSettings.closeButton);if($.isFunction(currentSettings.endFillContent))currentSettings.endFillContent(modal,currentSettings);modal.content.append(modal.scripts);$(currentSettings.closeSelector,modal.contentWrapper).unbind('click.nyroModal').bind('click.nyroModal',removeModal);$(currentSettings.openSelector,modal.contentWrapper).nyroModal(getCurrentSettingsNew())}function getCurrentSettingsNew(){return callingSettings;var currentSettingsNew=$.extend(true,{},currentSettings);if(resized.width)currentSettingsNew.width=null;else currentSettingsNew.width=initSettingsSize.width;if(resized.height)currentSettingsNew.height=null;else currentSettingsNew.height=initSettingsSize.height;currentSettingsNew.cssOpt.content.overflow='auto';return currentSettingsNew}function wrapContent(){debug('wrapContent');var wrap=$(currentSettings.wrap[currentSettings.type]);modal.content.append(wrap.children().remove());modal.contentWrapper.wrapInner(wrap);if(currentSettings.gallery){modal.content.append(currentSettings.galleryLinks);gallery.links=$('[rel="'+currentSettings.gallery+'"], [rel^="'+currentSettings.gallery+' "]');gallery.index=gallery.links.index(currentSettings.from);if(currentSettings.galleryCounts&&$.isFunction(currentSettings.galleryCounts))currentSettings.galleryCounts(gallery.index+1,gallery.links.length,modal,currentSettings);var currentSettingsNew=getCurrentSettingsNew();var linkPrev=getGalleryLink(-1);if(linkPrev){var prev=$('.nyroModalPrev',modal.contentWrapper).attr('href',linkPrev.attr('href')).click(function(e){e.preventDefault();$.nyroModalPrev();return false});if(isIE6&&currentSettings.type=='swf'){prev.before($('<iframe id="nyroModalIframeHideIeGalleryPrev" src="javascript:\'\';"></iframe>').css({position:prev.css('position'),top:prev.css('top'),left:prev.css('left'),width:prev.width(),height:prev.height(),opacity:0,border:'none'}))}}else{$('.nyroModalPrev',modal.contentWrapper).remove()}var linkNext=getGalleryLink(1);if(linkNext){var next=$('.nyroModalNext',modal.contentWrapper).attr('href',linkNext.attr('href')).click(function(e){e.preventDefault();$.nyroModalNext();return false});if(isIE6&&currentSettings.type=='swf'){next.before($('<iframe id="nyroModalIframeHideIeGalleryNext" src="javascript:\'\';"></iframe>').css($.extend({},{position:next.css('position'),top:next.css('top'),left:next.css('left'),width:next.width(),height:next.height(),opacity:0,border:'none'})))}}else{$('.nyroModalNext',modal.contentWrapper).remove()}}calculateSize()}function getGalleryLink(dir){if(currentSettings.gallery){if(!currentSettings.ltr)dir*=-1;var index=gallery.index+dir;if(index>=0&&index<gallery.links.length)return gallery.links.eq(index);else if(currentSettings.galleryLoop){if(index<0)return gallery.links.eq(gallery.links.length-1);else return gallery.links.eq(0)}}return false}function calculateSize(resizing){debug('calculateSize');modal.wrapper=modal.contentWrapper.children('div:first');resized.width=false;resized.height=false;if(false&&!currentSettings.windowResizing){initSettingsSize.width=currentSettings.width;initSettingsSize.height=currentSettings.height}if(currentSettings.autoSizable&&(!currentSettings.width||!currentSettings.height)){modal.contentWrapper.css({opacity:0,width:'auto',height:'auto'}).show();var tmp={width:'auto',height:'auto'};if(currentSettings.width){tmp.width=currentSettings.width}else if(currentSettings.type=='iframe'){tmp.width=currentSettings.minWidth}if(currentSettings.height){tmp.height=currentSettings.height}else if(currentSettings.type=='iframe'){tmp.height=currentSettings.minHeight}modal.content.css(tmp);if(!currentSettings.width){currentSettings.width=modal.content.outerWidth(true);resized.width=true}if(!currentSettings.height){currentSettings.height=modal.content.outerHeight(true);resized.height=true}modal.contentWrapper.css({opacity:1});if(!resizing)modal.contentWrapper.hide()}if(currentSettings.type!='image'&&currentSettings.type!='swf'){currentSettings.width=Math.max(currentSettings.width,currentSettings.minWidth);currentSettings.height=Math.max(currentSettings.height,currentSettings.minHeight)}var outerWrapper=getOuter(modal.contentWrapper);var outerWrapper2=getOuter(modal.wrapper);var outerContent=getOuter(modal.content);var tmp={content:{width:currentSettings.width,height:currentSettings.height},wrapper2:{width:currentSettings.width+outerContent.w.total,height:currentSettings.height+outerContent.h.total},wrapper:{width:currentSettings.width+outerContent.w.total+outerWrapper2.w.total,height:currentSettings.height+outerContent.h.total+outerWrapper2.h.total}};if(currentSettings.resizable){var maxHeight=modal.blockerVars?modal.blockerVars.height:$(window).height()-outerWrapper.h.border-(tmp.wrapper.height-currentSettings.height);var maxWidth=modal.blockerVars?modal.blockerVars.width:$(window).width()-outerWrapper.w.border-(tmp.wrapper.width-currentSettings.width);maxHeight-=currentSettings.padding*2;maxWidth-=currentSettings.padding*2;if(tmp.content.height>maxHeight||tmp.content.width>maxWidth){if(currentSettings.type=='image'||currentSettings.type=='swf'){var useW=currentSettings.imgWidth?currentSettings.imgWidth:currentSettings.width;var useH=currentSettings.imgHeight?currentSettings.imgHeight:currentSettings.height;var diffW=tmp.content.width-useW;var diffH=tmp.content.height-useH;if(diffH<0)diffH=0;if(diffW<0)diffW=0;var calcH=maxHeight-diffH;var calcW=maxWidth-diffW;var ratio=Math.min(calcH/useH,calcW/useW);calcW=Math.floor(useW*ratio);calcH=Math.floor(useH*ratio);tmp.content.height=calcH+diffH;tmp.content.width=calcW+diffW}else{tmp.content.height=Math.min(tmp.content.height,maxHeight);tmp.content.width=Math.min(tmp.content.width,maxWidth)}tmp.wrapper2={width:tmp.content.width+outerContent.w.total,height:tmp.content.height+outerContent.h.total};tmp.wrapper={width:tmp.content.width+outerContent.w.total+outerWrapper2.w.total,height:tmp.content.height+outerContent.h.total+outerWrapper2.h.total}}}if(currentSettings.type=='swf'){$('object, embed',modal.content).attr('width',tmp.content.width).attr('height',tmp.content.height)}else if(currentSettings.type=='image'){$('img',modal.content).css({width:tmp.content.width,height:tmp.content.height})}modal.content.css($.extend({},tmp.content,currentSettings.cssOpt.content));modal.wrapper.css($.extend({},tmp.wrapper2,currentSettings.cssOpt.wrapper2));if(!resizing)modal.contentWrapper.css($.extend({},tmp.wrapper,currentSettings.cssOpt.wrapper));if(currentSettings.type=='image'&&currentSettings.addImageDivTitle){$('img',modal.content).removeAttr('alt');var divTitle=$('div',modal.content);if(currentSettings.title!=currentSettings.defaultImgAlt&&currentSettings.title){if(divTitle.length==0){divTitle=$('<div>'+currentSettings.title+'</div>');modal.content.append(divTitle)}if(currentSettings.setWidthImgTitle){var outerDivTitle=getOuter(divTitle);divTitle.css({width:(tmp.content.width+outerContent.w.padding-outerDivTitle.w.total)+'px'})}}else if(divTitle.length=0){divTitle.remove()}}if(currentSettings.title)setTitle();tmp.wrapper.borderW=outerWrapper.w.border;tmp.wrapper.borderH=outerWrapper.h.border;setCurrentSettings(tmp.wrapper);setMargin()}function removeModal(e){debug('removeModal');if(e)e.preventDefault();if(modal.full&&modal.ready){$(document).unbind('keydown.nyroModal');if(!currentSettings.blocker)$(window).unbind('resize.nyroModal');modal.ready=false;modal.anim=true;modal.closing=true;if(modal.loadingShown||modal.transition){currentSettings.hideLoading(modal,currentSettings,function(){modal.loading.hide();modal.loadingShown=false;modal.transition=false;currentSettings.hideBackground(modal,currentSettings,endRemove)})}else{if(fixFF)modal.content.css({position:''});modal.wrapper.css({overflow:'hidden'});modal.content.css({overflow:'hidden'});$('iframe',modal.content).hide();if($.isFunction(currentSettings.beforeHideContent)){currentSettings.beforeHideContent(modal,currentSettings,function(){currentSettings.hideContent(modal,currentSettings,function(){endHideContent();currentSettings.hideBackground(modal,currentSettings,endRemove)})})}else{currentSettings.hideContent(modal,currentSettings,function(){endHideContent();currentSettings.hideBackground(modal,currentSettings,endRemove)})}}}if(e)return false}function showContentOrLoading(){debug('showContentOrLoading');if(modal.ready&&!modal.anim){if(modal.dataReady){if(modal.tmp.html()){modal.anim=true;if(modal.transition){fillContent();modal.animContent=true;currentSettings.hideTransition(modal,currentSettings,function(){modal.loading.hide();modal.transition=false;modal.loadingShown=false;endShowContent()})}else{currentSettings.hideLoading(modal,currentSettings,function(){modal.loading.hide();modal.loadingShown=false;fillContent();setMarginLoading();setMargin();modal.animContent=true;currentSettings.showContent(modal,currentSettings,endShowContent)})}}}else if(!modal.loadingShown&&!modal.transition){modal.anim=true;modal.loadingShown=true;if(modal.error)loadingError();else modal.loading.html(currentSettings.contentLoading);$(currentSettings.closeSelector,modal.loading).unbind('click.nyroModal').bind('click.nyroModal',removeModal);setMarginLoading();currentSettings.showLoading(modal,currentSettings,function(){modal.anim=false;showContentOrLoading()})}}}function ajaxLoaded(data){debug('AjaxLoaded: '+this.url);if(currentSettings.selector){var tmp={};var i=0;data=data.replace(/\r\n/gi,'nyroModalLN').replace(/<script(.|\s)*?\/script>/gi,function(x){tmp[i]=x;return'<pre style="display: none" class=nyroModalScript rel="'+(i++)+'"></pre>'});data=$('<div>'+data+'</div>').find(currentSettings.selector).html().replace(/<pre style="display: none;?" class="?nyroModalScript"? rel="(.?)"><\/pre>/gi,function(x,y,z){return tmp[y]}).replace(/nyroModalLN/gi,"\r\n")}modal.tmp.html(filterScripts(data));if(modal.tmp.html()){modal.dataReady=true;showContentOrLoading()}else loadingError()}function formDataLoaded(){debug('formDataLoaded');var jFrom=$(currentSettings.from);jFrom.attr('action',jFrom.attr('action')+currentSettings.selector);jFrom.attr('target','');$('input[name='+currentSettings.formIndicator+']',currentSettings.from).remove();var iframe=modal.tmp.children('iframe');var iframeContent=iframe.unbind('load').contents().find(currentSettings.selector||'body').not('script[src]');iframe.attr('src','about:blank');modal.tmp.html(iframeContent.html());if(modal.tmp.html()){modal.dataReady=true;showContentOrLoading()}else loadingError()}function iframeLoaded(){if((window.location.hostname&&currentSettings.url.indexOf(window.location.hostname)>-1)||currentSettings.url.indexOf('http://')){var iframe=$('iframe',modal.full).contents();var tmp={};if(currentSettings.titleFromIframe){tmp.title=iframe.find('title').text();if(!tmp.title){try{tmp.title=iframe.find('title').html()}catch(err){}}}var body=iframe.find('body');if(!currentSettings.height&&body.height())tmp.height=body.height();if(!currentSettings.width&&body.width())tmp.width=body.width();$.extend(initSettingsSize,tmp);$.nyroModalSettings(tmp)}}function galleryCounts(nb,total,elts,settings){if(total>1)settings.title+=(settings.title?' - ':'')+nb+'/'+total}function endHideContent(){debug('endHideContent');modal.anim=false;if(contentEltLast){contentEltLast.append(modal.content.contents());contentEltLast=null}else if(contentElt){contentElt.append(modal.content.contents());contentElt=null}modal.content.empty();gallery={};modal.contentWrapper.hide().children().remove().empty().attr('style','').hide();if(modal.closing||modal.transition)modal.contentWrapper.hide();modal.contentWrapper.css(currentSettings.cssOpt.wrapper).append(modal.content);showContentOrLoading()}function endRemove(){debug('endRemove');$(document).unbind('keydown',keyHandler);modal.anim=false;modal.full.remove();modal.full=null;if(isIE6){body.css({height:'',width:'',position:'',overflow:'',marginLeft:'',marginRight:''});$('html').css({overflow:''})}if($.isFunction(currentSettings.endRemove))currentSettings.endRemove(modal,currentSettings)}function endBackground(){debug('endBackground');modal.ready=true;modal.anim=false;showContentOrLoading()}function endShowContent(){debug('endShowContent');modal.anim=false;modal.animContent=false;modal.contentWrapper.css({opacity:''});fixFF=/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)&&parseFloat(browserVersion)<1.9&&currentSettings.type!='image';if(fixFF)modal.content.css({position:'fixed'});modal.content.append(modal.scriptsShown);if(currentSettings.type=='iframe')modal.content.find('iframe').attr('src',currentSettings.url);if($.isFunction(currentSettings.endShowContent))currentSettings.endShowContent(modal,currentSettings);if(shouldResize){shouldResize=false;$.nyroModalSettings({width:currentSettings.setWidth,height:currentSettings.setHeight});delete currentSettings['setWidth'];delete currentSettings['setHeight']}if(resized.width)setCurrentSettings({width:null});if(resized.height)setCurrentSettings({height:null})}function getHash(url){if(typeof url=='string'){var hashPos=url.indexOf('#');if(hashPos>-1)return url.substring(hashPos)}return''}function filterScripts(data){if(typeof data=='string')data=data.replace(/<\/?(html|head|body)([^>]*)>/gi,'');var tmp=new Array();$.each($.clean({0:data},this.ownerDocument),function(){if($.nodeName(this,"script")){if(!this.src||$(this).attr('rel')=='forceLoad'){if($(this).attr('rev')=='shown')modal.scriptsShown.push(this);else modal.scripts.push(this)}}else tmp.push(this)});return tmp}function getOuter(elm){elm=elm.get(0);var ret={h:{margin:getCurCSS(elm,'marginTop')+getCurCSS(elm,'marginBottom'),border:getCurCSS(elm,'borderTopWidth')+getCurCSS(elm,'borderBottomWidth'),padding:getCurCSS(elm,'paddingTop')+getCurCSS(elm,'paddingBottom')},w:{margin:getCurCSS(elm,'marginLeft')+getCurCSS(elm,'marginRight'),border:getCurCSS(elm,'borderLeftWidth')+getCurCSS(elm,'borderRightWidth'),padding:getCurCSS(elm,'paddingLeft')+getCurCSS(elm,'paddingRight')}};ret.h.outer=ret.h.margin+ret.h.border;ret.w.outer=ret.w.margin+ret.w.border;ret.h.inner=ret.h.padding+ret.h.border;ret.w.inner=ret.w.padding+ret.w.border;ret.h.total=ret.h.outer+ret.h.padding;ret.w.total=ret.w.outer+ret.w.padding;return ret}function getCurCSS(elm,name){var ret=parseInt($.curCSS(elm,name,true));if(isNaN(ret))ret=0;return ret}function debug(msg){if($.fn.nyroModal.settings.debug||currentSettings&&currentSettings.debug)nyroModalDebug(msg,modal,currentSettings||{})}function showBackground(elts,settings,callback){elts.bg.css({opacity:0}).fadeTo(500,0.75,callback)}function hideBackground(elts,settings,callback){elts.bg.fadeOut(300,callback)}function showLoading(elts,settings,callback){elts.loading.css({marginTop:settings.marginTopLoading+'px',marginLeft:settings.marginLeftLoading+'px',opacity:0}).show().animate({opacity:1},{complete:callback,duration:400})}function hideLoading(elts,settings,callback){callback()}function showContent(elts,settings,callback){elts.loading.css({marginTop:settings.marginTopLoading+'px',marginLeft:settings.marginLeftLoading+'px'}).show().animate({width:settings.width+'px',height:settings.height+'px',marginTop:settings.marginTop+'px',marginLeft:settings.marginLeft+'px'},{duration:350,complete:function(){elts.contentWrapper.css({width:settings.width+'px',height:settings.height+'px',marginTop:settings.marginTop+'px',marginLeft:settings.marginLeft+'px'}).show();elts.loading.fadeOut(200,callback)}})}function hideContent(elts,settings,callback){elts.contentWrapper.animate({height:'50px',width:'50px',marginTop:(-(25+settings.borderH)/2+settings.marginScrollTop)+'px',marginLeft:(-(25+settings.borderW)/2+settings.marginScrollLeft)+'px'},{duration:350,complete:function(){elts.contentWrapper.hide();callback()}})}function showTransition(elts,settings,callback){elts.loading.css({marginTop:elts.contentWrapper.css('marginTop'),marginLeft:elts.contentWrapper.css('marginLeft'),height:elts.contentWrapper.css('height'),width:elts.contentWrapper.css('width'),opacity:0}).show().fadeTo(400,1,function(){elts.contentWrapper.hide();callback()})}function hideTransition(elts,settings,callback){elts.contentWrapper.hide().css({width:settings.width+'px',height:settings.height+'px',marginLeft:settings.marginLeft+'px',marginTop:settings.marginTop+'px',opacity:1});elts.loading.animate({width:settings.width+'px',height:settings.height+'px',marginLeft:settings.marginLeft+'px',marginTop:settings.marginTop+'px'},{complete:function(){elts.contentWrapper.show();elts.loading.fadeOut(400,function(){elts.loading.hide();callback()})},duration:350})}function resize(elts,settings,callback){elts.contentWrapper.animate({width:settings.width+'px',height:settings.height+'px',marginLeft:settings.marginLeft+'px',marginTop:settings.marginTop+'px'},{complete:callback,duration:400})}function updateBgColor(elts,settings,callback){if(!$.fx.step.backgroundColor){elts.bg.css({backgroundColor:settings.bgColor});callback()}else elts.bg.animate({backgroundColor:settings.bgColor},{complete:callback,duration:400})}$($.fn.nyroModal.settings.openSelector).nyroModal()});var tmpDebug='';function nyroModalDebug(msg,elts,settings){if(elts.full&&elts.bg){elts.bg.prepend(msg+'<br />'+tmpDebug);tmpDebug=''}else tmpDebug+=msg+'<br />'};
jQuery(document).ready(function() {
	/**var minWidth = 1237;
	var ieWidthShift = (navigator.appVersion.indexOf('MSIE') > 0 && navigator.appVersion.match(/MSIE[\s]([\d])/i)[1] > 6) ? 10 : 20;
	var tWidth = jQuery(window).width() - ieWidthShift;

	if ('\v' == 'v' && jQuery('#top-banner-container').outerWidth() != null) {**/
		/** Min size of window **/
	/**if (tWidth < minWidth)
			tWidth = minWidth;
		
		jQuery('.categories-search-results').width(tWidth);
	}
	
	var ie67 = (navigator.appVersion.indexOf('MSIE') > 0 && navigator.appVersion.match(/MSIE[\s]([\d])/i)[1] < 8);
	var fShift = jQuery(window).height() - (jQuery('.region-page-top').outerHeight() + jQuery('#page-wrapper').outerHeight()) - (ie67 ? 25 : 30);
	if (fShift > 0)
		jQuery('#footer-wrapper').css('margin-top', fShift);**/
	
	
	var heightShift = 40;
	var tHeight = jQuery(window).height() - (jQuery('.region-page-top').outerHeight() + jQuery('#footer-wrapper').outerHeight()) - heightShift;
	jQuery('.section', '#header').height(tHeight);
});;
/*
 * jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */

;(function($) {
	
$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 20 : 150
		}, options);
		
		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };
		
		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;
		
		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8,
		RIGHT: 39
	};

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);
	
	var blockSubmit;
	
	// prevent form submit in opera when selecting with return key
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});
	
	// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// a keypress means the input has focus
		// avoids issue where input had focus before the autocomplete was applied
		hasFocus = 1;
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {
		
			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;
			
			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RIGHT:
				if( selectCurrent(false) ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = false;
					return false;
				}
				break;
			
			case KEY.RETURN:
				if( selectCurrent() ) {
					event.preventDefault();
				}
				break;
				
			case KEY.ESC:
				select.hide();
				break;
			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});
	
	
	function selectCurrent(isSubmit) {
		var selected = select.selected();
		if( !selected )
			return false;
		
		var v = selected.result;
		previousValue = v;
		
		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				var seperator = options.multipleSeparator.length;
				var cursorAt = $(input).selection().start;
				var wordAt, progress = 0;
				$.each(words, function(i, word) {
					progress += word.length;
					if (cursorAt <= progress) {
						wordAt = i;
						return false;
					}
					progress += seperator;
				});
				words[wordAt] = v;
				// TODO this should set the cursor to the right position, but it gets overriden somewhere
				//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
				v = words.join( options.multipleSeparator );
			}
			v += options.multipleSeparator;
		}
		
		/* --------------------- Changes for string id ---------------------[SD][Start] */
		matches = v.match('<span id=\'{0,1}\"{0,1}([0-9]+)\'{0,1}\"{0,1}>(.+?)<\/span>');
		try
		{
			if(matches[1] && matches[2])
			{
				id = matches[1];
				v = matches[2];
				if (typeof isSubmit == 'undefined' || (typeof isSubmit != 'undefined' && isSubmut == true)) {
					$.ajax({
						type: 'POST',
						url: options.stat_url,
						success:function(data)
						{ 
							window.location.replace(data);
							/**$input.parents('form:first').submit();**/
						},
						/**dataType: 'json',**/
						data: 'string_id=' + id //Pass a key/value pair
					});
				}
			}
		}
		catch(e){}

		jQuery('input[name="strings_search_rubric"]').val(matches[1]);
		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;				
		/* --------------------- Changes for string id ---------------------[SD][End] */
	}
	
	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}
		
		var currentValue = $input.val();
		
		if ( !skipPrevCheck && currentValue == previousValue )
			return;
		
		previousValue = currentValue;
		
		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			/**$input.addClass(options.loadingClass);**/
			clearSearchButtonHide(); /** Remove clear button **/
			
			$('.' + options.loadingDivClass).addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};
	
	function trimWords(value) {
		if (!value)
			return [""];
		if (!options.multiple)
			return [$.trim(value)];
		return $.map(value.split(options.multipleSeparator), function(word) {
			return $.trim(value).length ? $.trim(word) : null;
		});
	}
	
	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		if (words.length == 1) 
			return words[0];
		var cursorAt = $(input).selection().start;
		if (cursorAt == value.length) {
			words = trimWords(value)
		} else {
			words = trimWords(value.replace(value.substring(cursorAt), ""));
		}
		return words[words.length - 1];
	}
	
	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue)
	{
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE )
		{
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$(input).selection(previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else {
							$input.val( "" );
							$input.trigger("result", null);
						}
					}
				}
			);
		}
	};

	function receiveData(q, data)
	{
		if ( data && data.length && hasFocus )
		{
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data && data.length) {
			success(term, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			
			var extraParams = {
				timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});
			
			$.ajax({
				type: "POST",
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				data: $.extend({
					q: lastWord(term),
					limit: options.max
				}, extraParams),
				success: function(data) { 
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			failure(term);
		}
	};
	
	function parse(data)
	{
		var parsed = [];
		var rows = data.split("\n");
		
		for (var i=0; i < rows.length; i++)
		{
			var row = $.trim(rows[i]);
			if (row)
			{
				row = row.split("|");
				parsed[parsed.length] =
				{
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		/**$input.removeClass(options.loadingClass);**/
		$('.' + options.loadingDivClass).removeClass(options.loadingClass);
		checkClearSearchButton();
	};

	/** Clear input submit [OG][start] **/
	function checkClearSearchButton(event) {
		if (typeof event != 'undefined') {
			var keyInObject = false;
			for (var i in KEY) {
		        if ((event.keyCode != KEY.BACKSPACE && event.keyCode != KEY.DEL && event.keyCode == KEY[i]) || event.keyCode == 37) {
		        	keyInObject = true;
		        	break;
		        }
			}
			if (keyInObject == false)
				$('input[name="strings_search_rubric"]').val('');
		}
		if ($('#strings-search').val() != '') {
			$('.clear-input-container').show();
			$('.clear-input-container').click(function(){
				$('#strings-search').val('');
				$('#strings-search').focus().select();
				clearSearchButtonHide();
			});
		} else
			clearSearchButtonHide();
	}
	function clearSearchButtonHide() {
		$('.clear-input-container').hide();
	}
	checkClearSearchButton();
	$('#strings-search').keyup(function(event){checkClearSearchButton(event);});
	/** Clear input submit [OG][end] **/
};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	loadingDivClass: "auto-container",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: false,
	cacheLength: 10,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row){return row[0];},
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	highlight: function(value, term)
	{
		/* --------------------- Changes for string select ---------------------[SD][Start] */
		//return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)(.*)", "i"), "$1<strong>$2</strong>");
		/* --------------------- Changes for string select ---------------------[SD][End] */
	},
    scroll: true,
    scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;
	
	function matchSubset(s, sub) {
		if (!options.matchCase) 
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (options.matchContains == "word"){
			i = s.toLowerCase().search("\\b" + sub.toLowerCase());
		}
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};
	
	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){ 
			length++;
		}
		data[q] = value;
	}
	
	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;
		
		// track all options for minChars = 0
		stMatchSets[""] = [];
		
		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
			
			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;
				
			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] ) 
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};
			
			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}
	
	// populate any existing data
	setTimeout(populate, 25);
	
	function flush(){
		data = {};
		length = 0;
	}
	
	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/* 
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data )
				{
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}				
				return csub;
			} else 
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};
	
	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;
	
	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);
	
		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);            
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});
		
		if( options.width > 0 )
			element.css("width", options.width);
			
		needsInit = false;
	} 
	
	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};
	
	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}
	
	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}
	
	function fillList()
	{
		list.empty();
		var max = limitNumberOfItems(data.length);
		/* --------------------- Changes for string id ---------------------[SD][Start] */
		index = 0;
		var arr_strings_ids = new Array();
		for (var i=0; i < max; i++)
		{
			if ((i + 1 < max == false) && arr_strings_ids.length < 20 && max < data.length)
				max ++;
			
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			
			var re = new RegExp("(<span.*?)([0-9]+)(.*?>)(.+?)(<\/span>)", "i");
			matches = formatted.match(re);
			var string_id = matches[2] == null ? false : matches[2];
			
			if(string_id)
			{
				var tmp_term = String($.trim(term.toLowerCase()));
				var tmp_terms = tmp_term.split(" ");
				var terms = new Array();
				var tmp_index = 0;
				for(var k = 0; k < tmp_terms.length; k++)
				{
					if($.trim(tmp_terms[k]))
					{
						terms[tmp_index] = $.trim(tmp_terms[k]);
						tmp_index++;
					}
				}
				var search_term = terms.join(" ");
				
				var tmp_str = String(matches[4]);
				var tmp_words = tmp_str.split(" ");
				var words = new Array();
				var tmp_index = 0;
				for(var k = 0; k < tmp_words.length; k++)
				{
					if($.trim(tmp_words[k]))
					{
						words[tmp_index] = $.trim(tmp_words[k]);
						tmp_index++;
					}
				}
				var search_string = words.join(" ");
				
				if($.inArray( string_id, arr_strings_ids ) != -1)
					continue;
				else if(search_string.toLowerCase().search(search_term) == 0)
					arr_strings_ids[index] = string_id;
				else
					continue;
			}
			else
				continue;
			
			formatted = matches[1] + matches[2] + matches[3] + ucfirst(search_string) + matches[5];
			index++;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(index%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			/* --------------------- Changes for string id ---------------------[SD][End] */
			$.data(li, "ac_data", data[i]);
		}
		
		listItems = list.find("li");
		
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();

		/* --------------------- Changes for string id ---------------------[OG][start] */
		if (!listItems.length)
			setTimeout(function() {$('.ac_results').hide();}, 0.1)
		/* --------------------- Changes for string id ---------------------[OG][End] */
	}
	
	/* --------------------- Ucfirst javacsript function ---------------------[SD][start] */
	function ucfirst (str)
	{
	    // Makes a string's first character uppercase  
	    // 
	    // version: 1109.2015
	    // discuss at: http://phpjs.org/functions/ucfirst    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   bugfixed by: Onno Marsman
	    // +   improved by: Brett Zamir (http://brett-zamir.me)
	    // *     example 1: ucfirst('kevin van zonneveld');
	    // *     returns 1: 'Kevin van zonneveld'    str += '';
	    // var f = str.charAt(0).toUpperCase();
	    // return f + str.substr(1);
		return str;
	}
	/* --------------------- Ucfirst javacsript function ---------------------[SD][end] */

	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			/** Get input field width [OG] **/
			var iWidth = jQuery('input#strings-search').width() + 9;
			
			var offset = $(input).offset();
			element.css({
				width: iWidth, /** typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(), Remove option width [OG] **/
				top: offset.top + input.offsetHeight - 3,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});
				
                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }
                
            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.fn.selection = function(start, end) {
	if (start !== undefined) {
		return this.each(function() {
			if( this.createTextRange ){
				var selRange = this.createTextRange();
				if (end === undefined || start == end) {
					selRange.move("character", start);
					selRange.select();
				} else {
					selRange.collapse(true);
					selRange.moveStart("character", start);
					selRange.moveEnd("character", end);
					selRange.select();
				}
			} else if( this.setSelectionRange ){
				this.setSelectionRange(start, end);
			} else if( this.selectionStart ){
				this.selectionStart = start;
				this.selectionEnd = end;
			}
		});
	}
	var field = this[0];
	if ( field.createTextRange ) {
		var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
		range.text = teststring;
		var caretAt = field.value.indexOf(teststring);
		field.value = orig;
		this.selection(caretAt, caretAt + textLength);
		return {
			start: caretAt,
			end: caretAt + textLength
		}
	} else if( field.selectionStart !== undefined ){
		return {
			start: field.selectionStart,
			end: field.selectionEnd
		}
	}
};
})(jQuery);;

