;(function($) {
	var scope = $('body');
	function preLoad() {
		$.bindLoad('_preLoad', {}, scope);
		$.bindLoadAll();
	}
	function postLoad() {
		$.bindLoad('_postLoad', {}, scope);
	}
	function onLoad() {
		preLoad();
		postLoad();
	}
	$.ajaxSetup({
		error: function(xhr) {
			if (403 === xhr.status) {
				var req = this;
				$.one('user/login-success', function() { req.async = false; $.ajax(req); });
				$.bindLoad('user/login');
			}
		}});
	$.fn.coreLoad = $.fn.load;
	$.coreGet = $.get;
	$.fn.extend({
		load: function(path, data, callback) {
			scope = $(this);
			if ('undefined' === typeof data)
				return $.fn.coreLoad.apply(this, [path, onLoad]);
			if ('function' === typeof data)
				return $.fn.coreLoad.apply(this, [path, function() { preLoad(); data.apply(this, arguments); postLoad(); }]);
			if ('function' === typeof callback)
				return $.fn.coreLoad.apply(this, [path, data, function() { preLoad(); callback.apply(this, arguments); postLoad(); }]);
			return $.fn.coreLoad.apply(this, [path, data, onLoad]);
		}
	});
	$.extend({
		post: function(a, b, c) { $('#dummy').load(a, b, c); },
		get: function(a, b, c, d) { if (undefined !== d) return $.coreGet(a, b, c, d); $('#dummy').load(a, b, c); },
		bind: function(name, fn) { $('#dummy').bind('load.'+ name, fn); return this; },
		unbind: function(name) { $('#dummy').unbind('load.'+ name); return this; },
		one: function(name, fn) { $('#dummy').one('load.'+ name, fn); return this; },
		delegate: function(filter, name, fn) {
			$('#dummy').bind('load.'+ name, function(e) {
				for (f in filter)
					if (e.opt[f] !== filter[f])
						return;
				fn(e);
			});
			return this;
		},
		bindLoad: function(groups, opt, scope) {
			if (typeof groups == 'string') groups = groups.split(' ');
			$('#dev-toolbox ol.js').prepend('<li>'+ groups.join(', ') +'</li>');
			var e = jQuery.Event('load');
			e.scope = scope;
			e.opt = opt || {};
			for (var i in groups) {
				e.type = 'load.'+ groups[i];
				$('#dummy').trigger(e);
			}
			return false;
		},
		bindReplace: function(name, fn) {
			return $.unbind(name).bind(name, fn);
		},
		bindLoadAll: function() {
			var exit = false;
			$('kbd._bind').each(function() {
				var opt = $.parseJSON($(this).text()), title = $(this).attr('title');
				$(this).remove();
				switch (title) {
				case 'add':
					$.jsAdd(opt.src, opt.waitFor, $.bindLoadAll);
					exit = 1;
					break;
				}
				if (exit) return false;
			});
			if (exit) return;
			$('kbd').each(function() {
				/* .html() returns &quote; instead of " in Opera */
				var scope, opt = $.parseJSON($(this).text());
				switch ($(this).attr('title')) {
				case 'prev': scope = $(this).prev(':not(kbd)'); break;
				case 'next': scope = $(this).next(':not(kbd)'); break;
				case 'parent': scope = $(this).parent(); break;
				case 'grandparent': scope = $(this).parent().parent(); break;
				}
				$.bindLoad($(this).attr('class'), opt, scope);
				$(this).remove();
			});
			if (undefined === Bind) return;
			var e;
			while (e = Bind.queue.pop()) {
				$.bindLoad(e.group, e.data);
			}
			$.title();
		}
	});
	$(function() { onLoad(); });
})(jQuery);

/*
 * 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 ? 10 : 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
	};

	// 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.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				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() {
		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;
				words[words.length - 1] = 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;
		}
		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}
	
	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}
		
		var currentValue = $input.val();
		
		if ( !skipPrevCheck && currentValue == previousValue )
			return;
		
		previousValue = currentValue;
		
		var currentWord = lastWord(currentValue);
		if ( currentWord.length >= options.minChars) {
			$input.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({
				// 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: 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);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	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) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    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;
				
			if ( value != null )	
			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);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.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();
	}
	
	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() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				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);
$(function() {
	$('body').delegate('[href="#close"]', 'click', function(e) {
		$(e.target).parents('.closeable').first().remove();
		return false;
	});
});
/**
 * Timer, który okresla, czy doszło do onChange
 */
var timer = null;
/**
 * Czy wykonać onChange
 */
var doChange = false;

/**
 * Zmiana eventu onKeyPress na onChange - z pewnym, zadanym opóźnieniem.
 * Event onChange należy ubsłużyć tylko wtedy, gdy doChange jest TRUE
 */
$(function() {
	$(document).bind('keypress', function(e) {
		if(timer)
			clearTimeout(timer);
		timer = setTimeout(
			function() {
				doChange = true;
				$(e.target).trigger('change');
			}, 750);		// opóźnienie
	});
});

function _(str) { return str; }

function url(url, data, escape) {
	if (url.charAt(url.length-1) !== '?')
		url += (-1 === url.indexOf('?'))? '?' : '&';
	if ('?' === url.substr(0, 1)) {}
	else if ('http' === url.substr(0, 4)) {}
	else url = ROOT +'s/' + url;
	return url + $.stringify(data, true);
}

function notify(msg, param) {
	if ('string' === typeof param) param = {type: param};
	param = $.extend({
		type: 'info',
		header: '',
		sticky: param.sticky==undefined?false:param.type.sticky,
		glue: 'after',
		life: 4000}, param);
	var div = '<div class="flashMessage '+ param.type +'">'
		+'<div class="close">x</div>'
		+'<h4>'+ param.header +'</h4>'
		+'<div class="message">'+ msg +'</div>'
	+'</div>';
	var o;
	if ('after' === param.glue)
		o = $(div).appendTo('#flashMessageContainer');
	else if ('before' === param.glue)
		o = $(div).prependTo('#flashMessageContainer');
	else return;
	o
	.find('.close').bind('click', function() { $(this).parent().slideUp('fast', function() { $(this).remove(); }); return false; }).end()
	.hide().fadeIn('slow')
	.bind('mouseenter', function() { clearTimeout($(this).stop(true, false).data('timer')); $(this).fadeTo('fast', 100); })
	.bind('mouseleave', function() {
		var o = $(this);
		if (!param.sticky)
			o.data('timer', setTimeout(function() {
				o.fadeOut('slow', function() { o.remove(); });
			}, param.life));
	}).trigger('mouseleave');
}
$.bind('notify', function(e) { notify(e.opt.msg, e.opt.param); });

