/*  ticktoo.detonator.js 
*
*   A) In-Field Label jQuery Plugin 0.1 by Doug Neiner (Dual licensed under the MIT and GPL licenses, (c) 2009)
*   B) jquery.notice.js by Tim Benniks (MIT and GPL (c) 2009)
*   C) Modified Quicksearch Plugin based on http://rikrikrik.com/jquery/quicksearch/
*/


/* In-Field Label */

(function($){
    $.InFieldLabels = function(label,field, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        // Access to jQuery and DOM versions of each element
        base.$label = $(label);
        base.label = label;
     		base.$field = $(field);
		    base.field = field;
    		base.$label.data("InFieldLabels", base);
		    base.showing = true;
        base.init = function(){
        // Merge supplied options with default options
        base.options = $.extend({},$.InFieldLabels.defaultOptions, options);
        // Check if the field is already filled in
  			if(base.$field.val() != ""){
  				base.$label.hide();
  				base.showing = false;
  			};
			base.$field.focus(function(){
				base.fadeOnFocus();
			}).blur(function(){
				base.checkForEmpty(true);
			}).bind('keydown.infieldlabel',function(e){
				// Use of a namespace (.infieldlabel) allows us to unbind just this method later
				base.hideOnChange(e);
			}).change(function(e){
				base.checkForEmpty();
			}).bind('onPropertyChange', function(){
				base.checkForEmpty();
			});
        };
		// If the label is currently showing then fade it down to the amount specified in the settings
		base.fadeOnFocus = function(){
			if(base.showing){
				base.setOpacity(base.options.fadeOpacity);
			};
		};
		base.setOpacity = function(opacity){
			base.$label.stop().animate({ opacity: opacity }, base.options.fadeDuration);
			base.showing = (opacity > 0.0);
		};
		// Checks for empty as a fail safe set blur to true when passing from the blur event
		base.checkForEmpty = function(blur){
			if(base.$field.val() == ""){
				base.prepForShow();
				base.setOpacity( blur ? 1.0 : base.options.fadeOpacity );
			} else {
				base.setOpacity(0.0);
			};
		};
		base.prepForShow = function(e){
			if(!base.showing) {
				// Prepare for a animate in...
				base.$label.css({opacity: 0.0}).show();
				// Reattach the keydown event
				base.$field.bind('keydown.infieldlabel',function(e){
					base.hideOnChange(e);
				});
			};
		};
		base.hideOnChange = function(e){
			if(
				(e.keyCode == 16) || // Skip Shift
				(e.keyCode == 9) // Skip Tab
			  ) return; 
			if(base.showing){
				base.$label.hide();
				base.showing = false;
			};
			// Remove keydown event to save on CPU processing
			base.$field.unbind('keydown.infieldlabel');
		};
		// Run the initialization method
        base.init();
    };
    $.InFieldLabels.defaultOptions = {
        fadeOpacity: 0.5, // Once a field has focus, how transparent should the label be
		fadeDuration: 150 // How long should it take to animate from 1.0 opacity to the fadeOpacity
    };
    $.fn.inFieldLabels = function(options){
        return this.each(function(){
			// Find input or textarea based on for= attribute
			// The for attribute on the label must contain the ID of the input or textarea element
			var for_attr = $(this).attr('for');
			if( !for_attr ) return; // Nothing to attach, since the for field wasn't used
			// Find the referenced input or textarea element
			var $field = $(
				"input#" + for_attr + "[type='text']," + 
				"input#" + for_attr + "[type='password']," + 
				"textarea#" + for_attr
				);
			if( $field.length == 0) return; // Again, nothing to attach
			// Only create object for input[text], input[password], or textarea
            (new $.InFieldLabels(this, $field[0], options));
        });
    };
})(jQuery);


/* jquery.notice.js */

