/*
* jQuery UI @VERSION
*
* Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI
*/
(function($) {

    /** jQuery core modifications and additions **/

    var _remove = $.fn.remove;
    $.fn.remove = function() {
        $("*", this).add(this).triggerHandler("remove");
        return _remove.apply(this, arguments);
    };

    function isVisible(element) {
        function checkStyles(element) {
            var style = element.style;
            return (style.display != 'none' && style.visibility != 'hidden');
        }

        var visible = checkStyles(element);

        (visible && $.each($.dir(element, 'parentNode'), function() {
            return (visible = checkStyles(this));
        }));

        return visible;
    }

    $.extend($.expr[':'], {
        data: function(a, i, m) {
            return $.data(a, m[3]);
        },

        // TODO: add support for object, area
        tabbable: function(a, i, m) {
            var nodeName = a.nodeName.toLowerCase();

            return (
            // in tab order
			a.tabIndex >= 0 &&

			( // filter node types that participate in the tab order

            // anchor tag
				('a' == nodeName && a.href) ||

            // enabled form element
				(/input|select|textarea|button/.test(nodeName) &&
					'hidden' != a.type && !a.disabled)
			) &&

            // visible on page
			isVisible(a)
		);
        }
    });

    $.keyCode = {
        BACKSPACE: 8,
        CAPS_LOCK: 20,
        COMMA: 188,
        CONTROL: 17,
        DELETE: 46,
        DOWN: 40,
        END: 35,
        ENTER: 13,
        ESCAPE: 27,
        HOME: 36,
        INSERT: 45,
        LEFT: 37,
        NUMPAD_ADD: 107,
        NUMPAD_DECIMAL: 110,
        NUMPAD_DIVIDE: 111,
        NUMPAD_ENTER: 108,
        NUMPAD_MULTIPLY: 106,
        NUMPAD_SUBTRACT: 109,
        PAGE_DOWN: 34,
        PAGE_UP: 33,
        PERIOD: 190,
        RIGHT: 39,
        SHIFT: 16,
        SPACE: 32,
        TAB: 9,
        UP: 38
    };

    // $.widget is a factory to create jQuery plugins
    // taking some boilerplate code out of the plugin code
    // created by Scott González and Jörn Zaefferer
    function getter(namespace, plugin, method, args) {
        function getMethods(type) {
            var methods = $[namespace][plugin][type] || [];
            return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
        }

        var methods = getMethods('getter');
        if (args.length == 1 && typeof args[0] == 'string') {
            methods = methods.concat(getMethods('getterSetter'));
        }
        return ($.inArray(method, methods) != -1);
    }

    $.widget = function(name, prototype) {
        var namespace = name.split(".")[0];
        name = name.split(".")[1];

        // create plugin method
        $.fn[name] = function(options) {
            var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

            // prevent calls to internal methods
            if (isMethodCall && options.substring(0, 1) == '_') {
                return this;
            }

            // handle getter methods
            if (isMethodCall && getter(namespace, name, options, args)) {
                var instance = $.data(this[0], name);
                return (instance ? instance[options].apply(instance, args)
				: undefined);
            }

            // handle initialization and non-getter methods
            return this.each(function() {
                var instance = $.data(this, name);

                // constructor
                (!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options)));

                // method call
                (instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
            });
        };

        // create widget constructor
        $[namespace][name] = function(element, options) {
            var self = this;

            this.widgetName = name;
            this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
            this.widgetBaseClass = namespace + '-' + name;

            this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

            this.element = $(element)
			.bind('setData.' + name, function(e, key, value) {
			    return self._setData(key, value);
			})
			.bind('getData.' + name, function(e, key) {
			    return self._getData(key);
			})
			.bind('remove', function() {
			    return self.destroy();
			});

            this._init();
        };

        // add widget prototype
        $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

        // TODO: merge getter and getterSetter properties from widget prototype
        // and plugin prototype
        $[namespace][name].getterSetter = 'option';
    };

    $.widget.prototype = {
        _init: function() { },
        destroy: function() {
            this.element.removeData(this.widgetName);
        },

        option: function(key, value) {
            var options = key,
			self = this;

            if (typeof key == "string") {
                if (value === undefined) {
                    return this._getData(key);
                }
                options = {};
                options[key] = value;
            }

            $.each(options, function(key, value) {
                self._setData(key, value);
            });
        },
        _getData: function(key) {
            return this.options[key];
        },
        _setData: function(key, value) {
            this.options[key] = value;

            if (key == 'disabled') {
                this.element[value ? 'addClass' : 'removeClass'](
				this.widgetBaseClass + '-disabled');
            }
        },

        enable: function() {
            this._setData('disabled', false);
        },
        disable: function() {
            this._setData('disabled', true);
        },

        _trigger: function(type, e, data) {
            var eventName = (type == this.widgetEventPrefix
			? type : this.widgetEventPrefix + type);
            e = e || $.event.fix({ type: eventName, target: this.element[0] });
            return this.element.triggerHandler(eventName, [e, data], this.options[type]);
        }
    };

    $.widget.defaults = {
        disabled: false
    };


    /** jQuery UI core **/

    $.ui = {
        plugin: {
            add: function(module, option, set) {
                var proto = $.ui[module].prototype;
                for (var i in set) {
                    proto.plugins[i] = proto.plugins[i] || [];
                    proto.plugins[i].push([option, set[i]]);
                }
            },
            call: function(instance, name, args) {
                var set = instance.plugins[name];
                if (!set) { return; }

                for (var i = 0; i < set.length; i++) {
                    if (instance.options[set[i][0]]) {
                        set[i][1].apply(instance.element, args);
                    }
                }
            }
        },
        cssCache: {},
        css: function(name) {
            if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
            var tmp = $('<div class="ui-gen">').addClass(name).css({ position: 'absolute', top: '-5000px', left: '-5000px', display: 'block' }).appendTo('body');

            //if (!$.browser.safari)
            //tmp.appendTo('body'); 

            //Opera and Safari set width and height to 0px instead of auto
            //Safari returns rgba(0,0,0,0) when bgcolor is not set
            $.ui.cssCache[name] = !!(
			(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) ||
			!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
		);
            try { $('body').get(0).removeChild(tmp.get(0)); } catch (e) { }
            return $.ui.cssCache[name];
        },
        disableSelection: function(el) {
            return $(el)
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
        },
        enableSelection: function(el) {
            return $(el)
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
        },
        hasScroll: function(e, a) {

            //If overflow is hidden, the element might have extra content, but the user wants to hide it
            if ($(e).css('overflow') == 'hidden') { return false; }

            var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

            if (e[scroll] > 0) { return true; }

            // TODO: determine which cases actually cause this to happen
            // if the element doesn't have the scroll set, see if it's possible to
            // set the scroll
            e[scroll] = 1;
            has = (e[scroll] > 0);
            e[scroll] = 0;
            return has;
        }
    };


    /** Mouse Interaction Plugin **/

    $.ui.mouse = {
        _mouseInit: function() {
            var self = this;

            this.element.bind('mousedown.' + this.widgetName, function(e) {
                return self._mouseDown(e);
            });

            // Prevent text selection in IE
            if ($.browser.msie) {
                this._mouseUnselectable = this.element.attr('unselectable');
                this.element.attr('unselectable', 'on');
            }

            this.started = false;
        },

        // TODO: make sure destroying one instance of mouse doesn't mess with
        // other instances of mouse
        _mouseDestroy: function() {
            this.element.unbind('.' + this.widgetName);

            // Restore text selection in IE
            ($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
        },

        _mouseDown: function(e) {
            // we may have missed mouseup (out of window)
            (this._mouseStarted && this._mouseUp(e));

            this._mouseDownEvent = e;

            var self = this,
			btnIsLeft = (e.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
            if (!btnIsLeft || elIsCancel || !this._mouseCapture(e)) {
                return true;
            }

            this.mouseDelayMet = !this.options.delay;
            if (!this.mouseDelayMet) {
                this._mouseDelayTimer = setTimeout(function() {
                    self.mouseDelayMet = true;
                }, this.options.delay);
            }

            if (this._mouseDistanceMet(e) && this._mouseDelayMet(e)) {
                this._mouseStarted = (this._mouseStart(e) !== false);
                if (!this._mouseStarted) {
                    e.preventDefault();
                    return true;
                }
            }

            // these delegates are required to keep context
            this._mouseMoveDelegate = function(e) {
                return self._mouseMove(e);
            };
            this._mouseUpDelegate = function(e) {
                return self._mouseUp(e);
            };
            $(document)
			.bind('mousemove.' + this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.' + this.widgetName, this._mouseUpDelegate);

            return false;
        },

        _mouseMove: function(e) {
            // IE mouseup check - mouseup happened when mouse was out of window
            if ($.browser.msie && !e.button) {
                return this._mouseUp(e);
            }

            if (this._mouseStarted) {
                this._mouseDrag(e);
                return false;
            }

            if (this._mouseDistanceMet(e) && this._mouseDelayMet(e)) {
                this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, e) !== false);
                (this._mouseStarted ? this._mouseDrag(e) : this._mouseUp(e));
            }

            return !this._mouseStarted;
        },

        _mouseUp: function(e) {
            $(document)
			.unbind('mousemove.' + this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.' + this.widgetName, this._mouseUpDelegate);

            if (this._mouseStarted) {
                this._mouseStarted = false;
                this._mouseStop(e);
            }

            return false;
        },

        _mouseDistanceMet: function(e) {
            return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - e.pageX),
				Math.abs(this._mouseDownEvent.pageY - e.pageY)
			) >= this.options.distance
		);
        },

        _mouseDelayMet: function(e) {
            return this.mouseDelayMet;
        },

        // These are placeholder methods, to be overriden by extending plugin
        _mouseStart: function(e) { },
        _mouseDrag: function(e) { },
        _mouseStop: function(e) { },
        _mouseCapture: function(e) { return true; }
    };

    $.ui.mouse.defaults = {
        cancel: null,
        distance: 1,
        delay: 0
    };

})(jQuery); 