String.prototype.htmlentities = function() {
	return this.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function redirect(u, p) {
	if (!u) return window.location.reload();
	window.location.replace(url(u, p));
}
$.bind('redirect', function(e) { redirect(e.opt.url); });
//przy loadowaniu w tablicy parametrów trzeba podać 'className' => nazwa aby zamknąć dialog o id "nazwa"
$.bind('closeDialog', function (e) {
        $('.' + e.opt.className).dialog('close');
});
$.bind('facebookConnect', function(ev) {
	if (!ev.opt.appId) return;
	opt = {
		ifUserConnected: null,
		ifUserNotConnected: null,
		reloadIfSessionStateChanged: true};
	window.fbAsyncInit = function() {
		FB.init({
			appId  : ev.opt.appId,
			status : true, // check login status
			cookie : true, // enable cookies to allow the server to access the session
			xfbml  : true  // parse XFBML
		});
		FB.getLoginStatus(function(response) {
			if (response.session) {
				$.bindLoad(ev.opt.onSuccess);
			} else {
				$.bindLoad(ev.opt.onError);
			}
		});
		// \fixme
		// if (ev.opt.require) FB.Connect.requireSession();
	};
	var s = document.createElement('script');
	s.src = ev.opt.jsLib;
	s.async = true;
	document.getElementById('fb-root').appendChild(s);
});
$.bind('facebookLogout', function(e) {
	FB_RequireFeatures(["Connect", "CanvasUtil"], function() {
		FB.init(e.opt.apiKey, ROOT + 'xd_receiver.htm');
        FB.Connect.requireSession();
        FB.XdComm.Server.init(ROOT + 'xd_receiver.htm');
        FB.Connect.logoutAndRedirect(ROOT);
   });
});
$.bind('facebook/select/enable', function(e) {
	$.one(e.opt.enable, function() {
		e.scope.load(url('/user/select/facebook'));
	});
});
$.bind('facebook/share', function() {
	/* \todo */
	$('#facebookShare').unbind('click').bind('click', function() {
		FB.ui({method: 'stream.publish', message: $('.publish textarea').val()});
		return false;
	});
});
$.bind('facebook/share/simple', function(e) {
	/* \todo */
	e.scope.bind('click', function() {
		FB.ui({
			api_key: e.opt.api_key,
			method: 'stream.publish',
			attachment: e.opt.attachment,
			action_links: e.opt.action_links}, function(response) {
			if (response && response.post_id) {
				alert('Wiadomość została opublikowana.');
			} else {
				alert('Wiadomość nie została opublikowana.');
			}
		});
		return false;
	});
});
$.bind('focus', function(e) {
	e.scope.find('input,textarea').eq(0).focus();
});
$.bind('form/FieldCity', function(e) {
	e.scope.find('input').autocomplete(e.scope.find('span').html().split(';'), {
		'autoFill': true,
		'mustMatch': false});
});
$.bind('form/FieldMultiText', function(e) {
	e.scope
	// toggle pustych elementow formularza FieldMultiText
	.bind('click', function() {
		$(this).parent().parent().find('li.hide').toggle();
		return false;
	})
	;
});
$.bind('form/FieldUser', function(e) {
	var dialog;
	var list = {
		length: 0,
		items: {},
		push: function(k, v) {
			this.pull(k);
			this.items[k] = v;
			++this.length;
		},
		pull: function(k) {
			if (undefined === this.items[k]) return false;
			delete this.items[k];
			--this.length;
			return true;
		},
		keys: function() {
			var w = new Array(0);
			for (k in this.items)
				w.push(k);
			return w;
		},
		clear: function() { this.length = 0; this.items = {}; },
		load: function(items) { this.items = items; this.length = this.keys().length; }}, max = e.opt.max;
	function save() {
		e.scope.find('ol').html('');
		for (id in list.items) {
			e.scope.find('ol').append('<li />').find('li:last-child')
			.append('<a href="#rm" alt="'+ id +'">'+ list.items[id].name +'</a>')
			.append('<input type="hidden" name="'+ e.opt.fieldName +'[]" value="'+ id +'" />')
			.find('a[href="#rm"]').bind('click', function() {
				id = $(this).attr('alt');
				list.pull(id);
				$(this).parent().remove();
				return false;
			});
		}
		close();
	}
	function close() {
		if (dialog) {
			dialog.remove();
			dialog = null;
		}
	}

	list.load(e.opt.items);
	save();
	e.scope
	.find('a#addUser').bind('click', function() {
		if (1 === max) list.clear();
		dialog = $.dialog({
			url: url('/form/FieldUser', {formKey: e.opt.formKey, key: e.opt.key}),
			onLoad: function() {
				dialog
				.find('a#closeUser').bind('click', save).end()
				.find('a[href="#friend"]').bind('click', function() {
					dialog
					.find('.showFriends').show().end()
					.find('.showAll').hide().end()
					;
					return false;
				}).end()
				.find('a[href="#all"]').bind('click', function() {
					dialog
					.find('.showFriends').hide().end()
					.find('.showAll').show().end()
					;
					return false;
				}).end()
				;
			},

			draggable: false,
			modal: true,
			resizable: false,
			title: _('Wybierz użytkowników'),
			close: function() { close(); }});
	});
	$.bind('form/FieldUser-select', function(e) {
		e.scope
		.find('tr').bind('click', function() {
			var id = $(this).find('input').attr('value');
			$(this).val([id]);
			list.pull(id);
			if (!$(this).find('input:checked').length) return;
			if (list.length >= max) {
				notify(_('wybrano juz maksymalna liczbe uzytkownikow!'), 'error');
				return false;
			}
			list.push($(this).find('input').attr('value'), {
				name: $(this).find('td:first-child').html()});
			if (max < 2) save();
		}).end()
		.find('input[type="checkbox"]').val(list.keys()).end()
		;
	});
});
$.bind('form/File', function(e) {
	var upidActive;
	var count = 0;
	function update(cnt) {
		count += cnt;
		var input = e.scope.find('input[type="file"]');
		var lab	=	e.scope.find('input[type="file"]').closest('label');
		var placeholder = e.scope.find('li.placeholder');
		if (count >= e.opt.max) {
			input.hide();
			lab.hide();
		}
		else {
			input.show();
			lab.show();
		}
		if (count > 0)
			placeholder.hide();
		else
			placeholder.show();
	}
	e.scope.find('ol').bind('click', function(f) {
		if ('#cancel' !== $(f.target).attr('href')) return;
		update(-1);
		var li = $(f.target.parentNode);
		var upid = li.attr('alt');
		if (li.hasClass('done')) {
			$.bindLoad('rm', {_name: e.opt.name, item: li.data('item'), f: f}, e.scope);
		}
		li.remove();
		if (upidActive === upid) {
			formAbort.find('input[name="upid"]').val(upidActive);
			formAbort.submit();
		} else {
			$('form.upload[alt="'+ upid +'"]').remove();
		}
		return false;
	});

	var formTemplate = $('<form class="upload" enctype="multipart/form-data" method="post" target="upload" />');
	formTemplate.attr('action', url('/form/File/upload', {
		formKey: e.opt.formKey,
		key: e.opt.key,
		'noBack': '1'
	}));
	formTemplate.css('display', 'none');
	formTemplate.append('<input type="hidden" name="MAX_FILE_SIZE" />');

	var formAbort = $('form.abort');
	if (!formAbort.length) formAbort = $('body')
		.append('<form class="abort" method="post" target="upload" action="'+ url('/form/File/abort') +'"><input type="hidden" name="upid" /></form>')
		.find('form.abort')
	;

	var size = e.scope.parents('form').find('input[name="MAX_FILE_SIZE"]');
	if (!size.length) size = e.scope.parents('form')
		.append('<input type="hidden" name="MAX_FILE_SIZE" />')
		.find('input[name="MAX_FILE_SIZE"]')
	;

	var frame = $('iframe.upload');
	if (!frame.length) frame = $('body')
		.append('<iframe class="upload" style="display:none" name="upload" />')
		.find('iframe.upload')
	;

	function start() {
		if (upidActive) return;
		var form = $('form.upload').eq(0);
		if (!form.length) return;
		upidActive = form.data('upid');
		var li = $('#upload_'+ upidActive);

		if(form.attr('action').indexOf('X-Progress-ID') == -1)
			form.attr('action', form.attr('action') + '&X-Progress-ID=' + upidActive );
		form.submit();

		function progress(data) {
			//if nginx (http://wiki.nginx.org/NginxHttpUploadProgressModule#report_uploads)
			if(data.state) {
				switch(data.state) {
					case('starting'):
						data = {error:6, done:0, handler:'nginx'};
						break;
					case('error'):
						data = {error:data.status, done:0, handler:'nginx'};
							switch(data.error) {
								case 413:
									data.msg = _('Przekroczono dopuszczalny rozmiar pliku');
								case 500:
									alert('500');
									return;
								default:
									data.msg = _('Wystąpił błąd podczas wysyłania pliku. Kod błędu: ') + ' ('  + data.error +  ')';
							}
						break;

					case('done'):
						data = {error:1, done:100, handler:'nginx'};
						$.ajax({
							url: url('/form/File/preview', {"X-Progress-ID": upidActive, upid: upidActive, c: e.opt.c, 'noBack': '1'}),
							cache: false, 
							dataType: 'json',
							success: progress,
							error: end});
						break;
					case('uploading'):
						data = {error:0, done: Math.floor(100 * data.received / data.size), handler:'nginx'};
						break;

				}
			}
			//endif nginx
			li.find('.progress .done').css('width', data.done +'%');
			if (data.error)
				end(data);
			else setTimeout(function() {
				$.ajax({
					url: url('/form/File/progress', {"X-Progress-ID": upidActive, upid: upidActive, c: e.opt.c, 'noBack': '1'}),
					cache: false,
					dataType: 'json',
					success: progress,
					error: end});
			}, e.opt.poll);
		}
		progress({done: 0});
		form.remove();
	}
	function end(data) {
		if (data && data.msg) {
			var li = $('#upload_'+ upidActive);
			notify(data.msg, data.done >= 100? 'notify' : 'error');
			if (data.done >= 100) {
				done(data.item, li);
				$.bindLoad('done', {_name: e.opt.name, item: data.item}, e.scope);
			} else li.find('[href="#cancel"]').trigger('click');
		}

		if(data.handler!='nginx') {
			upidActive = null;
			start();
		} else {
			if(data.preview)
				upidActive = null;
		}
	}
	function add(item) {
		update(1);
		var li = e.scope.find('ol')
			.append('<li><div class="item">'+ item.name +'<div class="progress"><div class="done" /></div></div> <a href="#cancel">' +_('Cofnij')+ '</a> <a class="confirmPicUpload" href="#" onclick="$(\'#uploadForm\').submit(); return false;">' + _('Zapisz') + '</a></li>')
			.find('li:last-child')
		;
		if (item.upid)
			li.attr('alt', item.upid).attr('id', 'upload_'+ item.upid);
		else
			done(item, li);
	}
	function done(item, li) {
		li
			.data('item', item)
			.addClass('done')
			.append('<input type="hidden" name="'+ e.opt.name +'[]" value="'+ item._id +'" />')
		;
		li.find('.item').replaceWith(item.preview);
		e.scope.find('input[type="file"]').trigger('done');
	}
	for (id in e.opt.items)
		add(e.opt.items[id]);

	e.scope.find('input[type="file"]')
	.bind('mousedown', function() { size.val(e.opt.size); })
	.bind('change', function(f) {
		var upid = String(Math.floor(1e8 * Math.random()));
		var form = formTemplate.clone().appendTo('body');
		form.attr('alt', upid);
		form.find('input[name="MAX_FILE_SIZE"]').val(e.opt.size);
		form.append('<input type="hidden" name="APC_UPLOAD_PROGRESS" value="'+ upid +'" />');
		// np chrome przy clone() nie klonuje wybranej wartosci, wiec zabieramy oryginalny element, a zostawiamy klon
		$(this).after($(this).clone(true).val(null));
		form.append($(this).attr('name', 'file').unbind());
		add({upid: upid, name: $(this).val()});
		form.data('upid', upid);

		start();
	});
});
$.bind('form/TinyMce', function(e) {
	e.scope.tinymce({
			// Location of TinyMCE script
			script_url : ROOT + 'tiny_mce/tiny_mce.js',

			// General options
			theme : "simple",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			//content_css : "css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js"

			// Replace values for the template plugin
			//template_replace_values : {
			//	username : "Some User",
			//	staffid : "991234"
			//}
		});
});
$.bind('form/field/acuracy', function(e) {
	e.scope
		.data('accuracy', e.opt)
	;
});
$.bind('form/dateHourParams', function(e) {
	$('input#allDay').bind('click', function(){
		var t = $('span.time');
		if($(this).attr('checked')) {
			t.css('visibility', 'hidden');
			$(this).val(true);
			$(this).checked = true;
		} else {
			t.css('visibility', 'visible');
			$(this).val(false);
			$(this).checked = false;
		}
	})
});

function checkTime(){
	var dt = new Date();
	var d1 = $('#datehour_1_date');
	var d2 = $('#datehour_2_date');
	var t1o = $('#datehour_1_time option');
	var t2o = $('#datehour_2_time option');
	var t2s = $('#datehour_2_time :selected');

	var day = dt.getDate();
	if (day < 10) day = '0'+day;
	var month = dt.getMonth()+1;
	if (month < 10) month = '0'+month;

	var now = day+'.'+month+'.'+dt.getFullYear();

	var now_h = dt.getHours();
	var now_m = dt.getMinutes();
	var v = parseInt(now_h*100+parseInt(now_m/15)*15);

	if (d1.val() == now) {
		t1o.each(function(index, val){
			var t = $(this);
			if (parseInt(t.val()) < v) t.attr('disabled', true);
			else {
				t.removeAttr('disabled');
			}
		});
		var t1s = $('#datehour_1_time :selected');
		if (d2.val() == now) {
			t2o.each(function(index, val){
				var t = $(this);
				if(parseInt(t.val()) < parseInt(t1s.val())) t.attr('disabled', true);
				else {
					t.removeAttr('disabled');
				}
			});
		} else {
			t2o.each(function(index, val){
				$(this).removeAttr('disabled');
			});
		}
	} else {
		t1o.each(function(index, val){
			var t = $(this);
			t.removeAttr('disabled');
		});
		if (d2.val() == d1.val()) {
			t1s = $('#datehour_1_time :selected');
			t2o.each(function(index, val){
				var t = $(this);
				if(parseInt(t.val()) < parseInt(t1s.val())) t.attr('disabled', true);
				else {
					t.removeAttr('disabled');
				}
			});
		} else {
			t2o.each(function(index, val){
				$(this).removeAttr('disabled');
			});
		}
	}

	t1s = $('#datehour_1_time :selected');
	t2s = $('#datehour_2_time :selected');
	var s = false;
	if (t1s.attr('disabled')) {
		t1o.each(function(index, val){
			if (!$(this).attr('disabled') && s == false){
				$(this).attr('selected', true);
				s = true;
			}
		});
	}
	s = false;
	if (t2s.attr('disabled')) {
		t2o.each(function(index, val){
			if (!$(this).attr('disabled') && s == false){
				$(this).attr('selected', true);
				s = true;
			}
		});
	}
}

$.bind('form/datehourpicker', function(e) {
	var dt = new Date();	
	var options = {
		dateFormat: 'dd.mm.yy',
		altFormat: 'yy-mm-dd',
		altField: '#'+ e.opt.id,
		changeMonth: true,
		changeYear: true,
		onClose: function(sel) {
				checkTime();
		}
	};
	if (e.opt.params.type == 'constraint') {
		if (e.opt.params.today !== undefined) {
			options.minDate = dt;
		}
		if (e.opt.params.dateGT !== undefined) {
			options.onSelect = function(dateText, inst) {
				id = '#' + e.opt.params.dateGT;
				var myDate = new Date(e.scope.datepicker('getDate'));
				myDate.setDate(myDate.getDate());
				var endDate = new Date(e.scope.datepicker('getDate'));
				endDate.setMonth(myDate.getMonth()+1);
				$(id).datepicker('option', 'minDate', myDate);
				$(id).datepicker('option', 'maxDate', endDate);
				$(id).datepicker('option', 'onSelect', function() {
					if ($(id).datepicker('getDate').getTime() <= new Date(e.scope.datepicker('getDate')).getTime() && !$.browser.msie) {
						var newDate = e.scope.datepicker('getDate');
						newDate.setDate(newDate.getDate());
						$(id).datepicker('setDate', newDate);
					}
				});
			};
		}
	}
	if (undefined !== e.opt.min) {
		var min = 1000 * e.opt.min;
		if ('object' === typeof options.minDate)
			min = Math.max(min, options.minDate.getTime());
		options.minDate = new Date(min);
	}

	if (undefined !== e.opt.max) {
		options.maxDate = e.opt.max;
	}

	options.showOn = 'button';
	options.buttonImage = '/images/calendar-icon-big.png';
	options.buttonImageOnly = true;

	e.scope.datepicker(options);
});

$.bind('form/datehourpicker-time', function(){
	$('#datehour_1_time, #datehour_2_time').bind('change', checkTime);
});$.bind('form/datepicker', function(e) {
	var dt = new Date();

	var options = {
		dateFormat: 'd.m.yy',
		altFormat: 'yy-mm-dd',
		altField: '#'+ e.opt.id,
		changeMonth: true};

	if (e.opt.params.type == 'nameday') {
		options.minDate = new Date(dt.getFullYear(), 0, 1);
		options.maxDate = new Date(dt.getFullYear(), 11, 31);
	} else if (e.opt.params.type == 'birthday') {
		var yearEnd = dt.getFullYear() - 1;
		var yearStart = dt.getFullYear() - 100;
		options.changeYear = true;
		options.yearRange = (yearStart + ':' + yearEnd);
	} else if (e.opt.params.type == 'constraint') {
		if (e.opt.params.today !== undefined) {
			options.minDate = dt;
		}
		if (e.opt.params.dateGT !== undefined) {
			options.onSelect = function(dateText, inst) {
				id = '#' + e.opt.params.dateGT;
				var myDate = new Date(e.scope.datepicker('getDate'));
				myDate.setDate(myDate.getDate()+1);
				$(id).datepicker('option', 'minDate', myDate);

				$(id).datepicker('enable');
				$(id).datepicker('option', 'onSelect', function() {
					if ($(id).datepicker('getDate').getTime() <= new Date(e.scope.datepicker('getDate') + 1).getTime() && !$.browser.msie) {
						var newDate = e.scope.datepicker('getDate');
						newDate.setDate(newDate.getDate() + 1);
						$(id).datepicker('setDate', newDate);
					}
				});
			};
		}
	} else {
		var yearEnd = dt.getFullYear();
		var yearStart = dt.getFullYear() - 100;
		options.changeYear = true;
		options.yearRange = (yearStart + ':' + yearEnd);
	}

	e.scope.datepicker(options);
	if (e.opt.params.dateGTReverse !== undefined)
		e.scope.datepicker("disable");
});
/**
 * Zmienna zawierająca dane o wszystkich wartościach formularzy
 */
var form = Array();
var uniqueFields = Array();

/**
 * event tylko _pierwszego_ zaladowania formularza
 */
$.bind('form', function(e) {
	form[e.opt.name] = e.opt;
	function formDisable() { e.scope.attr('disabled', 'disabled'); }
	function formEnable() { e.scope.removeAttr('disabled'); }
	function load(url, post) {
		if (undefined === post)
			post = {};
		var target;
		formDisable();
		switch (e.opt.renderTarget) {
		case '%form': target = e.scope; break;
		case '%parent': target = e.scope.parent(); break;
		}
		if (target) {
			return $.post(url, post, function(data) {
				target.replaceWith(data);
				$.bindLoadAll();
				formEnable();
			}, 'html');
		}
		var target = e.opt.renderTarget
			? $(e.opt.renderTarget)
			: e.scope.find('fieldset');
		if (target.size() == 0) {
			target = e.scope.find('fieldset');
		}
		target.load(url, post, function() { formEnable(); });
	}
	e.scope
	/**
	 * Walidacja formularza po stronie js
	 */
	.delegate('li.field', 'change', function(f) {
		var submit = e.scope.find('input[type="submit"]');
		var changed = $(this).hasClass('changed');
		if (!changed)
			$(this).addClass('changed');
		if (!$(this).validate({ignoreEmpty: !changed})) {
			f.stopImmediatePropagation();
			submit.attr('disabled', 'disabled');
			return false;
		}
		// to pole jest poprawne, ale konieczne jest jeszcze sprawdzenie pozostalych
		if (e.scope.validated())
			submit.removeAttr('disabled');
	})
	.bind('submit', function(f) {
		if (!$(this).validate()) {
			f.stopImmediatePropagation();
			return false;
		}

		if ($(this).hasClass('ajaxCustom') || !$(this).hasClass('ajax')) return;

		$(this).find('input[type="submit"],input[type="image"]').attr('disabled', 'disabled');
		$(this).find('ol').first().append('<li class="wait">' + _('Trwa wysyłanie') + '</li>');
		if (!$(this).hasClass('noViewStyle'))
			$(this).addClass('view').removeClass('edit');
		load(url(e.scope.attr('action'), {key: e.opt.key}), $(this).serializeArray());

		return false;
	})
	/**
	 * Toggle formularzy, ktróe są w trybie view/edit (zmiana na widok edit)
	 */
	.delegate('.toEdit', 'click', function(f) {
		load(url('/form', {style: 'edit', key: e.opt.key}));
		$(this).parent().parent().addClass('edit').removeClass('view');
		return false;
	});
});

$.bind('form/fieldEnable', function(e) {
	$.bind(e.opt.event, function() {
		e.scope.find('input:disabled').removeAttr('disabled');
	});
});

$.bind('form/fieldUnique', function(e) {
	uniqueFields[e.opt.name] = e.opt.data;
});

$.bind('form/field/range', function(e) {
	e.scope
		.addClass('valid').addClass('range')
		.data('min', undefined === e.opt.min? Number.NEGATIVE_INFINITY : e.opt.min)
		.data('max', undefined === e.opt.max? Number.POSITIVE_INFINITY : e.opt.max)
	;
});
(function($){

	$.fn.alphanumeric = function(p) { 

		p = $.extend({
			ichars: "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- _",
			nchars: "",
			allow: ""
		  }, p);	

		return this.each
			(
				function() 
				{

					if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
					if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";
					
					s = p.allow.split('');
					for ( i=0;i<s.length;i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
					p.allow = s.join('|');
					
					var reg = new RegExp(p.allow,'gi');
					var ch = p.ichars + p.nchars;
					ch = ch.replace(reg,'');

					$(this).keypress
						(
							function (e)
								{
								
									if (!e.charCode) k = String.fromCharCode(e.which);
										else k = String.fromCharCode(e.charCode);
										
									if (ch.indexOf(k) != -1) e.preventDefault();
									if (e.ctrlKey&&k=='v') e.preventDefault();
									
								}
								
						);
						
					$(this).bind('contextmenu',function () {return false});
									
				}
			);

	};

	$.fn.numeric = function(p) {
	
		var az = "abcdefghijklmnopqrstuvwxyz";
		az += az.toUpperCase();

		p = $.extend({
			nchars: az
		  }, p);	
		  	
		return this.each (function()
			{
				$(this).alphanumeric(p);
			}
		);
			
	};
	
	$.fn.alpha = function(p) {

		var nm = "1234567890";

		p = $.extend({
			nchars: nm
		  }, p);	

		return this.each (function()
			{
				$(this).alphanumeric(p);
			}
		);
			
	};	

})(jQuery);
;(function($) {
	if (!$.support.hrefNormalized) {
		$.fn.coreAttr = $.fn.attr;
		$.fn.extend({
			attr: function(name, val) {
				if (undefined !== val) return $.fn.coreAttr.apply(this, [name, val]);
				var href = $.fn.coreAttr.apply(this, [name]);
				if (name !== 'href') 
					return href;
				if (undefined === href)
					return href;
				var hrefArr = href.split('#');
				if(undefined === hrefArr || hrefArr.length < 2) return href;
				return '#' + hrefArr[hrefArr.length-1];
			}
		})
	}
})(jQuery);;(function($) {
	$.fn.extend({
		checked: function() {
			return !!$(this).filter(':checked').length;
		},
		toggleCheckboxes: function(filter) {
			if (!filter) filter = '*';
			var all = $(this).find('input[type="checkbox"]').filter(filter);
			var checked = all.filter(':checked');
			var unchecked = all.not(':checked');
			checked.attr('checked', false);
			unchecked.attr('checked', 'checked');
		}});
})(jQuery);
;(function($) {
	$.extend({
		dialog: function(opt) {
			opt = $.extend({
				minWidth: 80,
				minHeight: 80,
				draggable: true,
				modal: true,
				resizable: false}, opt);
			$('body').append('<div />');
			var div = $('body > :last-child'), onLoad = opt.onLoad;
			opt.onLoad = function() {
				div.dialog('option', 'position', div.dialog('option', 'position'));
				if (onLoad)
					onLoad.apply(this, arguments)};
			if (undefined === opt.data) {
				opt.data = opt.onLoad;
				delete opt['onLoad'];
			}
			if (opt.url) div.load(opt.url, opt.data, opt.onLoad);
			div.dialog(opt);
			return div;
		}});
})(jQuery);
;(function($) {
	function flatten(target, obj, prefix) {
		for (var i in obj) {
			var buf = prefix +'['+ i +']';
			if ('object' === typeof obj[i]) flatten(target, obj[i], buf);
				else target[buf] = obj[i];
		}
	}
	$.extend({
		/// zagniezdzone obiekty zamienia w 1 obiekt
		flatten: function(obj) {
			for (var i in obj) {
				if ('object' === typeof obj[i]) {
					flatten(obj, obj[i], i);
					delete obj[i];
				}
			}
			return obj;
		},
		flattenArray: function(items) {
			/// \bug jezeli name=costam[], kolejne nadpisuja
			var w = {};
			for (var i = items.length - 1; i >= 0; --i)
				w[items[i].name] = items[i].value;
			return w;
		}});
})(jQuery);
;(function($) {
	$.extend({
		jsAdd: function(src, obj, callback) {
			if (undefined === callback) callback = function() { };
			if (!obj || (undefined === window[obj]))
				$('body').append('<script type="text/javascript" src="'+ src +'"></sript>');
			function wait() {
				if (undefined === window[obj]) {
					setTimeout(wait, 250);
				} else callback();
			}
			if (obj) wait();
				else callback();
		}});
})(jQuery);
	
	/**
	 * jQuery MD5 hash algorithm function
	 * 
	 * 	<code>
	 * 		Calculate the md5 hash of a String 
	 * 		String $.md5 ( String str )
	 * 	</code>
	 * 
	 * Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. 
	 * MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of data. The generated hash is also non-reversable. Data cannot be retrieved from the message digest, the digest uniquely identifies the data.
	 * MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1.
	 * This script is used to process a variable length message into a fixed-length output of 128 bits using the MD5 algorithm. It is fully compatible with UTF-8 encoding. It is very useful when u want to transfer encrypted passwords over the internet. If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). 
	 * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin.
	 * 
	 * Example
	 * 	Code
	 * 		<code>
	 * 			$.md5("I'm Persian."); 
	 * 		</code>
	 * 	Result
	 * 		<code>
	 * 			"b8c901d0f02223f9761016cfff9d68df"
	 * 		</code>
	 * 
	 * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
	 * @link http://www.semnanweb.com/jquery-plugin/md5.html
	 * @see http://www.webtoolkit.info/
	 * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
	 * @param {jQuery} {md5:function(string))
	 * @return string
	 */
	
	(function($){
		
		var rotateLeft = function(lValue, iShiftBits) {
			return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
		}
		
		var addUnsigned = function(lX, lY) {
			var lX4, lY4, lX8, lY8, lResult;
			lX8 = (lX & 0x80000000);
			lY8 = (lY & 0x80000000);
			lX4 = (lX & 0x40000000);
			lY4 = (lY & 0x40000000);
			lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
			if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
			if (lX4 | lY4) {
				if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
				else return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
			} else {
				return (lResult ^ lX8 ^ lY8);
			}
		}
		
		var F = function(x, y, z) {
			return (x & y) | ((~ x) & z);
		}
		
		var G = function(x, y, z) {
			return (x & z) | (y & (~ z));
		}
		
		var H = function(x, y, z) {
			return (x ^ y ^ z);
		}
		
		var I = function(x, y, z) {
			return (y ^ (x | (~ z)));
		}
		
		var FF = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};
		
		var GG = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};
		
		var HH = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};
		
		var II = function(a, b, c, d, x, s, ac) {
			a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
			return addUnsigned(rotateLeft(a, s), b);
		};
		
		var convertToWordArray = function(string) {
			var lWordCount;
			var lMessageLength = string.length;
			var lNumberOfWordsTempOne = lMessageLength + 8;
			var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64;
			var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
			var lWordArray = Array(lNumberOfWords - 1);
			var lBytePosition = 0;
			var lByteCount = 0;
			while (lByteCount < lMessageLength) {
				lWordCount = (lByteCount - (lByteCount % 4)) / 4;
				lBytePosition = (lByteCount % 4) * 8;
				lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition));
				lByteCount++;
			}
			lWordCount = (lByteCount - (lByteCount % 4)) / 4;
			lBytePosition = (lByteCount % 4) * 8;
			lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
			lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
			lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
			return lWordArray;
		};
		
		var wordToHex = function(lValue) {
			var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount;
			for (lCount = 0; lCount <= 3; lCount++) {
				lByte = (lValue >>> (lCount * 8)) & 255;
				WordToHexValueTemp = "0" + lByte.toString(16);
				WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
			}
			return WordToHexValue;
		};
		
		var uTF8Encode = function(string) {
			string = string.replace(/\x0d\x0a/g, "\x0a");
			var output = "";
			for (var n = 0; n < string.length; n++) {
				var c = string.charCodeAt(n);
				if (c < 128) {
					output += String.fromCharCode(c);
				} else if ((c > 127) && (c < 2048)) {
					output += String.fromCharCode((c >> 6) | 192);
					output += String.fromCharCode((c & 63) | 128);
				} else {
					output += String.fromCharCode((c >> 12) | 224);
					output += String.fromCharCode(((c >> 6) & 63) | 128);
					output += String.fromCharCode((c & 63) | 128);
				}
			}
			return output;
		};
		
		$.extend({
			md5: function(string) {
				var x = Array();
				var k, AA, BB, CC, DD, a, b, c, d;
				var S11=7, S12=12, S13=17, S14=22;
				var S21=5, S22=9 , S23=14, S24=20;
				var S31=4, S32=11, S33=16, S34=23;
				var S41=6, S42=10, S43=15, S44=21;
				string = uTF8Encode(string);
				x = convertToWordArray(string);
				a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
				for (k = 0; k < x.length; k += 16) {
					AA = a; BB = b; CC = c; DD = d;
					a = FF(a, b, c, d, x[k+0],  S11, 0xD76AA478);
					d = FF(d, a, b, c, x[k+1],  S12, 0xE8C7B756);
					c = FF(c, d, a, b, x[k+2],  S13, 0x242070DB);
					b = FF(b, c, d, a, x[k+3],  S14, 0xC1BDCEEE);
					a = FF(a, b, c, d, x[k+4],  S11, 0xF57C0FAF);
					d = FF(d, a, b, c, x[k+5],  S12, 0x4787C62A);
					c = FF(c, d, a, b, x[k+6],  S13, 0xA8304613);
					b = FF(b, c, d, a, x[k+7],  S14, 0xFD469501);
					a = FF(a, b, c, d, x[k+8],  S11, 0x698098D8);
					d = FF(d, a, b, c, x[k+9],  S12, 0x8B44F7AF);
					c = FF(c, d, a, b, x[k+10], S13, 0xFFFF5BB1);
					b = FF(b, c, d, a, x[k+11], S14, 0x895CD7BE);
					a = FF(a, b, c, d, x[k+12], S11, 0x6B901122);
					d = FF(d, a, b, c, x[k+13], S12, 0xFD987193);
					c = FF(c, d, a, b, x[k+14], S13, 0xA679438E);
					b = FF(b, c, d, a, x[k+15], S14, 0x49B40821);
					a = GG(a, b, c, d, x[k+1],  S21, 0xF61E2562);
					d = GG(d, a, b, c, x[k+6],  S22, 0xC040B340);
					c = GG(c, d, a, b, x[k+11], S23, 0x265E5A51);
					b = GG(b, c, d, a, x[k+0],  S24, 0xE9B6C7AA);
					a = GG(a, b, c, d, x[k+5],  S21, 0xD62F105D);
					d = GG(d, a, b, c, x[k+10], S22, 0x2441453);
					c = GG(c, d, a, b, x[k+15], S23, 0xD8A1E681);
					b = GG(b, c, d, a, x[k+4],  S24, 0xE7D3FBC8);
					a = GG(a, b, c, d, x[k+9],  S21, 0x21E1CDE6);
					d = GG(d, a, b, c, x[k+14], S22, 0xC33707D6);
					c = GG(c, d, a, b, x[k+3],  S23, 0xF4D50D87);
					b = GG(b, c, d, a, x[k+8],  S24, 0x455A14ED);
					a = GG(a, b, c, d, x[k+13], S21, 0xA9E3E905);
					d = GG(d, a, b, c, x[k+2],  S22, 0xFCEFA3F8);
					c = GG(c, d, a, b, x[k+7],  S23, 0x676F02D9);
					b = GG(b, c, d, a, x[k+12], S24, 0x8D2A4C8A);
					a = HH(a, b, c, d, x[k+5],  S31, 0xFFFA3942);
					d = HH(d, a, b, c, x[k+8],  S32, 0x8771F681);
					c = HH(c, d, a, b, x[k+11], S33, 0x6D9D6122);
					b = HH(b, c, d, a, x[k+14], S34, 0xFDE5380C);
					a = HH(a, b, c, d, x[k+1],  S31, 0xA4BEEA44);
					d = HH(d, a, b, c, x[k+4],  S32, 0x4BDECFA9);
					c = HH(c, d, a, b, x[k+7],  S33, 0xF6BB4B60);
					b = HH(b, c, d, a, x[k+10], S34, 0xBEBFBC70);
					a = HH(a, b, c, d, x[k+13], S31, 0x289B7EC6);
					d = HH(d, a, b, c, x[k+0],  S32, 0xEAA127FA);
					c = HH(c, d, a, b, x[k+3],  S33, 0xD4EF3085);
					b = HH(b, c, d, a, x[k+6],  S34, 0x4881D05);
					a = HH(a, b, c, d, x[k+9],  S31, 0xD9D4D039);
					d = HH(d, a, b, c, x[k+12], S32, 0xE6DB99E5);
					c = HH(c, d, a, b, x[k+15], S33, 0x1FA27CF8);
					b = HH(b, c, d, a, x[k+2],  S34, 0xC4AC5665);
					a = II(a, b, c, d, x[k+0],  S41, 0xF4292244);
					d = II(d, a, b, c, x[k+7],  S42, 0x432AFF97);
					c = II(c, d, a, b, x[k+14], S43, 0xAB9423A7);
					b = II(b, c, d, a, x[k+5],  S44, 0xFC93A039);
					a = II(a, b, c, d, x[k+12], S41, 0x655B59C3);
					d = II(d, a, b, c, x[k+3],  S42, 0x8F0CCC92);
					c = II(c, d, a, b, x[k+10], S43, 0xFFEFF47D);
					b = II(b, c, d, a, x[k+1],  S44, 0x85845DD1);
					a = II(a, b, c, d, x[k+8],  S41, 0x6FA87E4F);
					d = II(d, a, b, c, x[k+15], S42, 0xFE2CE6E0);
					c = II(c, d, a, b, x[k+6],  S43, 0xA3014314);
					b = II(b, c, d, a, x[k+13], S44, 0x4E0811A1);
					a = II(a, b, c, d, x[k+4],  S41, 0xF7537E82);
					d = II(d, a, b, c, x[k+11], S42, 0xBD3AF235);
					c = II(c, d, a, b, x[k+2],  S43, 0x2AD7D2BB);
					b = II(b, c, d, a, x[k+9],  S44, 0xEB86D391);
					a = addUnsigned(a, AA);
					b = addUnsigned(b, BB);
					c = addUnsigned(c, CC);
					d = addUnsigned(d, DD);
				}
				var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
				return tempValue.toLowerCase();
			}
		});
	})(jQuery);;(function($) {
	$.extend({
		modulesSave: function() {
			var dims = {};
			for (id in moduleConf)
				if (moduleConf[id].changed)
					dims[id] = moduleConf[id].dim;
			$.ajax({
				type: 'POST',
				url: url('/module/dims'),
				data: $.flatten({dims: dims}),
				async: false});
		},
		modulesReloadByType: function(type) {
			for (id in moduleConf)
				if (moduleConf[id].type === type)
					$('#'+ id).moduleLoad();
		}});
	$.fn.extend({
		moduleHit: function(mods) {
			var mod = this.get(0), hit = false, modA = this.moduleA(), modB = this.moduleB(modA);
			mods.each(function() {
				if (this === mod) return true;
				if (moduleOverlap($(this).moduleA(), $(this).moduleB(), modA, modB)) {
					hit = true;
					return false;
				}
			});
			return hit;
		},
		moduleA: function() { return {
			x: Math.round(parseInt(this.css('left')) / $.fn.moduleConf.grid),
			y: Math.round(parseInt(this.css('top')) / $.fn.moduleConf.grid)};
		},
		moduleB: function(a) {
			if (undefined === a) a = this.moduleA();
			var conf = moduleConf[this.attr('id')];
			return {
				x: a.x + conf.dim.w / $.fn.moduleConf.grid,
				y: a.y + conf.dim.h / $.fn.moduleConf.grid};
		},
		moduleResize: function(args) {
			if (undefined !== args) {
				this.data('args', args);
				this.css('width', ($.fn.moduleConf.grid * args.w - 6) + 'px');
				this.css('height', ($.fn.moduleConf.grid * args.h - 6) + 'px');
			}
			var id = this.attr('id');
			moduleConf[id].dim.x = parseInt(this.css('left'));
			moduleConf[id].dim.y = parseInt(this.css('top'));
			moduleConf[id].changed = true;
			return this;
		},
		moduleStop: function(args) {
			if (!this.moduleHit($('#grid .module'))) this.moduleResize();
			var id = this.attr('id');
			this.css('left', (moduleConf[id].dim.x) + 'px');
			this.css('top', (moduleConf[id].dim.y) + 'px');
			return this.removeClass('stopOk stopError');
		},
		moduleMoved: function(args) {
			/// \todo
			return true;
		},
		moduleDrag: function(args) {
			if (!this.moduleMoved()) return this;
			return this.removeClass('stopOk stopError').addClass(this.moduleHit($('#grid .module'))? 'stopError' : 'stopOk');
		},
		moduleOnLoad: function() {
		},
		moduleLoad: function(href, a, b) {
			if (undefined === href) href = '?';
			if ('http' !== href.substr(0, 4)) href = '/module/view/' + href;
			var data = {
				mod: $(this).attr('id')};
			if ($(this).data('UserId')) data.v = $(this).data('UserId');
			href = url(href, data);
			return $(this).find('.content').load(href, a, b);
		}});
	function moduleOverlap(a, b, c, d) {
		return (d.x > a.x && c.x < b.x) && (d.y > a.y && c.y < b.y);
	}
	$.fn.moduleConf = {
		grid: 10};
})(jQuery);
;(function($) {
	$.fn.extend({
		pages: function(opt) {
			function pagesAdd(i) {
				var w = '<li><a';
				if (i == opt.i) {
					w += ' class="active"';
				} else {
					w += ' href="#" alt="'+ i +'"';
				}
				return w +'>'+ (1+i) +'</a></li>';
			}
			$(this).each(function() {
				var w = '', a = 2, b = 5, c = 5, d = 2;
				if (opt.n < 2) {
					return $(this).html('');
				} else if (opt.n <= a+b+c+d) {
					for (var i = 0; i < opt.n; ++i) w += pagesAdd(i);
				} else {
					if (opt.i <= a+b) for (var i = 0; i <= opt.i; ++i) w += pagesAdd(i);
					else {
						for (var i = 0; i < a; ++i) w += pagesAdd(i);
						w += '<li>..</li>';
						for (var i = opt.i-b; i <= opt.i; ++i) w += pagesAdd(i);
					}
					if (opt.i >= opt.n-(c+d+1)) for (var i = opt.i+1; i < opt.n; ++i) w += pagesAdd(i);
					else {
						for (var i = opt.i+1; i <= opt.i+c; ++i) w += pagesAdd(i);
						w += '<li>..</li>';
						for (var i = opt.n-d; i < opt.n; ++i) w += pagesAdd(i);
					}
				}
				$(this).html('<ol>'+ w +'</ol>');
			});
			return $(this);
		}});
})(jQuery);
;(function($) {
	$.extend({
		stringify: function(obj, encode) {
			var w = '';
			var o = $.flatten(obj);
			if (encode) {
				for (i in o)
					w += i +'='+ encodeURIComponent(o[i]) +'&';
			} else {
				for (i in o)
					w += i +'='+ o[i] +'&';
			}
			return w;
		}});
})(jQuery);
(function(b){var e,d,a=[],c=window;b.fn.tinymce=function(j){var p=this,g,k,h,m,i,l="",n="";if(!p.length){return}if(!j){return tinyMCE.get(p[0].id)}function o(){var r=[],q=0;if(f){f();f=null}p.each(function(t,u){var s,w=u.id,v=j.oninit;if(!w){u.id=w=tinymce.DOM.uniqueId()}s=new tinymce.Editor(w,j);r.push(s);if(v){s.onInit.add(function(){var x,y=v;if(++q==r.length){if(tinymce.is(y,"string")){x=(y.indexOf(".")===-1)?null:tinymce.resolve(y.replace(/\.\w+$/,""));y=tinymce.resolve(y)}y.apply(x||tinymce,r)}})}});b.each(r,function(t,s){s.render()})}if(!c.tinymce&&!d&&(g=j.script_url)){d=1;h=g.substring(0,g.lastIndexOf("/"));if(/_(src|dev)\.js/g.test(g)){n="_src"}m=g.lastIndexOf("?");if(m!=-1){l=g.substring(m+1)}c.tinyMCEPreInit={base:h,suffix:n,query:l};if(g.indexOf("gzip")!=-1){i=j.language||"en";g=g+(/\?/.test(g)?"&":"?")+"js=true&core=true&suffix="+escape(n)+"&themes="+escape(j.theme)+"&plugins="+escape(j.plugins)+"&languages="+i;if(!c.tinyMCE_GZ){tinyMCE_GZ={start:function(){tinymce.suffix=n;function q(r){tinymce.ScriptLoader.markDone(tinyMCE.baseURI.toAbsolute(r))}q("langs/"+i+".js");q("themes/"+j.theme+"/editor_template"+n+".js");q("themes/"+j.theme+"/langs/"+i+".js");b.each(j.plugins.split(","),function(s,r){if(r){q("plugins/"+r+"/editor_plugin"+n+".js");q("plugins/"+r+"/langs/"+i+".js")}})},end:function(){}}}}b.ajax({type:"GET",url:g,dataType:"script",cache:true,success:function(){tinymce.dom.Event.domLoaded=1;d=2;o();b.each(a,function(q,r){r()})}})}else{if(d===1){a.push(o)}else{o()}}};b.extend(b.expr[":"],{tinymce:function(g){return g.id&&!!tinyMCE.get(g.id)}});function f(){function i(l){if(l==="remove"){this.each(function(n,o){var m=h(o);if(m){m.remove()}})}this.find("span.mceEditor,div.mceEditor").each(function(n,o){var m=tinyMCE.get(o.id.replace(/_parent$/,""));if(m){m.remove()}})}function k(n){var m=this,l;if(n!==e){i.call(m);m.each(function(p,q){var o;if(o=tinyMCE.get(q.id)){o.setContent(n)}})}else{if(m.length>0){if(l=tinyMCE.get(m[0].id)){return l.getContent()}}}}function h(m){var l=null;(m)&&(m.id)&&(c.tinymce)&&(l=tinyMCE.get(m.id));return l}function g(l){return !!((l)&&(l.length)&&(c.tinymce)&&(l.is(":tinymce")))}var j={};b.each(["text","html","val"],function(n,l){var o=j[l]=b.fn[l],m=(l==="text");b.fn[l]=function(r){var p=this;if(!g(p)){return o.call(p,r)}if(r!==e){k.call(p.filter(":tinymce"),r);o.call(p.not(":tinymce"),r);return p}else{var q="";(m?p:p.eq(0)).each(function(t,u){var s=h(u);q+=s?(m?s.getContent().replace(/<(?:"[^"]*"|'[^']*'|[^'">])*>/g,""):s.getContent()):o.call(b(u),r)});return q}}});b.each(["append","prepend"],function(n,m){var o=j[m]=b.fn[m],l=(m==="prepend");b.fn[m]=function(q){var p=this;if(!g(p)){return o.call(p,q)}if(q!==e){p.filter(":tinymce").each(function(s,t){var r=h(t);r&&r.setContent(l?q+r.getContent():r.getContent()+q)});o.call(p.not(":tinymce"),q);return p}}});b.each(["remove","replaceWith","replaceAll","empty"],function(m,l){var n=j[l]=b.fn[l];b.fn[l]=function(){i.call(this,l);return n.apply(this,arguments)}});j.attr=b.fn.attr;b.fn.attr=function(n,q,o){var m=this;if((!n)||(n!=="value")||(!g(m))){return j.attr.call(m,n,q,o)}if(q!==e){k.call(m.filter(":tinymce"),q);j.attr.call(m.not(":tinymce"),n,q,o);return m}else{var p=m[0],l=h(p);return l?l.getContent():j.attr.call(b(p),n,q,o)}}}})(jQuery);;(function($) {
	$.fn.extend({
		title: function(opt) {
			var opt = $.extend({
				top: 10,
				left: 0,
				follow: true}, opt), elements = $(this).not('.title-done');
			if (elements.length) elements.addClass('title-done').bind('mouseenter', function() {
				var title = $(this).attr('title');
				$('body').append('<div class="title-box">'+ title +'</div>');
				var div = $('body > :last-child').hide().fadeIn();
				if (opt.follow) $('body').bind('mousemove', function(e) {
					div.css('top', opt.top + e.pageY +'px');
					div.css('left', opt.left + e.pageX +'px');
				});
				$(this).removeAttr('title').one('mouseleave', function() {
					$(this).attr('title', title);
					div.remove();
					$('body').unbind('mousemove');
				});
			});

			return $(this);
		}});
	$.extend({
		title: function() {
			return $('.title').title();
		}});
})(jQuery);
/* Polish initialisation for the jQuery UI date picker plugin. */
/* Written by Jacek Wysocki (jacek.wysocki@gmail.com). */
;(function($){
	$.datepicker.regional['pl'] = {
		closeText: 'Zamknij',
		prevText: '&#x3c;Poprzedni',
		nextText: 'Następny&#x3e;',
		currentText: 'Dziś',
		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
		'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
		'Lip','Sie','Wrz','Pa','Lis','Gru'],
		dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
		dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
		dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
		weekHeader: 'Tydz',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['pl']);
})(jQuery);
;(function($) {
	$.fn.extend({
		valArray: function(val) {
			for (var i in val)
				$(this).find('[name="' + val[i].name + '"]').val(val[i].value);
			return $(this);
		},
		values: function() {
			var ret = [];
			$(this).each(function() {
				ret.push($(this).val());
			});
			return ret;
		}});
})(jQuery);
;(function($) {
	$.fn.extend({
		validate: function(args) {
			var opt = $.extend({}, $.fn.validate.defaults, args), valid = true;
			$(this).each(function() {
				$(this).find('span.error').remove();
				valid = valid && $(this).find('.valid').isValid(opt);
			});
			return valid;
		},
		validated: function() {
			return !$(this).find('span.error').length;
		},
		isSet: function() {
			var set = true;
			$(this).each(function() {
				var tagName = this.tagName.toLowerCase();
				if ($(this).hasClass('radio')) set = set && $(this).find('input:radio:checked').val();
				else if ('ol' === tagName) set = set && $(this).find('input[name]').length;
				else if ('textarea' === tagName) set = set && $(this).val().length;
				else if ('input' === tagName) switch ($(this).attr('type')) {
					case 'text':;
					case 'password':set = set && $(this).val().length;break
					case 'checkbox':set = set && $(this).filter(':checked').length;break;
				}
			});
			return set;
		},
		isValid: function(opt) {
			var valid = true;
			for (var i = 0; i < this.length; ++i) {
				var e = $(this[i]);
				if (!e.isSet()) {
					if (e.hasClass('required') && !opt.ignoreEmpty)
						valid = add_error(e, opt.required_error_message);
					continue;
				}
				if ('checkbox' === e.attr('type')) continue;

				if (e.hasClass('complexPassword') && (!valid_complex_pass(e.val()))) {
					valid = add_error(e, opt.complexPass_error_message);
					return valid;
				}
				if (e.hasClass('url') && !valid_url(e.val()))
					valid = add_error(e, opt.url_error_message);
				if (e.hasClass('email') && !valid_email(e.val()))
					valid = add_error(e, opt.email_error_message);
				if (e.hasClass('date')) {
					if (!valid_date(e.val(), opt.date_format))
						valid = add_error(e, opt.date_error_message);
				} else if (e.hasClass('datehour') && !e.hasClass['noValidate']) {
					if (!valid_datehour(e.val()))
						valid = add_error(e, opt.datehour_error_message);
				} else if (e.hasClass('int')) {
					if (!valid_integer(e.val()))
						valid = add_error(e, opt.integer_error_message);
				} else if (e.hasClass('number')) {
					var val = e.val();
					val = val.replace(',', '.');
					if (isNaN(val))
						valid = add_error(e, opt.number_error_message);
					if (e.data('accuracy') && valid == true) {
						val = val.split('.');
						if (val.length > 1 && val[1].length > e.data('accuracy'))
							valid = add_error(e, opt.accuracy_error_message);
					}
				}
				if (e.hasClass('match')) {
					var f = $("[name='" + e.attr('alt') + "']");
					var both = $($.merge(e.get(), f.get()));
					both.parents('.field').find('span.error.match').remove();
					if (e.val() !== f.val())
						valid = add_error(both, opt.match_error_message, 'match');
				}
				if (e.hasClass('ajax') && !e.hasClass('ajax-ok')) {
					$.ajax({
						url: url('/valid/' + e.attr('alt')),
						dataType: 'json',
						data: {val: e.val()},
						async: false,
						success: function(data) {
								if (data.code) {
									e.parent().find('.error').remove();
									valid = add_error(e, data.msg);
								}
						}
					}); 
				}
				if (e.hasClass('postalCode') && (!valid_postal_code(e.val()) || e.val().length>6))
					valid = add_error(e, opt.postal_code_error_message);
				if (e.hasClass('bankAccount') && (!valid_account_no(e.val()))) {
					valid = add_error(e, opt.account_no_error_message);
                                }
				if (e.hasClass('Tags') && (valid_tags(e.val()))) {
					valid = add_error(e, opt.tags_error_message);
				}
				if (e.hasClass('unique') && (!valid_unique(e.val(), e.attr('name')))) {
					valid = add_error(e, opt.unique_error_message);
				}
				if (e.hasClass('range') && valid == true) {
					var min = minLabel = e.data('min');
					var value = e.val();
					if (e.hasClass('date')) {
						minLabel = min['label'];
						min = min['value'];
						value = $.datepicker.parseDate('d.m.yy', value).getTime() / 1000;
						value -= (new Date()).getTimezoneOffset() * 60;
					} else if (e.hasClass('number')) {
						value = value.replace(',', '.');
					} else {
						value = value+'';
						value = value.length;
					}
					if (!valid_range(value, min, e.data('max')))
						valid = add_error(e, opt.range_error_message, 'range', {
							min: minLabel,
							max: e.data('max')});
				}
			}
			return valid;
		},
		validateError: function(msg) {
			add_error(this, msg);
		}});

	function parse_error(msg, params) {
		var buf = msg.split('%');
		for (var i = 1; i < buf.length; i += 2)
			buf[i] = params[buf[i]];
		return buf.join('');
	}

	function add_error(e, message, type, params) {
		var msg = e.parents('li.field').find('span.errorMessage');
		if (msg.length) {
			var messages = $.parseJSON(msg.text());
			if (undefined !== messages[type])
				message = parse_error(messages[type], params);
		} else {
			msg = e.parents('li.field').find('span.requiredError');
			if (msg.length) message = msg.text();
		}
		e.parent().append('<span class="error '+ (type||'') +'">' + message + '</span>');
		return false;
	}

	function valid_url(val) {
		var url_pattern  = /^(http(s)?\:\/\/)?(([-A-Za-z0-9]+\.)+)([-A-Za-z0-9]+)(\:[1-9][0-9]*)?(\/.*)?$/;
		return val.match(url_pattern);
	}

	function valid_email(val) {
		var email_pattern  = /^([a-zA-Z0-9_\.\-+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return val.match(email_pattern);
	}

	function valid_integer(val) {
		return val.match(/^(\d|([1-9]\d*))$/);
	}

	function valid_date(val, date_format) {

		return val.match(/^(0?[1-9]|[12][0-9]|3[01])\.(0?[1-9]|1[012])\.((19|20)[0-9]{2})$/);
	}

	function valid_datehour(val, date_format) {
	return false;	
	}

	function valid_postal_code(val) {
		return val.match(/[0-9]{2}-?[0-9]{3}/);
	}

	/**
	 * Sprawdza poprawność konta bankowego zgodnie ze standardem IBAN.
	 * Tablica "countryCodeLength" zawiera kody krajów oraz długości
	 * numerów kont bankowych specyficznych dla kraju. Jak nie ma kraju
	 * w tablicy to walidacja długości jest pomijana.
	 * @param val - konto bankowe
	 */
	function valid_account_no(val) {
		var shift = 55; // kod ASCII litery A = 65; wg IBAN A ma mieć 10, więc shif = 65 - 10 = 55;
		var countryCodeLength = {
			'AD' : 24, //Andora
			'AT' : 20, //Austria
			'BE' : 16, //Belgia
			'CY' : 28, //Cypr
			'CZ' : 24, //Czechy
			'DK' : 18, //Dania
			'EE' : 20, //Estonia
			'FI' : 18, //Finlandia
			'FR' : 27, //Francja
			'DE' : 22, //Niemcy
			'GI' : 23, //Gibraltar
			'GR' : 27, //Grecja
			'HU' : 28, //Węgry
			'IS' : 26, //Islandia
			'IE' : 22, //Irlandia
			'IT' : 27, //Włochy
			'LV' : 21, //Łotwa
			'LT' : 20, //Litwa
			'LU' : 20, //Luxemburg
			'NL' : 18, //Holandia
			'NO' : 15, //Norwegia
			'PL' : 28, //Polska
			'PT' : 25, //Portugalia
			'SK' : 24, //Słowacja
			'SI' : 19, //Słowenia
			'ES' : 24, //Hiszpania
			'SE' : 24, //Szwecja
			'CH' : 21, //Szwajcaria
			'GB' : 22 //Wielka Brytania
		}
		val = val.replace(/^\s+|\s+|\-+|\s+$/g, ''); //usunięcie białych znaków i myślników
		if (!val.match(/^[A-Za-z]{2}/))
			val = 'PL'+val; // jeżeli nie jest podane to przyjmujemy że polski numer konta
		val = val.toUpperCase();
		var countryCode = val.substr(0,2);
		if ((countryCodeLength[countryCode] != undefined) && (val.length != countryCodeLength[countryCode])) {//walidacja długości numery w zalezności od kraju
			return false;
		}
		//przeniesienie kodu kraju i sumy kontrolnej na koniec
		val = val.substr(4, val.length-4) + countryCode + val.substr(2,2);
		
		//zamiana liter na liczby
		var cVal = '';
		for (var i=0; i<val.length; i++) {
			if (val.charAt(i).match(/^[0-9]$/))
				cVal+=val.charAt(i);
			else
				cVal+=(val.charCodeAt(i) - shift).toString();
		}
		var parts = 3; //na ile części dzielimy stringa
		j = Math.ceil(cVal.length/parts); // dzielimy na części ponieważ za długa liczba dla int
		var rest = '';
		for (i=0; i<parts; i++) {
			rest = parseInt((rest +''+ cVal.substr(i*j, j)).replace(/^[0]+/, "")) % 97; //replace - usunięcie przednich zer
		}
		return rest == 1;
	}

	function valid_range(val, min, max) {
		val = Number(val);
		return min <= val && val <= max;
	}
	function valid_tags(val) {
		return val.match(/[0-9]+/);
	}
	function valid_unique(val, name) {
		var q = object_rec_replace(uniqueFields[name], '%value%', val);
		var code = false;
		$.ajax({
			async: false,
			type: 'POST',
			url: url('/valid/unique'),
			data: q,
			success: function(status) {
				code = (status == 0);
			}
		});
		return code;
	}

	function valid_complex_pass(val) {
		var test1 = val.match(/[a-zA-Z]+/);
		var test2 = val.match(/[^a-zA-Z]+/);
		return (
		(val.length >= 6) &&
		(val.length <= 25) &&
		(test1) && (test1.length>0) && 
		(test2) && (test2.length>0));
	}

	function object_rec_replace(obj, needle, val) {
		if (typeof obj == 'object') {
			var obj2 = jQuery.extend(true, {}, obj);
			for (i in obj2) {
				obj2[i] = object_rec_replace(obj2[i], needle, val);
			}
			return obj2;
		}
		obj = obj.replace(needle, val)
		return obj;
	}

	$.fn.validate.defaults = {
		url_error_message: _('Nieprawidłowy adres www.'),
		email_error_message: _('Adres email nie jest poprawny'),
		text_error_message: _('Może byc tylko tekstem'),
		number_error_message: _('Nie jest liczbą'),
		integer_error_message: _('Podana wartość nie jest liczbą całkowitą'),
		date_error_message: _('Niepoprawna data'),
		datehour_error_message: _('Podana wartość nie jest prawidłową datą'),
		required_error_message: _('Pole jest wymagane'),
		match_error_message: _('Hasła nie pasują'),
		ajax_error_message: _('trwa walidacja...'),
		postal_code_error_message: _('niepoprawny format'),
		range_error_message: _('pole poza zakresem'),
		date_format: _('mm/dd/yyyy'),
        account_no_error_message: _('Niepoprawny numer konta bankowego'),
		tags_error_message: _('Użyto nieprawidłowych znaków'),
		unique_error_message: _('Pole musi być unikalne'),
		complexPass_error_message: _('Hasło nie spełnia wymagań'),
		accuracy_error_message: _('Niepoprawna dokładność liczby')
	};
})(jQuery);

$.bind('validator/ajax', function(e) {
	e.scope
	.delegate('.ajax', 'change', function(f, autoSubmit) {
		var o = $(f.target).removeClass('ajax-ok');
		if (('email' == o.attr('alt')) && (o.val().length < 5))
			return;

		$.getJSON(url('/valid/' + o.attr('alt')), {val: o.val()}, function(data) {
			e.scope.find('.error').remove();
			if (!data.code) {
				var form = e.scope.parents('form');
				o.addClass('ajax-ok');
				form.find('input:disabled').removeAttr('disabled');
				if (autoSubmit)
					form.trigger('submit');
			} else o.validateError(data.msg);
		});
	});
});

$.bind('module', function(e) {
	var mod = e.scope;
	function hRm(e) { if (e.hasClass('h-rm')) mod.find('ol.history li:last-child').remove(); }
	e.scope
	.find('.head').bind('click', function(e) {
		if ('#reload' === $(e.target).attr('href')) {
			mod.moduleLoad($(e.target).attr('alt'));
			$(e.target).parent().nextAll().remove();
		} else if ('#resize' === $(e.target).attr('href')) {
			if ($(e.target).text() == '-') 
				$(e.target).text('+');
			else
				$(e.target).text('-');
			mod.find('.content').slideToggle('slow');
		} else return;
		return false;
	}).end()
	.find('.content').bind('click', function(e) {
		var href = $(e.target).attr('href');
		if (href !== '#reload')	return;
		var alt = $(e.target).attr('alt');
		if (undefined === alt)	return false;
		mod.moduleLoad(alt);
		if ($(e.target).hasClass('h'))
			if (alt !== mod.find('ol.history li:last-child a').attr('alt')) {
				hRm($(e.target));
				mod.find('ol.history').append('<li><a href="#reload" alt="'+ alt +'">'+ $(e.target).text() + '</a>');
			}
		return false;
	})
	// submit formularzy ajax'em
	.bind('submit', function(e) {
		var tagName;
		//alert(e.target.parentNode);
		// w ie e.target to INPUT, reszta FORM
		while ((tagName = e.target.tagName.toLowerCase()) !== 'form') {
			if ('document' === tagName) return false;
			e.target = e.target.parentNode;
		}
		if ($(e.target).hasClass('ajax')) return;
		mod.moduleLoad($(e.target).attr('action'), $(e.target).serializeArray());
		hRm($(e.target));
		return false;
	}).end()
	;
	if (e.opt.UserId) mod.data('UserId', e.opt.UserId);
	$.bind('module-history-clear', function(e) {
		mod.find('ol.history :not(li:first-child)').remove();
	});
	$.bind('module-history-add', function(e) {
		mod.find('ol.history').append('<li><a alt="'+ e.opt.alt +'" href="#reload">'+ e.opt.text +'</a></li>');
	});
});

$.bind('module-edit', function(e) {
	e.scope.draggable({
		containment: 'parent',
		handle: '.handle',
		grid: [$.fn.moduleConf.grid, $.fn.moduleConf.grid],
		stop: function(ev, ui) { $(ev.target).moduleStop(); },
		drag: function(ev, ui) { $(ev.target).moduleDrag(); }}).find('a[href="#rm"]').bind('click', function() {
		var module = $(this).parent(), id = module.attr('id');
		$.getJSON(url('/module/rm', {mod: id}), function(data) {
			module.remove();
			$('.dashboard a[href="#add"][alt="'+ moduleConf[id].type +'"]').parent().show();
		});
		$(this).remove();
		return false;
	});
});

$.bind('module-dashboard', function(e) {
	e.scope
	.find('a[href="#add"]').bind('click', function() {
		$.post(url('/module/add'), {page: PAGE, mod: $(this).attr('alt')}, function(data) {
			$('#grid').append(data);
			$.bindLoadAll();
		});
		$(this).parent().hide();
	});
});

var publish = {
	dialog: null,
	opt: null,
	data: null,
	fn: function(opt) {
		// kopia
		this.opt = $.extend(true, {}, opt);
		if (opt.attach) this.data = $.flattenArray($(opt.attach).serializeArray());
			else this.data = {};
			
		this.dialog = $.dialog({
			url: url('/publish', this.opt),
			data: this.data,
			title: opt.title,
			dialogClass: 'publish ' + (opt.className ? opt.className : ''),
			close: function() { $(this).remove(); }});
	}};
$.bind('publish', function(e) {
	e.scope.bind('click', function() { publish.fn(e.opt); return false; });
});
$.bind('publish/form', function(e) {
	e.scope.bind('submit', function() {
		$.post(url('/publish', {type: publish.opt.type}), e.scope.serializeArray());
		publish.dialog.remove();
		return false;
	});
});
$.bind('publish/close', function() {
	publish.dialog.remove();
});
$.bind('publish/select', function(e) {
	e.scope.find('li').bind('click', function() {
		publish.opt.type = $(this).attr('alt');
		publish.dialog.load(url('/publish', publish.opt), publish.data);
	});
});
$.bind('table', function(e) {
	var getParams = e.opt.get;
	var pageActive = e.opt.page;
	var table = e.scope, body = e.scope.find('.Table-body'), key = e.opt.key, js = e.opt.load;
	function onLoad() {
		$.bindLoad(js, {key: key}, body);
	}
	var tableFilter = {};
	function load(data) {
		if (undefined === data) data = {};
		tableFilter = $.extend(tableFilter, data, {tableKey: key});
		body.load(url('/table', tableFilter), onLoad);
	}
	e.scope.bind('click', function(e) {
		if ('#all' === $(e.target).attr('href')) {
			var c = 1 + $(e.target).parent().prevAll().length;
			if ($.browser.msie) {
				$(this).find('tbody tr').find('td:nth-child('+ c +') input:not(:checked)').attr('checked', 'checked').trigger('click').attr('checked', 'checked');
				return false;
			}
			$(this).find('tbody tr').find('td:nth-child('+ c +') input:not(:checked)').trigger('click').trigger('change');
		} else if ('#rmById' === $(e.target).attr('href')) {
			if (!confirm(_("Jesteś pewien?")))
				return false;
			load({rm: $(e.target).attr('alt')});
		} else return;
		return false;
	})
	.find('form.Table-form').bind('submit', function() {
		if (!doChange) return;
		doChange = false;
		load($.flattenArray($(this).serializeArray()));
		return false;
	})
		.find('input,select').bind('change', function() { doChange = true; $(this).trigger('submit'); }).end()
	.end()
	.find('.Table-sort a').bind('click', function() {
		load({sort: $(this).attr('alt'), dir: $(this).attr('href').substr(1)})
		return false;
	}).end()
	.find('.Table-pager')
		.bind('click', function(f) {
			var page = parseInt($(f.target).attr('alt'));
			if (Number.NaN === page) page = 0;
			pageActive = page;
			var params = {page: page};
			$.each(getParams, function(k,v){
				if (k != 'page')
					params[k] = v;
			});
			load(params);
			return false;
		})
	.end()
	;
	if (e.opt.refresh !== undefined) {
		window.setInterval(function() {
			load({page: pageActive});
		}, e.opt.refresh * 1000);
	}
	onLoad();

	$.bind('table-rows-'+ key, function(e) {
		table
		.find('.Table-pager').pages({i: e.opt.page, n: e.opt.pageCnt});
	});
});

/**
 * Przypinanie/odpinaie tagów - Eksperyment, panel administracyjny
 */
$.bind('tableBody', function(e) {
	e.scope
	.find('a.plug').each(function() {
		var href = $(this).attr('alt');
		var MainTagId = $('#selectMainTag').val() ;
		if (MainTagId == undefined) return;		
		$(this).attr('href', href + 'MainTagId=' + MainTagId + '&');
	}).end()
	.find('a.unplug').each(function() {
		$(this).attr('href', $(this).attr('alt'));
	}).end()
	;
});
/**
 * Pobieranie adresu URL z tabelki do formularza
 */
$.bind('tableURLPick', function(e) {
	e.scope.find('a.editLink').bind('click', function() {
		var alt = $(this).attr('alt');
		var array = alt.split('|');
		$('#UrlId').val(array[0]);
		$('#UrlTitle').val(array[2]);
		$('#UrlHref').val(array[1]);
	});
});
$.bind('ticket-click', function(e) {
	var options = {
		url: url('/report/form'),
		draggable: true,
		width: 400,
		modal: true,
		dialogClass: 'simi-popup',
		resizable: false,
		title: _('Zgłoś błąd'),
		position: 'center',
		close: function() { $(this).remove(); }};
	if (e.opt.dialogOptions)
		$.extend(options, e.opt.dialogOptions);

	var dialog = $.dialog(options);
	try {
		pageTracker._trackPageview('/click/opinia');
	} catch (_e) {}

	$.bind('ticket-submit', function() {
		dialog.dialog('close');
	});
});
$.bind('ticket', function(e) {
	e.scope.bind('click', function() {
		$.bindLoad('ticket-click');
		return false;
	});
});

$.bind('user/login/redirect', function() { redirect('/user/login'); });
$.bind('user/remind', function(e) {
	var dialog = e.opt.dialog || {};
	$.dialog($.extend({
		draggable: true,
		modal: true,
		dialogClass: 'simi-popup',
		width: 465,
		title: _('Przypomnienie hasła'),
		url: url('user/password/remind')}, dialog));
});

$.bind('user/sso', function(e) {
	$.ajax({
		async: e.opt.async,
		data: {user: e.opt.uid},
		cache: false,
		url: e.opt.url,
		dataType: 'jsonp',
		success: function(change) {
			if (!change) return;
			if (!e.opt.async) window.location.reload();
		}});
});
$(function() {
	$('body')
	.delegate('[href="#remind"]', 'click', function(e) {
		$.bindLoad('user/remind');
		return false;
	})
	;
});


$(function() {
	$('body')
	.delegate('[href="#logon"]', 'click', function(e) {
		$.bindLoad('user/logon');
		return false;
	})
	;
});$.bind('abuse', function(e) {
	e.scope.find('a').bind('click', function() {
		e.scope.find('#abuseDiv').toggle();
	});
	e.scope.find('input[type=submit]').bind('click', function() {
		if (e.scope.find('#comment').attr('value') != '') {
			e.scope.toggle();
			e.scope.find('#abuseDiv').toggle();
		}
	});
});
$('#searchPanelBlockAddSimiButton button').bind('click', function(){
	var dialog = $.dialog({
	url: url('/myobjects/addForm', {noBack:1}),
		draggable: true,
		modal: true,
		resizable: false,
		title: _('Wyszukiwarka skojarzeń - wgraj zdjęcie'),
		position: 'center',
		width:  500,
		dialogClass: 'addSimiDialog',
		//height: 600,
		close: function() {
			$(this).remove(); 
		}});
		try {
			pageTracker._trackPageview('/click/addsimi');
		} catch (_e) {}
		try {
			pageTracker2._trackPageview('/click/addsimi'); 
		} catch (_e) {}

		$.bind('addsimi-submit', function(e) {
			dialog.dialog('close');
			window.location = url('/simimap', {photo: e.opt.id});
		});
		return false;

	});

function handleImageOnError() {
    var $cancel = $('[href="#cancel"]');
    $cancel.trigger('click');
}
$(function() {
	$('a.pageRm').bind('click', function() {
		$.get($(this).attr('alt'));
		$(this).parent().remove();
	});
});
$.bind('adminChooseImage', function(e) {
e.scope.bind('click', function(ev) {
	var $dialog = $.dialog({
		url: url('/admin/imageType?dialog=1'), // + $(this).find('#buttonYCenter').attr('value')),
		title:_('Wybierz zdjęcie'),
		width: 1000,
		height: 800,
		onLoad: function(){
			$($dialog).dialog('widget')[0].result = null;
		    /*$('#imageTypeChangeForm').unbind('closeDialog');
		    $('#imageTypeChangeForm').bind('closeDialog',function() {
			    $dialog.dialog('destroy');
			    $dialog = null;
			});
			$('#imageTypeChangeForm\\[submit\\]').bind('click', function() {
			    $('#imageTypeChangeForm').trigger('closeDialog');
			})*/
		}
	});
	$($dialog).dialog('widget').bind('closeDialog', function(){
		$dialog.dialog('close');
		var result = $($dialog).dialog('widget')[0].result;
		if(result) {
			var myurl = url('/admin/imagePair/add');
			$.post(url('/admin/imagePair/add', {photo:e.opt.photo,photoId: result}), function(){
				window.location = myurl;
			});
		}
	});
})
});

$.bind('admin/eksperyment/dictionary', function(e) {

//usuwanie tagu głównego
	$('#deleteMainTag').unbind().bind('click', function(){
		var mainTag = $('#selectMainTag').val();
		if (mainTag == "") {
			alert(_('Nie wybrałeś tagu głównego'));
		} else {
			var x=window.confirm(_('Czy na pewno usunąć ten tag główny?'));
			if (x) {
				$('#pluggedTags').html("");
				$('#mutualTags').html("");
				$.post(url('/admin/eksperyment/dictionary/deleteMainTag'), {'id':mainTag}, function() {
					$('#dictionaryLeftTop').load(url('/admin/eksperyment/dictionary/chooseMainTag'), 'exp='+ EkspId);
				});
			} else {
				;
			}
		}
	});

// admin/dictionaryChangeVisibility
	$('a.dictElement').bind('click', function() {
		var id = $(this).attr('alt');
		$('#'+ id).load(url('/admin/eksperyment/dictionary/dictionaryChangeVisibility'), {'id': id});
	});

	$('#selectMainTag').unbind().bind('change', function() {
		var o = {
			EkspId: EkspId,
			mainTag: $(this).val()};
		var u = '/admin/eksperyment/dictionary/tag';
		$('#pluggedTags').load(url(u, {type: 'plugged'}), o);
		$('#notPluggedTags').load(url(u, {type: 'unplugged'}), o);
		$('#mutualTags').load(url(u, {type: 'mutual'}), o);
		$.post(url('/admin/eksperyment/dictionary/tag/synonym'), {mainTagId:$('#selectMainTag').val()}, function(data){
			$('#synonymForMainTag').html(data);
		})
	});

	if (e.opt.mainTag)
		$("#selectMainTag").val(e.opt.mainTag);
	$("#selectMainTag").trigger("change");
});
$.bind('admin/eksperyment/mutualFilter', function(e) {
	e.scope.find('#EkspTag-mutualUnplugged').bind('change', function(){
		if (!$('#EkspTag-mutualUnplugged').attr('checked')) {
			var params = {
				EkspId: EkspId,
				mainTag: $('#selectMainTag').val(),
				unpluggedMutualTag: 0} 
		}
		else 
			var params = {
				EkspId: EkspId,
				mainTag: $('#selectMainTag').val(),
				unpluggedMutualTag: 1}

		var path = '/admin/eksperyment/dictionary/tag';
		$('#mutualTags').load(url(path, {type: 'mutual'}), params);
	});
});
$.bind('admin/eksperyment/tag', function(e) {
	e.scope.find('tr td:first-child').attr({
			'style': 'cursor:pointer', 
			'title': 'Click to show image'});
	e.scope.find('tr:not(.pager) td:first-child').bind('click', function() {		
		$('#tagImage').load(url('/admin/eksperyment/dictionary/findPhotoByTag'), {'tag': $(this).html()});
		return false;
	}).end()
	.find('.markAsInvalid').bind('change', function() {
		$.post(url('/admin/eksperyment/dictionary/tag/set'), {EkspTagId: $(this).attr('alt'), type: 'invalid', value: $(this).checked()});
	});
});
$.bind('admin/eksperyment/test/edit', function(e) {
	var i = 0;
	var data = new Array();
	function updateNames(f) {
		f.attr('alt', f.attr('alt') +'['+ (i++) +']')
		.find('input').each(function() {
			$(this).attr('name', f.attr('alt') + $(this).attr('alt'));
		}).end()
		;
	}
	function refreshStats() {
		var max = 0;
		for (var j in data) 
			if (data[j] > max) max = data[j];
		max *= 1.2; // zapas na etykietę, żeby była widoczna
		var numbers = '&chd=t:';
		for (var j in data) 
			numbers += Math.round(data[j]/max*100).toString() + ',';
		numbers = numbers.substr(0, numbers.length-1);
		var label = '&chxl=0:|';
		var k = 0;
		for (var j in data) {
			if (k%2 != 0)
				label += '|' + j + '|';
			k++;
		}
		label = label.substr(0, label.length-1);
		var label1 = '&chm=';
		var k =0;
		for (var j in data) {
			if (k%2 == 0)
				label1 += 'f' + j + ',0000FF,0,' + k +',10|'; // http://code.google.com/intl/pl/apis/chart/labels.html#data_point_labels
			k++;
		}
		label1 = label1.substr(0, label1.length-1);
		var url = 'http://chart.apis.google.com/chart?';
		url += 'chxt=x,y'; //pokaż labele na dole i po lewej
		url += '&cht=bvs'; //wykres słupkowy
		url += numbers; //dane
		url += '&chxr=1,0,'+ max; // zakres <index pozycji>,<min val>,<max val>,<interval>
		url += label; // labele
		url += label1; // labele
		url += '&chco=FF0000'; //color
		url += '&chls=2.0'; //linia
		url += '&chs=800x200'; //rozmiar
		$('.imageTestCreateStat').html('');
		$('.imageTestCreateStat').image(url);
	}
	$.fn.image = function(src, f){
	    return this.each(function(){
	    	var j = new Image();
            j.src = src;
            j.onload = f;
            this.appendChild(j);
	    });
	}
	e.scope.find('ul.pairs > li:not(:first-child)').each(function() { updateNames($(this)); }).end()
	.find('ul.images.all a[href="#image"]').bind('click', function() {
		var id = $(this).attr('id');
		for (var j in e.opt.EventTag[id]){
			if (data[j] > 0)
				data[j] += e.opt.EventTag[id][j];
			else
				data[j] = e.opt.EventTag[id][j];
		}
		refreshStats();
		$(this).parent().clone().appendTo(e.scope.find('ul.pairs > li:first-child ul')).bind('click', function() {
			var id = $(":first-child", this).attr('id');
			for (j in e.opt.EventTag[id])
				data[i] -= e.opt.EventTag[id][j];
			refreshStats();
			e.scope.find('ul.images.all input[value="'+ $(this).find('input').val() +'"]').parent().parent().show();
			$(this).remove();
		});
		$(this).parent().hide();
		return false;
	}).end()
	.find('a[href="#new"]').bind('click', function() {
		var f = e.scope.find('ul.pairs > li:first-child');
		updateNames(f.clone().appendTo(e.scope.find('ul.pairs')));
		f
		.find('ul').html('').end()
		.find('input').val('').end()
		;
		e.scope.find('ul.images.all li').show();
		return false;
	});
});
$.bind('admin/imageType', function(e) {
	$('.changeObjType').bind('click', function() {

		var $dialog = $.dialog({
			url: url('/admin/imageType/imageTypeChange?id=' + $(this).find('#buttonYCenter').attr('value')),
			title:_('Zmiana typu obiektu'),
			width: 440,
			onLoad: function(){
			    $('#imageTypeChangeForm').unbind('closeDialog');
			    $('#imageTypeChangeForm').bind('closeDialog',function() {
				    $dialog.dialog('destroy');
				    $dialog = null;
				});
				//$('#imageTypeChangeForm fieldset ol li input.button').bind('click', function() {
				$('#imageTypeChangeForm\\[submit\\]').bind('click', function() {
				    $('#imageTypeChangeForm').trigger('closeDialog');
				})
			}
		});		

	});

	$('.changeObjDesc').bind('click', function() {

		var $dialog = $.dialog({
			url: url('/admin/imageType/imageDescChange?id=' + $(this).find('#buttonYCenter').attr('value')),
			title:_('Zmiana opisu obiektu'),
			width: 640,
			onLoad: function(){
			    $('#imageDescChangeForm').unbind('closeDialog');
			    $('#imageDescChangeForm').bind('closeDialog',function() {
				    $dialog.dialog('destroy');
				    $dialog = null;
				});
				//$('#imageTypeChangeForm fieldset ol li input.button').bind('click', function() {
				$('#imageDescChangeForm\\[submit\\]').bind('click', function() {
				    $('#imageDescChangeForm').trigger('closeDialog');
				})
			}
		});		

	});




});




$.bind('admin/imageTypeChanged', function(e) {
	$('table tr.row_' + e.opt.id + ' td.stats span.tagging').html(escapeHtml(e.opt.strType));
	$('table tr.row_' + e.opt.id + ' td.stats span.wordTagging').html(escapeHtml(''+e.opt.stats.wordTagging));
	$('table tr.row_' + e.opt.id + ' td.stats span.clanTagging').html(escapeHtml(''+e.opt.stats.clanTagging));
	$('table tr.row_' + e.opt.id + ' td.stats span.skippedWordTagging').html(escapeHtml(''+e.opt.stats.skippedWordTagging));
	$('table tr.row_' + e.opt.id + ' td.stats span.skippedClanTagging').html(escapeHtml(''+e.opt.stats.skippedClanTagging));
});

$.bind('admin/user', function(e) {
	e.scope.find('a.bannLink').bind('click', function(){
		$(this).load(url('/admin/user/bann'), {'_id':$(this).attr('id')});	
	});
});
$.bind('bubbles', function(e) {
        
	var $learn 		= e.scope.find('#learn');
    var $addObject 	= e.scope.find('#package');
	var $explore 	= e.scope.find('#explore');
	var $search 	= e.scope.find('#search');
	var $searchInput = e.scope.find('#searchInput');
	//var $closeDialog = e.scope.find('#close');

        $addObject.bind({
	    mouseover: function() {
		$(this).removeClass('alpha80');
		$(this).addClass('pointer');
	    },
	    mouseout: function() {
		$(this).addClass('alpha80');
		$(this).removeClass('pointer');
	    }
	});

	$learn.bind({
	    mouseover: function() {
		$(this).removeClass('alpha80');
		$(this).addClass('pointer');
	    },
	    mouseout: function() {
		$(this).addClass('alpha80');
		$(this).removeClass('pointer');
	    }
	});

	$explore.bind({
	    mouseover: function() {
		$(this).removeClass('alpha80');
		$(this).addClass('pointer');
	    },
	    mouseout: function() {
		$(this).addClass('alpha80');
		$(this).removeClass('pointer');
	    }
	});

	$search.bind({
	   mouseover: function() {
	       if('' != $searchInput.val()) {
		   $(this).removeClass('alpha80');
		   $(this).addClass('pointer');
	       }
	   },
	   mouseout: function() {
		$(this).addClass('alpha80');
		$(this).removeClass('pointer');
	    },
	    click: function() {
		if('' != $searchInput.val()) {
		    document.forms['searchPanelSearchForm'].submit();
		}
	    }
	});

	
        /*
	$closeDialog.bind({
	    click: function() {
                $('#exploreDialog').hide();
                $('#cwtest').hide();
	    }
	});
        */
});

$('#packageLink').bind({
	    click: function(){
		var dialog = $.dialog({
		url: url('/myobjects/addForm', {noBack:1}),
			draggable: true,
			modal: true,
			resizable: false,
			title: _('Wyszukiwarka skojarzeń - wgraj zdjęcie'),
			position: 'center',
			dialogClass: 'simi-popup',
			width:  400,
			open: function() {
				$(this).html('<div><img src=\'/images/indicator.gif\'/></div>'); 
			},
			close: function() {
				$(this).remove();
			}});
			try {
				pageTracker._trackPageview('/click/addsimi');
			} catch (_e) {}
			try {
				pageTracker2._trackPageview('/click/addsimi');
			} catch (_e) {}

			$.bind('addsimi-submit', function(e) {
				dialog.dialog('close');
				//window.location = url('/simimap', {photo: e.opt.id});
			});
			return false;

		}
});
/**
 * Przechodzenie po drzewie kategorii (ajax)
 */
$.bind('category', function(e) {
	e.scope.find('.categoryLink').bind('click', function() {
		e.scope.load(url('/category', {'id' : $(this).attr('alt'), 'showAll' : e.opt.showAll}));
	});
});

function loadCategory() {
	$('#catField').val(
			$('#catId').attr('alt')
	);
	return true;
}$.bind('clan/check', function(e) {
	var scope = e.scope.parent();
	scope.find('.clanCheckButtonActive').bind('click', function() {
		redirect('clan/unlock', {clan: $(this).attr('alt')});
	});
	scope.find('.clanCheckButtonInActive').bind('click', function() {
		$.dialog({url: url('clan/inactive', {clan : $(this).attr('alt')}), title : _('Simisfera zablokowana')});
	});
	scope.find('.clanCheckButtonNone').bind('click', function() {
		redirect('index', {clan: $(this).attr('alt')});
	});
	scope.find('li.y').bind('click', function() {
		var a = $(this).find('.clanCheckButtonNone');
		redirect('index', {clan: a.attr('alt')});
	});
});var form;
$.bind('crop', function(e) {
    jQuery(function() {
        jQuery('#' + e.opt.imageId).Jcrop({
				onChange: showCoords});
        form = $('#' + e.opt.formId);
    });	
});

function showCoords(c) {
	jQuery('#x', form).val(c.x);
	jQuery('#y', form).val(c.y);
	jQuery('#w', form).val(c.w);
	jQuery('#h', form).val(c.h);
}$.bind('favourites/remove', function(e){
	e.scope.bind('click', function() {
		if(e.opt.image)
			e.scope.load(url('/favourites/rm', {image : e.opt.image, location: e.opt.location, fromlist : e.opt.fromlist, confirmed : e.opt.confirmed}));
		else if(e.opt.user)
			e.scope.load(url('/favourites/rm', {user : e.opt.user, location: e.opt.location, fromlist : e.opt.fromlist, confirmed : e.opt.confirmed}));		
	});
});


$.bind('favourites/update', function(e) {

	if(e.opt.photoid)
	{
		var favLinkHtml = '<a href="" onclick="$(this).load(url(\'/favourites/add\', {image : \'' + e.opt.photoid + '\', location: \'search\'}), null, function() {}); $(this).hide(); return false">do ulubionych</a>';
		var objectId = e.opt.photoid;
	}
	else if(e.opt.userid) {
		var favLinkHtml = '<a href="" onclick="$(this).load(url(\'/favourites/add\', {user : \'' + e.opt.userid + '\', location: \'search\'}), null, function() {}); $(this).hide(); return false">do ulubionych</a>';
		var objectId = e.opt.userid;
	}
	

	//object from list
	if(e.opt.fromlist) {
		if(e.opt.location == 'favourites') {
			//remove entire row to refresh list
			$('li.result[data-id="' + objectId + '"]').closest('div.favouriteRow').slideUp('slow', function() {
				$(this).remove();
			});
		}
		else {
			//change favLink only
			$('li#favOperation_' + objectId).html(favLinkHtml);
		}
	}
	//no photo from list, main photo assumed
	else {
		$('div#addToFavouriteDiv').html(favLinkHtml); 
	}
	
	e.scope.parents(window).dialog('close');
	
});
function deleteUser() {
    var ans = confirm(_('Czy na pewno chcesz usunąć konto?'));
    if(ans) {
	window.location = url('/user/delete');
    }
    return;
}


$.bind('experiment', function(e) {
	var tagRegex = '/^[0-9]$/';
//pSpell
	var options = new Array(5);
	options["delay"] = 300;
	options["multiple"] = true;
	options["scroll"] = false;
	options["autofill"] = false;
	options["mustMatch"] = false;
	options["minChars"] = 3; ///<Minimalna ilość znaków, jaką użytkownik musi wpisać, aby autocompleter zadziałał
	options["selectFirst"] = false; ///<wartość ustalona na true powoduje na automatyczne wybranie pierwszje podpowiedzi w momencie wciśnięcia przecinka bądź tab
	
	$('#tags').alpha({allow : "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- _"});
	$('#tags').autocomplete(url('/eksperyment/tagSuggestion'), options);
	
	$('#tags').result(function(event, data, formatted) {
		$.post(url('/eksperyment/tagSuggestionStat'), {tag: data});
	});
	
	$('.mainTagLink').bind('click', function(){
		e.scope.load($(this).attr('alt'));
	});
	
	$('#photoSkipButton').bind('click', function(f) {
		$('#tags').val('');
		e.scope.parents('form').trigger('submit');
		f.preventDefault();
	});
});

$.bind('experimentEnd', function(e) {
	e.scope.find('.linkTip')
	.bind('mouseenter', function() {
		$('#' + $(this).attr('alt')).show();
	})
	.bind('mouseleave', function() {
		$('#' + $(this).attr('alt')).hide();
	});
});

$.bind('expRedirect', function(e) {
	window.location = url('/eksperyment/index');
});
$.bind('experiment/survey', function(e) {
	e.scope.find('a').bind('click', function() {
		if ($(this).parent().hasClass('checked'))
			$(this).parent().removeClass('checked');
		else
			$(this).parent().addClass('checked');
		$.post(url('eksperyment/survey'), {'save' : 1, 'text' : $(this).text(), 'checked' : $(this).parent().hasClass('checked')});
	});
	$('#saveSurveyDiv').dialog();
	$('#saveSurveyDiv').dialog('option', 'modal', true);
	$('#saveSurveyDiv').dialog('option', 'buttons',
		{
		"OK": function() {
			$(this).dialog("close");
			}
		}
	);
	$('#saveSurveyDiv').dialog('option', 'title', _('Similaria.pl - Ankieta'));
	$('#saveSurveyDiv').dialog('close');
	e.scope.find('#saveSurvey').bind('click', function() {
		$('#saveSurveyDiv').dialog('open');
	});
});

$.bind('experiment/surveyClose', function(e) {
	e.scope.find('button#close').bind('click', function() {
		$('#saveSurveyDiv').dialog('close');
	})
});

$.bind('explore/startExplore', function(e){
	e.scope.bind('click', function() {
		$('<div class="ExploreDiv"></div>')
			.load(url('/explore/startExplore', {start:0}))
			.dialog({
				dialogClass: 'ExploreDiv',
				draggable: false,
				width: 790,
				height: 400,
				modal: true,
				resizable: false,
				title: _('EKSPLORUJ'),
				close: function(event, ui) {
					$('.testDialogParentDiv').remove();
					$('.ac_results').remove();
				}

			});
		});
});
$.bind('facebook/select/enable', function(e) {
	$.one(e.opt.enable, function() {
		e.scope.load(url('/user/select/facebook'));
	});
});
$.bind('facebook/share/images', function(e) {
	/* \todo */
	e.scope.bind('click', function() {
		var data = $('#ekspImages').serializeArray();
		if (!data.length) {
			notify(_('Wybierz zdjecia'), 'facebookShareMsg' );
			return false;
		}

		var res;
		$.ajax({
			type: 'POST',
			url: url('/eksperyment/publish/images', e.opt),
			async: false,
			data: $.flattenArray(data),
			success: function(data) { res = data; }});
		FB_RequireFeatures(['Connect'], function() {
			FB.Connect.requireSession(function() { FB.Connect.streamPublish(res); });
		});

		return false;
	});
});
var GSFN = {};
 
$.bind('feedback', function() {

if(!GSFN.initialized) {
  
  GSFN.gId = function(id) {
    return document.getElementById(id);
  };

  GSFN.hasClassName = function(element, className) {
    var elementClassName = element.className;

    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  };

  GSFN.addClassName = function(element, className) {
    if (!GSFN.hasClassName(element, className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
  };

  GSFN.removeClassName = function(element, className) {
    var newClass = GSFN.strip(element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' '));
    element.className = newClass;
    return element;
  };

  GSFN.strip = function(string) {
    return string.replace(/^\s+/, '').replace(/\s+$/, '');
  };
  
  GSFN.add_css = function(css_content) {
    var head = document.getElementsByTagName('head')[0];
    var style = document.createElement('style');
    style.type = 'text/css';
    
    if(style.styleSheet) {
      style.styleSheet.cssText = css_content;
    } else {
      rules = document.createTextNode(css_content);
      style.appendChild(rules);
    }
    head.appendChild(style);
  }

  GSFN.initialized = true;
}

GSFN.feedback_widget = function(options) {
  this.options = options;
  this.is_ssl = ("https:" == document.location.protocol);
  
  if(!this.options.display){ this.options.display = "overlay";}
  
  if(this.is_ssl) {
    this.feedback_base_url = this.local_ssl_base_url;
    this.asset_base_url = this.s3_ssl_base_url;
  } else {
    this.feedback_base_url = this.local_base_url;
    this.asset_base_url = this.s3_base_url;
  }
  
  if(this.options.local_assets == true) {
    this.asset_base_url = this.feedback_base_url;  
  }

  var disable_tagging = this.options.auto_tag == false;

  query_string_obj = [];
  
  if(!disable_tagging){
    if(this.options.product){ 
      query_string_obj.push("product=" + encodeURIComponent(this.options.product));
    }
  
    if(this.options.tag){
      query_string_obj.push("tag=" + encodeURIComponent(this.options.tag));
    }
  
    if(this.options.user_defined_code){ 
      query_string_obj.push("user_defined_code=" + encodeURIComponent(this.options.user_defined_code));
    }
  }
  
  if(this.options.display){ 
    query_string_obj.push("display=" + encodeURIComponent(this.options.display));
  }
  
  if(this.options.style){ 
    query_string_obj.push("style=" + encodeURIComponent(this.options.style));
  }
  
  if(this.options.popular_topics){ 
    query_string_obj.push("popular_topics=" + encodeURIComponent(this.options.popular_topics));
  }

  if(this.options.limit){
    query_string_obj.push("limit=" + encodeURIComponent(this.options.limit));
  }
  
  if(this.options.problem){ 
    query_string_obj.push("problem=" + encodeURIComponent(this.options.problem));
  }
    
  if(this.options.powered_by){ 
    query_string_obj.push("powered_by=" + encodeURIComponent(this.options.powered_by));
  }
  
  if(this.options.custom_css){
    query_string_obj.push("custom_css=" + encodeURIComponent(this.options.custom_css));
  }
  
  if(this.options.auto_tag == false){
    query_string_obj.push("auto_tag=" + encodeURIComponent(this.options.auto_tag));
  }
  
  if(this.options.interstitial) {
    query_string_obj.push("interstitial=" + encodeURIComponent(this.options.interstitial));
  }
  
  if(this.options.community_base_url) {
    query_string_obj.push("community_base_url=" + encodeURIComponent(this.options.community_base_url));
  }
  
  query_string = "?" + query_string_obj.join("&");

  this.feedback_url = this.feedback_base_url + "/" + this.options.company + "/feedback/topics/new" + query_string;
  
  this.options = options ? options : {};
  this.options.placement = this.options.placement ? this.options.placement : 'left';
  this.options.color = this.options.color ? this.options.color : '#222';

  if(this.options.display == 'overlay') {
    this.initial_iframe_url = this.empty_url();
    if(!this.options.width)   { this.options.width = "658px"; }
    if(!this.options.height)  { this.options.height = "100%"; }
  } else {
    this.initial_iframe_url = this.feedback_url;
    if(!this.options.width)   { this.options.width = "100%"; }
    if(!this.options.height)  { this.options.height = "500px"; }
  }
  
  this.iframe_html = '<iframe id="fdbk_iframe" allowTransparency="true" scrolling="no" frameborder="0" class="loading"' +
                      ' src="'    + this.initial_iframe_url + '"' +
                      ' width="'  + this.options.width + '"' +
                      ' height="'  + this.options.height + '"' +
                      ' style="width: '  + this.options.width + '; height: '  + this.options.height + ';"></iframe>';
  
  this.tab_html = '<a href="#" id="fdbk_tab" class="fdbk_tab_'+this.options.placement+'" style="background-color:'+this.options.color+'">' + _('FEEDBACK') + '</a>';
  this.overlay_html = '<div id="fdbk_overlay" style="display:none">' +
                        '<div id="fdbk_container">' +
                          '<a href="#" id="fdbk_close"></a>' +
                          this.iframe_html + 
                        '</div>' +
                        '<div id="fdbk_screen"></div>' +
                      '</div>';
  
  if(this.options.display == 'overlay') {
    raw_css = "#fdbk_overlay {\n  width: 100%;\n  height: 100%;\n  top: 0;\n  left: 0;\n  z-index: 1000000;\n  position: absolute; }\n\n#fdbk_screen {\n  top: 0;\n  left: 0;\n  z-index: 1;\n  width: 100%;\n  position: absolute;\n  background-color: #000;\n  opacity: 0.45;\n  -moz-opacity: 0.45;\n  filter: alpha(opacity=45); }\n\n#fdbk_container {\n  width: 680px;\n  height: 640px;\n  margin: 0 auto;\n  z-index: 2;\n  position: relative; }\n  #fdbk_container iframe {\n    width: 658px;\n    height: 100%;\n    margin: 20px;\n    background: transparent; }\n  #fdbk_container iframe.loading {\n    background: transparent url(https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/fb_loading.png) no-repeat; }\n\na#fdbk_tab {\n  top: 25%;\n  left: 0;\n  width: 42px;\n  height: 102px;\n  color: #FFF;\n  cursor: pointer;\n  text-indent: -100000px;\n  overflow: hidden;\n  position: fixed;\n  z-index: 100000;\n  margin-left: -7px;\n  background-image: url(https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/feedback_trans_tab.png);\n  _position: absolute;\n  _background-image: url(https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/feedback_tab_ie6.png); }\n  a#fdbk_tab:hover {\n    margin-left: -4px; }\n\na.fdbk_tab_right {\n  right: 0 !important;\n  left: auto !important;\n  margin-right: 0 !important;\n  margin-left: auto !important;\n  width: 35px !important; }\n  a.fdbk_tab_right:hover {\n    width: 38px !important;\n    margin-right: 0 !important;\n    margin-left: auto !important; }\n\na.fdbk_tab_bottom {\n  top: auto!important;\n  bottom: 0 !important;\n  left: 20% !important;\n  height: 38px !important;\n  width: 102px !important;\n  background-position: 0 -102px !important;\n  margin-bottom: -7px !important;\n  margin-left: auto !important; }\n  a.fdbk_tab_bottom:hover {\n    margin-bottom: -4px !important;\n    margin-left: auto !important; }\n\na.fdbk_tab_hidden {\n  display: none !important; }\n\na#fdbk_close {\n  position: absolute;\n  cursor: pointer;\n  outline: none;\n  top: 0;\n  left: 0;\n  z-index: 4;\n  width: 42px;\n  height: 42px;\n  overflow: hidden;\n  background-image: url(https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/feedback-close.png);\n  _background: none;\n  _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='https:\/\/s3.amazonaws.com\/getsatisfaction.com\/images\/feedback-close.png', sizingMethod='crop'); }\n  a#fdbk_close:hover {\n    background-position: -42px 0; }\n\n.feedback_tab_on embed, .feedback_tab_on select, .feedback_tab_on object {\n  visibility: hidden; }\n";
	  replacer_regex = new RegExp(this.s3_ssl_base_url, "g");
    translated_css = raw_css.replace(replacer_regex, this.asset_base_url);
    GSFN.add_css(translated_css);
    
    if(this.options.container) {
      var container_el = GSFN.gId(this.options.container); 
      container_el.innerHTML = this.tab_html + this.overlay_html;
    } else {
      try {document.write(this.tab_html); }catch(err){$('#feedback').append(this.tab_html)};
      try {document.write(this.overlay_html);  }catch(err){$('#feedback').append(this.overlay_html)};    
    }
    
    var feedback_obj = this;
    GSFN.gId('fdbk_tab').onclick = function() { feedback_obj.show(); return false; }
    GSFN.gId('fdbk_close').onclick = function() { feedback_obj.hide(); return false; }
    GSFN.gId('fdbk_iframe').setAttribute("src", this.empty_url());

  } else {
    if(this.options.container) {
      var container_el = GSFN.gId(this.options.container);
      container_el.innerHTML = this.iframe_html; 
    } else {
      try {document.write(this.iframe_html);  }catch(err){$('#feedback').append(this.iframe_html)};
    }
  }

};

GSFN.feedback_widget.prototype = {
  local_base_url: "http:\/\/getsatisfaction.com",
  local_ssl_base_url: "https:\/\/getsatisfaction.com",
  s3_base_url: "http://s3.amazonaws.com/getsatisfaction.com",
  s3_ssl_base_url: "https://s3.amazonaws.com/getsatisfaction.com",
  
  asset_url: function(asset) {
    return this.asset_base_url + asset;
  },
  
  empty_url : function() {
    return this.asset_url("/images/transparent.gif");
  },
  
  set_position : function() {
    this.scroll_top = document.documentElement.scrollTop || document.body.scrollTop;
    this.scroll_height = document.documentElement.scrollHeight;
    this.client_height = window.innerHeight || document.documentElement.clientHeight;
    
    GSFN.gId('fdbk_screen').style.height = this.scroll_height+"px";
    GSFN.gId('fdbk_container').style.top = this.scroll_top+(this.client_height*0.1)+"px";
  },
  
  show : function() {
    GSFN.gId('fdbk_iframe').setAttribute("src", this.feedback_url);
    if (GSFN.gId('fdbk_iframe').addEventListener) {
      GSFN.gId('fdbk_iframe').addEventListener("load", this.loaded, false);
    } else if (GSFN.gId('fdbk_iframe').attachEvent) {
      GSFN.gId('fdbk_iframe').attachEvent("onload", this.loaded);
    }
    this.set_position();

    GSFN.addClassName(document.getElementsByTagName('html')[0], 'feedback_tab_on');
    GSFN.gId('fdbk_overlay').style.display = "block";
  },
  
  hide : function() {
    if (GSFN.gId('fdbk_iframe').addEventListener) {
      GSFN.gId('fdbk_iframe').removeEventListener("load", this.loaded, false);
    } else if (GSFN.gId('fdbk_iframe').attachEvent) {
      GSFN.gId('fdbk_iframe').detachEvent("onload", this.loaded);
    }
    
    GSFN.gId('fdbk_overlay').style.display = "none";
    GSFN.gId('fdbk_iframe').setAttribute("src", this.empty_url());
    GSFN.gId('fdbk_iframe').className = "loading";

    GSFN.removeClassName(document.getElementsByTagName('html')[0], 'feedback_tab_on');
  },
  
  loaded : function() {
    GSFN.gId('fdbk_iframe').className = "loaded";
  }
}

var feedback_widget = new GSFN.feedback_widget({
	display: 'overlay',
	company: 'similaria',
	placement: 'right',
	color: '#222',
	style: 'idea'});
});$.bind('gmail/select/enable', function(e) {
	$.one('user/import/closed', function() {
		e.scope.load(url('/user/select/gmail'));
	});
});
$.bind('group', function(e) {
	e.scope.find('#groupMainCategory').bind('change', function(){
		e.scope.load(url('/group/create'), {'groupMainCategoryId':$('#groupMainCategory').val()});
	});
	e.scope.find('#addTag').bind('click', function(el){
		ob = $('#groupTag'); 
		if ((groupTag = ob.val()) != '') {
			$('#tagListDiv').append(groupTag+'<br/>');
			$('#tagList').val($('#tagList').val() + groupTag + ';');
			ob.val('');
		}
	});
	$("#groupSubCategorySearch").autocomplete($('#groupSubCategoryList').val().split(';'), {'autoFill':true, 'mustMatch':true})
});$.bind('group/create', function(e) {
	e.scope.find('#groupMainCategory').bind('change', function(){
		e.scope.load(url('/group/create'+window.location.search), {'groupMainCategoryId':$('#groupMainCategory').val()});
	});
	$("#groupSubCategorySearch").autocomplete($('#groupSubCategoryList').val().split(';'), {'autoFill':true, 'mustMatch':true});
});
$.bind('group/list', function(e) {
	e.scope.find('.categoryLink').bind('click', function() {
		e.scope.find('#' + $(this).attr('alt')).toggle();
		e.scope.find('#' + $(this).attr('alt')).load(url('/group/index'), { 'getList' : $(this).attr('rel'), 'parentId' : $(this).attr('alt')});
	});
});;(function($) {
	$.extend({
		jsAdd: function(src, obj, callback) {
			if (undefined === callback) callback = function() { };
			if (!obj || (undefined === window[obj]))
				$('body').append('<script type="text/javascript" src="'+ src +'"></sript>');
			function wait() {
				if (undefined === window[obj]) {
					setTimeout(wait, 250);
				} else callback();
			}
			if (obj) wait();
				else callback();
		}});
})(jQuery);
/**
 * jquery.simpletip 1.3.1. A simple tooltip plugin
 * 
 * Copyright (c) 2009 Craig Thompson
 * http://craigsworks.com
 *
 * Licensed under GPLv3
 * http://www.opensource.org/licenses/gpl-3.0.html
 *
 * Launch  : February 2009
 * Version : 1.3.1
 * Released: February 5, 2009 - 11:04am
 */
(function($){

   function Simpletip(elem, conf)
   {
      var self = this;
      elem = jQuery(elem);
      
      var tooltip = jQuery(document.createElement('div'))
                     .addClass(conf.baseClass)
                     .addClass( (conf.fixed) ? conf.fixedClass : '' )
                     .addClass( (conf.persistent) ? conf.persistentClass : '' )
                     .html(conf.content)
                     .appendTo(elem);
      
      if(!conf.hidden) tooltip.show();
      else tooltip.hide();
      
      if(!conf.persistent)
      {
         elem.hover(
            function(event){ self.show(event) },
            function(){ self.hide() }
         );
         
         if(!conf.fixed)
         {
            elem.mousemove( function(event){ 
               if(tooltip.css('display') !== 'none') self.updatePos(event); 
            });
         };
      }
      else
      {
         elem.click(function(event)
         {
            if(event.target === elem.get(0))
            {
               if(tooltip.css('display') !== 'none')
                  self.hide();
               else
                  self.show();
            };
         });
         
         jQuery(window).mousedown(function(event)
         { 
            if(tooltip.css('display') !== 'none')
            {
               var check = (conf.focus) ? jQuery(event.target).parents('.tooltip').andSelf().filter(function(){ return this === tooltip.get(0) }).length : 0;
               if(check === 0) self.hide();
            };
         });
      };
      
      
      jQuery.extend(self,
      {
         getVersion: function()
         {
            return [1, 2, 0];
         },
         
         getParent: function()
         {
            return elem;
         },
         
         getTooltip: function()
         {
            return tooltip;
         },
         
         getPos: function()
         {
            return tooltip.offset();
         },
         
         setPos: function(posX, posY)
         {
            var elemPos = elem.offset();
            
            if(typeof posX == 'string') posX = parseInt(posX) + elemPos.left;
            if(typeof posY == 'string') posY = parseInt(posY) + elemPos.top;
            
            tooltip.css({ left: posX, top: posY });
            
            return self;
         },
         
         show: function(event)
         {
            conf.onBeforeShow.call(self);
            
            self.updatePos( (conf.fixed) ? null : event );
            
            switch(conf.showEffect)
            {
               case 'fade': 
                  tooltip.fadeIn(conf.showTime); break;
               case 'slide': 
                  tooltip.slideDown(conf.showTime, self.updatePos); break;
               case 'custom':
                  conf.showCustom.call(tooltip, conf.showTime); break;
               default:
               case 'none':
                  tooltip.show(); break;
            };
            
            tooltip.addClass(conf.activeClass);
            
            conf.onShow.call(self);
            
            return self;
         },
         
         hide: function()
         {
            conf.onBeforeHide.call(self);
            
            switch(conf.hideEffect)
            {
               case 'fade': 
                  tooltip.fadeOut(conf.hideTime); break;
               case 'slide': 
                  tooltip.slideUp(conf.hideTime); break;
               case 'custom':
                  conf.hideCustom.call(tooltip, conf.hideTime); break;
               default:
               case 'none':
                  tooltip.hide(); break;
            };
            
            tooltip.removeClass(conf.activeClass);
            
            conf.onHide.call(self);
            
            return self;
         },
         
         update: function(content)
         {
            tooltip.html(content);
            conf.content = content;
            
            return self;
         },
         
         load: function(uri, data)
         {
            conf.beforeContentLoad.call(self);
            
            tooltip.load(uri, data, function(){ conf.onContentLoad.call(self); });
            
            return self;
         },
         
         boundryCheck: function(posX, posY)
         {
            var newX = posX + tooltip.outerWidth();
            var newY = posY + tooltip.outerHeight();
            
            var windowWidth = jQuery(window).width() + jQuery(window).scrollLeft();
            var windowHeight = jQuery(window).height() + jQuery(window).scrollTop();
            
            return [(newX >= windowWidth), (newY >= windowHeight)];
         },
         
         updatePos: function(event)
         {
            var tooltipWidth = tooltip.outerWidth();
            var tooltipHeight = tooltip.outerHeight();
            
            if(!event && conf.fixed)
            {
               if(conf.position.constructor == Array)
               {
                  posX = parseInt(conf.position[0]);
                  posY = parseInt(conf.position[1]);
               }
               else if(jQuery(conf.position).attr('nodeType') === 1)
               {
                  var offset = jQuery(conf.position).offset();
                  posX = offset.left;
                  posY = offset.top;
               }
               else
               {
                  var elemPos = elem.position(); //offset();
		  var elemOffset = elem.offset();
                  var elemWidth = elem.outerWidth();
                  var elemHeight = elem.outerHeight();
                  
                  switch(conf.position)
                  {
                     case 'top':
                        var posX = elemPos.left - (tooltipWidth / 2) + (elemWidth / 2);
                        var posY = elemPos.top - tooltipHeight;
                        break;
                        
                     case 'bottom':
                        var posX = elemPos.left - (tooltipWidth / 2) + (elemWidth / 2);
                        var posY = elemPos.top + elemHeight;
                        break;
                     
                     case 'left':
                        var posX = elemPos.left - tooltipWidth;
                        var posY = elemPos.top - (tooltipHeight / 2) + (elemHeight / 2);
                        break;
                        
                     case 'right':
                        var posX = elemPos.left + elemWidth;
                        var posY = elemPos.top - (tooltipHeight / 2) + (elemHeight / 2);
                        break;
                     
                     default:
                     case 'default':
                        var posX = elemPos.left - tooltipWidth - 20;
                        var posY =  elemPos.top;
                        break;
                  };
               };
            }
            else
            {
               var posX = event.pageX;
               var posY = event.pageY;
            };
            
            if(typeof conf.position != 'object')
            {
               posX = posX + conf.offset[0];
               posY = posY + conf.offset[1]; 
               
               if(conf.boundryCheck)
               {
                  var overflow = self.boundryCheck(posX, posY);
                                    
                  if(overflow[0]) posX = posX - (tooltipWidth / 2) - (2 * conf.offset[0]);
                  if(overflow[1]) posY = posY - (tooltipHeight / 2) - (2 * conf.offset[1]);
               }
            }
            else
            {
               if(typeof conf.position[0] == "string") posX = String(posX);
               if(typeof conf.position[1] == "string") posY = String(posY);
            };
            
            self.setPos(posX, posY);
            
            return self;
         }
      });
   };
   
   jQuery.fn.simpletip = function(conf)
   { 
      // Check if a simpletip is already present
      var api = jQuery(this).eq(typeof conf == 'number' ? conf : 0).data("simpletip");
      if(api) return api;
      
      // Default configuration
      var defaultConf = {
         // Basics
         content: 'A simple tooltip',
         persistent: false,
         focus: false,
         hidden: true,
         
         // Positioning
         position: 'default',
         offset: [0, 0],
         boundryCheck: true,
         fixed: true,
         
         // Effects
         showEffect: 'fade',
         showTime: 150,
         showCustom: null,
         hideEffect: 'fade',
         hideTime: 150,
         hideCustom: null,
         
         // Selectors and classes
         baseClass: 'tooltip',
         activeClass: 'active',
         fixedClass: 'fixed',
         persistentClass: 'persistent',
         focusClass: 'focus',
         
         // Callbacks
         onBeforeShow: function(){},
         onShow: function(){},
         onBeforeHide: function(){},
         onHide: function(){},
         beforeContentLoad: function(){},
         onContentLoad: function(){}
      };
      jQuery.extend(defaultConf, conf);
      
      this.each(function()
      {
         var el = new Simpletip(jQuery(this), defaultConf);
         jQuery(this).data("simpletip", el);  
      });
      
      return this; 
   };
})();
var globalInterval = null;
var debug = {
    info: function(text) {
	$('#scrollDebug').append('<p>'+text+'</p>');
    }
}

var scroll = {
    intervalId: null,
    startScroll: function(options) {
	this.stopScroll();
	var intervalSpeed = options.intervalSpeed == undefined ? 20 : options.intervalSpeed
        var scrolling = document.getElementById(options.scrolling);
	if(!scrolling) return;
        var scrollingCopy = document.getElementById(options.scrolling+'Copy');
        var stopPosition = options.stopPosition;
	    if(parseInt(scrolling.style.left) >= -1*options.stopPosition) {
                scrolling.style.left = parseInt(scrolling.style.left) - 1 + 'px';
                scrollingCopy.style.left = parseInt(scrollingCopy.style.left) - 1 + 'px';
            } else {
                scrolling.style.left = (options.stopPosition)+'px';
            }

            if(parseInt(scrollingCopy.style.left) >= -1*options.stopPosition) {
                scrolling.style.left = parseInt(scrolling.style.left) - 1 + 'px';
                scrollingCopy.style.left = parseInt(scrollingCopy.style.left) - 1 + 'px';
            } else {
                scrollingCopy.style.left = (options.stopPosition)+'px';
	    }
        
        if(this.intervalId == null) {
            this.intervalId = setInterval('scroll.startScroll({scrolling: "'+options.scrolling+'", stopPosition: '+stopPosition+', intervalSpeed: '+intervalSpeed+'})', intervalSpeed);
        }
    },
	startScrollOposite: function(options) {
		this.stopScroll();
		var intervalSpeed = options.intervalSpeed == undefined ? 20 : options.intervalSpeed
        var scrolling = document.getElementById(options.scrolling);
        if(!scrolling) return;
        var scrollingCopy = document.getElementById(options.scrolling+'Copy');
        var stopPosition = options.stopPosition;

            if(parseInt(scrolling.style.left) <= options.stopPosition) {
                scrolling.style.left = parseInt(scrolling.style.left) + 1 + 'px';
                scrollingCopy.style.left = parseInt(scrollingCopy.style.left) + 1 + 'px';
            } else {
                scrolling.style.left = (-1*options.stopPosition)+'px';
            }

            if(parseInt(scrollingCopy.style.left) <= options.stopPosition) {
		scrolling.style.left = parseInt(scrolling.style.left) + 1 + 'px';
                scrollingCopy.style.left = parseInt(scrollingCopy.style.left) + 1 + 'px';
            } else {
                scrollingCopy.style.left = (-1*options.stopPosition)+'px';
	    }
	    
        if(this.intervalId == null) {
            this.intervalId = setInterval('scroll.startScrollOposite({scrolling: "'+options.scrolling+'", stopPosition: '+stopPosition+', intervalSpeed: '+intervalSpeed+'})', intervalSpeed);
        }
    },

    stopScroll: function() {
        if(this.intervalId  != null) {
			clearInterval(this.intervalId);
			this.intervalId = null;
        }
    }
}

var contWidth = parseInt($('#userPhotos #userPhotoCont #userPhotoScroll').css('width'));
$('#userPhotos #userPhotoCont #userPhotoScrollCopy').css('left',contWidth);

globalInterval = setInterval('scroll.startScrollOposite({scrolling: "userPhotoScroll", stopPosition: '+contWidth+', intervalSpeed: 70})', 70);

$('#userPhotos #userPhotoCont #leftArrow').bind({
    mouseover: function() {
	clearInterval(globalInterval);
	scroll.startScroll({
	    scrolling: 'userPhotoScroll',
            stopPosition: contWidth,
	    intervalSpeed: 30
	});
    },
    mouseout: function() {
	scroll.stopScroll();
	globalInterval = setInterval('scroll.startScrollOposite({scrolling: "userPhotoScroll", stopPosition: '+contWidth+', intervalSpeed: 70})', 70);
    }
});

$('#userPhotos #userPhotoCont #rightArrow').bind({
    mouseover: function() {
	clearInterval(globalInterval);
	scroll.startScrollOposite({
	    scrolling: 'userPhotoScroll',
            stopPosition: contWidth,
	    intervalSpeed: 30
	});
    },
    mouseout: function() {
	scroll.stopScroll();
	globalInterval = setInterval('scroll.startScrollOposite({scrolling: "userPhotoScroll", stopPosition: '+contWidth+', intervalSpeed: 70})', 70);
    }
});

$.bind('messages/write', function(e) {
	e.scope.find('#msgSendBttn').bind('click', function() {
		$.dialog({url: url('/messages/send'), title:_('Nowa wiadomość'), width: 440});
	});
});

$.bind('messages/read', function(e) {
	$('.msgReadBttn').bind('click', function() {
		$.dialog({url: url('/messages/read', {msg : $(this).attr('alt')}), title:_('Wiadomość')});
	});
});

$.bind('messages/rm', function(e) {
	$('#msgRmBttn').bind('click', function() {
		window.location = url('/messages/rm', {id : $('.msgRmChkbox:checked').values()});
	});
});

$.bind('messages/writeTo', function(e) {
	var location = window.location.toString().split('/');
		location = location[location.length-1];
	
	$('.msgSendBttn').unbind('click');
	$('.msgSendBttn').bind('click', function() {
		$.dialog({url: url('/messages/send', {reciever: $(this).attr('alt')}), title:_('Nowa wiadomość'), width: 440});
	});

	$('.blinkBttn').unbind('click');
	$('.blinkBttn').bind('click', function() {
		$(this).load(url('/messages/blink', {reciever : $(this).attr('alt')}));
		$(this).toggle();
	});

	$('.favAddUserBttn').unbind('click');
	$('.favAddUserBttn').bind('click', function() { 
		
		$(this).load(url('/favourites/add', {user : $(this).attr('alt'), location: location}), null, function() {
		    //window.location = url('favourites');
		});
		$(this).toggle();
	});
	$('.favAddImageBttn').unbind('click');
	$('.favAddImageBttn').bind('click', function() {
		$(this).load(url('/favourites/add', {image : $(this).attr('alt'), location: location}), null, function() {
		    //window.location = url('favourites');
		});
		$(this).toggle();
	});

});

$.bind('alerts/rm', function(e) {
	$('.alertRmBttn').bind('click', function() {
		window.location = url('/messages/rm', {id : $('.alertRmChkbox:checked').values(), route : 'alerts'});
	});
	$('.remove').bind('click', function() {
		window.location = url('/messages/rm', {id : $(this).parent().find('input').val(), route : 'alerts'});
	});
	$('.alertRmAllBttn').bind('click', function() {
		window.location = url('/messages/rm', {id : $('.alertRmChkbox').values(), route : 'alerts'});
	});
});
$(document).ready(function() {

	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		//Get the A tag
		var id = $(this).attr('href');

		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();

		//Set height and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});

		//transition effect
		$('#mask').fadeIn(1000);
		$('#mask').fadeTo("fast",0.8);

		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();

		//Set the popup window to center
		var topScroll = document.body.scrollTop?document.body.scrollTop:document.documentElement.scrollTop;
		$(id).css('top',  winH/2-$(id).height()/2 + topScroll);
		$(id).css('left', winW/2-$(id).width()/2);

		//transition effect
		$(id).fadeIn(2000);

	    });

	//if close button is clicked
	$('.window .close').click(function (e) {
                    //Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	    });

	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	    });

    });
var global_search_count = 0;
$.bind('searchCheck', function(e){
	var searchCheck = function(){
		global_search_count++;
		if(global_search_count >= 120) { //20 req * 1.5s = 30 sek, podbite do 120 żeby działało na stage
			$('#objectSearchResults').html(_('Nie znaleziono pasujących obiektów'));
			return;
		}
		$('#objectSearchResults').load(url('/search/search3', {getQueryId:e.opt._id, search:'alg', noBack:1}));
	};
	if(e.opt._id) {
		setTimeout(searchCheck, 1500);
	}
});

$.bind('myobjects/rm', function(e) {
	$('.remove').bind('click', function() {
	    //var c = confirm(_('Czy na pewno chcesz usunąć zdjęcie?'));
	   // if(c==true)
		//$.post('/s/myobjects/remove', { ekspImageId : $(this).attr('alt') } );
		
		$.dialog({
			url: url('/myobjects/remove', {ekspImageId : $(this).attr('alt') }),
			draggable: true,
			modal: true,
			dialogClass: 'simi-popup',
			resizable: false,
			title: _('Usuń obiekt'),
			position: 'center',
			width:  400,
			open: function() {
				$(this).html('<div><img src=\'/images/indicator.gif\'/></div>'); 
			},
			close: function() {
				$(this).remove();
			}
		});
		
		
		
		
	});
	$('.hideObj').bind('click', function() {
		$.post('/s/myobjects/hide', { ekspImageId : $(this).attr('alt') } );
	});
	$('.showObj').bind('click', function() {
		$.post('/s/myobjects/show', { ekspImageId : $(this).attr('alt') } );
	});
	$('.renameObj').bind('click', function() {

		var $dialog = $.dialog({
			url: url('/myobjects/rename?id=' + $(this).attr('alt')),
			title:_('Modyfikacja obiektu'),
			width: 440,
			dialogClass: 'simi-popup',
			open: function() {
				$(this).html('<div><img src=\'/images/indicator.gif\'/></div>'); 
			},
			onLoad: function(){
			    $('#renameSimiForm').unbind('closeRenameDialog');
			    $('#renameSimiForm').bind('closeRenameDialog',function() {
				    $dialog.dialog('destroy');
				    $dialog = null;
				});
				$('#renameSimiForm fieldset ol li input.simi-popup-button').bind('click', function() {
				    $('#renameSimiForm').trigger('closeRenameDialog');
				})
			}
		});
		
		

	});

});

$.bind('myobjects/hidden', function(e) {
	$('.img_' +  e.opt._id + ' .hideObj')
		.text(_('Pokaż'));
	$('.img_' +  e.opt._id + ' .hideObj')
		.removeClass('hideObj')
		.addClass('showObj')
		.unbind('click')
		.bind('click', function() {
			$.post('/s/myobjects/show', { ekspImageId : $(this).attr('alt') } );
		});


});

$.bind('myobjects/shown', function(e) {

	$('.img_' +  e.opt._id + ' .showObj')
		.text(_('Ukryj'));

	$('.img_' +  e.opt._id + ' .showObj')
		.removeClass('showObj')
		.addClass('hideObj')
		.unbind('click')
		.bind('click', function() {
			$.post('/s/myobjects/hide', { ekspImageId : $(this).attr('alt') } );
		});


});

$.bind('myobjects/removed', function(e) {
	$('.img_' +  e.opt._id).remove();
});

$.bind('myobjects/renamed', function(e) {
	$('.img_' +  e.opt._id ).find('.img-name').html(escapeHtml('„' + e.opt.description + '”')); 
});

$.bind('myobjects/changetype', function(e) {
	if(e.opt.newIcon)
		$('.img_' +  e.opt._id ).find('div dt').html(e.opt.newIcon);
	else
		$('.img_' +  e.opt._id ).find('div dt').html(''); 
});

$.bind('myobjects/form', function(e) {
    $('#type .textField .field select').bind('change', function() {
	var value = $(this).val();
	var $options = $(this).children();
	$options.each(function(i) {
	    if($(this).val() == value) {
		$('.addPhotoDiv2 #'+$(this).val()).removeClass('hidden');
                $('.addPhotoDiv2 #'+$(this).val()+' .requiredRemoved').each(function(i) {
                    $(this).removeClass('requiredRemoved');
                    $(this).addClass('required');
                    $(this).addClass('valid');
                    $(this).attr('disabled','false');
                });
	    } else  {
                $('.addPhotoDiv2 #'+$(this).val()+' .required').each(function(i) {
                    $(this).removeClass('required');
                    $(this).removeClass('valid');
                    $(this).addClass('requiredRemoved');
                    $(this).attr('disabled','true');
                });
		$('.addPhotoDiv2 #'+$(this).val()).addClass('hidden');
	    }
	})
    });
});

$.bind('myobjects/filter', function(e){
	try {

		//ie hack - inaczej przełącza się w tryb zgodności i /favourites się rozwala
		$(window).load(function(){
			$('select#category').dropdownchecklist({
				closeRadioOnClick: false,
				firstItemChecksAll: true, 
				forceMultiple: true,
				emptyText: _('Wybierz...'),
				icon: {placement: 'right', toOpen: 'ui-icon-triangle-1-w'}, 
				width: 150,
				positionHow: 'relative',
				onComplete: function (selector) {
					/* #5165, usuwamy defaultowe zaznaczanie wszystkich, kiedy nic nie wybrano
					if(!$('select#category').val()) {
						for(var i = 0; i< $('select#category')[0].options.length; i++)
							$('select#category')[0].options[i].selected="selected";
						$("select#category").dropdownchecklist("refresh");
					}
					*/
					if($('select#category').val()) {
						var values = $.grep($('select#category').val(), function(v){ return v != 'all' && v != ''});
						if(values.length > 0) {
							if (e.opt.tab == 'myobjects')
								window.location = url('myobjects/', {type:values.join(',')});
							if (e.opt.tab == 'favourites')
								window.location = url('favourites/', {type:values.join(',')});
							if (e.opt.tab == 'similars')
								window.location = url('similars/', {type:values.join(',')});
						}
						
					}					
				} 
			});
			$('select#category').dropdownchecklist('_syncSelected');
		});
	} catch(e) {};
	try {
	    $options = $('#ddcl-category-ddw').children('div').children('div');
	    first = $options[0];
	    $(first).after('<div><div id="horizLine"></div></div>');
	} catch(e) {}
});
/**
 * Funkcja zmienia password_box w zależności od wprowadzonego ciagu znaków
 * @author Elban
 */

$("#password")
		.bind(
				"keyup",
				function(e) {
					if ($(this).val().length < 4) {
						$("#password_box").removeClass().addClass('smallStrength');
					} else if (($(this).val().length < 6)
							|| (checkRegExp($(this).val()) == 1)) { // jeżeli długość
															// znaków jest
															// mniejsza 6 lub
															// (większa równa 6
															// i zawiera tylko
															// jeden znak)
						$("#password_box").removeClass().addClass('mediumStrength');
					} else if (checkRegExp($(this).val()) > 1) {
						$("#password_box").removeClass().addClass('largeStrength');
					}
				});
/**
 * Funkcja zwraca ile różnych znaków zawiera ciąg string
 * @author Elban
 * @param string
 *            ciąg do sprawdzenia
 * @return counter ile wystąpiło różnych znaków
 */
function checkRegExp(checkString) {
	var count = 0;
	if (checkString.match(/[a-zA-Z]/)) count++;
	if (checkString.match(/[0-9]/)) count++;
	if (checkString.match(/[^0-9a-zA-Z]/)) count++;
	return count;
};
$.bind('photosimimap', function(e) {
    function slide(event, ui) {
	$('#simimapContainer').load(url('simimap',{'slider': ui.value, 'sliderName': $(this).attr('id'), 'currentPhoto': $(this).attr('currentPhoto')}));
    }
    $('.slider').each(function(index) {
	$(this).slider({min:-1, max:1, step:0.00001, value: $(this).attr('simi'), animate:true, change:slide});
     });

     $('#photoSimilarTabs #searchTabs').tabs({
		selected:0
     });


     		if($('li#searchTabs1').hasClass('ui-tabs-selected')) {
                $('li#searchTabs2').removeClass('selectedTab');
                $('li#searchTabs1').addClass('selectedTab');
            }
            if($('li#searchTabs2').hasClass('ui-tabs-selected')) {
                $('li#searchTabs2').addClass('selectedTab');
                $('li#searchTabs1').removeClass('selectedTab');
            }

     $('a[href=#searchTabs-1]').bind({
         click: function() {
             $('li#searchTabs2').removeClass('selectedTab');
             $('li#searchTabs1').addClass('selectedTab');
			 $("select#category option[value='-1']").remove(); 
			 $('div.ui-dropdownchecklist-item').remove(':contains("użytkownicy")');
			 
	 		 $('select#category').append('<option value="-1">użytkownicy</option>');
			 $('div.ui-dropdownchecklist-dropcontainer').append('<div class="ui-dropdownchecklist-item ui-state-default" style="white-space: nowrap;"><input value="-1" index="3" disabled="disabled" id="ddcl-category-i3" class="active" tabindex="0" type="checkbox"><label style="cursor: default;" class="ui-dropdownchecklist-text" for="ddcl-category-i3">użytkownicy</label></div>');
			 
         }
     })

     $('a[href=#searchTabs-2]').bind({
         click: function() {
             $('li#searchTabs2').addClass('selectedTab');
             $('li#searchTabs1').removeClass('selectedTab');
			 $("select#category option[value='-1']").remove(); 
			 $('div.ui-dropdownchecklist-item').remove(':contains("użytkownicy")');
         }
     });

try {
	
	
		$('select#category').dropdownchecklist({
			closeRadioOnClick: false,
			firstItemChecksAll: true,
			forceMultiple: true,
			emptyText: _('Wybierz...'),
			icon: {placement: 'right', toOpen: 'ui-icon-triangle-1-w'},
			width: 150,
			onComplete: function (selector) {
				/* #5165, usuwamy defaultowe zaznaczanie wszystkich, kiedy nic nie wybrano
				if(!$('select#category').val()) {
					for(var i = 0; i< $('select#category')[0].options.length; i++)
						$('select#category')[0].options[i].selected="selected";
					$("select#category").dropdownchecklist("refresh");
				}
				*/
				if($('select#category').val()) {
					
					var values = $.grep($('select#category').val(), function(v){ return v != 'all' && v != ''});
					var activeTabDiv = $($('#searchTabs')
						.tabs('widget')
						.find('li.ui-tabs-selected')
						.attr('class')
						.split(/\s+/))
						.filter(function(k,v){return v.indexOf('searchTab') > -1})[0]
						.replace('-nav','');
					switch(activeTabDiv) {

						case 'searchTabSimilar':
							$('div.searchTabSimilar div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'similar', objectsPerPage: 10, id: $('div.searchTabSimilar').attr('data-id') , types: values.join(',')}));

							//load to a second tab too
							$('div.searchTabMyObjects div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'myobjects', objectsPerPage: 10, userId: $('div.searchTabMyObjects').attr('data-id') , types: values.join(',')}));
							//...and third
							$('div.searchTabSolr div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'solr', objectsPerPage: 10, query: $('div.searchTabSolr').attr('data-query') , types: values.join(',')}));
								
							break;
							
						//load to both tabs at once
						case 'searchTabSolr':
						case 'searchTabAlg':
							$('div.searchTabSolr div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'solr', objectsPerPage: 10, query: $('div.searchTabSolr').attr('data-query') , types: values.join(',')}));
						
							$('div.searchTabAlg div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'alg', objectsPerPage: 10, getQueryId: $('div.searchTabAlg').attr('data-getqueryid') , types: values.join(',')}));
								
							$('div.searchTabSimilar div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'similar', objectsPerPage: 10, id: $('div.searchTabSimilar').attr('data-id') , types: values.join(',')}));
								
							break;
							
						case 'searchTabMyObjects':
							$('div.searchTabMyObjects div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'myobjects', objectsPerPage: 10, userId: $('div.searchTabMyObjects').attr('data-id') , types: values.join(',')}));
							//load to a first tab too
							$('div.searchTabSimilar div.searchTabInnerDiv')
								.load(url('/search/search3', {noBack:1, search:'similar', objectsPerPage: 10, id: $('div.searchTabSimilar').attr('data-id') , types: values.join(',')}));
								
							break;

					}
				}
			}
		});
		$('select#category').dropdownchecklist('_syncSelected');
		

	} catch(e) {};
     
});

$.bind('stepTest', function(e) {
    $('#stepTestLink').click(function(ee) {
       ee.preventDefault();
       if($('#stepTest').html() == '') {
           if(e.opt.type == 0) {
               $('#stepTest').load(url('/eksperyment/tagging', {noBack: 1, image: ''+e.opt.photoId+'', dialog: 1, modalWindowId: e.opt.modalWindowId}), function() {
           $('#stepTestLinkHidden').trigger('click');
       $('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	    });
           });
           } else {
               $('#stepTest').load(url('/eksperyment/userClanTest', {noBack: 1, EkspClanImageId: ''+e.opt.photoId+'', dialog: 1, modalWindowId: e.opt.modalWindowId}), function() {
           $('#stepTestLinkHidden').trigger('click');
       $('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	    });
           });
           }
           
       } else {
          $('#stepTestLinkHidden').trigger('click');
       $('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	    });
       }
       
    });
});



/**
 * Wysyłanie oczek i innych uśmieszków
 * @param id Osoba, której mamy wyłsąc wiadomość 
 * @param type Typ wiadomości
 * @param item Jakie pole zastapić wynikiem
 * @return HTML wyslany przez ajax
 */
function MessageSpecialSend(id, type, item) {
	$(item).parent().load(url('/user/profile/specialMessage'), {'UserId':id, 'special':type});
}

/**
 * Wysyłanie zaproszenia do znajomych.
 * @param id osoba, którą zapraszamy
 * @param item jakie pole zastąpić wynikiem
 * @return
 */
function sendInvitation(id, item) {
	$(item).parent().load(url('/user/profile/sendInvitation'), {'inviteeUserId':id});
}

function changeEyeTitle(obj) {
	if( $(obj).attr('title') == _('Kliknij na oczko, aby ukryć ten element przed innymi użytkownikami' ))
		$(obj).attr('title', _('Kliknij na oczko, aby pokazać ten element innym użytkownikom'));
	else $(obj).attr('title', _('Kliknij na oczko, aby ukryć ten element przed innymi użytkownikami'));
}$.bind('regulamin', function(e) {
	function close() {
		$('#regulamin').fadeOut(function() { $(this).remove(); });
	}
	e.scope
	.find('a[href="#add"]').bind('click', function() {
		$('body').append('<div id="regulamin" class="fade"><div /></div>');
		$('#regulamin div').load(url('/page/regulamin'), {'noHeader' : 1}, function() {
			$(this).find('a[href="#close"]').bind('click', function() {
				close();
				return false;
			}).end();
		});
	});
});
$('#reportabuse').click(function () {
	var image = window.location.href.split('photo=')[1].split('&')[0];
	image = image.substr(0, 24);
	
	$.post('/s/abuse/report?imageId='+image, {'Formabuse[_key]': $('#report form ._time').val(), 'Formabuse[report]': $('#report form #freport').val()});

	return false;
    });
try {
    $('#tags').addClass('ui-corner-all');
} catch(e) {}
/**
 * obsługa wiadomości przesyłanych w czasie rzeczywistym (w tym chat)
 */

//ustawienie domeny dokumentu - iframe z chatem musi posiadać identyczny document.domain, inaczej nie zadziała wysyłanie zapytań ajaxowych do chatu
//document.domain = window.location.hostname; http://agilo.similaria.pl/agilo/ticket/1374

/**
 * inicjalizacja komunikacji z serwerem czatu - utworzenie odpowiedzialnej za to ramki
 * parametry: eventType: typ eventów które mają być odbierane, mozliwe warto ści to events (wszystko) oraz chat 
 *
 **/
function initRTEventFrame(eventType, host, port, userId, otherParams) {
    var tempIFrame=document.createElement('iframe');
    tempIFrame.setAttribute('id','RTEventFrame');
    tempIFrame.style.display='none';
    if (eventType == 'events') {
        tempIFrame.setAttribute('src','http://' + Math.floor(Math.random()*(10000)) + '.chat.' + host + ':' + port + '/html/rteventsframe.html?userId=' + userId);
    } else if (eventType == 'chat') {
        tempIFrame.setAttribute('src','http://' + Math.floor(Math.random()*(10000)) + '.chat.' + host + ':' + port + '/html/chatframe.html?userId=' + userId + '&userName=' + otherParams['userName'] + '&userToId=' + otherParams['userToId']);
    };
    IFrameObj = document.body.appendChild(tempIFrame); 
}

/**
 * Otwarcie nowego okna chatu z podanym użytkownikiem
 * parametry: userId: tekst zawierający id użytkownika z którym chcemy nawiązać kontakt
 */
function openChatWindow(userId) {
    var url =  '/s/user/chat/userchat?userToId=' + userId;
    window.open(url, 'chat_' + userId, 'status=0,toolbar=0,location=0,menubar=0,width=400,height=600');
}

/**
 * pomocnicza funkcja do bezpiecznego wstawiania tekstu na stronę
 * */
function escapeHtml(s) {
    return s.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;');
}


/**
 *  
 */
function formatRTMsg(msg) {
    if(msg.type == 'chat') {
        var htmlMsg = '<div>' + escapeHtml(msg.time)  + ' wiadomość od <b>' + escapeHtml(msg.fromName) + '</b><br/>' + escapeHtml(msg.content)  + '<br/><a href="" onclick="openChatWindow(\''+msg.from+'\');">'+_('Kliknij aby otworzyć okno czatu')+'</a></div>';
        return htmlMsg;
    }
}

/**
 *   Funkcja wywoływana po otrzymaniu wiadomości
 *   parametry: msg: otrzymana wiadomość
 *
 **/
function recvRTMsg(msg) {
    notify(formatRTMsg(msg));
}

function sendRTMsg(msg) {
    // \todo
}
$.bind('searchInitResults', function(){
	$('li.result.img-with-cloud').each(function(idx, domnode){
		var imgId = domnode.getAttribute('data-id');
		if(imgId) {
			$(domnode).find('a[class="thumb"]').simpletip({content: '', hidden: true});
			var st = $(domnode).find('a[class="thumb"]').eq(0).simpletip();
			st.load(url('/simimap/tagcloud', {id: imgId, noBack:1} ));
		}
	});



});


$('#searchPanelBlockSearchButton button').bind('click', function(){
	document.forms['searchPanelSearchForm'].submit();
});


$.bind('searchInit', function(e){
	$('#searchTabs').tabs({
		selected: e.opt.tab == 'solr' ? 1:0,
		select: function(event, ui) {
			var tab = 'alg';
			if( ui.index == 1)
				tab = 'solr';
			$.post(url('/search/tab'), {tab:tab});
		}
	});
	
	try {
		$('select#category').dropdownchecklist({
			closeRadioOnClick: false,
			firstItemChecksAll: true, 
			forceMultiple: true,
			emptyText: _('Wybierz...'),
			icon: {placement: 'right', toOpen: 'ui-icon-triangle-1-w'}, 
			width: 150,
			onComplete: function (selector) {
				/* #5165, usuwamy defaultowe zaznaczanie wszystkich, kiedy nic nie wybrano
				if(!$('select#category').val()) {
					for(var i = 0; i< $('select#category')[0].options.length; i++)
						$('select#category')[0].options[i].selected="selected";
					$("select#category").dropdownchecklist("refresh");
				}
				*/

				if($('select#category').val()) {
				var values = $.grep($('select#category').val(), function(v){ return v != 'all' && v != ''});
					if(values.length > 0) {
						//if($('#searchTabs').tabs('option','selected') == 0) {
							var queryId = $('.searchQueryId').html();
							//$('div.searchTabAlg div.searchTabInnerDiv').load(url('/search/search3', {noBack:1, search:'alg', query:$('.searchPanelSearchForm input').get(0).value, getQueryId: queryId, types: values.join(',')}));
							$('#objectSearchResults').load(url('/search/search3', {noBack:1, search:'alg', query:$('.searchPanelSearchForm input').get(0).value, getQueryId: queryId, types: values.join(',')}));
						//} else
							//$('div.searchTabSolr div.searchTabInnerDiv').load(url('/search/search3', {noBack:1, search:'solr', query:$('.searchPanelSearchForm input').get(0).value, types: values.join(',')}));
							$('#objectSearchResults2').load(url('/search/search3', {noBack:1, search:'solr', query:$('.searchPanelSearchForm input').get(0).value, types: values.join(',')}));
					}
				}

					
			} 
		});
		$('select#category').dropdownchecklist('_syncSelected');
	} catch(e) {};
	try {
	    $options = $('#ddcl-category-ddw').children('div').children('div');
	    first = $options[0];
	    $(first).after('<div><div id="horizLine"></div></div>');
	} catch(e) {}

        if($('li#searchTabs1').hasClass('ui-tabs-selected')) {
                $('li#searchTabs2').removeClass('selectedTab');
                $('li#searchTabs1').addClass('selectedTab');
            }
            if($('li#searchTabs2').hasClass('ui-tabs-selected')) {
                $('li#searchTabs2').addClass('selectedTab');
                $('li#searchTabs1').removeClass('selectedTab');
            }

     $('a[href=#searchTabs-1]').bind({
         click: function() {
             $('li#searchTabs2').removeClass('selectedTab');
                $('li#searchTabs1').addClass('selectedTab');
         }
     })

     $('a[href=#searchTabs-2]').bind({
         click: function() {
             $('li#searchTabs2').addClass('selectedTab');
                $('li#searchTabs1').removeClass('selectedTab');
         }
     });

});



$.bind('simiLoginWord-closeDialog', function(e) {
	e.scope.bind('click', function() {
		$('.ui-dialog-content').dialog('close');
		$('#openLoginForm').trigger('click');
	});
});

$(window).load(function() {
    if($('#simiLogin').val() == '') {
        $('#simiLogin').val('email');
    
        $('#simiLogin').bind({
            click: function() {
                if($(this).attr('value') == 'email')
        	        $(this).attr('value','');
            },
            focus: function() {
                if($(this).attr('value') == 'email')
        	        $(this).attr('value','');
            },
            focusout: function() {
                $value = $(this).attr('value');
                if($value=='') {
                    $(this).attr('value','email');
        	    }
            }
        });

	$('#simiPassword').val('difoltpass');
        $('#simiPassword').bind({
            click: function() {                           	    
        	if($(this).attr('value') == 'difoltpass')     
        	    $(this).attr('value','');
            },
            focus: function() {
        	if($(this).attr('value') == 'difoltpass')
        	    $(this).attr('value','');
            },
            focusout: function() {
        	$value = $(this).attr('value');
        	if($value=='') {
        	    $(this).attr('value',_('difoltpass'));
        	}
        
            }
        });


    }


});




if($.browser.msie) {
	var $loginForm = $('#cntnt').find('form');
	var $liElement = $loginForm.find('fieldset').find('ol').find('li');
	$liElement.each(function(idx) {
		switch (idx) {
			case 0:
				$(this).addClass('ieEmailStyle');
				break;
			case 1:
				$(this).addClass('iePasswordStyle');
				break;
			case 2:
				$(this).addClass('ieRemMeStyle');
				var $remMeInput = $(this).find('label').find('input');
				$remMeInput.addClass('ieRemMeInputStyle');
				break;
			case 3:
				$(this).addClass('ieLoginButtonStyle');
				break;
		}
	});
}
$.bind('simibox/create', function(e) {
    $('input:radio').bind({
	click: function() {
	    var radioValue = $(this).val();
	    if('v' == radioValue) {
		$('.height').val('600');
		$('.width').val('150');
	    } else if('h' == radioValue) {
		$('.height').val('150');
		$('.width').val('600');
	    }
	}
    });
    $('.colorpicker').jPicker({
	window: {
	    position: {
		x: 'left', // acceptable values "left", "center", "right",
                         // "screenCenter", or relative px value
		y: 'bottom' // acceptable values "top", "bottom", "center", or relative px value
	    }
	},localization: // alter these to change the text presented by the picker
                // (e.g. different language)
	{
	    text: {
		title: 'Przesu\u0144 marker aby wybra\u0107 kolor',
		newColor: 'nowy',
		currentColor: 'aktualny',
		ok: 'Wybierz',
		cancel: 'Anuluj'
	    },
	    tooltips: {
		colors: {
		    newColor: 'New Color - Press "OK" To Commit',
		    currentColor: 'Click To Revert To Original Color'
		},
		buttons: {
		    ok: 'Commit To This Color Selection',
		    cancel: 'Cancel And Revert To Original Color'
		},
		hue: {
		    radio: 'Set To "Hue" Color Mode',
		    textbox: 'Enter A "Hue" Value (0-360°)'
		},
		saturation: {
		    radio: 'Set To "Saturation" Color Mode',
		    textbox: 'Enter A "Saturation" Value (0-100%)'
		},
		value: {
		    radio: 'Set To "Value" Color Mode',
		    textbox: 'Enter A "Value" Value (0-100%)'
		},
		red: {
		    radio: 'Set To "Red" Color Mode',
		    textbox: 'Enter A "Red" Value (0-255)'
		},
		green: {
		    radio: 'Set To "Green" Color Mode',
		    textbox: 'Enter A "Green" Value (0-255)'
		},
		blue: {
		    radio: 'Set To "Blue" Color Mode',
		    textbox: 'Enter A "Blue" Value (0-255)'
		},
		alpha: {
		    radio: 'Set To "Alpha" Color Mode',
		    textbox: 'Enter A "Alpha" Value (0-100)'
		},
		hex: {
		    textbox: 'Enter A "Hex" Color Value (#000000-#ffffff)',
		    alpha: 'Enter A "Alpha" Value (#00-#ff)'
		}
	    }
	}

    });
});


﻿(function(e,a){var d=function(z,k){var o=this,j=z.find("img:first"),F=0,E=100,w=100,D=0,C=100,v=100,s=0,p=0,n,q,u=new Array(),l=function(y){for(var x=0;x<u.length;x++){u[x].call(o,o,y)}},H=function(x){var y=z.offset();n={l:y.left|0,t:y.top|0};clearTimeout(q);q=setTimeout(function(){A.call(o,x)},0);e(document).bind("mousemove",h).bind("mouseup",B);x.stopPropagation();x.preventDefault();return false},h=function(x){clearTimeout(q);q=setTimeout(function(){A.call(o,x)},0);x.stopPropagation();x.preventDefault();return false},B=function(x){e(document).unbind("mouseup",B).unbind("mousemove",h);x.stopPropagation();x.preventDefault();return false},A=function(M){var K=M.pageX-n.l,x=M.pageY-n.t,L=z.w,y=z.h;if(K<0){K=0}else{if(K>L){K=L}}if(x<0){x=0}else{if(x>y){x=y}}J.call(o,"xy",{x:((K/L)*w)+F,y:((x/y)*v)+D})},r=function(){var L=0,x=0,N=z.w,K=z.h,M=j.w,y=j.h;setTimeout(function(){if(w>0){if(s==E){L=N}else{L=((s/w)*N)|0}}if(v>0){if(p==C){x=K}else{x=((p/v)*K)|0}}if(M>=N){L=(N>>1)-(M>>1)}else{L-=M>>1}if(y>=K){x=(K>>1)-(y>>1)}else{x-=y>>1}j.css({left:L+"px",top:x+"px"})},0)},J=function(x,K,y){var O=K!==undefined;if(!O){if(x===undefined||x==null){x="xy"}switch(x.toLowerCase()){case"x":return s;case"y":return p;case"xy":default:return{x:s,y:p}}}if(y!=null&&y==o){return}var N=false,M,L;if(x==null){x="xy"}switch(x.toLowerCase()){case"x":M=K&&(K.x&&K.x|0||K|0)||0;break;case"y":L=K&&(K.y&&K.y|0||K|0)||0;break;case"xy":default:M=K&&K.x&&K.x|0||0;L=K&&K.y&&K.y|0||0;break}if(M!=null){if(M<F){M=F}else{if(M>E){M=E}}if(s!=M){s=M;N=true}}if(L!=null){if(L<D){L=D}else{if(L>C){L=C}}if(p!=L){p=L;N=true}}N&&l.call(o,y||o)},t=function(x,L){var P=L!==undefined;if(!P){if(x===undefined||x==null){x="all"}switch(x.toLowerCase()){case"minx":return F;case"maxx":return E;case"rangex":return{minX:F,maxX:E,rangeX:w};case"miny":return D;case"maxy":return C;case"rangey":return{minY:D,maxY:C,rangeY:v};case"all":default:return{minX:F,maxX:E,rangeX:w,minY:D,maxY:C,rangeY:v}}}var O=false,N,K,M,y;if(x==null){x="all"}switch(x.toLowerCase()){case"minx":N=L&&(L.minX&&L.minX|0||L|0)||0;break;case"maxx":K=L&&(L.maxX&&L.maxX|0||L|0)||0;break;case"rangex":N=L&&L.minX&&L.minX|0||0;K=L&&L.maxX&&L.maxX|0||0;break;case"miny":M=L&&(L.minY&&L.minY|0||L|0)||0;break;case"maxy":y=L&&(L.maxY&&L.maxY|0||L|0)||0;break;case"rangey":M=L&&L.minY&&L.minY|0||0;y=L&&L.maxY&&L.maxY|0||0;break;case"all":default:N=L&&L.minX&&L.minX|0||0;K=L&&L.maxX&&L.maxX|0||0;M=L&&L.minY&&L.minY|0||0;y=L&&L.maxY&&L.maxY|0||0;break}if(N!=null&&F!=N){F=N;w=E-F}if(K!=null&&E!=K){E=K;w=E-F}if(M!=null&&D!=M){D=M;v=C-D}if(y!=null&&C!=y){C=y;v=C-D}},I=function(x){if(e.isFunction(x)){u.push(x)}},m=function(y){if(!e.isFunction(y)){return}var x;while((x=e.inArray(y,u))!=-1){u.splice(x,1)}},G=function(){e(document).unbind("mouseup",B).unbind("mousemove",h);z.unbind("mousedown",H);z=null;j=null;u=null};e.extend(true,o,{val:J,range:t,bind:I,unbind:m,destroy:G});j.src=k.arrow&&k.arrow.image;j.w=k.arrow&&k.arrow.width||j.width();j.h=k.arrow&&k.arrow.height||j.height();z.w=k.map&&k.map.width||z.width();z.h=k.map&&k.map.height||z.height();z.bind("mousedown",H);I.call(o,r)},b=function(t,y,k){var q=this,l=t.find("td.Text input"),r=l.eq(3),v=l.eq(4),h=l.eq(5),o=l.length>7?l.eq(6):null,n=l.eq(0),p=l.eq(1),x=l.eq(2),s=l.eq(l.length>7?7:6),A=l.length>7?l.eq(8):null,w=function(C){if(C.target.value==""&&C.target!=s.get(0)&&(k!=null&&C.target!=k.get(0)||k==null)){return}if(!u(C)){return C}switch(C.target){case r.get(0):r.val(j.call(q,r.val(),0,255));y.val("r",r.val(),C.target);break;case v.get(0):v.val(j.call(q,v.val(),0,255));y.val("g",v.val(),C.target);break;case h.get(0):h.val(j.call(q,h.val(),0,255));y.val("b",h.val(),C.target);break;case o&&o.get(0):o.val(j.call(q,o.val(),0,100));y.val("a",o.val(),C.target);break;case n.get(0):n.val(j.call(q,n.val(),0,360));y.val("h",n.val(),C.target);break;case p.get(0):p.val(j.call(q,p.val(),0,100));y.val("s",p.val(),C.target);break;case x.get(0):x.val(j.call(q,x.val(),0,100));y.val("v",x.val(),C.target);break;case s.get(0):s.val(s.val().replace(/[^a-fA-F0-9]/g,"").toLowerCase().substring(0,6));k&&k.val(s.val());y.val("hex",s.val()!=""?s.val():null,C.target);break;case k&&k.get(0):k.val(k.val().replace(/[^a-fA-F0-9]/g,"").toLowerCase().substring(0,6));s.val(k.val());y.val("hex",k.val()!=""?k.val():null,C.target);break;case A&&A.get(0):A.val(A.val().replace(/[^a-fA-F0-9]/g,"").toLowerCase().substring(0,2));y.val("a",A.val()!=null?((parseInt(A.val(),16)*100)/255):null,C.target);break}},z=function(C){if(y.val()!=null){switch(C.target){case r.get(0):r.val(y.val("r"));break;case v.get(0):v.val(y.val("g"));break;case h.get(0):h.val(y.val("b"));break;case o&&o.get(0):o.val(y.val("a"));break;case n.get(0):n.val(y.val("h"));break;case p.get(0):p.val(y.val("s"));break;case x.get(0):x.val(y.val("v"));break;case s.get(0):case k&&k.get(0):s.val(y.val("hex"));k&&k.val(y.val("hex"));break;case A&&A.get(0):A.val(y.val("ahex").substring(6));break}}},u=function(C){switch(C.keyCode){case 9:case 16:case 29:case 37:case 38:case 40:return false;case"c".charCodeAt():case"v".charCodeAt():if(C.ctrlKey){return false}}return true},j=function(E,D,C){if(E==""||isNaN(E)){return D}if(E>C){return C}if(E<D){return D}return E},m=function(E,C){var D=E.val("all");if(C!=r.get(0)){r.val(D!=null?D.r:"")}if(C!=v.get(0)){v.val(D!=null?D.g:"")}if(C!=h.get(0)){h.val(D!=null?D.b:"")}if(o&&C!=o.get(0)){o.val(D!=null?D.a:"")}if(C!=n.get(0)){n.val(D!=null?D.h:"")}if(C!=p.get(0)){p.val(D!=null?D.s:"")}if(C!=x.get(0)){x.val(D!=null?D.v:"")}if(C!=s.get(0)&&(k&&C!=k.get(0)||!k)){s.val(D!=null?D.hex:"")}if(k&&C!=k.get(0)&&C!=s.get(0)){k.val(D!=null?D.hex:"")}if(A&&C!=A.get(0)){A.val(D!=null?D.ahex.substring(6):"")}},B=function(){r.add(v).add(h).add(o).add(n).add(p).add(x).add(s).add(k).add(A).unbind("keyup",w).unbind("blur",z);y.unbind(m);r=null;v=null;h=null;o=null;n=null;p=null;x=null;s=null;A=null};e.extend(true,q,{destroy:B});r.add(v).add(h).add(o).add(n).add(p).add(x).add(s).add(k).add(A).bind("keyup",w).bind("blur",z);y.bind(m)};e.jPicker={List:[],Color:function(z){var q=this,j,o,t,u,n,A,x,k=new Array(),m=function(r){for(var h=0;h<k.length;h++){k[h].call(q,q,r)}},l=function(h,G,r){var F=G!==undefined;if(!F){if(h===undefined||h==null||h==""){h="all"}switch(h.toLowerCase()){case"ahex":return j!=null?g.rgbaToHex({r:j,g:o,b:t,a:u}):null;case"hex":var D=l("ahex");return D&&D.substring(0,6)||null;case"all":return j!=null?{r:j,g:o,b:t,a:u,h:n,s:A,v:x,hex:l.call(q,"hex"),ahex:l.call(q,"ahex")}:null;default:var D={};for(var B=0;B<h.length;B++){switch(h.charAt(B)){case"r":if(h.length==1){D=j}else{D.r=j}break;case"g":if(h.length==1){D=o}else{D.g=o}break;case"b":if(h.length==1){D=t}else{D.b=t}break;case"a":if(h.length==1){D=u}else{D.a=u}break;case"h":if(h.length==1){D=n}else{D.h=n}break;case"s":if(h.length==1){D=A}else{D.s=A}break;case"v":if(h.length==1){D=x}else{D.v=x}break}}return D=={}?l.call(q,"all"):D;break}}if(r!=null&&r==q){return}var v=false;if(h==null){h=""}if(G==null){if(j!=null){j=null;v=true}if(o!=null){o=null;v=true}if(t!=null){t=null;v=true}if(u!=null){u=null;v=true}if(n!=null){n=null;v=true}if(A!=null){A=null;v=true}if(x!=null){x=null;v=true}v&&m.call(q,r||q);return}switch(h.toLowerCase()){case"ahex":case"hex":var D=g.hexToRgba(G&&(G.ahex||G.hex)||G||"00000000");l.call(q,"rgba",{r:D.r,g:D.g,b:D.b,a:h=="ahex"?D.a:u!=null?u:100},r);break;default:if(G&&(G.ahex!=null||G.hex!=null)){l.call(q,"ahex",G.ahex||G.hex||"00000000",r);return}var s={},E=false,C=false;if(G.r!==undefined&&!h.indexOf("r")==-1){h+="r"}if(G.g!==undefined&&!h.indexOf("g")==-1){h+="g"}if(G.b!==undefined&&!h.indexOf("b")==-1){h+="b"}if(G.a!==undefined&&!h.indexOf("a")==-1){h+="a"}if(G.h!==undefined&&!h.indexOf("h")==-1){h+="h"}if(G.s!==undefined&&!h.indexOf("s")==-1){h+="s"}if(G.v!==undefined&&!h.indexOf("v")==-1){h+="v"}for(var B=0;B<h.length;B++){switch(h.charAt(B)){case"r":if(C){continue}E=true;s.r=G&&G.r&&G.r|0||G&&G|0||0;if(s.r<0){s.r=0}else{if(s.r>255){s.r=255}}if(j!=s.r){j=s.r;v=true}break;case"g":if(C){continue}E=true;s.g=G&&G.g&&G.g|0||G&&G|0||0;if(s.g<0){s.g=0}else{if(s.g>255){s.g=255}}if(o!=s.g){o=s.g;v=true}break;case"b":if(C){continue}E=true;s.b=G&&G.b&&G.b|0||G&&G|0||0;if(s.b<0){s.b=0}else{if(s.b>255){s.b=255}}if(t!=s.b){t=s.b;v=true}break;case"a":s.a=G&&G.a!=null?G.a|0:G!=null?G|0:100;if(s.a<0){s.a=0}else{if(s.a>100){s.a=100}}if(u!=s.a){u=s.a;v=true}break;case"h":if(E){continue}C=true;s.h=G&&G.h&&G.h|0||G&&G|0||0;if(s.h<0){s.h=0}else{if(s.h>360){s.h=360}}if(n!=s.h){n=s.h;v=true}break;case"s":if(E){continue}C=true;s.s=G&&G.s!=null?G.s|0:G!=null?G|0:100;if(s.s<0){s.s=0}else{if(s.s>100){s.s=100}}if(A!=s.s){A=s.s;v=true}break;case"v":if(E){continue}C=true;s.v=G&&G.v!=null?G.v|0:G!=null?G|0:100;if(s.v<0){s.v=0}else{if(s.v>100){s.v=100}}if(x!=s.v){x=s.v;v=true}break}}if(v){if(E){j=j||0;o=o||0;t=t||0;var D=g.rgbToHsv({r:j,g:o,b:t});n=D.h;A=D.s;x=D.v}else{if(C){n=n||0;A=A!=null?A:100;x=x!=null?x:100;var D=g.hsvToRgb({h:n,s:A,v:x});j=D.r;o=D.g;t=D.b}}u=u!=null?u:100;m.call(q,r||q)}break}},p=function(h){if(e.isFunction(h)){k.push(h)}},y=function(r){if(!e.isFunction(r)){return}var h;while((h=e.inArray(r,k))!=-1){k.splice(h,1)}},w=function(){k=null};e.extend(true,q,{val:l,bind:p,unbind:y,destroy:w});if(z){if(z.hex!=null){l("hex",z)}else{if(z.ahex!=null){l("ahex",z)}else{if(z.r!=null&&z.g!=null&&z.b!=null){l("rgb",z)}else{if(z.h!=null&&z.s!=null&&z.v!=null){l("hsv",z)}}}}}},ColorMethods:{hexToRgba:function(m){m=this.validateHex(m);if(m==""){return{r:null,g:null,b:null,a:null}}var l="00",k="00",h="00",j="100";if(m.length==6){m+="ff"}if(m.length>6){l=m.substring(0,2);k=m.substring(2,4);h=m.substring(4,6);j=m.substring(6,m.length)}else{if(m.length>4){l=m.substring(4,m.length);m=m.substring(0,4)}if(m.length>2){k=m.substring(2,m.length);m=m.substring(0,2)}if(m.length>0){h=m.substring(0,m.length)}}return{r:this.hexToInt(l),g:this.hexToInt(k),b:this.hexToInt(h),a:((this.hexToInt(j)*100)/255)|0}},validateHex:function(h){h=h.toLowerCase().replace(/[^a-f0-9]/g,"");if(h.length>8){h=h.substring(0,8)}return h},rgbaToHex:function(h){return this.intToHex(h.r)+this.intToHex(h.g)+this.intToHex(h.b)+this.intToHex(((h.a*255)/100)|0)},intToHex:function(j){var h=(j|0).toString(16);if(h.length==1){h=("0"+h)}return h.toLowerCase()},hexToInt:function(h){return parseInt(h,16)},rgbToHsv:function(l){var o=l.r/255,n=l.g/255,j=l.b/255,k={h:0,s:0,v:0},m=0,h=0,p;if(o>=n&&o>=j){h=o;m=n>j?j:n}else{if(n>=j&&n>=o){h=n;m=o>j?j:o}else{h=j;m=n>o?o:n}}k.v=h;k.s=h?(h-m)/h:0;if(!k.s){k.h=0}else{p=h-m;if(o==h){k.h=(n-j)/p}else{if(n==h){k.h=2+(j-o)/p}else{k.h=4+(o-n)/p}}k.h=parseInt(k.h*60);if(k.h<0){k.h+=360}}k.s=(k.s*100)|0;k.v=(k.v*100)|0;return k},hsvToRgb:function(n){var r={r:0,g:0,b:0,a:100},m=n.h,x=n.s,u=n.v;if(x==0){if(u==0){r.r=r.g=r.b=0}else{r.r=r.g=r.b=(u*255/100)|0}}else{if(m==360){m=0}m/=60;x=x/100;u=u/100;var l=m|0,o=m-l,k=u*(1-x),j=u*(1-(x*o)),w=u*(1-(x*(1-o)));switch(l){case 0:r.r=u;r.g=w;r.b=k;break;case 1:r.r=j;r.g=u;r.b=k;break;case 2:r.r=k;r.g=u;r.b=w;break;case 3:r.r=k;r.g=j;r.b=u;break;case 4:r.r=w;r.g=k;r.b=u;break;case 5:r.r=u;r.g=k;r.b=j;break}r.r=(r.r*255)|0;r.g=(r.g*255)|0;r.b=(r.b*255)|0}return r}}};var f=e.jPicker.Color,c=e.jPicker.List,g=e.jPicker.ColorMethods;e.fn.jPicker=function(j){var h=arguments;return this.each(function(){var w=this,av=e.extend(true,{},e.fn.jPicker.defaults,j);if(e(w).get(0).nodeName.toLowerCase()=="input"){e.extend(true,av,{window:{bindToInput:true,expandable:true,input:e(w)}});if(g.validateHex(e(w).val())){av.color.active=new f({hex:e(w).val(),a:av.color.active.val("a")});av.color.current=new f({hex:e(w).val(),a:av.color.active.val("a")})}}if(av.window.expandable){e(w).after('<span class="jPicker"><span class="Icon"><span class="Color">&nbsp;</span><span class="Alpha">&nbsp;</span><span class="Image" title="Click To Open Color Picker">&nbsp;</span><span class="Container">&nbsp;</span></span></span>')}else{av.window.liveUpdate=false}var Q=parseFloat(navigator.appVersion.split("MSIE")[1])<7&&document.body.filters,R=null,l=null,s=null,au=null,at=null,ar=null,P=null,O=null,N=null,M=null,L=null,K=null,D=null,U=null,aw=null,J=null,I=null,am=null,ai=null,E=null,an=null,ah=null,X=null,ab=null,aq=null,r=null,C=null,u=null,ag=function(aB){var aD=G.active,aE=n.clientPath,aA=aD.val("hex"),aC,az;av.color.mode=aB;switch(aB){case"h":setTimeout(function(){y.call(w,l,"transparent");x.call(w,au,0);Y.call(w,au,100);x.call(w,at,260);Y.call(w,at,100);y.call(w,s,"transparent");x.call(w,P,0);Y.call(w,P,100);x.call(w,O,260);Y.call(w,O,100);x.call(w,N,260);Y.call(w,N,100);x.call(w,M,260);Y.call(w,M,100);x.call(w,K,260);Y.call(w,K,100)},0);D.range("all",{minX:0,maxX:100,minY:0,maxY:100});U.range("rangeY",{minY:0,maxY:360});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("s"),y:100-aD.val("v")},D);U.val("y",360-aD.val("h"),U);break;case"s":setTimeout(function(){y.call(w,l,"transparent");x.call(w,au,-260);x.call(w,at,-520);x.call(w,P,-260);x.call(w,O,-520);x.call(w,K,260);Y.call(w,K,100)},0);D.range("all",{minX:0,maxX:360,minY:0,maxY:100});U.range("rangeY",{minY:0,maxY:100});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("h"),y:100-aD.val("v")},D);U.val("y",100-aD.val("s"),U);break;case"v":setTimeout(function(){y.call(w,l,"000000");x.call(w,au,-780);x.call(w,at,260);y.call(w,s,aA);x.call(w,P,-520);x.call(w,O,260);Y.call(w,O,100);x.call(w,K,260);Y.call(w,K,100)},0);D.range("all",{minX:0,maxX:360,minY:0,maxY:100});U.range("rangeY",{minY:0,maxY:100});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("h"),y:100-aD.val("s")},D);U.val("y",100-aD.val("v"),U);break;case"r":aC=-1040;az=-780;D.range("all",{minX:0,maxX:255,minY:0,maxY:255});U.range("rangeY",{minY:0,maxY:255});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("b"),y:255-aD.val("g")},D);U.val("y",255-aD.val("r"),U);break;case"g":aC=-1560;az=-1820;D.range("all",{minX:0,maxX:255,minY:0,maxY:255});U.range("rangeY",{minY:0,maxY:255});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("b"),y:255-aD.val("r")},D);U.val("y",255-aD.val("g"),U);break;case"b":aC=-2080;az=-2860;D.range("all",{minX:0,maxX:255,minY:0,maxY:255});U.range("rangeY",{minY:0,maxY:255});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("r"),y:255-aD.val("g")},D);U.val("y",255-aD.val("b"),U);break;case"a":setTimeout(function(){y.call(w,l,"transparent");x.call(w,au,-260);x.call(w,at,-520);x.call(w,P,260);x.call(w,O,260);Y.call(w,O,100);x.call(w,K,0);Y.call(w,K,100)},0);D.range("all",{minX:0,maxX:360,minY:0,maxY:100});U.range("rangeY",{minY:0,maxY:100});if(aD.val("ahex")==null){break}D.val("xy",{x:aD.val("h"),y:100-aD.val("v")},D);U.val("y",100-aD.val("a"),U);break;default:throw ("Invalid Mode");break}switch(aB){case"h":break;case"s":case"v":case"a":setTimeout(function(){Y.call(w,au,100);Y.call(w,P,100);x.call(w,N,260);Y.call(w,N,100);x.call(w,M,260);Y.call(w,M,100)},0);break;case"r":case"g":case"b":setTimeout(function(){y.call(w,l,"transparent");y.call(w,s,"transparent");Y.call(w,P,100);Y.call(w,au,100);x.call(w,au,aC);x.call(w,at,aC-260);x.call(w,P,az-780);x.call(w,O,az-520);x.call(w,N,az);x.call(w,M,az-260);x.call(w,K,260);Y.call(w,K,100)},0);break}if(aD.val("ahex")==null){return}aj.call(w,aD)},aj=function(aA,az){if(az==null||(az!=U&&az!=D)){v.call(w,aA,az)}setTimeout(function(){ay.call(w,aA);al.call(w,aA);W.call(w,aA)},0)},z=function(aA,az){var aC=G.active;if(az!=D&&aC.val()==null){return}var aB=aA.val("all");switch(av.color.mode){case"h":aC.val("sv",{s:aB.x,v:100-aB.y},az);break;case"s":case"a":aC.val("hv",{h:aB.x,v:100-aB.y},az);break;case"v":aC.val("hs",{h:aB.x,s:100-aB.y},az);break;case"r":aC.val("gb",{g:255-aB.y,b:aB.x},az);break;case"g":aC.val("rb",{r:255-aB.y,b:aB.x},az);break;case"b":aC.val("rg",{r:aB.x,g:255-aB.y},az);break}},ac=function(aA,az){var aB=G.active;if(az!=U&&aB.val()==null){return}switch(av.color.mode){case"h":aB.val("h",{h:360-aA.val("y")},az);break;case"s":aB.val("s",{s:100-aA.val("y")},az);break;case"v":aB.val("v",{v:100-aA.val("y")},az);break;case"r":aB.val("r",{r:255-aA.val("y")},az);break;case"g":aB.val("g",{g:255-aA.val("y")},az);break;case"b":aB.val("b",{b:255-aA.val("y")},az);break;case"a":aB.val("a",100-aA.val("y"),az);break}},v=function(aC,az){if(az!=D){switch(av.color.mode){case"h":var aH=aC.val("sv");D.val("xy",{x:aH!=null?aH.s:100,y:100-(aH!=null?aH.v:100)},az);break;case"s":case"a":var aB=aC.val("hv");D.val("xy",{x:aB&&aB.h||0,y:100-(aB!=null?aB.v:100)},az);break;case"v":var aE=aC.val("hs");D.val("xy",{x:aE&&aE.h||0,y:100-(aE!=null?aE.s:100)},az);break;case"r":var aA=aC.val("bg");D.val("xy",{x:aA&&aA.b||0,y:255-(aA&&aA.g||0)},az);break;case"g":var aI=aC.val("br");D.val("xy",{x:aI&&aI.b||0,y:255-(aI&&aI.r||0)},az);break;case"b":var aG=aC.val("rg");D.val("xy",{x:aG&&aG.r||0,y:255-(aG&&aG.g||0)},az);break}}if(az!=U){switch(av.color.mode){case"h":U.val("y",360-(aC.val("h")||0),az);break;case"s":var aJ=aC.val("s");U.val("y",100-(aJ!=null?aJ:100),az);break;case"v":var aF=aC.val("v");U.val("y",100-(aF!=null?aF:100),az);break;case"r":U.val("y",255-(aC.val("r")||0),az);break;case"g":U.val("y",255-(aC.val("g")||0),az);break;case"b":U.val("y",255-(aC.val("b")||0),az);break;case"a":var aD=aC.val("a");U.val("y",100-(aD!=null?aD:100),az);break}}},ay=function(aA){try{var az=aA.val("all");E.css({backgroundColor:az&&"#"+az.hex||"transparent"});Y.call(w,E,az&&az.a||0)}catch(aB){}},al=function(aC){switch(av.color.mode){case"h":y.call(w,l,new f({h:aC.val("h")||0,s:100,v:100}).val("hex"));break;case"s":case"a":var aB=aC.val("s");Y.call(w,at,100-(aB!=null?aB:100));break;case"v":var aA=aC.val("v");Y.call(w,au,aA!=null?aA:100);break;case"r":Y.call(w,at,(aC.val("r")||0)/255*100);break;case"g":Y.call(w,at,(aC.val("g")||0)/255*100);break;case"b":Y.call(w,at,(aC.val("b")||0)/255*100);break}var az=aC.val("a");Y.call(w,ar,100-(az||0))},W=function(aF){switch(av.color.mode){case"h":var aH=aF.val("a");Y.call(w,L,100-(aH||0));break;case"s":var aA=aF.val("hva"),aB=new f({h:aA&&aA.h||0,s:100,v:aA!=null?aA.v:100});y.call(w,s,aB.val("hex"));Y.call(w,O,100-(aA!=null?aA.v:100));Y.call(w,L,100-(aA&&aA.a||0));break;case"v":var aC=aF.val("hsa"),aE=new f({h:aC&&aC.h||0,s:aC!=null?aC.s:100,v:100});y.call(w,s,aE.val("hex"));Y.call(w,L,100-(aC&&aC.a||0));break;case"r":case"g":case"b":var aD=0,aG=0,az=aF.val("rgba");if(av.color.mode=="r"){aD=az&&az.b||0;aG=az&&az.g||0}else{if(av.color.mode=="g"){aD=az&&az.b||0;aG=az&&az.r||0}else{if(av.color.mode=="b"){aD=az&&az.r||0;aG=az&&az.g||0}}}var aI=aG>aD?aD:aG;Y.call(w,O,aD>aG?((aD-aG)/(255-aG))*100:0);Y.call(w,N,aG>aD?((aG-aD)/(255-aD))*100:0);Y.call(w,M,aI/255*100);Y.call(w,L,100-(az&&az.a||0));break;case"a":var aH=aF.val("a");y.call(w,s,aF.val("hex")||"000000");Y.call(w,L,aH!=null?0:100);Y.call(w,K,aH!=null?100:0);break}},y=function(az,aA){az.css({backgroundColor:aA&&aA.length==6&&"#"+aA||"transparent"})},t=function(az,aA){if(Q&&(aA.indexOf("AlphaBar.png")!=-1||aA.indexOf("Bars.png")!=-1||aA.indexOf("Maps.png")!=-1)){az.attr("pngSrc",aA);az.css({backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+aA+"', sizingMethod='scale')"})}else{az.css({backgroundImage:"url("+aA+")"})}},x=function(az,aA){az.css({top:aA+"px"})},Y=function(aA,az){aA.css({visibility:az>0?"visible":"hidden"});if(az>0&&az<100){if(Q){var aB=aA.attr("pngSrc");if(aB!=null&&(aB.indexOf("AlphaBar.png")!=-1||aB.indexOf("Bars.png")!=-1||aB.indexOf("Maps.png")!=-1)){aA.css({filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+aB+"', sizingMethod='scale') progid:DXImageTransform.Microsoft.Alpha(opacity="+az+")"})}else{aA.css({opacity:az/100})}}else{aA.css({opacity:az/100})}}else{if(az==0||az==100){if(Q){var aB=aA.attr("pngSrc");if(aB!=null&&(aB.indexOf("AlphaBar.png")!=-1||aB.indexOf("Bars.png")!=-1||aB.indexOf("Maps.png")!=-1)){aA.css({filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+aB+"', sizingMethod='scale')"})}else{aA.css({opacity:""})}}else{aA.css({opacity:""})}}}},B=function(){G.active.val("ahex",G.current.val("ahex"))},T=function(){G.current.val("ahex",G.active.val("ahex"))},A=function(az){ag.call(w,az.target.value)},Z=function(){B.call(w)},q=function(){B.call(w);av.window.expandable&&ao.call(w);e.isFunction(ax)&&ax.call(w,G.active,X)},m=function(){T.call(w);av.window.expandable&&ao.call(w);e.isFunction(ae)&&ae.call(w,G.active,ah)},af=function(){V.call(w)},ap=function(aB,az){var aA=aB.val("hex");an.css({backgroundColor:aA&&"#"+aA||"transparent"});Y.call(w,an,aB.val("a")||0)},H=function(aC,az){var aB=aC.val("hex");var aA=aC.val("va");aq.css({backgroundColor:aB&&"#"+aB||"transparent"});Y.call(w,r,100-(aA&&aA.a||0));if(av.window.bindToInput){av.window.input.css({backgroundColor:aB&&"#"+aB||"transparent",color:aA&&aA.v>75?"#000000":"#ffffff"})}},S=function(aB){var az=av.window.element,aA=av.window.page;J=parseInt(R.css("left"));I=parseInt(R.css("top"));am=aB.pageX;ai=aB.pageY;e(document).bind("mousemove",k).bind("mouseup",p);aB.stopPropagation();aB.preventDefault();return false},k=function(az){R.css({left:J-(am-az.pageX)+"px",top:I-(ai-az.pageY)+"px"});az.stopPropagation();az.preventDefault();return false},p=function(az){e(document).unbind("mousemove",k).unbind("mouseup",p);az.stopPropagation();az.preventDefault();return false},F=function(az){az.preventDefault();az.stopPropagation();G.active.val("ahex",e(this).attr("title")||null,az.target);return false},ae=e.isFunction(h[1])&&h[1]||null,ad=e.isFunction(h[2])&&h[2]||null,ax=e.isFunction(h[3])&&h[3]||null,V=function(){if(document.all){var az=false;for(i=0;i<c.length;i++){if(az){c[i].icon.css({display:"none"})}if(c[i]==w){az=true}}}G.current.val("ahex",G.active.val("ahex"));switch(av.window.effects.type){case"fade":R.fadeIn(av.window.effects.speed.show);break;case"slide":R.slideDown(av.window.effects.speed.show);break;case"show":default:R.show(av.window.effects.speed.show);break}},ao=function(){if(document.all){var az=false;for(i=0;i<c.length;i++){if(az){c[i].icon.css({display:"inline-block"})}if(c[i]==w){az=true}}}switch(av.window.effects.type){case"fade":R.fadeOut(av.window.effects.speed.hide);break;case"slide":R.slideUp(av.window.effects.speed.hide);break;case"show":default:R.hide(av.window.effects.speed.hide);break}},o=function(){var aF=av.window;R=aF.expandable?e(w).next().find(".Container:first"):e(w);if(aF.expandable){R.css({left:aF.position.x=="left"?(0-520-(aF.position.y=="center"?25:0))+"px":aF.position.x=="center"?"-249px":aF.position.x=="right"?(0+(aF.position.y=="center"?25:0))+"px":aF.position.x=="screenCenter"?((e(document).width()>>1)-249)-e(w).next().offset().left+"px":aF.position.x,position:"absolute",top:aF.position.y=="top"?"-312px":aF.position.y=="center"?"-156px":aF.position.y=="bottom"?"25px":aF.position.y})}if((typeof(G.active)).toString().toLowerCase()=="string"){G.active=new f({ahex:G.active})}R.html('<table class="jPicker" cellpadding="0" cellspacing="0"><tbody>'+(aF.expandable?'<tr><td class="Move" colspan="6">&nbsp;</td></tr>':"")+'<tr><td rowspan="9"><h2 class="Title">'+(aF.title||aa.text.title)+'</h2><div class="Map"><span class="Map1">&nbsp;</span><span class="Map2">&nbsp;</span><span class="Map3">&nbsp;</span><img src="'+n.clientPath+n.colorMap.arrow.file+'" class="Arrow"/></div></td><td rowspan="9"><div class="Bar"><span class="Map1">&nbsp;</span><span class="Map2">&nbsp;</span><span class="Map3">&nbsp;</span><span class="Map4">&nbsp;</span><span class="Map5">&nbsp;</span><span class="Map6">&nbsp;</span><img src="'+n.clientPath+n.colorBar.arrow.file+'" class="Arrow"/></div></td><td colspan="3" class="Preview">'+aa.text.newColor+'<div><span class="Active" title="'+aa.tooltips.colors.newColor+'">&nbsp;</span><span class="Current" title="'+aa.tooltips.colors.currentColor+'">&nbsp;</span></div>'+aa.text.currentColor+'</td><td rowspan="9" class="Button"><input type="button" class="Ok" value="'+aa.text.ok+'" title="'+aa.tooltips.buttons.ok+'"/><input type="button" class="Cancel" value="'+aa.text.cancel+'" title="'+aa.tooltips.buttons.cancel+'"/><hr/><div class="Grid">&nbsp;</div></td></tr><tr class="Hue"><td class="Radio"><input type="radio" id="jPicker_Hue_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="h" title="'+aa.tooltips.hue.radio+'"'+(av.color.mode=="h"?' checked="checked"':"")+'/></td><td class="Label"><label for="jPicker_Hue_'+c.length+'" title="'+aa.tooltips.hue.radio+'">H:</label></td><td class="Text"><input type="text" maxlength="3" value="'+G.active.val("h")+'" title="'+aa.tooltips.hue.textbox+'"/>&nbsp;&deg;</td></tr><tr class="Saturation"><td class="Radio"><input type="radio" id="jPicker_Saturation_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="s" title="'+aa.tooltips.saturation.radio+'"'+(av.color.mode=="s"?' checked="checked"':"")+'/></td><td class="Label"><label for="jPicker_Saturation_'+c.length+'" title="'+aa.tooltips.saturation.radio+'">S:</label></td><td class="Text"><input type="text" maxlength="3" value="'+G.active.val("s")+'" title="'+aa.tooltips.saturation.textbox+'"/>&nbsp;%</td></tr><tr class="Value"><td class="Radio"><input type="radio" id="jPicker_Value_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="v" title="'+aa.tooltips.value.radio+'"'+(av.color.mode=="v"?' checked="checked"':"")+'/><br/><br/></td><td class="Label"><label for="jPicker_Value_'+c.length+'" title="'+aa.tooltips.value.radio+'">V:</label><br/><br/></td><td class="Text"><input type="text" maxlength="3" value="'+G.active.val("v")+'" title="'+aa.tooltips.value.textbox+'"/>&nbsp;%<br/><br/></td></tr><tr class="Red"><td class="Radio"><input type="radio" id="jPicker_Red_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="r" title="'+aa.tooltips.red.radio+'"'+(av.color.mode=="r"?' checked="checked"':"")+'/></td><td class="Label"><label for="jPicker_Red_'+c.length+'" title="'+aa.tooltips.red.radio+'">R:</label></td><td class="Text"><input type="text" maxlength="3" value="'+G.active.val("r")+'" title="'+aa.tooltips.red.textbox+'"/></td></tr><tr class="Green"><td class="Radio"><input type="radio" id="jPicker_Green_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="g" title="'+aa.tooltips.green.radio+'"'+(av.color.mode=="g"?' checked="checked"':"")+'/></td><td class="Label"><label for="jPicker_Green_'+c.length+'" title="'+aa.tooltips.green.radio+'">G:</label></td><td class="Text"><input type="text" maxlength="3" value="'+G.active.val("g")+'" title="'+aa.tooltips.green.textbox+'"/></td></tr><tr class="Blue"><td class="Radio"><input type="radio" id="jPicker_Blue_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="b" title="'+aa.tooltips.blue.radio+'"'+(av.color.mode=="b"?' checked="checked"':"")+'/></td><td class="Label"><label for="jPicker_Blue_'+c.length+'" title="'+aa.tooltips.blue.radio+'">B:</label></td><td class="Text"><input type="text" maxlength="3" value="'+G.active.val("b")+'" title="'+aa.tooltips.blue.textbox+'"/></td></tr><tr class="Alpha"><td class="Radio">'+(aF.alphaSupport?'<input type="radio" id="jPicker_Alpha_'+c.length+'" name="jPicker_Mode_'+c.length+'" value="a" title="'+aa.tooltips.alpha.radio+'"'+(av.color.mode=="a"?' checked="checked"':"")+"/>":"&nbsp;")+'</td><td class="Label">'+(aF.alphaSupport?'<label for="jPicker_Alpha_'+c.length+'" title="'+aa.tooltips.alpha.radio+'">A:</label>':"&nbsp;")+'</td><td class="Text">'+(aF.alphaSupport?'<input type="text" maxlength="3" value="'+G.active.val("a")+'" title="'+aa.tooltips.alpha.textbox+'"/>&nbsp;%':"&nbsp;")+'</td></tr><tr class="Hex"><td colspan="3" class="Text"><label for="jPicker_Hex_'+c.length+'" title="'+aa.tooltips.hex.textbox+'">#:</label><input type="text" maxlength="6" class="Hex" id="jPicker_Hex_'+c.length+'" value="'+G.active.val("hex")+'" title="'+aa.tooltips.hex.textbox+'"/>'+(aF.alphaSupport?'<input type="text" maxlength="2" class="AHex" value="'+G.active.val("ahex").substring(6)+'" title="'+aa.tooltips.hex.alpha+'"/></td>':"&nbsp;")+"</tr></tbody></table>");var aC=R.find("tbody:first");l=aC.find("div.Map:first");s=aC.find("div.Bar:first");var aI=l.find("span"),aH=s.find("span");au=aI.filter(".Map1:first");at=aI.filter(".Map2:first");ar=aI.filter(".Map3:first");P=aH.filter(".Map1:first");O=aH.filter(".Map2:first");N=aH.filter(".Map3:first");M=aH.filter(".Map4:first");L=aH.filter(".Map5:first");K=aH.filter(".Map6:first");D=new d(l,{map:{width:n.colorMap.width,height:n.colorMap.height},arrow:{image:n.clientPath+n.colorMap.arrow.file,width:n.colorMap.arrow.width,height:n.colorMap.arrow.height}});D.bind(z);U=new d(s,{map:{width:n.colorBar.width,height:n.colorBar.height},arrow:{image:n.clientPath+n.colorBar.arrow.file,width:n.colorBar.arrow.width,height:n.colorBar.arrow.height}});U.bind(ac);aw=new b(aC,G.active,aF.expandable&&aF.bindToInput?aF.input:null);var aA=G.active.val("hex"),aG=aC.find(".Preview"),aD=aC.find(".Button");E=aG.find(".Active:first").css({backgroundColor:aA&&"#"+aA||"transparent"});an=aG.find(".Current:first").css({backgroundColor:aA&&"#"+aA||"transparent"}).bind("click",Z);ah=aD.find(".Ok:first").bind("click",m);X=aD.find(".Cancel:first").bind("click",q);ab=aD.find(".Grid:first");setTimeout(function(){t.call(w,au,n.clientPath+"Maps.png");t.call(w,at,n.clientPath+"Maps.png");t.call(w,ar,n.clientPath+"map-opacity.png");t.call(w,P,n.clientPath+"Bars.png");t.call(w,O,n.clientPath+"Bars.png");t.call(w,N,n.clientPath+"Bars.png");t.call(w,M,n.clientPath+"Bars.png");t.call(w,L,n.clientPath+"bar-opacity.png");t.call(w,K,n.clientPath+"AlphaBar.png");t.call(w,aG.find("div:first"),n.clientPath+"preview-opacity.png")},0);aC.find("td.Radio input").bind("click",A);if(G.quickList&&G.quickList.length>0){var aE="";for(i=0;i<G.quickList.length;i++){if((typeof(G.quickList[i])).toString().toLowerCase()=="string"){G.quickList[i]=new f({hex:G.quickList[i]})}var aB=G.quickList[i].val("ahex");var az=G.quickList[i].val("hex");aE+='<span class="QuickColor" title="'+(aB&&"#"+aB||"")+'" style="background-color: '+(az&&"#"+az||"transparent")+";"+(az?"":" background-image: url("+n.clientPath+"NoColor.png);")+'">&nbsp;</span>'}ab.html(aE);ab.find(".QuickColor").click(F)}ag.call(w,av.color.mode);G.active.bind(aj);e.isFunction(ad)&&G.active.bind(ad);G.current.bind(ap);if(aF.expandable){w.icon=R.parents(".Icon:first");aq=w.icon.find(".Color:first").css({backgroundColor:aA&&"#"+aA||"transparent"});r=w.icon.find(".Alpha:first");t.call(w,r,n.clientPath+"bar-opacity.png");Y.call(w,r,100-G.active.val("a"));C=w.icon.find(".Image:first").css({backgroundImage:"url("+n.clientPath+n.picker.file+")"}).bind("click",af);if(aF.bindToInput){aF.input.css({backgroundColor:aA&&"#"+aA||"transparent",color:G.active.val("v")>75?"#000000":"#ffffff"})}u=aC.find(".Move:first").bind("mousedown",S);G.active.bind(H)}else{V.call(w)}c.push(w)},ak=function(){R.find("td.Radio input").unbind("click",A);an.unbind("click",Z);X.unbind("click",q);ah.unbind("click",m);if(av.window.expandable){C.unbind("click",af);u.unbind("mousedown",S);w.icon=null}R.find(".QuickColor").unbind("click",F);l=null;s=null;au=null;at=null;ar=null;P=null;O=null;N=null;M=null;L=null;K=null;D.destroy();D=null;U.destroy();U=null;aw.destroy();aw=null;E=null;an=null;ah=null;X=null;ab=null;ae=null;ax=null;ad=null;R.html("");for(i=0;i<c.length;i++){if(c[i]==w){c.splice(i,1)}}},n=av.images,aa=av.localization,G={active:(typeof(av.color.active)).toString().toLowerCase()=="string"?new f({ahex:av.color.active}):new f({ahex:av.color.active.val("ahex")}),current:(typeof(av.color.active)).toString().toLowerCase()=="string"?new f({ahex:av.color.active}):new f({ahex:av.color.active.val("ahex")}),quickList:av.color.quickList};e.extend(true,w,{commitCallback:ae,liveCallback:ad,cancelCallback:ax,color:G,show:V,hide:ao,destroy:ak});setTimeout(function(){o.call(w)},0)})};e.fn.jPicker.defaults={window:{title:null,effects:{type:"slide",speed:{show:"slow",hide:"fast"}},position:{x:"screenCenter",y:"top"},expandable:false,liveUpdate:true,alphaSupport:false},color:{mode:"h",active:new f({ahex:"#ffcc00ff"}),quickList:[new f({h:360,s:33,v:100}),new f({h:360,s:66,v:100}),new f({h:360,s:100,v:100}),new f({h:360,s:100,v:75}),new f({h:360,s:100,v:50}),new f({h:180,s:0,v:100}),new f({h:30,s:33,v:100}),new f({h:30,s:66,v:100}),new f({h:30,s:100,v:100}),new f({h:30,s:100,v:75}),new f({h:30,s:100,v:50}),new f({h:180,s:0,v:90}),new f({h:60,s:33,v:100}),new f({h:60,s:66,v:100}),new f({h:60,s:100,v:100}),new f({h:60,s:100,v:75}),new f({h:60,s:100,v:50}),new f({h:180,s:0,v:80}),new f({h:90,s:33,v:100}),new f({h:90,s:66,v:100}),new f({h:90,s:100,v:100}),new f({h:90,s:100,v:75}),new f({h:90,s:100,v:50}),new f({h:180,s:0,v:70}),new f({h:120,s:33,v:100}),new f({h:120,s:66,v:100}),new f({h:120,s:100,v:100}),new f({h:120,s:100,v:75}),new f({h:120,s:100,v:50}),new f({h:180,s:0,v:60}),new f({h:150,s:33,v:100}),new f({h:150,s:66,v:100}),new f({h:150,s:100,v:100}),new f({h:150,s:100,v:75}),new f({h:150,s:100,v:50}),new f({h:180,s:0,v:50}),new f({h:180,s:33,v:100}),new f({h:180,s:66,v:100}),new f({h:180,s:100,v:100}),new f({h:180,s:100,v:75}),new f({h:180,s:100,v:50}),new f({h:180,s:0,v:40}),new f({h:210,s:33,v:100}),new f({h:210,s:66,v:100}),new f({h:210,s:100,v:100}),new f({h:210,s:100,v:75}),new f({h:210,s:100,v:50}),new f({h:180,s:0,v:30}),new f({h:240,s:33,v:100}),new f({h:240,s:66,v:100}),new f({h:240,s:100,v:100}),new f({h:240,s:100,v:75}),new f({h:240,s:100,v:50}),new f({h:180,s:0,v:20}),new f({h:270,s:33,v:100}),new f({h:270,s:66,v:100}),new f({h:270,s:100,v:100}),new f({h:270,s:100,v:75}),new f({h:270,s:100,v:50}),new f({h:180,s:0,v:10}),new f({h:300,s:33,v:100}),new f({h:300,s:66,v:100}),new f({h:300,s:100,v:100}),new f({h:300,s:100,v:75}),new f({h:300,s:100,v:50}),new f({h:180,s:0,v:0}),new f({h:330,s:33,v:100}),new f({h:330,s:66,v:100}),new f({h:330,s:100,v:100}),new f({h:330,s:100,v:75}),new f({h:330,s:100,v:50}),new f()]},images:{clientPath:"/jPicker/images/",colorMap:{width:256,height:256,arrow:{file:"mappoint.gif",width:15,height:15}},colorBar:{width:20,height:256,arrow:{file:"rangearrows.gif",width:20,height:7}},picker:{file:"picker.gif",width:25,height:24}},localization:{text:{title:"Drag Markers To Pick A Color",newColor:"new",currentColor:"current",ok:"OK",cancel:"Cancel"},tooltips:{colors:{newColor:"New Color - Press &ldquo;OK&rdquo; To Commit",currentColor:"Click To Revert To Original Color"},buttons:{ok:"Commit To This Color Selection",cancel:"Cancel And Revert To Original Color"},hue:{radio:"Set To &ldquo;Hue&rdquo; Color Mode",textbox:"Enter A &ldquo;Hue&rdquo; Value (0-360&deg;)"},saturation:{radio:"Set To &ldquo;Saturation&rdquo; Color Mode",textbox:"Enter A &ldquo;Saturation&rdquo; Value (0-100%)"},value:{radio:"Set To &ldquo;Value&rdquo; Color Mode",textbox:"Enter A &ldquo;Value&rdquo; Value (0-100%)"},red:{radio:"Set To &ldquo;Red&rdquo; Color Mode",textbox:"Enter A &ldquo;Red&rdquo; Value (0-255)"},green:{radio:"Set To &ldquo;Green&rdquo; Color Mode",textbox:"Enter A &ldquo;Green&rdquo; Value (0-255)"},blue:{radio:"Set To &ldquo;Blue&rdquo; Color Mode",textbox:"Enter A &ldquo;Blue&rdquo; Value (0-255)"},alpha:{radio:"Set To &ldquo;Alpha&rdquo; Color Mode",textbox:"Enter A &ldquo;Alpha&rdquo; Value (0-100)"},hex:{textbox:"Enter A &ldquo;Hex&rdquo; Color Value (#000000-#ffffff)",alpha:"Enter A &ldquo;Alpha&rdquo; Value (#00-#ff)"}}}}})(jQuery,"1.1.2");$('#invEmail').bind({
    click: function() {
	$default = 'Wpisz adresy email znajomych, rozdzielając je przecinkami';
	$fieldValue = $(this).val();
	if($default==$fieldValue) {
	    $(this).val('');
	};
    },
    focusout: function() {
	$fieldValue = $(this).val();
	if($fieldValue == '')
	    $(this).val('Wpisz adresy email znajomych, rozdzielając je przecinkami');
    }
});