(function(jQuery)
{
	jQuery.extend({			
		noticeAdd: function(options)
		{	
			var defaults = {
				inEffect: 			{opacity: 'show'},	// in effect
				inEffectDuration: 	600,				// in effect duration in miliseconds
				stayTime: 			3000,				// time in miliseconds before the item has to disappear
				text: 				'',					// content of the item
				stay: 				false,				// should the notice item stay or not?
				type: 				'notice' 			// could also be error, succes
			}
			// declare varaibles
			var options, noticeWrapAll, noticeItemOuter, noticeItemInner, noticeItemClose;
			options 		= jQuery.extend({}, defaults, options);
			noticeWrapAll	= (!jQuery('.app_notice').length) ? jQuery('<div></div>').addClass('app_notice').appendTo('body') : jQuery('.app_notice');
			noticeItemOuter	= jQuery('<div></div>').addClass('notice-item-wrapper');
			noticeItemInner	= jQuery('<div></div>').hide().addClass('item ' + options.type).appendTo(noticeWrapAll).html('<p>'+options.text+'</p>').animate(options.inEffect, options.inEffectDuration).wrap(noticeItemOuter);
			noticeItemClose	= jQuery('<div></div>').addClass('item_close').prependTo(noticeItemInner).html('x').click(function() { jQuery.noticeRemove(noticeItemInner) });
			// hmmmz, zucht
			if(navigator.userAgent.match(/MSIE 6/i)) 
			{
		    	noticeWrapAll.css({top: document.documentElement.scrollTop});
		    }
			if(!options.stay)
			{
				setTimeout(function()
				{
					jQuery.noticeRemove(noticeItemInner);
				},
				options.stayTime);
			}
		},
		noticeRemove: function(obj)
		{
			obj.animate({opacity: '0'}, 600, function()
			{
				obj.parent().animate({height: '0px'}, 300, function()
				{
					obj.parent().remove();
				});
			});
		}
	});
})(jQuery);

/* Quicksearch */