/**
* @author alexander.farkas
* checkboxes
*/
(function($) {
	$.widget('ui.checkBox', {
		_init: function() {
			var that = this,
			opts = this.options,
			toggleHover = function(e) {
				if (this.disabledStatus) return false;
				that.hover = (e.type == 'focus' || e.type == 'mouseenter');
				that._changeStateClassChain();
			};

			this.labels = $([]);
			this.checkedStatus = false;
			this.disabledStatus = false;
			this.hoverStatus = false;
			this.radio = (this.element.is(':radio'));
			this.visualElement = $('<span />')
				.addClass(this.radio ? 'ui-radio' : 'ui-checkbox')
				.bind('mouseenter.checkBox mouseleave.checkBox', toggleHover)
				.bind('click.checkBox', function(e) {
					(!this.disabledStatus && that.toggle.call(that, e));
					$(this).siblings("input").trigger("click");
					return false;
				});

			if (opts.replaceInput) {
				this.element
				.addClass('ui-helper-hidden-accessible')
				.after(this.visualElement[0])
				.bind('usermode', function(e) {
					(e.enabled && that.destroy.call(that, true));
				});
			}

			this.element.bind('click.checkBox', $.bind(this, this.reflectUI)).bind('focus.checkBox blur.checkBox', toggleHover);

			if (opts.addLabel) {
				//ToDo: Add Closest Ancestor
				this.labels = $('label[for=' + this.element.attr('id') + ']').addClass("ui-checkbox-label")
				.bind('mouseenter.checkBox mouseleave.checkBox', toggleHover).click(function(e) {
					(!this.disabledStatus && that.toggle.call(that, e));
					$(this).siblings("input").trigger("click");
				});
			}

			this.reflectUI({ type: 'initialReflect' });
        },
				
		_changeStateClassChain: function() {
			if (this.hover && this.checkedStatus) return; // added by ibi

			var stateClass = (this.checkedStatus) ? '-checked' : '', baseClass = 'ui-' + ((this.radio) ? 'radio' : 'checkbox') + '-state';
			stateClass += (this.disabledStatus) ? '-disabled' : '';
			stateClass += (this.hover) ? '-hover' : '';

			if (stateClass) stateClass = baseClass + stateClass;

			function switchStateClass() {
				var classes = this.className.split(' '),
				found = false;
				$.each(classes, function(i, classN) {
					if (classN.indexOf(baseClass) === 0) {
						found = true;
						classes[i] = stateClass;
						return false;
					}
				});
				if (!found)
					classes.push(stateClass);

				this.className = classes.join(' ');
			}

			this.labels.each(switchStateClass);
			this.visualElement.each(switchStateClass);
		},

		destroy: function(onlyCss) {
			this.element.removeClass('ui-helper-hidden-accessible');
			this.visualElement.addClass('ui-helper-hidden');
			if (!onlyCss) {
				var o = this.options;
				this.element.unbind('.checkBox');
				this.visualElement.remove();
				this.labels.unbind('.checkBox').removeClass('ui-state-hover ui-state-checked ui-state-disabled');
			}
		},

		disable: function() {
			this.element[0].disabled = true;
			this.reflectUI({ type: 'manuallyDisabled' });
		},

		enable: function() {
			this.element[0].disabled = false;
			this.reflectUI({ type: 'manuallyenabled' });
		},

		toggle: function(e) {
			this.changeCheckStatus((this.element.is(':checked')) ? false : true, e);
		},

		changeCheckStatus: function(status, e) {
			if (e && e.type == 'click' && this.element[0].disabled) return false;
			this.element.attr({ 'checked': status });
			this.reflectUI(e || {
				type: 'changeCheckStatus'
			});
		},

		propagate: function(n, e, _noGroupReflect) {
			if (!e || e.type != 'initialReflect') {
				if (this.radio && !_noGroupReflect) {
					//dynamic
					$(document.getElementsByName(this.element.attr('name'))).checkBox('reflectUI', e, true);
				}
				return this._trigger(n, e, {
					options: this.options,
					checked: this.checkedStatus,
					labels: this.labels,
					disabled: this.disabledStatus
				});
			}
		},

		reflectUI: function(elm, e) {
			var oldChecked = this.checkedStatus, oldDisabledStatus = this.disabledStatus;
			e = e || elm;

			this.disabledStatus = this.element.is(':disabled');
			this.checkedStatus = this.element.is(':checked');

			if (this.disabledStatus != oldDisabledStatus || this.checkedStatus !== oldChecked) {
				this._changeStateClassChain();
				(this.disabledStatus != oldDisabledStatus && this.propagate('disabledChange', e));
				(this.checkedStatus !== oldChecked && this.propagate('change', e));
			}

		}
	});
	$.ui.checkBox.defaults = {
		replaceInput: true,
		addLabel: true
	};

})(jQuery);