function setSimiTimer() {
	    val = ($('#body-timer').attr('value'))*1;
	    if(val>0) {
		val -= 1;

		hours = parseInt(val/3600);
		minutes = parseInt((val%3600)/60);
		seconds = parseInt(((val%3600)%60)%60);

		bodyDate = $('#body-date');

		hours = (hours.toString().length==1)?('0'+hours):hours;
		minutes = (minutes.toString().length==1)?('0'+minutes):minutes;
		seconds = (seconds.toString().length==1)?('0'+seconds):seconds;

		$('#body-date').text(hours+'h '+minutes+'m '+seconds+'s ');
		$('#body-timer').val(val);


	    } else {
                $('#body-date').text(' 0h 0m 0s ');
		$('a').each(function() {
		    if($(this).attr('id') == 'checkButton') {
			if($(this).attr('class') == 'clanCheckButtonInActive') {
			    $(this).attr('class','clanCheckButtonActive');
			}
		    }
		});
	    }
	    
	    setTimeout("setSimiTimer()",1000);
	}
	setSimiTimer();


$.bind('socialLinksTracker', function(){
	$('#linkFacebook').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkFacebook'); 
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkFacebook');
	    } catch(err) {}
	});
	
	$('#linkMyspace').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkMyspace');
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkMyspace');
	    } catch(err) {}
	});
	
	$('#linkTwitter').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkTwitter');
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkTwitter');
	    } catch(err) {}
	});
	
	$('#linkWykop').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkWykop');
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkWykop');
	    } catch(err) {}
	});
	
	$('#linkNk').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkNk');
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkNk');
	    } catch(err) {}
	});
	
	$('#linkFlaker').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkFlaker');
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkFlaker');
	    } catch(err) {}
	});
	
	$('#linkBlip').bind('click', function() {
	    try {
		pageTracker._trackPageview('/click/linkBlip');
	    } catch(err) {}
	    try {
		pageTracker2._trackPageview('/click/linkBlip');
	    } catch(err) {}
	});
});$.bind('test/image', function(e) {
	e.scope
	.find('a[href="#next"]').bind('click', function() {
		$(this).parent().hide().next().show();
		return false;
	}).end()
	.find('a[href="#prev"]').bind('click', function() {
		$(this).parent().hide().prev().show();
		return false;
	}).end()
	;
});
$.bind('test/image/send', function(e) {
	e.scope.bind('click', function() {
		var dialog = $.dialog({
			url: url('/test/image/send', {id: e.opt.id}),

			draggable: false,
			modal: true,
			resizable: false,
			title: _('Wyślij test'),
			close: function() { $(this).remove(); }});

		$.bind('test/image/send-submit', function() {
			dialog.dialog('close');
		});
		return false;
	});
});
$.bind('tests/TestSetUser', function(e){
	$('<div class="TestSetUserDialogParentDiv testDialogParentDiv"></div>')
		.load(url('/test2/testSetUser', {}))
		.dialog({
			dialogClass: 'TestSetUserDialog',
			closeOnEscape: false,
			draggable: false,
			width: 900,
			height: 550,
			modal: true,
			resizable: false,
			title: _('Pomóż nam uczyć Similarię. Wybierz zdjęcie, które Ci bardziej odpowiada.'),
			close: function(event, ui) {
				$('.testDialogParentDiv').remove();
			}
		});
});