jQuery(function ($) {
	$.fn.quicksearch = function (opt) {
		
		function is_empty(i) 
		{
			return (i === null || i === undefined || i === false) ? true: false;
		}
		
		function strip_html(input)
		{
			var regexp = new RegExp(/\<[^\<]+\>/g);
			var output = input.replace(regexp, "");
			output = $.trim(output.toLowerCase().replace(/\n/, '').replace(/\s{2,}/, ' '));
			return output;
		}
		
		function get_key()
		{
			var input = strip_html($('input[rel="' + options.randomElement + '"]').val());
			
			if (input.indexOf(' ') === -1)
			{
				return input;
			}
			else
			{
				return input.split(" ");
			}
		}
		
		function test_key(k, value, type)
		{
			if (type === "string")
			{
				return test_key_string(k, value);
			}
			else
			{
				return test_key_arr(k, value);
			}
		}
		
		function test_key_string(k, value)
		{
			return (value.indexOf(k) > -1);
		}
		
		function test_key_arr(k, value)
		{
			for (var i = 0; i < k.length; i++) {
				var test = value.indexOf(k[i]);	
				if (test === -1) {	
					return false;
				}
			}			
			return true;
		}
		
		function select_element(el) 
		{
			if (options.hideElement === "grandparent") 
			{
				return $(el).parent().parent();
			} 
			else if (options.hideElement === "parent") 
			{
				return $(el).parent();
			} 
			else
			{
				return $(el);
			}
		}
		
		function stripe(el)
		{
			if (doStripe)
			{
				var i = 0;
				select_element(el).filter(':visible').each(function () {
					
					for (var j = 0; j < stripeRowLength; j++)
					{
						if (i === j)
						{
							$(this).addClass(options.stripeRowClass[i]);
							
						}
						else
						{
							$(this).removeClass(options.stripeRowClass[j]);
						}
					}
					i = (i + 1) % stripeRowLength;
				});
			}
		}
		
		function fix_widths(el)
		{
			$(el).find('td').each(function () {
				$(this).attr('width', parseInt($(this).css('width')));
			});
		}
		
		function loader(o) {
			if (options.loaderId) 
			{
				var l = $('input[rel="' + options.randomElement + '"]').parent().find('.loader');
				if (o === 'hide') 
				{
					l.hide();
				} 
				else 
				{
					l.show();
				}
			}			
		}
		
		function place_form() {
			var formPosition = options.position;
			var formAttached = options.attached;

			if (formPosition === 'before') {
				$(formAttached).before(make_form());
			} else if (formPosition === 'prepend') {
				$(formAttached).prepend(make_form());
			} else if (formPosition === 'append') {
				$(formAttached).append(make_form());
			} else {
				$(formAttached).after(make_form());
			}
		}
				
		function make_form_label()
		{
			if (!is_empty(options.labelText)) {
				return '<span style="background-color: #fff; border: 1px solid #ddd; position: absolute; right: 0; top: -30px; -moz-border-radius: 12px;"><label for="' + options.randomElement + '" '+
							'class="' + options.labelClass + '"' + 'style="background: url(' + options.labelImg + ') no-repeat 7px 4px; height: 20px; width: 24px; display: block; float: left; text-indent: -9999px; cursor: pointer;"' + '>'
							+ options.labelText
							+ '</label> ';	
			}
			return '';
		}
		
		function make_form_input()
		{
			var val = (!is_empty(options.inputText)) ? options.inputText : ""
			return '<input type="text" value="' + val + '" rel="' + options.randomElement  + '" class="' + options.inputClass + '" id="' + options.randomElement + '"' + 'style="position: relative; border: 0; background-color: transparent; color: #777; padding: 3px 24px 3px 0px; font-size: 12px;"' + '/> ';
		}
		
		function make_form_loader()
		{
			if (!is_empty(options.loaderImg)) {
				return '<img src="' + options.loaderImg + '" alt="Loading" id="' + options.loaderId + '" class="' + options.loaderClass + '"' + 'style="position: absolute; top: 3px; right: 4px;"' + ' />';
			} else {
				return '<span id="' + options.loaderId + '" class="' + options.loaderClass + '">' + options.loaderText + '</span>';
			}
		}
		
		function make_form()
		{
			var f = (!options.isFieldset) ? 'form' : 'fieldset';
			return '<' + f + ' action="#" ' + 'id="'+ options.formId + '" ' + 'class="quicksearch"' + 'style="position: relative;"' + '>' +
						make_form_label() +	make_form_input() + make_form_loader() +
					'</' + f + '></span>';
		}
			
		function focus_on_load()
		{
			$('input[rel="' + options.randomElement + '"]').get(0).focus();
		}
		
		function toggle_text() {
			$('input[rel="' + options.randomElement + '"]').focus(function () {
				if ($(this).val() === options.inputText) {
					$(this).val('');
				}
			});
			$('input[rel="' + options.randomElement + '"]').blur(function () {
				if ($(this).val() === "") {
					$(this).val(options.inputText);
				}
			});
		}
		
		function get_cache(el) 
		{
			return $(el).map(function(){
				return strip_html(this.innerHTML);
			});
		}
		
		////////////////////////////////////////////////////////
		//Added functions to this plugin
		////////////////////////////////////////////////////////
		function addReset() {
  		$("#" + options.formId + " input." + options.inputClass).after(" &nbsp; <input id='" + options.resetId + "' class='" + options.resetClass + "' style='display:none; height: 20px; width: 22px; border: 0; text-indent: -9999px; position: absolute; top: -1px; right: 1px; cursor: pointer; background: url(" + options.resetImg + ") no-repeat 50% 50%;'>");
			$("#" + options.resetId).click( function() { 
					$("#" + options.formId + " input." + options.inputClass).val('');
					qs();
				} );
		}
		
		function checkReset() {
			if ($("#" + options.formId + " input." + options.inputClass).val() != '') {
				$("#" + options.resetId).css('display', 'inline');
			}
			else {
				$("#" + options.resetId).hide();
			}
		}
		///////////////////////////////////////////////////////
		//End additional functions.
		///////////////////////////////////////////////////////
		
		function init()
		{
			place_form();
			if (options.fixWidths) fix_widths(el);
			if (options.focusOnLoad) focus_on_load();
			if (options.inputText != "" && options.inputText != null) toggle_text();
			
			cache = get_cache(el);
			
			//Added check to actually initalize the reset.
			if (options.reset)	addReset();
			
			stripe(el);
			loader('hide');
		}
		
		function qs() 
		{
			
		
			clearTimeout(timeout);
			timeout = setTimeout(function () {
				
				loader('show');
				
				setTimeout(function () {
					options.onBefore();
					
					//////////////////////////////////////////
					//Reset modification.
					//////////////////////////////////////////
					if (options.resetId) checkReset();
					
					var k = get_key();
					var k_type = (typeof k);
					var i = 0;
					
					k = options.filter(k);
					
					if (k != "")
					{
						if (typeof score[k] === "undefined")
						{
							score[k] = new Array();
							cache.each(function (i) {
								if (test_key(k, cache[i], k_type))
								{
									score[k][i] = true;
								}
							});
						}
						
						if (score[k].length === 0)
						{
							select_element(el).hide();
						}
						else
						{
							$(el).each(function (i) {
								if (score[k][i])
								{
									select_element(this).show();
								}
								else
								{
									select_element(this).hide();
								}
							});
							
						}
					}
					else
					{
						select_element(el).show();
					}
				
					////////////////////////////////////////////////////
					//Modified location to enable onAfter functions to 
					//   be called earlier in search.
					////////////////////////////////////////////////////
					options.onAfter();
				
					stripe(el);
				}, options.delay/2);
				
				setTimeout( function () { 
					loader('hide');
				}, options.delay/2);
				
				/////////////////////////////////////////////////
				// Originial spot for options.onAfter();
				/////////////////////////////////////////////////
				//options.onAfter();
				
			}, options.delay/2);

		}
		
		var options = $.extend({
			position: 'before',
			attached: 'body',
			formId: 'quicksearch',
			labelText: 'Schnellsuche',
			labelClass: 'qs_label',
			labelImg: '/assets/img/app_quicksearch.png',
			inputText: 'Schnellsuche',
			inputClass: 'qs_input',
			loaderId: 'loader',
			loaderClass: 'loader',
			loaderImg: '/assets/img/app_quicksearch_spinner.gif',
			loaderText: 'Loading...',
			
			
			//////////////////////////////////////////////////////
			//Added options.
			//////////////////////////////////////////////////////
			
			reset: true,					//Is reset enabled? (true/false)
			resetId: 'resetQS',				//ID for reset button.
			resetClass: null,				//Class for reset button.
			resetLabel: 'Reset',			//Text inside reset button.
			resetImg: '/assets/img/app_quicksearch_reset.png',
			
			//////////////////////////////////////////////////////
			//End of added options.
			//////////////////////////////////////////////////////
			
			stripeRowClass: null,
			hideElement: null,
			delay: 500,
			focusOnLoad: false,
			onBefore: function () { },
			onAfter: function () { },
			filter: function (i) { 
				return i;
			},
			randomElement: 'qs' + Math.floor(Math.random() * 1000000),
			isFieldset: false,
			fixWidths: false
		}, opt);
		
		var timeout;
		var score = {};
		var stripeRowLength = (!is_empty(options.stripeRowClass)) ? options.stripeRowClass.length : 0;
		var doStripe = (stripeRowLength > 0) ? true : false;
		var el = this;
		var cache;
		var selector = $(this).selector;
		
		$.fn.extend({
			reset_cache: function () {
				el = $(selector);
				cache = get_cache(el);
			}
		});
		
		init();
		
		$('input[rel="' + options.randomElement + '"]').keydown(function (e) {
			var keycode = e.keyCode;
			if (!(keycode === 9 || keycode === 13 || keycode === 16 || keycode === 17 || keycode === 18 || keycode === 38 || keycode === 40 || keycode === 224))
			{
				qs();
			}
		});
		
		$('form.quicksearch, fieldset.quicksearch').submit( function () { return false; });
		
		return this;
	};
});