/**
 * @author trixta
 * $bind
 */
(function($) {
	$.bind = function(object, method) {
		var args = Array.prototype.slice.call(arguments, 2);
		if (args.length) {
			return function() {
				var args2 = [this].concat(args, $.makeArray(arguments));
				return method.apply(object, args2);
			};
		} else {
			return function() {
				var args2 = [this].concat($.makeArray(arguments));
				return method.apply(object, args2);
			};
		}
	};

})(jQuery);

/*
 * Thickbox 3 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
var tb_pathToImage = "/_layouts/images/Migros.SP.MKS.Frontend/ajax-loader.gif";

//on page load call tb_init
$(document).ready(function(){   
  tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
  $(domChunk).click(function(){
  var t = this.title || this.name || null;
  var a = this.href || this.alt;
  var g = this.rel || false;
  tb_show(t,a,g);
  this.blur();
  return false;
  });
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
  try {
	if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css("overflow","hidden");
		if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
			$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
			$("#TB_overlay").click(tb_remove);
		}
	}else{//all others
		if(document.getElementById("TB_overlay") === null){
			$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
			$("#TB_overlay").click(tb_remove);
		}
	}

	if(tb_detectMacXFF()){
		$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
	}else{
		$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
	}

	if(caption===null){caption="";}
	$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
	$('#TB_load').show();//show loader

	var baseURL;
	if(url.indexOf("?")!==-1){ //ff there is a query string involved
		baseURL = url.substr(0, url.indexOf("?"));
	}else{ 
		baseURL = url;
	}

	var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$|\.ashx\?*/;
	var urlType = baseURL.toLowerCase().match(urlString);		 
	if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp' || urlType == '.ashx'){//code to show images        
		TB_PrevCaption = "";
		TB_PrevURL = "";
		TB_PrevHTML = "";
		TB_NextCaption = "";
		TB_NextURL = "";
		TB_NextHTML = "";
		TB_imageCount = "";
		TB_FoundURL = false;
		if(imageGroup){
			TB_TempArray = $("a[rel="+imageGroup+"]").get();
			for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
				var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
				if (!(TB_TempArray[TB_Counter].href == url)) {            
					if (TB_FoundURL) {
						TB_NextCaption = TB_TempArray[TB_Counter].title;
						TB_NextURL = TB_TempArray[TB_Counter].href;
						TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
					} else {
						TB_PrevCaption = TB_TempArray[TB_Counter].title;
						TB_PrevURL = TB_TempArray[TB_Counter].href;
						TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
					}
				} else {
					TB_FoundURL = true;
					TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);                      
				}
			}
		}
		imgPreloader = new Image();
		imgPreloader.onload = function(){    
			imgPreloader.onload = null;

			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing

			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>&nbsp;</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>"+Utils.tb_CloseMessage(true)+"</a></div></div>");
			$("#TB_window").append("<div id='ajaxContent'><a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"</div></div>");
			$("#TB_closeWindowButton").click(tb_remove);

			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;  
				}
				$("#TB_prev").click(goPrev);
			}

			if (!(TB_NextHTML === "")) {    
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);        
					return false;  
				}
				$("#TB_next").click(goNext);
			}
			document.onkeydown = function(e){   
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}  
			};
		  
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
		};

		imgPreloader.src = url;
	}else{//code to show html		
		var queryString = url.replace(/^[^\?]+\??/,'');		
		var params = tb_parseQuery( queryString );		
		TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
		TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
		ajaxContentW = TB_WIDTH - 30;
		ajaxContentH = TB_HEIGHT - 45;

		if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window    
			urlNoQuery = url.split('TB_');
			$("#TB_iframeContent").remove();
			if(params['modal'] != "true"){//iframe no modal
				$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>"+Utils.tb_CloseMessage(true)+"</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
			}else{//iframe modal
			$("#TB_overlay").unbind();
			$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
		  }
		}else{// not an iframe, ajax
		  if($("#TB_window").css("display") != "block"){
			if(params['modal'] != "true"){//ajax no modal
				$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>"+Utils.tb_CloseMessage(true)+"</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
			}else{//ajax modal
				$("#TB_overlay").unbind();
				$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");  
			}
			}else{
				$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
				$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
				$("#TB_ajaxContent")[0].scrollTop = 0;
				$("#TB_ajaxWindowTitle").html(caption);
			}
		}

		$("#TB_closeWindowButton").click(tb_remove);

		if(url.indexOf('TB_inline') != -1){					 
		  $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
		  $("#TB_window").unload(function () {
			$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
		  });
		  tb_position();
		  $("#TB_load").remove();
		  $("#TB_window").css({display:"block"}); 
		}else if(url.indexOf('TB_iframe') != -1){
		  tb_position();
		  if($.browser.safari){//safari needs help because it will not fire iframe onload
			$("#TB_load").remove();
			$("#TB_window").css({display:"block"});
		  }
		}else{
		  $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
			tb_position();
			$("#TB_load").remove();
			tb_init("#TB_ajaxContent a.thickbox");
			$("#TB_window").css({display:"block"});
		  });
		}

		}

	tb_printHide();
  } catch(e) {
    //nothing here
  }
}
//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
	$("body","html").css({height: "auto", width: "auto"});
	$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	tb_printShow();
	return false;
}
// added by namics
function tb_printHide(){
	$("#DynamicContentWrapper").addClass("printHide");
}