$.bind('tests/TestSetForUnlogged', function(e){
	$('<div class="TestSetForUnloggedDialogParentDiv testDialogParentDiv"></div>')
		.load(url('/test2/testSetForUnlogged', {}))
		.dialog({
			dialogClass: 'TestSetUserDialog',
			closeOnEscape: false,
			draggable: false,
			width: 900,
			height: 550,
			modal: true,
			resizable: false,
			title: _('Pomóż nam uczyć Similarię'),
			open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
			close: function(event, ui) {
				$.post(url('/test2/testSetForUnlogged'), {close:1});
				$('.testDialogParentDiv').remove();
				$('.ac_results').remove();
				$('#searchInput').trigger('focus');
			}});
});


$.bind('tests/Handlers', function(e){
	 e.scope.bind('testResult', function(event, params) {
		e.scope.load(url(e.opt.url, params));
	 });

});

$.bind('tests/updateProgress', function(e){
	var i = 0;
	if(e.opt.step != null) {
		$(
			$('.testHeaderDiv #progress li')
			.splice(0, e.opt.step+1)
		).each(function(idx, li){
			$(li).addClass('stage-full')
		});
	}
});

$.bind('tests/close', function(e){
	$('div.testDialogParentDiv').dialog('close');
});


$.bind('tests/TestSetTeach', function(e){
	e.scope.bind('click', function() {
		$('<div class="TestSetTeachDialogParentDiv testDialogParentDiv"></div>')
			.load(url('/test2/testSetTeach', {EkspImageId: e.opt.EkspImageId, start:1, mainPicture:0}))
			.dialog({
				dialogClass: 'TestSetTeachDialog',
				draggable: false,
				width: 800,
				height: 540,
				modal: true,
				resizable: false,
				title: _('Ucz'),
				close: function(event, ui) {
					$('.testDialogParentDiv').remove();
					$('.ac_results').remove();
				}

			});
		});
});


$.bind('tests/TestSetTeachMainInEksp', function(e){
	e.scope.bind('click', function() {
		$('<div class="TestSetTeachDialogParentDiv testDialogParentDiv"></div>')
			.load(url('/test2/testSetTeach', {EkspImageId: e.opt.EkspImageId, start:1, mainPicture:1}))
			.dialog({
				dialogClass: 'TestSetTeachDialog',
				draggable: false,
				width: 800,
				height: 540,
				modal: true,
				resizable: false,
				title: _('Ucz'),
				close: function(event, ui) {
					$('.testDialogParentDiv').remove();
					$('.ac_results').remove();
					$('#searchInput').trigger('focus');
				}

			});
		});
});


$.bind('tests/TestSetGlobalTeach', function(e){
	e.scope.bind('click', function() {
		$('<div class="TestSetGlobalTeachDialogParentDiv testDialogParentDiv"></div>')
			.load(url('/test2/testSetGlobalTeach', {start:1, showCounter: e.opt.showCounter, noBack:1 }))
			.dialog({
				dialogClass: 'TestSetGlobalTeachDialog',
				draggable: false,
				width: 800,
				height: 540,
				modal: true,
				resizable: false,
				title: _('Ucz'),
				close: function(event, ui) {
					$('.testDialogParentDiv').remove();
					$('.ac_results').remove();
					$('#searchInput').trigger('focus');
				}
			});
		});
});