function tb_printShow(){
	$("#DynamicContentWrapper").removeClass("printHide");
}

function tb_position() {
	$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
  }
}

function tb_parseQuery ( query ) {
	var Params = {};
	if ( ! query ) {return Params;}// return empty object
		var Pairs = query.split(/[;&]/);
		for ( var i = 0; i < Pairs.length; i++ ) {
			var KeyVal = Pairs[i].split('=');
			if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
		var key = unescape( KeyVal[0] );
		var val = unescape( KeyVal[1] );
		val = val.replace(/\+/g, ' ');
		Params[key] = val;
	}
	return Params;
}
function tb_getPageSize(){
  var de = document.documentElement;
  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
  arrayPageSize = [w,h];
  return arrayPageSize;
}
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 * >> modified by I. Bikmaz
 * >> removed z-index problem and div overlapping
 */
jQuery.fn.extend({
    selectbox: function(options) {
        return this.each(function() {
            new jQuery.SelectBox(this, options);
        });
    }
});


jQuery.SelectBox = function(selectobj, options) {
	var opt = options || {};
	opt.inputClass = opt.inputClass || "selectbox";
	opt.containerClass = opt.containerClass || "selectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "current";
	opt.currentClass = opt.selectedClass || "selected"
	opt.debug = opt.debug || false;

	var elm_id = selectobj.id;
	var active = 0;
	var inFocus = false;
	var hasfocus = 0;
	var $select = $(selectobj);
	var $container = setupContainer(opt);
	var $input = setupInput(opt);

	// CHANGES: by I. Bikmaz
	$(window).resize(function() {
		setPosition(true);
	});

	$(document).ready(init);

	$("#searchTerm").focus(function() {
		$(this).select();
	});

	$('#searchInputWrapper').click(function() {
		$input.focus();
	});

	$("li.topCity:last", $container).addClass("lastTopCity");
	// End Changes

	// Input field
	$input.click(function() {
		setPosition(false); 
		$container.toggle();
	})
	.focus(function() {
		inFocus = true;
		setPosition(false);
		$container.show();
	})
	.keydown(function(event) {
		switch (event.keyCode) {
			case 38: // up
				event.preventDefault();
				$container.show();
				moveSelect(-1);
				break;
			case 40: // down
				event.preventDefault();
				$container.show();
				moveSelect(1);
				break;
			case 9:  // tab
				break;
			case 13: // return
				event.preventDefault(); // seems not working in mac !
				$('li.' + opt.hoverClass).trigger('click');
							$("#searchSubmit").focus();
				break;
			case 27: //escape
				hideMe();
				break;
			default: // chars
				event.preventDefault();
				$container.show();
				moveToNextChar(String.fromCharCode(event.keyCode));
		}
	})
	.blur(function() {
		if ($container.is(':visible') && hasfocus > 0) {
		} else {
			// Workaround for ie scroll - thanks to Bernd Matzner
			if ($.browser.msie || $.browser.safari) { // check for safari too - workaround for webkit
				if (document.activeElement.getAttribute('id').indexOf('_container') == -1) {
					hideMe();
				} else {
					$input.focus();
				}
			} else {
				hideMe();
			}
		}
	});

	function setPosition(isResized) {
		isResized = isResized || true;
		if (isResized) {
			var p = $input.offset();
			$container.css({ "position": "absolute", "top": (p.top + 25), "left": p.left });
		}
	}
		
	function submitForm() {
	    $("#searchForm").append('<input type="hidden" name="search_submit" value="Suchen" />');
		$('.btnBack').css('display','none');
		$("#aspnetForm").submit();
	}

	function hideMe() {
		hasfocus = 0;
		$container.hide();
	}

	function init() {
		$select.hide().before($input);
		$input.wrap("<div id='searchInputWrapper'></div>");
		$("body").append($container); 
		$container.append(getSelectOptions($input.attr('id'))).hide();
	}

	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id + '_container');
		$container.addClass(options.containerClass);
		return $container;
	}

	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id + "_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		return $input;
	}

	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis || lis.length == 0) return false;
		active += step;
		//loop through list
		if (active < 0) {
			active = lis.size();
		} else if (active > lis.size()) {
			active = 0;
		}
		scroll(lis, active);
		lis.removeClass(opt.hoverClass);
		$(lis[active]).addClass(opt.hoverClass);
	}
	
	function moveToNextChar( pressedCh ){
		var lis = $("li", $container);
        if (!lis || lis.length == 0) return false;
		var active 		= -1;
		var i 			= lis.index( $("." + opt.hoverClass) );
		var liLength 	= lis.size();
		
		for (var loops=0; loops <= 1; loops++) {
			for (++i; i < liLength; i++) {
				var ch = lis.eq(i).text().substr(0,1).toUpperCase();
				if (ch === pressedCh){
					active = i;
					break;
				}
			}
			
			if (i == liLength)
			{
				i = -1;
			}else{
				break;
			}
		}		
		
		if (active !== -1) {
			scroll(lis, active);
			lis.removeClass(opt.hoverClass);
			$(lis[active]).addClass(opt.hoverClass);
		}
	}

	function scroll(list, active) {
		var el = $(list[active]).get(0);
		var list = $container.get(0);

		if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight) {
			list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;
		} else if (el.offsetTop < list.scrollTop) {
			list.scrollTop = el.offsetTop;
		}
	}

	function setCurrent() {
		var li = $("li." + opt.currentClass, $container).get(0);
		var ar = ('' + li.id).split('_');
		var el = ar[ar.length - 1];
		$select.val(el);
		$input.val($(li).html());
		return true;
	}

	// select value
	function getCurrentSelected() {
		return $select.val();
	}

	// input value
	function getCurrentValue() {
		return $input.val();
	}

	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.currentClass);
			}
			li.className = $(this).get(0).className;
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
				var fl = $('li.' + opt.hoverClass, $container).get(0);
				$('li.' + opt.currentClass).removeClass(opt.currentClass);
				$(this).addClass(opt.currentClass);
				setCurrent();
				//$select.change();
				$select.get(0).blur();
				$("#searchSubmit").focus();
				hideMe();
			});
		});
		return ul;
	}
	};