$.bind('tests/removeTeachButton', function(e){
	$('ol#results li.img_' + e.opt.EkspImageId + ' ul.actions li.teach').remove();
});


$.bind('tests/removeTeachButtonMainEksp', function(e){
	$('div#helpBuildProfile').remove();
});

$.bind('tests/setFocus', function(e){
	$('#' + e.opt.inputId).focus();
});

$.bind('tests/setHeader', function(e){
	var title = e.opt.title;
	e.scope.parents('.ui-widget-content').find('div.ui-dialog-titlebar span').html(title);
});

$.bind('test2/setHeader', function(e){
	var title = e.opt.title;
	$('div#pictureNo').html(title);
});



$.bind('test2/closeDialog', function(e){
	e.scope.bind('click', function() {
		e.scope.parents('div.testDialogParentDiv').dialog('close');
	});
});


$.bind('test2/clanTest-selectImage', function(e){
	e.scope.bind('click', function() {
		var options = {EkspClanImageId: e.opt.EkspClanImageId, dialog:1, EkspImageChosenId:e.opt.EkspImageNonChosenId, EkspImageNonChosenId:e.opt.EkspImageNonChosenId, ImagePairId: e.opt.ImagePairId};
		if(e.opt.skip)
			options.skip =1
		$('div.clanTestDialogParentDiv').load(url('/test2/clanTest', options ));
		return false;
	});
});

$.bind('test2/tagTest', function(e){
	e.scope.bind('click', function() {
		$('<div class="tagTestDialogParentDiv testDialogParentDiv"></div>')
			.load(url('/test2/tagTest', {EkspImageId: e.opt.EkspImageId, dialog:1}))
			.dialog({
				dialogClass: 'tagTestDialog',
				draggable: false,
				width: 800,
				height: 540,
				modal: true,
				resizable: false,
				title: _('Ucz'),
				close: function(event, ui) {
					$('.tagTestDialogParentDiv').remove();
				}
			});
		});
});

$.bind('test2/tagTestForm', function(e){
	$('#tagowanie').submit(function(){
		$('.ac_results').remove();
		$('.testContentDiv').trigger('testResult', {EkspImageId: $('#photo').attr('data-id'), tags: $('#tags')[0].value});
		return false;
		
	});
});

$.bind('test2/stageExceed', function(e){
	$('div.testDialogParentDiv').dialog('close');
});

$.bind('test2/showProfile', function(e){
	window.location = url('/user/profile', {user: e.opt.UserId});
});

$.bind('user/LoginOrRegister', function(e){
	$.dialog({
		url: url('/user/profile', {noBack:1}),
		draggable: true,
		modal: true,
		resizable: false,
		title: _('Przeglądaj profil użytkownika'),
		position: 'center',
		width:  400,
		close: function() {
			$(this).remove();
		}});
		return false;
});

$.bind('dialog/close', function(e){
	e.scope.bind('click', function() {
		e.scope.parents(window).dialog('close');
	});
});$.bind('tiny_mce', function(e){
	e.scope.find('textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : ROOT + 'tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

			// Theme options
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			//content_css : "css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js"});
});$.bind('tooltipMsg', function(e) {
	e.scope.find('a.x').bind('click', function() {
		$('#alertContainer').css('display', 'none');
		$(this).parent().hide();
		$('#alertContainer').load(url('/user/tooltipMsgRm', {'hash' : $(this).attr('alt')})).slideToggle('slow');
	})
});;(function($) {
    /*
    * ui.dropdownchecklist
    *
    * Copyright (c) 2008-2010 Adrian Tosca, Copyright (c) 2010 Ittrium LLC
    * Dual licensed under the MIT (MIT-LICENSE.txt)
    * and GPL (GPL-LICENSE.txt) licenses.
    *
    */
    // The dropdown check list jQuery plugin transforms a regular select html element into a dropdown check list.
    $.widget("ui.dropdownchecklist", {
    	// Some globlals
    	// $.ui.dropdownchecklist.gLastOpened - keeps track of last opened dropdowncheck list so we can close it
    	// $.ui.dropdownchecklist.gIDCounter - simple counter to provide a unique ID as needed
        version: function() {
            alert('DropDownCheckList v1.1');
        },    	
        // Creates the drop container that keeps the items and appends it to the document
        _appendDropContainer: function( controlItem ) {
            var wrapper = $("<div/>");
            // the container is wrapped in a div
            wrapper.addClass("ui-dropdownchecklist ui-dropdownchecklist-dropcontainer-wrapper");
            wrapper.addClass("ui-widget");
            // assign an id
            wrapper.attr("id",controlItem.attr("id") + '-ddw');
            // initially hidden
            wrapper.css({ position: 'absolute', left: "-33000px", top: "-33000px"  });
          
            var container = $("<div/>"); // the actual container
            container.addClass("ui-dropdownchecklist-dropcontainer ui-widget-content");
            container.css("overflow-y", "auto");
            wrapper.append(container);
            
            // insert the dropdown after the master control to try to keep the tab order intact
            // if you just add it to the end, tabbing out of the drop down takes focus off the page
            // @todo 22Sept2010 - check if size calculation is thrown off if the parent of the
            //		selector is hidden.  We may need to add it to the end of the document here, 
            //		calculate the size, and then move it back into proper position???
			//$(document.body).append(wrapper);
            wrapper.insertAfter(controlItem);

            // flag that tells if the drop container is shown or not
            wrapper.isOpen = false;
            return wrapper;
        },
        // Look for browser standard 'open' on a closed selector
		_isDropDownKeyShortcut: function(e,keycode) {
			return e.altKey && ($.ui.keyCode.DOWN == keycode);// Alt + Down Arrow
		},
		// Look for key that will tell us to close the open dropdown
		_isDropDownCloseKey: function(e,keycode) {
			return ($.ui.keyCode.ESCAPE == keycode) || ($.ui.keyCode.ENTER == keycode);
		},
		// Handler to change the active focus based on a keystroke, moving some count of
		// items from the element that has the current focus
		_keyFocusChange: function(target,delta,limitToItems) {
			// Find item with current focus
			var focusables = $(":focusable");
			var index = focusables.index(target);
			if ( index >= 0 ) {
				index += delta;
				if ( limitToItems ) {
					// Bound change to list of input elements
	            	var allCheckboxes = this.dropWrapper.find("input:not([disabled])");
	            	var firstIndex = focusables.index(allCheckboxes.get(0));
	            	var lastIndex = focusables.index(allCheckboxes.get(allCheckboxes.length-1));
	            	if ( index < firstIndex ) {
	            		index = lastIndex;
	            	} else if ( index > lastIndex ) {
	            		index = firstIndex;
	            	}
	            }
				focusables.get(index).focus();
			}
		},
		// Look for navigation, open, close (wired to keyup)
		_handleKeyboard: function(e) {
			var self = this;
			var keyCode = (e.keyCode || e.which);
			if (!self.dropWrapper.isOpen && self._isDropDownKeyShortcut(e, keyCode)) {
				// Key command to open the dropdown
				e.stopImmediatePropagation();
				self._toggleDropContainer(true);
			} else if (self.dropWrapper.isOpen && self._isDropDownCloseKey(e, keyCode)) {
				// Key command to close the dropdown (but we retain focus in the control)
				e.stopImmediatePropagation();
				self._toggleDropContainer(false);
				self.controlSelector.focus();
			} else if (self.dropWrapper.isOpen 
					&& (e.target.type == 'checkbox')
					&& ((keyCode == $.ui.keyCode.DOWN) || (keyCode == $.ui.keyCode.UP)) ) {
				// Up/Down to cycle throught the open items
				e.stopImmediatePropagation();
				self._keyFocusChange(e.target, (keyCode == $.ui.keyCode.DOWN) ? 1 : -1, true);
			} else if (self.dropWrapper.isOpen && (keyCode == $.ui.keyCode.TAB) ) {
				// I wanted to adjust normal 'tab' processing here, but research indicates
				// that TAB key processing is NOT a cancelable event. You have to use a timer
				// hack to pull the focus back to where you want it after browser tab
				// processing completes.  Not going to work for us.
				//e.stopImmediatePropagation();
				//self._keyFocusChange(e.target, (e.shiftKey) ? -1 : 1, true);
           }
		},
		// Look for change of focus
		_handleFocus: function(e,focusIn,forDropdown) {
			var self = this;
			if (forDropdown && !self.dropWrapper.isOpen) {
				// if the focus changes when the control is NOT open, mark it to show where the focus is/is not
				e.stopImmediatePropagation();
				if (focusIn) {
					self.controlSelector.addClass("ui-state-hover");
					if ($.ui.dropdownchecklist.gLastOpened != null) {
						$.ui.dropdownchecklist.gLastOpened._toggleDropContainer( false );
					}
				} else {
					self.controlSelector.removeClass("ui-state-hover");
				}
           	} else if (!forDropdown && !focusIn) {
           		// The dropdown is open, and an item (NOT the dropdown) has just lost the focus.
           		// we really need a reliable method to see who has the focus as we process the blur,
           		// but that mechanism does not seem to exist.  Instead we rely on a delay before
           		// posting the blur, with a focus event cancelling it before the delay expires.
				if ( e != null ) { e.stopImmediatePropagation(); }
				self.controlSelector.removeClass("ui-state-hover");
				self._toggleDropContainer( false );	        	
           	}
		},
		// Clear the pending change of focus, which keeps us 'in' the control
		_cancelBlur: function(e) {
			var self = this;
			if (self.blurringItem != null) {
				clearTimeout(self.blurringItem);
				self.blurringItem = null;
			} 
		},
        // Creates the control that will replace the source select and appends it to the document
        // The control resembles a regular select with single selection
        _appendControl: function() {
            var self = this, sourceSelect = this.sourceSelect, options = this.options;

            // the control is wrapped in a basic container
            var wrapper = $("<span/>");
            wrapper.addClass("ui-dropdownchecklist ui-dropdownchecklist-selector-wrapper ui-widget");
            wrapper.css({ cursor: "default", overflow: "hidden" });
            
            // assign an ID 
            var baseID = sourceSelect.attr("id");
            if ((baseID == null) || (baseID == "")) {
            	baseID = "ddcl-" + $.ui.dropdownchecklist.gIDCounter++;
            } else {
            	baseID = "ddcl-" + baseID;
			}
			wrapper.attr("id",baseID);
			
            // the actual control which you can style
            // inline-block needed to enable 'width' but has interesting problems cross browser
            var control = $("<span/>");
            control.addClass("ui-dropdownchecklist-selector ui-state-default");
            control.css( { display: "inline-block", overflow: "hidden", 'white-space': 'nowrap'} );
            // Setting a tab index means we are interested in the tab sequence
            var tabIndex = sourceSelect.attr("tabIndex");
            if ( tabIndex == null ) {
            	tabIndex = 0;
            } else {
            	tabIndex = parseInt(tabIndex);
            	if ( tabIndex < 0 ) {
            		tabIndex = 0;
            	}
            }
			control.attr("tabIndex", tabIndex);
			control.keyup(function(e) {self._handleKeyboard(e);});
			control.focus(function(e) {self._handleFocus(e,true,true);});
			control.blur(function(e) {self._handleFocus(e,false,true);});
            wrapper.append(control);

			// the optional icon (which is inherently a block)
			if (options.icon != null) {
				var iconPlacement = (options.icon.placement == null) ? "left" : options.icon.placement;
	            var anIcon = $("<div/>");
	            anIcon.addClass("ui-icon");
	            anIcon.addClass( (options.icon.toOpen != null) ? options.icon.toOpen : "ui-icon-triangle-1-e");
	            anIcon.css({ 'float': iconPlacement });
	            control.append(anIcon);
			}
            // the text container keeps the control text that is built from the selected (checked) items
            // inline-block needed to enable 'width' but has interesting problems cross browser
            var textContainer = $("<span/>");
            textContainer.addClass("ui-dropdownchecklist-text");
            textContainer.css( {  display: "inline-block", 'white-space': "nowrap", overflow: "hidden" } );
            control.append(textContainer);

            // add the hover styles to the control
            wrapper.hover(
	            function() {
	                if (!self.disabled) {
	                    control.addClass("ui-state-hover");
	                }
	            }
	        , 	function() {
	                if (!self.disabled) {
	                    control.removeClass("ui-state-hover");
	                }
	            }
	        );
            // clicking on the control toggles the drop container
            wrapper.click(function(event) {
                if (!self.disabled) {
                    event.stopImmediatePropagation();
                    self._toggleDropContainer( !self.dropWrapper.isOpen );
                }
            });
            wrapper.insertAfter(sourceSelect);

			// Watch for a window resize and adjust the control if open
            $(window).resize(function() {
                if (!self.disabled && self.dropWrapper.isOpen) {
                	// Reopen yourself to get the position right
                    self._toggleDropContainer(true);
                }
            });       
            return wrapper;
        },
        // Creates a drop item that coresponds to an option element in the source select
        _createDropItem: function(index, tabIndex, value, text, checked, disabled, indent) {
            var self = this, options = this.options, sourceSelect = this.sourceSelect, controlWrapper = this.controlWrapper;
            // the item contains a div that contains a checkbox input and a lable for the text
            // the div
            var item = $("<div/>");
            item.addClass("ui-dropdownchecklist-item");
            item.css({'white-space': "nowrap"});
            var checkedString = checked ? ' checked="checked"' : '';
			var classString = disabled ? ' class="inactive"' : ' class="active"';
			
			// generated id must be a bit unique to keep from colliding
			var idBase = controlWrapper.attr("id");
			var id = idBase + '-i' + index;
            var checkBox;
            
            // all items start out disabled to keep them out of the tab order
            if (self.isMultiple) { // the checkbox
                checkBox = $('<input disabled type="checkbox" id="' + id + '"' + checkedString + classString + ' tabindex="' + tabIndex + '" />');
            } else { // the radiobutton
                checkBox = $('<input disabled type="radio" id="' + id + '" name="' + idBase + '"' + checkedString + classString + ' tabindex="' + tabIndex + '" />');
            }
            checkBox = checkBox.attr("index", index).val(value);
            item.append(checkBox);
            
            // the text
            var label = $("<label for=" + id + "/>");
            label.addClass("ui-dropdownchecklist-text");
            label.css({ cursor: "default" });
            label.text(text);
			if (indent) {
				item.addClass("ui-dropdownchecklist-indent");
			}
			item.addClass("ui-state-default");
			if (disabled) {
				item.addClass("ui-state-disabled");
			}
	        label.click(function(e) {e.stopImmediatePropagation();});
            item.append(label);
            
           	// active items display themselves with hover
            item.hover(
            	function(e) {
            		var anItem = $(this);
                	if (!anItem.hasClass("ui-state-disabled")) { anItem.addClass("ui-state-hover"); }
            	}
            , 	function(e) {
            		var anItem = $(this);
                	anItem.removeClass("ui-state-hover");
            	}
            );
            // clicking on the checkbox synchronizes the source select
	        checkBox.click(function(e) {
	        	var aCheckBox = $(this);
				e.stopImmediatePropagation();
				if (options.closeRadioOnClick || aCheckBox.hasClass("active") ) {
					// Active checkboxes take active action
	                self._syncSelected(aCheckBox);
	                self.sourceSelect.trigger("change", 'ddcl_internal');
	                if (options.closeRadioOnClick) {
	                	self._toggleDropContainer(false);
	                }
				}
	        });
	        // we are interested in the focus leaving the check box
	        // but we need to detect the focus leaving one check box but
	        // entering another. There is no reliable way to detect who
	        // received the focus on a blur, so post the blur in the future,
	        // knowing we will cancel it if we capture the focus in a timely manner
	        // 23Sept2010 - unfortunately, IE 7+ and Chrome like to post a blur
	        // 				event to the current item with focus when the user
	        //				clicks in the scroll bar. So if you have a scrollable
	        //				dropdown with focus on an item, clicking in the scroll
	        //				will close the drop down.
	        //				I have no solution for blur processing at this time.
/*********
			var timerFunction = function(){ 
				// I had a hell of a time getting setTimeout to fire this, do not try to
				// define it within the blur function
				try { self._handleFocus(null,false,false); } catch(ex){ alert('timer failed: '+ex);}
			};
			checkBox.blur(function(e) { 
				self.blurringItem = setTimeout( timerFunction, 200 ); 
			});
			checkBox.focus(function(e) {self._cancelBlur();});
**********/	
	        // check/uncheck the item on clicks on the entire item div
	        item.click(function(e) {
	        	var anItem = $(this);
                e.stopImmediatePropagation();
				if (!anItem.hasClass("ui-state-disabled") ) {
					// check/uncheck the underlying control
					var aCheckBox = anItem.find("input");
	                var checked = aCheckBox.attr("checked");
	                aCheckBox.attr("checked", !checked);
	                self._syncSelected(aCheckBox);
	                self.sourceSelect.trigger("change", 'ddcl_internal');
	                if (!checked && !self.isMultiple && options.closeRadioOnClick) {
	                	self._toggleDropContainer(false);
	                }
				} else {
					// retain the focus even if disabled
					anItem.focus();
					self._cancelBlur();
				}
	        });
	        // do not let the focus wander around
			item.focus(function(e) { 
	        	var anItem = $(this);
                e.stopImmediatePropagation();
            });
			item.keyup(function(e) {self._handleKeyboard(e);});
            return item;
        },
		_createGroupItem: function(text,disabled) {
			var self = this;
			var group = $("<div />");
			group.addClass("ui-dropdownchecklist-group ui-widget-header");
			if (disabled) {
				group.addClass("ui-state-disabled");
			}
			group.css({'white-space': "nowrap"});
			
            var label = $("<span/>");
            label.addClass("ui-dropdownchecklist-text");
            label.css( { cursor: "default" });
            label.text(text);
			group.append(label);
			
			// anything interesting when you click the group???
	        group.click(function(e) {
	        	var aGroup= $(this);
                e.stopImmediatePropagation();
                // retain the focus even if no action is taken
                aGroup.focus();
                self._cancelBlur();
            });
	        // do not let the focus wander around
			group.focus(function(e) { 
	        	var aGroup = $(this);
                e.stopImmediatePropagation();
            });
			return group;
		},
        // Creates the drop items and appends them to the drop container
        // Also calculates the size needed by the drop container and returns it
        _appendItems: function() {
            var self = this, sourceSelect = this.sourceSelect, dropWrapper = this.dropWrapper;
            var dropContainerDiv = dropWrapper.find(".ui-dropdownchecklist-dropcontainer");
			sourceSelect.children().each(function(index) { // when the select has groups
				var opt = $(this);
                if (opt.is("option")) {
                    self._appendOption(opt, dropContainerDiv, index, false, false);
                } else if (opt.is("optgroup")) {
					var disabled = opt.attr("disabled");
                    var text = opt.attr("label");
                    if (text != "") {
	                    var group = self._createGroupItem(text,disabled);
	                    dropContainerDiv.append(group);
	                }
                    self._appendOptions(opt, dropContainerDiv, index, true, disabled);
                }
			});
            var divWidth = dropContainerDiv.outerWidth();
            var divHeight = dropContainerDiv.outerHeight();
            return { width: divWidth, height: divHeight };
        },
		_appendOptions: function(parent, container, parentIndex, indent, forceDisabled) {
			var self = this;
			parent.children("option").each(function(index) {
                var option = $(this);
                var childIndex = (parentIndex + "." + index);
                self._appendOption(option, container, childIndex, indent, forceDisabled);
            });
		},
        _appendOption: function(option, container, index, indent, forceDisabled) {
            var self = this;
            var text = option.text();
            var value = option.val();
            var selected = option.attr("selected");
			var disabled = (forceDisabled || option.attr("disabled"));
			// Use the same tab index as the selector replacement
			var tabIndex = self.controlSelector.attr("tabindex");
            var item = self._createDropItem(index, tabIndex, value, text, selected, disabled, indent);
            container.append(item);
        },
        // Synchronizes the items checked and the source select
        // When firstItemChecksAll option is active also synchronizes the checked items
        // senderCheckbox parameters is the checkbox input that generated the synchronization
        _syncSelected: function(senderCheckbox) {
            var self = this, options = this.options, sourceSelect = this.sourceSelect, dropWrapper = this.dropWrapper;
            var allCheckboxes = dropWrapper.find("input.active");
			//var allCheckboxes = dropWrapper.find("input");
			
			/* dont allow disabled to be checked
			var disabledChecks = dropWrapper.find("input.inactive");
			disabledChecks.attr("checked", false );
			*/
			
            if (options.firstItemChecksAll) {
                // if firstItemChecksAll is true, check all checkboxes if the first one is checked
                if ((senderCheckbox != null) && (senderCheckbox.attr("index") == 0)) {
                    allCheckboxes.attr("checked", senderCheckbox.attr("checked"));
                } else  {
                    // check the first checkbox if all the other checkboxes are checked
                    var allChecked = true;
                    var firstCheckbox = null;
                    allCheckboxes.each(function(index) {
                        if (index > 0) {
                            var checked = $(this).attr("checked");
                            if (!checked) { allChecked = false; }
                        } else {
                        	firstCheckbox = $(this);
                        }
                    });
                    if ( firstCheckbox != null ) {
                    	firstCheckbox.attr("checked", allChecked );
                    }
                }
            }
            // do the actual synch with the source select
            allCheckboxes = dropWrapper.find("input");
            var selectOptions = sourceSelect.get(0).options;
            allCheckboxes.each(function(index) {
                $(selectOptions[index]).attr("selected", $(this).attr("checked"));
            });
            // update the text shown in the control
            self._updateControlText();
        	
        	// Ensure the focus stays pointing where the user is working
        	if ( senderCheckbox != null) { senderCheckbox.focus(); }
        },
        _sourceSelectChangeHandler: function(event) {
            var self = this, dropWrapper = this.dropWrapper;
            dropWrapper.find("input").val(self.sourceSelect.val());

        	// update the text shown in the control
        	self._updateControlText();
        },
        // Updates the text shown in the control depending on the checked (selected) items
        _updateControlText: function() {
            var self = this, sourceSelect = this.sourceSelect, options = this.options, controlWrapper = this.controlWrapper;
            var firstOption = sourceSelect.find("option:first");
            var selectOptions = sourceSelect.find("option");
            var text = self._formatText(selectOptions, options.firstItemChecksAll, firstOption);
            var controlLabel = controlWrapper.find(".ui-dropdownchecklist-text");
            controlLabel.html(text);
            controlLabel.attr("title", text);
        },
        // Formats the text that is shown in the control
        _formatText: function(selectOptions, firstItemChecksAll, firstOption) {
            var text;
            if ( $.isFunction(this.options.textFormatFunction) ) {
            	// let the callback do the formatting, but do not allow it to fail
            	try {
                	text = this.options.textFormatFunction(selectOptions);
                } catch(ex) {
                	alert( 'textFormatFunction failed: ' + ex );
                }
            } else if (firstItemChecksAll && (firstOption != null) && firstOption.attr("selected")) {
                // just set the text from the first item
                text = firstOption.text();
            } else {
                // concatenate the text from the checked items
                text = "";
                selectOptions.each(function() {
                    if ($(this).attr("selected")) {
                        if ( text != "" ) { text += ", "; }
                        text += $(this).text();
                    }
                });
                if ( text == "" ) {
                    text = (this.options.emptyText != null) ? this.options.emptyText : "&nbsp;";
                }
            }
            return text;
        },
        // Shows and hides the drop container
        _toggleDropContainer: function( makeOpen ) {
            var self = this;
            // hides the last shown drop container
            var hide = function(instance) {
                if ((instance != null) && instance.dropWrapper.isOpen ){
                    instance.dropWrapper.isOpen = false;
                    $.ui.dropdownchecklist.gLastOpened = null;

	            	var config = instance.options;
                    instance.dropWrapper.css({
                        top: "-33000px",
                        left: "-33000px"
                    });
                    var aControl = instance.controlSelector;
	                aControl.removeClass("ui-state-active");
	                aControl.removeClass("ui-state-hover");

                    var anIcon = instance.controlWrapper.find(".ui-icon");
                    if ( anIcon.length > 0 ) {
                    	anIcon.removeClass( (config.icon.toClose != null) ? config.icon.toClose : "ui-icon-triangle-1-s");
                    	anIcon.addClass( (config.icon.toOpen != null) ? config.icon.toOpen : "ui-icon-triangle-1-e");
                    }
                    $(document).unbind("click", hide);
                    
                    // keep the items out of the tab order by disabling them
                    instance.dropWrapper.find("input.active").attr("disabled","disabled");
                    
                    // the following blur just does not fire???  because it is hidden???  because it does not have focus???
			  		//instance.sourceSelect.trigger("blur");
			  		//instance.sourceSelect.triggerHandler("blur");
			  		if($.isFunction(config.onComplete)) { try {
			     		config.onComplete.call(instance,instance.sourceSelect.get(0));
                    } catch(ex) {
                    	alert( 'callback failed: ' + ex );
                    }}
                }
            };
            // shows the given drop container instance
            var show = function(instance) {
            	if ( !instance.dropWrapper.isOpen ) {
	                instance.dropWrapper.isOpen = true;
	                $.ui.dropdownchecklist.gLastOpened = instance;

	            	var config = instance.options;
	                instance.dropWrapper.css({
	                    top: instance.controlWrapper.position().top + instance.controlWrapper.outerHeight() + "px",
	                    left: instance.controlWrapper.position().left + "px"
	                });
					var ancestorsZIndexes = instance.controlWrapper.parents().map(
						function() {
							var zIndex = $(this).css("z-index");
							return isNaN(zIndex) ? 0 : zIndex; }
						).get();
					var parentZIndex = Math.max.apply(Math, ancestorsZIndexes);
					if (parentZIndex > 0) {
						instance.dropWrapper.css({
							zIndex: (parentZIndex+1)
						});
					}
	                var aControl = instance.controlSelector;
	                aControl.addClass("ui-state-active");
	                aControl.removeClass("ui-state-hover");
	                
	                var anIcon = instance.controlWrapper.find(".ui-icon");
	                if ( anIcon.length > 0 ) {
	                	anIcon.removeClass( (config.icon.toOpen != null) ? config.icon.toOpen : "ui-icon-triangle-1-e");
	                	anIcon.addClass( (config.icon.toClose != null) ? config.icon.toClose : "ui-icon-triangle-1-s");
	                }
	                $(document).bind("click", function(e) {hide(instance);} );
	                
                    // insert the items back into the tab order by enabling all active ones
                    var activeItems = instance.dropWrapper.find("input.active");
                    activeItems.removeAttr("disabled");
                    
                    // we want the focus on the first active input item
                    var firstActiveItem = activeItems.get(0);
                    if ( firstActiveItem != null ) {
                    	firstActiveItem.focus();
                    }
			    }
            };
            if ( makeOpen ) {
            	hide($.ui.dropdownchecklist.gLastOpened);
            	show(self);
            } else {
            	hide(self);
            }
        },
        // Set the size of the control and of the drop container
        _setSize: function(dropCalculatedSize) {
            var options = this.options, dropWrapper = this.dropWrapper, controlWrapper = this.controlWrapper;

            // use the width from config options if set, otherwise set the same width as the drop container
            var controlWidth = dropCalculatedSize.width;
            if (options.width != null) {
                controlWidth = parseInt(options.width);
            } else if (options.minWidth != null) {
                var minWidth = parseInt(options.minWidth);
                // if the width is too small (usually when there are no items) set a minimum width
                if (controlWidth < minWidth) {
                    controlWidth = minWidth;
                }
            }
            var control = this.controlSelector;
            control.css({ width: controlWidth + "px" });
            
            // if we size the text, then Firefox places icons to the right properly
            // and we do not wrap on long lines
            var controlText = control.find(".ui-dropdownchecklist-text");
            var controlIcon = control.find(".ui-icon");
            if ( controlIcon != null ) {
            	// Must be an inner/outer/border problem, but IE6 needs an extra bit of space
            	controlWidth -= (controlIcon.outerWidth() + 6);
            	controlText.css( { width: controlWidth + "px" } );
            }
            // Account for padding, borders, etc
            controlWidth = controlWrapper.outerWidth();
            
            // the drop container height can be set from options
            var maxDropHeight = (options.maxDropHeight != null)
            					? parseInt(options.maxDropHeight)
            					: -1;
            var dropHeight = ((maxDropHeight > 0) && (dropCalculatedSize.height > maxDropHeight))
            					? maxDropHeight 
            					: dropCalculatedSize.height;
            // ensure the drop container is not less than the control width (would be ugly)
            var dropWidth = dropCalculatedSize.width < controlWidth ? controlWidth : dropCalculatedSize.width;

            $(dropWrapper).css({
                height: dropHeight + 10 + "px",
                width: dropWidth + "px"
            });
            dropWrapper.find(".ui-dropdownchecklist-dropcontainer").css({
                height: dropHeight + 10 + "px"
            });
        },
        // Initializes the plugin
        _init: function() {
            var self = this, options = this.options;
			if ( $.ui.dropdownchecklist.gIDCounter == null) {
				$.ui.dropdownchecklist.gIDCounter = 1;
			}
            // item blurring relies on a cancelable timer
            self.blurringItem = null;

            // sourceSelect is the select on which the plugin is applied
            var sourceSelect = self.element;
            self.initialDisplay = sourceSelect.css("display");
            sourceSelect.css("display", "none");
            self.initialMultiple = sourceSelect.attr("multiple");
            self.isMultiple = self.initialMultiple;
            if (options.forceMultiple != null) { self.isMultiple = options.forceMultiple; }
            sourceSelect.attr("multiple", true);
            self.sourceSelect = sourceSelect;

            // append the control that resembles a single selection select
            var controlWrapper = self._appendControl();
            self.controlWrapper = controlWrapper;
            self.controlSelector = controlWrapper.find(".ui-dropdownchecklist-selector");

            // create the drop container where the items are shown
            var dropWrapper = self._appendDropContainer(controlWrapper);
            self.dropWrapper = dropWrapper;

            // append the items from the source select element
            var dropCalculatedSize = self._appendItems();

            // updates the text shown in the control
            self._updateControlText(controlWrapper, dropWrapper, sourceSelect);

            // set the sizes of control and drop container
            self._setSize(dropCalculatedSize);
            
            // look for possible auto-check needed on first item
			if ( options.firstItemChecksAll ) {
				self._syncSelected(null);
			}
            // BGIFrame for IE6
			if (options.bgiframe && typeof self.dropWrapper.bgiframe == "function") {
				self.dropWrapper.bgiframe();
			}
          	// listen for change events on the source select element
          	// ensure we avoid processing internally triggered changes
          	self.sourceSelect.change(function(event, eventName) {
	            if (eventName != 'ddcl_internal') {
	                self._sourceSelectChangeHandler(event);
	            }
	        });
        },
        // Refresh the disable and check state from the underlying control
        _refreshOption: function(item,disabled,selected) {
			var aParent = item.parent();
			// account for enabled/disabled
            if ( disabled ) {
            	item.attr("disabled","disabled");
            	item.removeClass("active");
            	item.addClass("inactive");
            	aParent.addClass("ui-state-disabled");
            } else {
            	item.removeAttr("disabled");
            	item.removeClass("inactive");
            	item.addClass("active");
            	aParent.removeClass("ui-state-disabled");
            }
            // adjust the checkbox state
            item.attr("checked",selected);
        },
        _refreshGroup: function(group,disabled) {
            if ( disabled ) {
            	group.addClass("ui-state-disabled");
            } else {
            	group.removeClass("ui-state-disabled");
            }
        },
        refresh: function() {
            var self = this, sourceSelect = this.sourceSelect, dropWrapper = this.dropWrapper;
            
            var allCheckBoxes = dropWrapper.find("input");
            var allGroups = dropWrapper.find(".ui-dropdownchecklist-group");
            
            var groupCount = 0;
            var optionCount = 0;
			sourceSelect.children().each(function(index) {
				var opt = $(this);
				var disabled = opt.attr("disabled");
                if (opt.is("option")) {
                	var selected = opt.attr("selected");
                	var anItem = $(allCheckBoxes[optionCount]);
                    self._refreshOption(anItem, disabled, selected);
                    optionCount += 1;
                } else if (opt.is("optgroup")) {
                    var text = opt.attr("label");
                    if (text != "") {
                    	var aGroup = $(allGroups[groupCount]);
                    	self._refreshGroup(aGroup, disabled);
                    	groupCount += 1;
	                }
					opt.children("option").each(function(subindex) {
		                var subopt = $(this);
						var subdisabled = (disabled || subopt.attr("disabled"));
                		var selected = subopt.attr("selected");
                		var subItem = $(allCheckBoxes[optionCount + subindex]);
		                self._refreshOption(subItem, subdisabled, selected );
		            });
                }
			});
        	// update the text shown in the control
        	self._updateControlText();
        },
        enable: function() {
            this.controlSelector.removeClass("ui-state-disabled");
            this.disabled = false;
        },
        disable: function() {
            this.controlSelector.addClass("ui-state-disabled");
            this.disabled = true;
        },
        destroy: function() {
            $.Widget.prototype.destroy.apply(this, arguments);
            this.sourceSelect.css("display", this.initialDisplay);
            this.sourceSelect.attr("multiple", this.initialMultiple);
            this.controlWrapper.unbind().remove();
            this.dropWrapper.remove();
        }
    });

    $.extend($.ui.dropdownchecklist, {
        defaults: {
            width: null,
            maxDropHeight: null,
            firstItemChecksAll: false,
            closeRadioOnClick: false,
            minWidth: 50,
            bgiframe: false
        }
    });

})(jQuery);
$.bind('userActivation/showLoginForm', function() {
	$(window).load(function(){
		$('#openLoginForm').click();
	});
});
$.bind('user/addToFavourites', function() {
	$('#addToFavourites').delegate('a', 'click', function(e) {
		$(this).parent().load(url('/user/profile/addToFavourites'), {'UserId' : $(this).attr('alt')});
		return false;
	});
});
function loadChannelList() {
    $('#channel_list').load('/s/user/channel/list');
    $('#channel_info').html('');
}

$.bind('loadChannelList', loadChannelList);

function post_add_channel_callback(data) {
if (data.errorMsg != null) {

    alert(data.errorMsg);
    return;
} else {
   notify(_('Kanał został dodany'));
   loadChannelList();

};

}

function post_add_channel(name) {
    if(name.replace(/^\s+|\s+$/g,"") == '') {
        alert(_('Nazwa nie może być pusta.'));
	return;
    };
    $.ajax( {
        url: "/s/user/channel/addChannel",
        type: 'POST',
        data: { name: name },
        cache: false,
        dataType: 'json',
        success: function(data){post_add_channel_callback(data)}});

}


function add_channel() {
    if ($('#dialog_add_channel').length == 0) {
        $('#dummy').append('<div id="dialog_add_channel" title="' + _('Nowy kanał') +'" ><form name="form_new_channel" onsubmit="return false;"><label for="channel_name">' + _('Nazwa:') + '</label><input name="channel_name" id="channel_name" type="text" value="'+ _('nowy kanał') + '" /></form></div>');

        $('#dialog_add_channel').dialog({
			bgiframe: true,
			height: 240,
			width: 400,
			modal: true,
			buttons: {
			     'Ok' : function (){ post_add_channel($('#channel_name').get(0).value); $(this).dialog("close");  },
			     'Cancel' : function() { $(this).dialog("close"); }}});


    } else {

        $('#dialog_add_channel').dialog('open');
	$('#channel_name').get(0).value = _('nowy kanał');
    };
    $('#channel_name').focus();
};

function load_channel(channelId, channelInfoSelector) {
	$(channelInfoSelector).load('/s/user/channel/channelInfo?id='+channelId);

};



function deleteEventFromChannel(channelId, eventId) {
	if ($('#dialog_del_event_from_channel').length == 0) {
		$('#dummy').append('<div id="dialog_del_event_from_channel" title="'+ _('Usuń wydarzenie z kanału.')+'"><p>'+ _('Czy na pewno chcesz usunąć wydarzenie z kanału?') + '</p></div>');
	
		$("#dialog_del_event_from_channel").dialog({
			resizable: false,
			autoOpen: true,
			height:240,
			width: 400,
			modal: true,
			buttons: {
				'Usuń': function() {

				    $.ajax( {
				        url: "/s/user/channel/delEventFromChannel",
				        type: 'POST',
				        data: { channelId: channelId, eventId: eventId },
				        cache: false,
				        dataType: 'json',
				        success: function(data) {
						if(data.errorMsg != null)
							notify(data.errorMsg)
						else
							notify(_('Wydarzenie zostało usunięte z kanału'));
					}});


					$(this).dialog('close');
				},
				'Anuluj': function() {
					$(this).dialog('close');
				}
			}
		});
	};
	$("#dialog_del_event_from_channel").dialog('open');

};

function deleteCategoryFromChannel(channelId, categoryId) {
	if ($('#dialog_del_category_from_channel').length == 0) {
		$('#dummy').append('<div id="dialog_del_category_from_channel" title="'+ _('Usuń kategorię z kanału.') + '"><p>'+ _('Czy na pewno chcesz kategorię wydarzenie z kanału?') + '</p></div>');
	
		$("#dialog_del_category_from_channel").dialog({
			resizable: false,
			autoOpen: true,
			height:240,
			width: 400,
			modal: true,
			buttons: {
				'Usuń': function() {

				    $.ajax( {
				        url: "/s/user/channel/delCategoryFromChannel",
				        type: 'POST',
				        data: { channelId: channelId, categoryId: categoryId },
				        cache: false,
				        dataType: 'json',
				        success: function(data) {
						if(data.errorMsg != null)
							notify(data.errorMsg)
						else
							notify(_('Kategoria została usunięte z kanału'));
					}});


					$(this).dialog('close');
				},
				'Anuluj': function() {
					$(this).dialog('close');
				}
			}
		});
	};
	$("#dialog_del_category_from_channel").dialog('open');

};

function deleteChannel(channelId) {
	if ($('#dialog_del_channel').length == 0) {
		$('#dummy').append('<div id="dialog_del_channel" title="'+ _('Usuń kanał.') + '"><p>'+ _('Czy na pewno chcesz usunąć kanał?') + '</p></div>');
	
		$("#dialog_del_channel").dialog({
			resizable: false,
			autoOpen: true,
			height:240,
			width: 400,
			modal: true,
			buttons: {
				'Usuń': function() {

				    $.ajax( {
				        url: "/s/user/channel/delChannel",
				        type: 'POST',
				        data: { channelId: channelId },
				        cache: false,
				        dataType: 'json',
				        success: function(data) {
						if(data.errorMsg != null)
							notify(data.errorMsg)
						else
							notify(_('Kanał został usunęty.'));
							loadChannelList();
					}});

					$(this).dialog('close');
				},
				'Anuluj': function() {
					$(this).dialog('close');
				}
			}
		});
	};
	$("#dialog_del_channel").dialog('open');

};



function addCategoryToChannel(channelId) {

   if ($('#dialog_add_category_to_channel').length == 0) {
        $('#dummy').append('<div id="dialog_add_category_to_channel" title="'+ _('Dodaj kategorię do kanału') + '" ></div>');
        $('#dialog_add_category_to_channel').load('/s/user/channel/addCategoryToChannelForm?channelId=' + channelId);

        $('#dialog_add_category_to_channel').dialog({
                        bgiframe: true,
                        height: 240,
                        width : 400,
                        modal: true,
                        buttons: {
                             'Ok' : function (){
                                if (document.forms['addCategoryToChannelForm'].channelId.value != '')

                                $.ajax( {
                                    url: '/s/user/channel/addCategoryToChannel',
                                    type: 'POST',
                                    data: { categoryId: document.forms['addCategoryToChannelForm'].categoryId.value, channelId: document.forms['addCategoryToChannelForm'].channelId.value  },
                                    cache: false,
                                    dataType: 'json',
                                    success: function(data){
                                        if (data.errorMsg != null )
                                            notify(data.errorMsg);
                                        else
                                            notify(_('Kategoria została dodana do kanału.'));
                                        }} );


                                $(this).dialog("close");
                                },
                             'Cancel' : function() { $(this).dialog("close"); }}});


    } else {
        $('#dialog_add_category_to_channel').load('/s/user/channel/addCategoryToChannelForm?channelId=' + channelId);
        $('#dialog_add_category_to_channel').dialog('open');
    };

};
function groupAction(userId, groupId, action){
	//alert(userId+' '+action+' '+groupId);
	$.post(url('/group/action'), {
		userId : userId,
		groupId: groupId,
		action : action},
	function(data){
		//odswierzanie modułów
		$.modulesReloadByType('UserFriendship');
		$.modulesReloadByType('UserProfileNearbyGroup');
		

	});
}

function createGroup(UserId){
	window.location = url('group/createNearby', {user: UserId});
}
$.bind('getLocation', function(e) {
	function responseToAddress(resp, latlng){
		addr = resp.split(',');
		street = addr[0];
		arr = street.split(' ');
		street = '';
		for(i=0; i<arr.length-1; i++)
			street = street+' '+arr[i];
		number = arr[arr.length-1];
		city = addr[1];
		street = street.replace(/^\s+|\s+$/g, '');
		number = number.replace(/^\s+|\s+$/g, '');
		city = city.replace(/^\s+|\s+$/g, '');
		$.post(url('/user/getLocation'), {
			street: street,
			number: number,
			city: city,
			lat: latlng.lat(),
			lng: latlng.lng(),
			country: geoip_country_name(),
			region: geoip_region_name() 
		});
	}

	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(geoip_latitude(), geoip_longitude());
	if (geocoder) {
		geocoder.geocode({'latLng': latlng}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				if (results[0]) {
					responseToAddress(results[0].formatted_address, latlng);
				}else if(results[1]){
					responseToAddress(results[1].formatted_address, latlng);
				}
			} else {
				notify("Nie udało się ustalić Twojej lokalizacji. (" + status + ")");
			}
		});
	}
});/**
 * Licznik "pulsu"
 */
var heartbeatCount = 1;
/**
 * Zmienna zegara
 */
var heartbeatTimer = null;

/**
 * Wysłanie kolejnego sygnału aktywności po określonym czasie
 */
function heartbeat(){
	heartbeatTimer = setTimeout(
			function() {
				$.get(url('/user/heartbeat'), {'count':heartbeatCount++});
				heartbeat();
			}, 180000);		// Co jaki czas ma być wysyłany hearbeat, jak często user się ma nam "meldować" (sekundy)
}
heartbeat();$.bind('user/import/table', function(e) {
	$('.top a#selectAll').bind('click', function () {
		$('li.item').removeClass('choosen').click();
	});
	$('li.item').bind('click', function () {
		if ($(this).hasClass('choosen')) {
			$(this).removeClass('choosen');
		} else {
			$(this).addClass('choosen');
		}
		$(this).parent().find('input[alt='+$(this).attr('id')+']').click();
	});
	e.scope.find('input:checkbox').bind('click', function () {
		if ($.browser.msie) {
			if ($(this).checked()) {
				var newCh = $(this).parent().parent().clone(true);
				newCh.find('input').val([$(this).attr('name')]);
				newCh.find('input').attr('checked', 'checked');
				$('#userImport').append(newCh);
			}
		}
	});
	e.scope.find('input').bind('change', function() {
		if (!$.browser.msie) {
			if ($(this).checked()) {
				$('#userImport').append($(this).parent().parent().clone(true));
			} else {
				$('#userImport').find('input[name="'+ $(this).attr('name') + '"]').parent().parent().remove();
			}
		}
	});
	$('#userImport').find('input').each(function() {
		e.scope.find('input[name="'+ $(this).attr('name') + '"]').attr('checked', 'checked');	
	});
});

$.bind('user/import', function(e) {
	e.scope.find('input#sendInvitation').bind('click', function () {
		var email = '';
		var fb = [];
		if(e.scope.find('#invEmail').val() != undefined && e.scope.find('#invEmail').val() != _('Wpisz adresy email znajomych, rozdzielając je przecinkami')) {
		    email = e.scope.find('#invEmail').val();
		}
		$('li.item.choosen.gmail').each(function () {
			if (email != '')
				email += ',';
			email += $(this).attr('id');
		});
		$('li.item.choosen.fb').each(function () {
			fb.push($(this).attr('id'));
		});
		$.ajax({
			type: 'POST',
			success: function(){
			    redirect('/index');
			},
			url: url('/user/import/send'),
			data: {
				'email' : email,
				'fb' : fb
			}
		});
		return false;
	});
	$(window).bind('unload', function() {
		var data = [];
		$('#userImport').find('input').each(function() { data.push($(this).attr('alt')); });
		$.post(url('/user/import/save'), {selected: data});
	});

	$('#userImport')
	.load(url('/user/import/load'), function() {
		$(this).find('input:checkbox').attr('checked', 'checked');
		/// \todo dup line 19
		$('#userImport').find('input').each(function() {
			e.scope.find('input[name="'+ $(this).attr('name') + '"]').attr('checked', 'checked');	
		});
	})
	.delegate('input:checkbox', 'click', function() {
		e.scope.find('input[name="'+ $(this).attr('name') +'"]').val([false]);
		$(this).parent().parent().remove();
	});
	;
	$('#fb a').bind('click', function () {
		$('#ajax-wait').toggle();
	});
});
/*
 * dodwanie kategorii do strony glownej
 */
$.bind('indexCategoryAction', function(e) {
	$('a.categoryAdd').bind('click', function(){
		id = $(this).attr('alt');
		$.post(url('/user/category'), {
			id: id,
			action: 1});
		$(this).text('-');
		$(this).removeClass('categoryAdd');
		$(this).addClass('categoryRemove');
		rankingSystemAction(id, 'indexAdd', 'tag');
		notify(_('Dodano kategorię do strony głównej'));
	});
	$('a.categoryRemove').bind('click', function(){
		$.post(url('/user/category'), {
			id: $(this).attr('alt'),
			action: 0});
		$(this).text('+');
		$(this).removeClass('categoryRemove');
		$(this).addClass('categoryAdd');
		notify(_('Usunięto kategorię ze strony głównej'));
	});
});function refuseInvitation(user1, item, del){
	var x=window.confirm(_('Czy na pewno usunąć znajomego?'));
	if (x) {
		$(item).parent().remove();
		$.get(url('/user/profile/sendInvitation'), {'UserId':user1, 'del':del});	
	}
}

function sendMailInvitation(mail, item) {
	$(item).parent().html('');
	$.get(url('/user/profile/sendInvitation'), {'email':mail}, function(data){
		notify(data);
	});
}
/**
 * ezMark (Minified) - A Simple Checkbox and Radio button Styling plugin. This plugin allows you to use a custom Image for 
 * Checkbox or Radio button. Its very simple, small and easy to use.
 * 
 * Copyright (c) Abdullah Rubiyath <http://www.itsalif.info/>.
 * Released under MIT License
 * 
 * @author Abdullah Rubiyath
 * @version 1.0
 * @date June 27, 2010
 */
(function($){$.fn.ezMark=function(options){options=options||{};var defaultOpt={checkboxCls:options.checkboxCls||'ez-checkbox',radioCls:options.radioCls||'ez-radio',checkedCls:options.checkedCls||'ez-checked',selectedCls:options.selectedCls||'ez-selected',hideCls:'ez-hide'};return this.each(function(){var $this=$(this);var wrapTag=$this.attr('type')=='checkbox'?'<div class="'+defaultOpt.checkboxCls+'">':'<div class="'+defaultOpt.radioCls+'">';if($this.attr('type')=='checkbox'){$this.addClass(defaultOpt.hideCls).wrap(wrapTag).change(function(){if($(this).is(':checked')){$(this).parent().addClass(defaultOpt.checkedCls);}
else{$(this).parent().removeClass(defaultOpt.checkedCls);}});if($this.is(':checked')){$this.parent().addClass(defaultOpt.checkedCls);}}
else if($this.attr('type')=='radio'){$this.addClass(defaultOpt.hideCls).wrap(wrapTag).change(function(){$('input[name="'+$(this).attr('name')+'"]').each(function(){if($(this).is(':checked')){$(this).parent().addClass(defaultOpt.selectedCls);}else{$(this).parent().removeClass(defaultOpt.selectedCls);}});});if($this.is(':checked')){$this.parent().addClass(defaultOpt.selectedCls);}}});}})(jQuery);/**
 * Usuwanie wszystkich zaznaczonych wiadomości poczty wewnętrznej
 */
$.bind('messageRmAll', function(e) {
	e.scope.find('.rmAllButton').bind('click', function(){
		var arr = Array();
		e.scope.find('.rmAll:checked').each(function(elem){
			arr.push($(this).attr('name'));
		})
		e.scope.load(url('/mail', {'delMessage' : arr, 'box' : e.opt.box, 'type' : e.opt.type}));
		return false;
	})
	.end()
	.find('.switchAllButton').bind('click', function(){
			e.scope.toggleCheckboxes(".rmAll");
			return false;
	});
});
$.bind('message/action', function(e) {
	//e.scope.find('.action').html('');
	e.scope.find('.action').bind('click', function(){
		$(this).load($(this).attr('alt'));
		//$(this).hide();
		return false;
	})
});$.bind('user/photos', function(e) {
	var scope = e.scope.parent();
	scope.find('a.userPhotosNext').bind('click', function() {
		var page = e.opt.page+1;
		if( page * 7 <= e.opt.count)
		    $('#userPhotos').load('/s/user/photos?page=' + page,
					  function () {
					      $('#userPhotosPage').val(page);
					  });
	});
	scope.find('a.userPhotosPrev').bind('click', function() {
		var page = e.opt.page-1;
		if (page<0) page = 0;
		if (page != e.opt.page)
		    $('#userPhotos').load('/s/user/photos?page=' + page,
					  function () {
					      $('#userPhotosPage').val(page);
					  });
	});

});
/**
 * Lubię/nie lubię użytkownika
 */
$.bind('profile/like', function(e) {
	e.scope.find('.like').bind('click', function() {
		var alt = $(this).attr('alt').split('|');
		e.scope.load(url('user/profile/like'), {'UserId': alt[1], 'value':alt[0]});
		return false;
	});
});

$.bind('profile/moderate', function(e) {
	e.scope.find('.moderateProfil').bind('click', function() {
		e.scope.find('#moderateProfilDiv').toggle();
	});
	e.scope.find('.bannLink').bind('click', function() {
		$(this).load(url('/admin/user/bann'), {'_id':$(this).attr('id')});
	});
	e.scope.find('#sendMessage').bind('click', function() {
		e.scope.find('#sendMessageDiv').toggle();
	});
	e.scope.find('#showUserStats').bind('click', function() {
		var UserId = $(this).attr('alt');
		e.scope.find('#showUserStatsDiv').load(url('/user/abuse/stat'), {'UserId' : UserId, 'noHeader' : 1});
		e.scope.find('#showUserStatsDiv').toggle('');
	});
});

$.bind('avatar', function(e) {
	function close() {
		$('#avatar').fadeOut(function() { $(this).remove(); });
	}
	e.scope
	.find('a[href="#avatarChange"]').bind('click', function() {
		$.dialog({url: url('/user/avatar')});
		/*$('body').append('<div id="avatar" class="fade"><div /></div>');
		$('#avatar div').load(url('/user/avatar'), {'noHeader' : 0}, function() {
			$(this).find('a[href="#close"]').bind('click', function() {
				close();
				return false;
			}).end();
		});*/
	});
});

$.bind('editprofile/eyes', function(e) {
	$('.eye-checkbox').ezMark();
});
var map = null;
var geocoder = null;
var zoom;

var point;
var info;
var address;

function saveLocation(place){
	$.post(url('/user/saveLocation'), {
		place: place,
		lat: point.lat(),
		lng: point.lng(),
		address: address},
	function(data){
		if(data){
			window.location = url('/user/profile');
			//alert(data);
		}
	});

}

function createMarker(point, info, icon) { 
	map.checkResize();
	map.setCenter(point, zoom);
	var marker = new GMarker(point, icon); 
	if(!info)  info =
		_('Info:') + '<ul>' +
		'<li>' + _('lat:') +'<b>'+point.lat()+'</b></li>' +
		'<li>' + _('lng:') +'<b> '+point.lng()+'</b></li>' +
		'</li>';
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(info);
	});
	return marker;   
}

function showPointAddress(response) {
	alert('showPointAddress');
	  map.clearOverlays();
	  if (!response || response.Status.code != 200) {
	    alert("Status Code:" + response.Status.code);
	  } else {
	    place = response.Placemark[0];
	    address = place.address;
	    point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
	    map.addOverlay(createMarker(point, address));
	    map.checkResize();
	    map.setCenter(point, zoom);
	  }
	}

function getAddress(overlay, latlng) {
	if (latlng != null) {
		map.checkResize();
		address = latlng;
		geocoder.getLocations(latlng, showPointAddress);
	}
}

function findAddress(address, info){
	if(geocoder){
		geocoder.getLatLng(
						   address,
						   function(tpoint){
							   if(!tpoint){
							   }else{
								   map.clearOverlays();
								   point = new GLatLng(tpoint.lat(), tpoint.lng());
								   map.checkResize();
								   map.setCenter(point, zoom);
								   if(!info)
									   info = '<b>' + _('Adres') +'</b><ul>' + 
										'<li><b>' + _('Szerokość: ') + '</b>' + point.lat() + '</li>' +
								        '<li><b>' + _('Długość: ') + '</b>' + point.lng() + '</li>' +
								        '<li><b>' + _('Ulica: ') + '</b>' + address.split(',')[0] + '</li>' +
								        '<li><b>' + _('Miasto: ') + '</b>' + address.split(',')[1] + '</li></ul>';
								   map.addOverlay(createMarker(point, info));
								   map.checkResize();
								   map.setCenter(point, zoom);
							   }
						   }
						   );
	}
}

function initializeMap(mapClass, point, address){
	if(GBrowserIsCompatible()){
		$('.'+mapClass).each (function () {
			map = new GMap2(this);
			map.setUIToDefault();
			GEvent.addListener(map, "dragstart", map.checkResize);
			if(mode == 'find') GEvent.addListener(map, "click", getAddress);
			map.checkResize();
			geocoder = new GClientGeocoder();
			if(address != null)findAddress(address, info);
			else if(point){
				map.checkResize();
				map.setCenter(point, zoom);
				map.addOverlay(createMarker(map.getCenter(), info));
			}
	});
	}
}
//formId, mapClass, mode [find|show], [addr|point], [info], zoom
$.bind('showLocation', function(e) {
	mode = e.opt.mode;
	if(e.opt.formId) {
		formId = e.opt.formId;
		if(mode != 'find') $('#'+formId).hide();
	}
	mapClass = e.opt.mapClass;
	info = e.opt.info;
	address = e.opt.address;
	if (address != null) 
		findAddress(address, info);
	if (e.opt.point != null){
		point = new GLatLng(e.opt.point.lat, e.opt.point.lng);
		//alert(point.lat());
	}
	zoom = e.opt.zoom;
	if($('div.'+mapClass))
		initializeMap(mapClass, point, address);
	$('a#saveLocation').bind('click', function(){
		saveLocation($(this).attr('place'));
	});
});

