// dz
var jq = jQuery.noConflict(false);
var INVALID_VALUE = 0xFFFF8000;

//------------------------------------------------------------------------------
var browserWindow = {
	getWidth: function() {
		var windowWidth = undefined;

		if( typeof( window.innerWidth ) == 'number' ) {
			windowWidth = window.innerWidth;
		} else if( document.documentElement && document.documentElement.clientWidth) {
			windowWidth = document.documentElement.clientWidth;
		} else if( document.body && document.body.clientWidth) {
			windowWidth = document.body.clientWidth;
		}

		return windowWidth;
	},

	getHeight: function() {
		var windowHeight = 0;

		if( typeof(window.innerHeight) == 'number' ) {
			windowHeight = window.innerHeight;
		} else if(document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		} else if(document.body && document.body.clientHeight) {
			windowHeight = document.body.clientHeight;
		}
		
		return windowHeight;
	},

	getScrollLeftOffset: function() {
		var offsetX = 0;

		if( typeof(window.pageXOffset) == 'number' ) {
		  offsetX = window.pageXOffset;
		} else if(document.body && document.body.scrollLeft) {
		  offsetX = document.body.scrollLeft;
		} else if(document.documentElement && document.documentElement.scrollLeft) {
		  offsetX = document.documentElement.scrollLeft;
		}

		return offsetX;
	},

	getScrollTopOffset: function() {
		var offsetY = 0;
		
		if( typeof(window.pageYOffset) == 'number' ) {
		  offsetY = window.pageYOffset;
		} else if(document.body && document.body.scrollTop) {
		  offsetY = document.body.scrollTop;
		} else if(document.documentElement && document.documentElement.scrollTop) {
		  offsetY = document.documentElement.scrollTop;
		}

		return offsetY;
	}
}

//------------------------------------------------------------------------------

Application = {
	flashQueue: new Array(),
	internalMenus: new Array(),
	swfCount: 0,
	
	options: {
		modalDialogId:	'application-modal-message',
		noFlashEmbed: false,
		noCufonFonts: false,
		resizeHandled: false,
		embedTimeout: 1000,
		JCWComponent: null,
		stageArea: {
			oid:  'mainStage_swf',
			main: 'main_stage_area',
			sub:  'stageArea_sub'
		}
	},
	
	/*
	 * Ujednolica wyświetlanie wszystkich alertów
	 */ 
	
	messageBox: function(text, title, onClose) {
		jq('#'+Application.options.modalDialogId).remove();
		
		var div = jq('<div>').attr('id', Application.options.modalDialogId).css('display', 'none');
		
		div.attr('title', title?title:"MINI");
		
		var p = jq('<p/>');
		p.html(text);
		
		div.append(p);
		div.appendTo('body');
		
		div.dialog({
			modal: true,
			buttons: {
				"Ok": function() {
					jq(this).dialog('close');
					jq('#'+Application.options.modalDialogId).remove();
					if(typeof(onClose) == 'function') {
						onClose();
					}
				}
			}
		});
	},
	
	quicklinks: function(links) {
		jq(links).each(function(index, el) {
			jq(el).addClass('quicklink_link').addClass('js-cufon-replace-link');
			jq(el).parent().addClass('quicklink');
			var text = jq(this).text();
			text += ' ';
			jq(this).text(text);
		});
	},
	
	cufonReplace: function(forceReplace) {
		if(((Application.options.noCufonFonts) && !forceReplace)) {
			return false;
		}
		
		var items = new Array();
		items = jq('.js-cufon-replace-link, .js-cufon-replace, h5, h6, .js-cufon-replace-delayed').get();
		
		if(!jq.browser.msie) {
			items = items.concat(jq('.js-cufon-replace-menu-item').get());
		}
		
		var tmp = new Array();
		var fnQueue = new Array();
		var itemsQueue = new Array();
		var count = 0;
		
		for(i in items) {
			tmp.push(items[i]);
			if(i % 30 == 29 || i == items.length - 1) {
				fnQueue.push(function(i){ Cufon.replace(jq(itemsQueue[i]), { fontFamily: 'MINI Type Global Pro Headline', hover: true});});
				itemsQueue.push(jq(tmp));
				tmp.splice(0, tmp.length);
			}
		}
		
		var foo = function(fnQueue) {
			if(fnQueue.length == 0) { Application.fixDimensions('.js-teaser-fix-image', null, true); return; }
			fnQueue.shift()(count++);
			setTimeout(function(){foo(fnQueue)}, 200);
		}
		
		foo(fnQueue);
		
		return true;
	},
	
	cufonRefresh: function() {
		Application.cufonReplace();
	},

	embedComplete: function() {
		if(++Application.swfCount == Application.flashQueue.length || Application.options.noFlashEmbed) {
			if(Application.options.noFlashEmbed) {
				log('Flash został chwilowo wyłaczony. Przepraszamy ;)');
			} else {
				log('Flash załadowany.');
			}
			jq('#contentOut').css({visibility: 'visible'});
			setTimeout(function(){Application.cufonReplace(false);}, 350);
		}
	},
	
	embed: function(container, cfg) {
		var params = {};
		var width = cfg.width || '100%';
		var height = cfg.height || '100%';
		var id = cfg.id || 'flash-wrapper-'+Math.floor(Math.random()*1543584652878954);
		var flashWrapper = jq('<div>').attr('id', id);
		var movie = cfg.swf;
		var delayed = cfg.delayed || false;
		
		jq(container).append(flashWrapper);
		
		for(i in cfg) {
			if(i != 'container' && i != 'flashvars' && i != 'swf' && i != 'movie' && i != 'delayed') {
				eval('params.'+i+'="'+cfg[i]+'"');
			}
		}
		
		if(delayed) {
			Application.embedComplete();
			setTimeout(function(){
				swfobject.embedSWF(movie.replace('&amp;', '&'), id, width, height, '9.0.0', 'expressInstall.swf', cfg.flashvars, params, {}, function(){});
			}, Application.options.embedTimeout);
		} else {
			swfobject.embedSWF(movie.replace('&amp;', '&'), id, width, height, '9.0.0', 'expressInstall.swf', cfg.flashvars, params, {}, function(){Application.embedComplete();})
		}
	},
	
	embedDelayed: function(container, cfg) {
		setTimeout(function(){
			Application.embed(container, cfg);
		}, Application.options.embedTimeout);
	},
	
	runFlashContent: function(delayed) {
		
		if(Application.flashQueue.length == 0 || this.options.noFlashEmbed) {
			Application.cufonReplace();
			Application.embedComplete();
			return;
		}
		
		for(i in Application.flashQueue) {
			if(delayed) {
				Application.embedDelayed(Application.flashQueue[i].container, Application.flashQueue[i]);
			} else {
				Application.embed(Application.flashQueue[i].container, Application.flashQueue[i]);
			}
		}
	},

	findClassPrefix: function(element, splitter) {
		splitterChar = splitter || '_';
        var cls = String(jq(element).attr('class')).split(splitterChar);
		return String(cls[0]) || undefined;
	},
	
	onWindowResize: function(event) {
		if(Application.options.JCWComponent) {
			Application.correctBackground(Application.options.JCWComponent);
		}
	},
	
	correctBackground: function(elem) {
		if(jq('.subPage-JohnCooperWorks').length == 0) {
			return;
		}
		
		function fixBg() {
			var bgComponent = jq(elem);
			var componetHeight = 0;
			var offset = 1;
			var yOffset = 0;
			
			if(jq.browser.mozilla) {
				yOffset = 16;
			}
			
			componetHeight += parseInt(jq('#header').height());
			componetHeight += parseInt(jq('#content').height());
			componetHeight += parseInt(jq('#teaser').css('margin-top').replace('px', ''));
			bgComponent.height(parseInt(componetHeight+offset));
			bgComponent.width(browserWindow.getWidth() - yOffset);
		}
		
		fixBg();
		
		if(!Application.options.resizeHandled) {
			Application.options.resizeHandled = true;
			Application.options.JCWComponent = elem;
			jq(window).resize(Application.onWindowResize);
			jq('#contentOut').resize(Application.onWindowResize);
		}
		
	},
	
	buildInternalMenus: function() {
		for(i in Application.internalMenus) {
			var ul = jq('<ul>');
			jq('a.js-anchorLink').each(function(idx, elem) {
				ul.append(jq('<li>').append(jq('<a>').addClass('js-cufon-replace-link').addClass('teaser_link_standard').attr('href', '#'+elem.id).text(jq(elem).attr('rel'))));
			});
			jq(Application.internalMenus[i]).append(ul).parent().next().css({marginTop: '0px'});
		}
	},
	
	// FIXME: czasem źle oblicza rozmiary obrazka!
	fixDimensions: function(elem1, elem2, withParent) {
		log('Korekta rozmiarów obrazów...');		
		var child = jq(elem1);
		var childCount = child.length;
		
		Application.correctBackground('.jcwBg_component');
		
		child.each(function(idx, elem){
			jq(elem).bind('load', null, function(event){
				var width = jq(this).width();
				var height = jq(this).height();
				
				jq(this).attr('width', width).attr('height', height);
				
				if(jq(elem2).length > 0) {
					jq(elem2).width(width).height(height);
				}
				
				if(withParent) {
					jq(this).parent().width(width).height(height);
				}
				
				if(jq(this).hasClass('js-teaser-fix-next')) {
					var nextObj = jq(this).next();
					if(nextObj.hasClass('teaser_content_main_headline') || nextObj.hasClass('teaser_content_sub_headline')) {
						nextObj.css({paddingLeft: width});
					}
				}
				
				if(--childCount == 0) {
					Application.correctBackground('.jcwBg_component');
				}
				
			});
		});
		
	},
	
	resize: function(elemId, width, height) {
		var elem = jq(elemId);
		var withParent = elem.is('object');
		
		width	= parseInt(String(width).replace('px', ''));
		height	= parseInt(String(height).replace('px', ''));
		
		if(width && width != INVALID_VALUE) {
			elem.width(width);
			if(withParent) {
				elem.parent().width(width);
			}
		}
		
		if(height && height != INVALID_VALUE) {
			elem.height(height);
			if(withParent) {
				elem.parent().height(height);
			}
		}
	},
	
	combobox: function(elem) {
		
		var cb = elem || jq('select');
		
		if(cb.length <= 0) {
			return;
		}
		
		var cbOptions = {
			animationType: 'fade',
			width: '236px'
		};
		
		var cbStyles = {
			comboboxContainerClass: 'comboboxContainerClass',
			comboboxValueContainerClass: 'comboboxValueContainerClass',
			comboboxValueContentClass: 'comboboxValueContentClass',
			comboboxDropDownClass: 'comboboxDropDownClass',
			comboboxDropDownButtonClass: 'comboboxDropDownButtonClass',
			comboboxDropDownItemClass: 'comboboxDropDownItemClass',
			comboboxDropDownItemHoverClass: 'comboboxDropDownItemHoverClass',
			comboboxDropDownGroupItemHeaderClass: 'comboboxDropDownGroupItemHeaderClass',
			comboboxDropDownGroupItemContainerClass: 'comboboxDropDownGroupItemContainerClass'
		};
		
		jq(cb).combobox(cbStyles, cbOptions);
		log('ComboBoxes: '+cb.length);
	},
	
	cssImport: function(url) {
		var cssNode = document.createElement('link');
		cssNode.type = 'text/css';
		cssNode.href = url;
		cssNode.rel = 'stylesheet';
		cssNode.media = 'all';
		var head = document.getElementsByTagName('head')[0];
		head.appendChild(cssNode);	
	},
	
	scriptImport: function(url) {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.async = false;
		script.src = url;
		var head = document.getElementsByTagName('head')[0];
		head.appendChild(script);	
	},
	
	ojax: function(data) {
		var result = null;

		function parsePostData(value) {
			var result = {};
			for(var i in value) {
				if(i != 'dataType' && i != 'type') {
					eval('result.'+i+'="'+value[i]+'"');
				}
			}
			return result;
		}
		
		jq.ajax({
			type: data.type || 'POST',
			url: '/tools/datasheet/getData.php',
			async: false,
			cache: false,
			data: parsePostData(data),
			dataType: data.dataType || 'json',
			processData: data.processData || true,
			success: function(data, textStatus, XMLHttpRequest) {
				result = data;
			}, error: function(XMLHttpRequest, textStatus, errorThrown) {
				Application.messageBox('Status: '+textStatus + '<br />' + 'Błąd: ' + errorThrown, 'MINI - Error');
			}
		});
		
		return result;
	},
	
	setDataSheet: function(elem, data) {
		var body = Application.ojax({dataType: 'text', model_1: data.model.toUpperCase()||'', action: 'technical'});
		jq(elem).find('tbody').html(body);
	},
	
	showModelList: function() {
		var models = Application.ojax({dataType: 'json', action: 'getModelList'});
		var ul_lvl1 = jq('<ul/>').css({marginLeft: '20px', marginTop: '0', paddingTop: '0'});
		
		for(var i in models) {
			var ul_lvl2 = jq('<ul/>').css({marginLeft: '20px'});
			var li_lvl1 = jq('<li/>');
			var span_lvl1 = jq('<span/>').css({fontSize: '11px', color: '#a9a9a9'}).text(i);
			
			li_lvl1.append(span_lvl1);
			
			for(var j in models[i]) {
				var li_lvl2 = jq('<li/>');
				var span_lvl2_1 = jq('<span/>').css({width: '40px', color: '#a9a9a9', float: 'left', fontSize: '10px'}).text(models[i][j].code);
				var span_lvl2_2 = jq('<span/>').css({width: '200px', color: '#a9a9a9', float: 'left', fontSize: '10px'}).text(models[i][j].engine);				
				li_lvl2.append(span_lvl2_1);
				li_lvl2.append(span_lvl2_2);
				ul_lvl2.append(li_lvl2);
			}
			
			li_lvl1.append(ul_lvl2);
			ul_lvl1.append(li_lvl1);
			
		}
		Application.messageBox('<ul>'+ul_lvl1.html()+'</ul>', 'Lista model MINI');
	},
	
	iePNGFix: function() {

		function getPNGImages(node) {
			var result = [];
			
			function recursiveSearch(childNode) {
				jq(childNode).children().each(function() {
					var src = '';
					var fileName = '';
					var isImage = jq(this).is('img');
					
					if(isImage) {
						fileName = jq(this).attr('src');
					} else {
						fileName = jq(this).css('background-image');
					}
					
					var regEx = /^url\(\"(.*)\"\)$/;
					var isPNG = /\.(png)$/;
					
					fileName = String(fileName).match(regEx);
					
					if(fileName && (isPNG.test(fileName[1]))) {
						result.push({node: this, src: fileName[1]});
					}
					
					if(jq(this).children().length > 0) {
						recursiveSearch(this);
					}
					
				});	
			}	
			
			recursiveSearch(node);
			return result;
		};

		var images = getPNGImages('body');
		
		function setAlphaFilter(elem) {
			var style = jq(elem.node).attr('style');
			var isImage = jq(elem.node).is('img');
			
			if(isImage) {
				
			} else {
				jq(elem.node).css('background-image', 'none');
				jq(elem.node).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + elem.src + "',sizingMethod='scale')";
			}
		}
		
		for(var i in images) {
			setAlphaFilter(images[i]);
		}
		
	}
};

//------------------------------------------------------------------------------

Faq = {
	init: function(faqs_root) {
		jq(faqs_root).find('.faq_triggers a').click(function(){ Faq.toggle(faqs_root, this); return false;});
	},
	
	mainStageUpdate: function(elem) {
		var mainStage = jq('.mainStage_component');
		var stageImage = mainStage.find('.stageImage');
		var img = stageImage.find('img');
		var newImg = jq(elem).find('.js-main-stage-image').clone(true);
		var linkList = mainStage.find('.linkList');
		var newLink = jq(elem).find('.js-main-stage-link').clone(true);
		
		if(newImg.length > 0 && img.length > 0) {
			jq(img).remove();
			jq(stageImage).append(newImg);
		}
		
		if(newLink.length > 0 && linkList.length > 0) {
			linkList.find('.teaser_link_standard').remove();
			linkList.append(newLink);
		}
		
	},
	
	toggle: function(container, trigger) {
		var current = jq(container).find('.faq_triggers .teaser_link_standard-active');
		jq(current).removeClass('teaser_link_standard-active');
		jq(container).find('.faq_id-'+jq(current).attr('rel')).hide();
		jq(container).find('.faq_id-'+jq(trigger).attr('rel')).show();
		jq(trigger).addClass('teaser_link_standard-active');
		var mst = jq(trigger).parent().find('.js-main-stage-teaser');
		if(mst.length > 0) {
			Faq.mainStageUpdate(mst);
		}
		
		if(!Application.options.noCufonFonts /*&& !jq.browser.msie*/) {
			Cufon.replace(jq(container).find('.js-cufon-replace-link'));
		}
	}
}

//------------------------------------------------------------------------------

MainMenu = {
    root: null,
    menuId: '',
    options: {
        css: {
          subMenu: ''
        },
        toShow: null,
        toHide: null,
		openSpeed: 150,
		timeout: 150,
		animation: 'swing'
		
    },
    
    load: function(id) {
        MainMenu.root = jq(id);
        MainMenu.menuId = id;
		
        var config = {
            over:       MainMenu.onShow,
            out:        MainMenu.onHide,
            timeout:    MainMenu.options.timeout
        };
        MainMenu.root.find('> li').hoverIntent(config);
		
		config.timeout	= 0;
		config.over		= MainMenu.highlightItem;
		config.out		= MainMenu.unhighLightItem;
		MainMenu.root.find('> li').find('li').hoverIntent(config);
		
		MainMenu.root.find('a').click(MainMenu.onClick);
		MainMenu.hideAllSub();
		
    },
    
	// funkcja zastąpiona przez Application.
	getLevelClass: function(element) {
        var el = jq(element);
        var cls = String(el.attr('class')).split(' ');
		
        return String(cls[0]) || undefined;
	},
	
    getHoverClass: function(element) {
		var lvlClass = Application.findClassPrefix(element, ' ');//MainMenu.getLevelClass(element);
		
		if(lvlClass != undefined) {
			lvlClass = lvlClass + '-hover';
		}
		
        return lvlClass;
    },
	
    getTextClass: function(element) {
		var lvlClass = Application.findClassPrefix(element, ' ');//MainMenu.getLevelClass(element);
		
		if(lvlClass != undefined) {
			lvlClass = lvlClass + '-text';
		}
		
        return lvlClass;
    },
    
	mouseOver: function(toShow, displayStyle) {
		var hoverCls = MainMenu.getHoverClass(toShow);
        var el = jq(toShow);
		
		if(!el.hasClass(hoverCls)) {
            el.addClass(hoverCls);
			el.find('.'+MainMenu.getTextClass(toShow)).css({display: 'none'});
			var li = el.find('.'+hoverCls);
			li.css('display', displayStyle);				
			var sub = el.find('ul').first();
			if(sub.length > 0) {
				MainMenu.showSub(sub);
			}
		}
	},
	
	mouseOut: function(toHide, displayStyle) {
		var hoverCls = MainMenu.getHoverClass(toHide);
        var el = jq(toHide);
        if(el.hasClass(hoverCls)) {
            el.removeClass(hoverCls);
			el.find('.'+hoverCls).css({display: 'none'});
			
			var li = el.find('.'+MainMenu.getTextClass(toHide));
			li.css({display: displayStyle});
			
			var sub = el.find('ul').first();				
			if(sub.length > 0) {
				MainMenu.hideSub(sub);
			}
		}
	},
	
	onShow: function(event) {
        MainMenu.mouseOver(event.currentTarget, 'inline');
    },
    
    onHide: function(event) {
        MainMenu.mouseOut(event.currentTarget,  'inline');
    },
	
	highlightItem: function(event) {
		MainMenu.mouseOver(event.currentTarget, 'block');
	},
    
	unhighLightItem: function(event) {
		MainMenu.mouseOut(event.currentTarget,  'block');
	},
	
	onClick: function(event) {
		if(jq(event.currentTarget).hasClass('showSub')) {
			return false;
		} else {
			return true;
		}
	},
	
    showSub: function(toShow) {
        if(typeof(toShow) == 'object' && toShow.length > 0) {
            MainMenu.options.toHide = toShow;
            var hoverCls = MainMenu.getHoverClass(toShow);
			
			toShow.animate({height: 'show' }, this.options.openSpeed, this.options.animation);
			
            var lrtl = MainMenu.root.find('.lrtl').last();
            
            if(lrtl.length > 0) {
                toShow.css('left', '-'+toShow.outerWidth()+'px');
            } else if(!toShow.hasClass('level-1') && !toShow.hasClass('level-2')) {
                if(jq(window).width() < (toShow.offset().left + toShow.width())) {
                    toShow.css('left', '-'+toShow.outerWidth()+'px');
                    toShow.addClass('lrtl');
                }
            }
            
            MainMenu.options.activeItem = toShow;
        }
    },
    
    hideSub: function(toHide) {
        if(typeof(toHide) == 'object' && toHide.length > 0) {
            var hoverCls = MainMenu.getHoverClass(toHide);
			
			toHide.animate({height: 'hide' }, 0, this.options.animation);
            toHide.removeClass('lrtl');
			
            if(!toHide.hasClass('level-1') && !toHide.hasClass('level-2')) {
                toHide.css('left', '184px');
            }
        }
    },
	
	hideAllSub: function() {
		this.root.find('li').each(function(index, item){
			jq(item).removeClass(MainMenu.getHoverClass(item));
		});
	}
};

//------------------------------------------------------------------------------

SideMenu = {
	actionTimer: 0,
	timeout: 150,
	delay: 150,
	speed: 250,
	menu: null,
	initState: 'show',
	closeDelayed: 5000,
	root: null,
	clsPrefix: '',
	
	init: function(elem) {
		var _this = this;
		this.root = jq(elem);
		this.clsPrefix = Application.findClassPrefix(this.root);		
		this.menu = this.root.find('.'+this.clsPrefix);
		
		if(this.root.length == 0 ) {
			return;
		}
		
		if(!Application.options.noCufonFonts) {
			var links = this.root.find('.js-cufon-replace-immediately');
			if(links.length > 0) {
				Cufon.replace(links, { fontFamily: 'MINI Type Global Pro Headline', hover: false}); 
			}
		}
		
		if(this.initState == 'show') {
			this.show();
		}
		
		if(this.closeDelayed > 0) {
			setTimeout(function(){SideMenu.hide();}, SideMenu.closeDelayed);
		}
		
		this.root.hover(
			function(){
				SideMenu.setOpenTimer();
			},
			function(){
				SideMenu.unsetActionTimer();
			}
		);
		
		this.root.find('li').hover(
			function() {
				SideMenu.highlight(this, false);
			},
			function() {
				SideMenu.highlight(this, true);
			}
		);
		
		jq('.'+this.clsPrefix+'_close_trigger').click(function(){ SideMenu.hide(); return false; });
		
		
	},
	
	setOpenTimer: function() {
		this.unsetActionTimer();
		this.actionTimer = window.setTimeout(function(){SideMenu.show();}, this.timeout);
	},
	
	unsetActionTimer: function() {
		if(this.actionTimer) {
			window.clearTimeout(this.actionTimer);
			this.actionTimer = null;
		}
	},
	
	show: function() {
		ModelSelector.closeMenu(0);
		window.setTimeout(function(){
			SideMenu.root.find('.'+SideMenu.clsPrefix).slideRight(function() {
				SideMenu.root.find('.'+SideMenu.clsPrefix+' .submenu_level1').css({display: 'block'});
			});
		}, this.timeout);
	},
	
	hide: function() {
		SideMenu.root.find('.'+SideMenu.clsPrefix+' .submenu_level1').css({display: 'none'});
		this.root.find('.'+SideMenu.clsPrefix).slideLeft();
	},
	
	highlight: function(elem, unhighLight) {		
		if(jq(elem).hasClass('show_always')) {
			return;
		}
		
		unhighLight = unhighLight || false;
		
		if(unhighLight) {
			jq(elem).children('.sideMenu_text_hover').css({display: 'none'}); //.hide();
			jq(elem).children('.sideMenu_text').css({display: 'block'}); //.show();
		} else {
			jq(elem).children('.sideMenu_text').css({display: 'none'}); //.hide();
			jq(elem).children('.sideMenu_text_hover').css({display: 'block'}); //.show();
		}
	}
};

//------------------------------------------------------------------------------

ModelSelector = {
	root: null,
	rootCls: '',
	
	timeout: 0,
	actionTimer: null,
	menuItem: null,
	subMenuItem: null,
	detailItem: null,
	subMenuItemHighlighted: 0,
	menuItemHighlighted: 0,
	toggler: null,
	
	init: function(elem) {
		ModelSelector.root = jq(elem);
		ModelSelector.rootCls = ModelSelector.getRootClass(ModelSelector.root);		
		ModelSelector.menuItem = ModelSelector.root.find('.'+ModelSelector.rootCls);
		ModelSelector.subMenuItem = ModelSelector.root.find('.'+ModelSelector.rootCls+'_submenu');
		ModelSelector.detailItem = ModelSelector.root.find('.'+ModelSelector.rootCls+'_details');
		
		if(ModelSelector.root.parent().find('.sidemenu_trigger').length > 0) {
			ModelSelector.menuItem.css({top: '-200px'});
			ModelSelector.subMenuItem.css({top: '-200px'});
			ModelSelector.detailItem.css({top: '-200px'});
		}
		
		var t = ModelSelector.root.parent().find('.'+ModelSelector.rootCls+'_trigger');
		if(t.length > 0) {
			ModelSelector.toggler = t;
			ModelSelector.toggler.hover(function(){ModelSelector.showDelayed(0, this);}, function(){ModelSelector.hideDelayed(2);});
		}
		ModelSelector.detailItem.hover(function(){ModelSelector.unsetTimer();}, function(){ModelSelector.hideDelayed(2, 1);});
		
		ModelSelector.menuItem.parent().hover(
									function(){ModelSelector.showDelayed(0, this);},
									function(){ModelSelector.hideDelayed(1);});
		
		ModelSelector.menuItem.find('.modelNav').hover(
									function(){ModelSelector.showDelayed(1, this);},
									function(){ModelSelector.hideDelayed(0, 1);});
		
		ModelSelector.menuItem.find('.modelNav .submenu').hover(
									function(){},
									function(){ ModelSelector.unsetTimer();});
		
		ModelSelector.menuItem.find('.submenu > li > a').each(function(idx, elem) {
			var config = {
				timeout: 1,
				over: function(event) { log(idx); },
				out: function(event) { }
			};
			jq(this).hoverIntent(config);
		});
		
		ModelSelector.menuItem.find('.submenu > li').hover(
									function(){ModelSelector.showDelayed(2, this);},
									function(){ModelSelector.hideDelayed(2, 1);});
		
		// hover dla pierszego elementu menu który jest zwykłym linkiem
		ModelSelector.menuItem.find('.modelNav').first().hover(
			function() {
				jq(this).find('.modelNav-text').css({display: 'none'});
				jq(this).find('.modelNav-hover').css({display: 'block'});
			},
			function() {
				jq(this).find('.modelNav-hover').css({display: 'none'});
				jq(this).find('.modelNav-text').css({display: 'block'});
			}
		);
		
	},
	
	getRootClass: function(element) {
        var cls = String(jq(element).attr('class')).split('_');
        return String(cls[0]) || undefined;	
	},
	
	showDelayed: function(level, elem) {
		ModelSelector.unsetTimer();
		switch(level) {
			case 0: {
				ModelSelector.actionTimer = window.setTimeout(function(){ModelSelector.openMenu();}, ModelSelector.timeout);				
				break;
			}
			case 1: {
				ModelSelector.actionTimer = window.setTimeout(function(){ModelSelector.openSubMenu(elem);}, ModelSelector.timeout);
				break;
			}
			case 2: {
				ModelSelector.actionTimer = window.setTimeout(function(){ModelSelector.openDetailMenu(elem)}, ModelSelector.timeout);
			}
		}
	},
	
	hideDelayed: function(level, stopClose) {
		ModelSelector.unsetTimer();
		ModelSelector.actionTimer = window.setTimeout(function(){ModelSelector.closeMenu(level,stopClose !== undefined ? stopClose : -1); }, ModelSelector.timeout);
	},
	
	unsetTimer: function() {
		if(ModelSelector.actionTimer) {
			window.clearTimeout(ModelSelector.actionTimer);
			ModelSelector.actionTimer = null;
		}
	},
	
	openMenu: function() {
		SideMenu.hide();
		ModelSelector.menuItem.slideRight(function(){
			ModelSelector.menuItem.find('ul:first-child').show();
		});		
	},
	
	closeMenu: function(level, stopClose) {
		if(level == 2 && stopClose < 2) {
			ModelSelector.highlightSubmenu(null);
			if(ModelSelector.detailItem.is(':visible')) {
				ModelSelector.detailItem.slideLeft(function() {
					if(stopClose == 1) {
						ModelSelector.closeMenu(1, stopClose);
					}
					ModelSelector.detailItem.css('borderWidth', '1px');
					ModelSelector.detailItem.empty();
				});
			} else {
				ModelSelector.closeMenu(1, stopClose);
			}
			return;
		}
		
		if(level == 1 && stopClose < 1) {
			ModelSelector.highlightMenu(null);
			ModelSelector.detailItem.hide();
			if(ModelSelector.subMenuItem.is(':visible')) {
				ModelSelector.subMenuItem.slideLeft(function(){
					ModelSelector.closeMenu(0, stopClose);
					ModelSelector.subMenuItem.empty();
				});
			} else {
				ModelSelector.closeMenu(0, stopClose);
			}
			return;
		}
		
		if(level == 0 && stopClose < 0) {
			ModelSelector.detailItem.hide();
			ModelSelector.subMenuItem.hide();
			if(ModelSelector.menuItem.is(':visible')) {
				ModelSelector.menuItem.find('ul:first-child').hide();
				ModelSelector.menuItem.slideLeft();
			}
			return;
		}
	},
	
	openSubMenu: function(elem) {
		ModelSelector.closeMenu(2, 1);
		ModelSelector.highlightMenu(elem);
		
		var submenu = jq(elem).find('.submenu');
		if(submenu.length > 0) {
			ModelSelector.subMenuItem.empty();
			ModelSelector.subMenuItem.append(submenu.clone(true));

			if(!jq.browser.msie && !Application.options.noCufonFonts) {
				Cufon.replace(ModelSelector.subMenuItem.find('.js-cufon-replace-beforeShow'));
			}
			
			ModelSelector.subMenuItem.slideRight();
		} else {
			ModelSelector.closeMenu(1, 0);
		}
	},
	
	highlightMenu: function(elem) {
		
		if(ModelSelector.menuItemHighlighted) {
			ModelSelector.menuItemHighlighted.flash(function() {
				if(typeof(this.showMouseLeave) == 'function') {
					this.showMouseLeave();
				}
			});
			ModelSelector.menuItemHighlighted = null;
		}
		
		if(elem) {
			ModelSelector.menuItemHighlighted = jq(elem);
			ModelSelector.menuItemHighlighted.flash(function() {
				if(typeof(this.showMouseEnter) == 'function') {
					this.showMouseEnter();
			    }
			});
		}
		
	},
	
	highlightSubmenu: function(elem) {
		if(ModelSelector.subMenuItemHighlighted) {
			jq(ModelSelector.subMenuItemHighlighted).find('.modelNav-sub-text').show();
			jq(ModelSelector.subMenuItemHighlighted).find('.modelNav-sub-hover').hide();
		}
		if(elem) {
			ModelSelector.subMenuItemHighlighted = elem;
			jq(ModelSelector.subMenuItemHighlighted).find('.modelNav-sub-hover').show();
			jq(ModelSelector.subMenuItemHighlighted).find('.modelNav-sub-text').hide();
		}
	},
	
	openDetailMenu: function(elem) {
		if(ModelSelector.detailItem.length > 0 && !ModelSelector.subMenuItem.is(':visible')) {
			ModelSelector.detailItem.hide();
			return true;
		}
		
		ModelSelector.highlightSubmenu(elem);
		
		ModelSelector.detailItem.empty();
		var qf = jq(elem).find('.modelQuickfacts').clone(true);
		if(qf.length > 0) {
			qf.show();
			ModelSelector.detailItem.append(qf);
			if(!jq.browser.msie && !Application.options.noCufonFonts) {
				Cufon.replace(ModelSelector.detailItem.find('.js-cufon-replace-beforeShow1'));
			}
			ModelSelector.detailItem.slideRight();
		} else {
			ModelSelector.closeMenu(2, 1);
		}
		return true;
	}
};

//------------------------------------------------------------------------------

Teaser = {
	root: null, // dotyczy tylko dolnych teaserów
	options: {
		prefix: 'teaser',
		prefixBox: 'teaser-box',
		openSpeed: 150,
		openDelay: 500,
		closeDelay: 500,
		animation: '',
		actionTimer : null,
		autoChangeTimer: null,		
		autoChange: true,
		autoChangeInterval: 12000,
		simpleRotator: {
			timeout: 5000,
			animationSpeed: 500,
			actionTimer: null,
			items: null,
			current: null
		}
	},
	rows: 0,
	currentRow: 0,
	
	init: function(el) {
		// dolny teaser
		this.root = jq('#teaser');
		this.currentRow = this.root.find('.teaser-row:visible');
		this.rows = this.root.find('.teaser-row').length;
		
		this.root.find('.'+this.options.prefix+'-row').each(function(rowIdx, row){
			jq(row).addClass('teaser-row-'+rowIdx);
			jq(row).find('.'+Teaser.options.prefix+'-box').each(function(boxIdx, box) {
				var boxSmall = jq(box).find('.'+Teaser.options.prefixBox+'-small');
				boxSmall.hover(Teaser.showBigTeaserDelayed, Teaser.claerActionTimer);
			});
		});
		
		this.root.mouseleave(function(){Teaser.hideAllTeaserDelayed();});
		this.root.find('.js-'+this.options.prefix+'-trigger-left').click(function(){Teaser.toggleTeaserRow(1);});
		this.root.find('.js-'+this.options.prefix+'-trigger-right').click(function(){Teaser.toggleTeaserRow(2);});
		
		this.modelQuickfacts('.top-teasers .quickfacts_module');
		this.simpleRotator('.top-teasers .teaser_rotator');
		
		this.startTeaserAutoChange();
		//this.simpleTab('.teaser_tab_component');
		
	},
	
	/*
	 * Dolny przewijany teaser
	 */
	
	// TODO: Auto rotacja
	showBigTeaser: function(teaserDiv) {
		Teaser.hideAllTeaser();
		window.clearTimeout(Teaser.options.actionTimer);
		teaserDiv.css('display', 'inline');
	},
	
	showBigTeaserDelayed: function(event) {
		var teaserBig = jq(event.currentTarget).parent().find('.'+Teaser.options.prefixBox+'-big');
		Teaser.options.actionTimer = window.setTimeout(function() { Teaser.showBigTeaser(teaserBig); }, Teaser.options.openDelay);
		Teaser.stopTeaserAutoChange();
	},
	
	hideAllTeaser: function() {
		Teaser.root.find('.'+Teaser.options.prefixBox+'-big').css('display', 'none');
	},
	
	hideAllTeaserDelayed: function(event) {
		Teaser.claerActionTimer();
		Teaser.options.actionTimer = window.setTimeout(function(){Teaser.hideAllTeaser();}, Teaser.options.closeDelay);
	},
	
	claerActionTimer: function(event) {
		if(Teaser.options.actionTimer) {
			window.clearTimeout(Teaser.options.actionTimer);
		}
		Teaser.startTeaserAutoChange();
	},
	
	toggleTeaserRow: function(direction) {
		Teaser.currentRow.hide();
		Teaser.hideAllTeaser();
		var tmp = direction == 1 ? Teaser.currentRow.prev() : Teaser.currentRow.next();
		if(tmp.hasClass('teaser-row')) {
			tmp.show();
			Teaser.currentRow = tmp;
		} else {
			Teaser.currentRow = direction == 1 ? Teaser.root.find('.teaser-row').last() : Teaser.root.find('.teaser-row').first();
			Teaser.currentRow.show();
		}
	},
	
	startTeaserAutoChange: function() {	
		if(Teaser.options.autoChangeTimer) {
			return;
		}
		
		if(Teaser.options.autoChange) {
			Teaser.options.autoChangeTimer = window.setInterval('Teaser.toggleTeaserRow(false);', Teaser.options.autoChangeInterval);
		}
	},

	stopTeaserAutoChange: function() {	
		if(!Teaser.options.autoChangeTimer) {
			return;
		}
		
		window.clearInterval(Teaser.options.autoChangeTimer);
		Teaser.options.autoChangeTimer = null;
	},
	
	/*
	 * Quickfact teaser, u góry strony
	 */
	
	modelQuickfacts: function(elem) {
		var rootCls = Application.findClassPrefix(elem);
		var components = jq(elem).find('.'+rootCls+'_component');
		var triggers = jq(elem).find('.js-'+rootCls+'-show');
		triggers.first().css('marginTop', '13px');
		
		triggers.click(function(){
			triggers.hide();
			jq(elem).find('.js-'+jq(this).attr('rel')).show();
			Teaser.simpleRotatorToggle();
			return false;
		});
		
		components.find('.js-'+rootCls+'-close').click(function(){
			components.hide();
			triggers.show();
			Teaser.simpleRotatorToggle();
			return false;
		});
	
		if(triggers.length > 1) {
			triggers.show();
		} else if (components.length == 1) {
			components.show();
			Teaser.simpleRotatorToggle();
			window.setTimeout(function(){ components.find('.js-'+rootCls+'-close').trigger('click'); }, 10000);
		}
		
		jq('.quickfacts_component .quickfacts_background').css({opacity: 0.5});
		
		jq('a.quickfacts_link').click(function(e) {
			e.preventDefault();
		});
		
		/*var qlink = jq('.quickfacts_link');
		var qcolor = qlink.css('color');
		qlink.hover(
					function(){
						qlink.css({color: '#fff'});
					},
					function(){
						qlink.css({color: qcolor});
					}
		);
		*/
	},
	
	/*
	 * prosty rotator, teasery tekstowe u góry strony
	 */
	
	// FIXME: przenikanie źle wygląda we wszytkich IE
	simpleRotator: function(rotator_root) {
		Teaser.options.simpleRotator.items = jq(rotator_root).children().hide();
		Teaser.options.simpleRotator.current = Teaser.options.simpleRotator.items.first().addClass('js-tsr-current');
		Teaser.simpleRotatorToggle();
	},
	
	simpleRotatorToggle: function() {
		if(!Teaser.options.simpleRotator.actionTimer) {
			if(Teaser.options.simpleRotator.current) {
				Teaser.options.simpleRotator.current.show();
			}
			Teaser.options.simpleRotator.actionTimer = setInterval(function(){
				var next = Teaser.options.simpleRotator.current.next();
				if(next.length == 0) {
					next = Teaser.options.simpleRotator.items.first();
				}
				Teaser.options.simpleRotator.current.fadeOut(Teaser.options.simpleRotator.animationSpeed).removeClass('js-tsr-current');
				Teaser.options.simpleRotator.current = next.fadeIn(Teaser.options.simpleRotator.animationSpeed).addClass('js-tsr-current');
			}, Teaser.options.simpleRotator.timeout);
		} else {
			clearInterval(Teaser.options.simpleRotator.actionTimer);
			Teaser.options.simpleRotator.actionTimer = null;
			Teaser.options.simpleRotator.items.hide();
		}
	},
	
	/*
	 * tab teaser
	 */
	simpleTab: {
		init: function(tab_root) {
			var _this = this;
			var root = jq(tab_root);
			var oid = root.find('.taser_tab_toggler .tab_toggler-current').attr('rel');			
			
			// ten typ nie trzeba potraktować osobno
			if(root.hasClass('teaser_tab_component-tab5')) {
				_this.toggleCmp5(root);
				return;
			}
			
			_this.fixIt(root);
			
			jq(document).ready(function(){ _this.showInfoTable(root, oid); });
			
			root.find('.teaser_tab_image .tab_image-'+oid).addClass('tab_image-current').show();
			root.find('.teaser_tab_content .tab_text-'+oid).addClass('tab_text-current').show();
			
			if(root.find('.taser_tab_toggler a').length <= 1) {
				root.find('.taser_tab_toggler').css({display: 'none'});
			}
			
			root.find('.taser_tab_toggler a').click(function(e) {
				root.find('.teaser_tab_content .tab_text-current').hide().removeClass('tab_text-current');
				root.find('.taser_tab_toggler .tab_toggler-current').removeClass('tab_toggler-current').addClass('tab_toggler');

				var oid = jq(this).attr('rel');
				var nextImg = root.find('.teaser_tab_image .tab_image-'+oid);
				
				if(nextImg.length > 0) {
					root.find('.teaser_tab_image .tab_image-current').hide().removeClass('tab_image-current');
					nextImg.addClass('tab_image-current').show();
				}
				
				root.find('.teaser_tab_content .tab_text-'+oid).addClass('tab_text-current').show();
				jq(this).removeClass('tab_toggler').addClass('tab_toggler-current');
				
				if(root.hasClass('teaser_tab_component-tab4')) {
					_this.toggleCmp4(root, oid);
				} else {
					_this.closeAllFacts(null);
					_this.showInfoTable(root, oid);
				}
				
				if(!Application.options.noCufonFonts) {
					Cufon.replace('.taser_tab_toggler .js-cufon-replace-link');
				}
				
				return false;
			});
		},
		
		fixIt: function(root) {
			var itables = root.find('.teaser_tab_information_table .information_table .information_table_content');
			itables.each(function(){
				var lists = jq(this).find('ul');
				lists.each(function(index, elem) {
					if(index > 0) {
						jq(this).hide();
					}
					jq(this).find('li:first-child').addClass('first');
					jq(this).find('li:last-child').addClass('last');
				});
			});
		},
		
		showInfoTable: function(root, oid) {
			var infoTable = root.find('.teaser_tab_information_table .information_table-'+oid);
			
			if(infoTable.length > 0) {
				var tableContainer = jq.find('.teaser_information_table .teaser_information_table_content');
				
				jq(tableContainer).empty();
				jq(tableContainer).append(infoTable.clone(false));
				
				var lists = jq(tableContainer).find('.information_table_content ul');
				
				if(lists.length > 1) {
					jq(tableContainer).find('.information_table_footer .information_table_footer_toggler').text('Zobacz wszytkie fakty').click(Teaser.simpleTab.toggleAllFacts).show();
					jq(tableContainer).find('.information_table_footer .information_table_footer_toggler_icon').click(Teaser.simpleTab.toggleAllFacts).show();
				}
				
				if(!Application.options.noCufonFonts) {
					Cufon.replace('.teaser_information_table .teaser_information_table_content .information_table_headline .js-cufon-replace');
				}
				
				jq(infoTable).show();
			}
		},
		
		toggleCmp4: function(root, oid) {
			var tc = root.find('.teaser_tab-current');
			var tn = root.find('.teaser_tab-current').next();
			
			if(tn.length == 0 || tn.hasClass('teaser_tab_noactive')) {
				tn = root.find('.teaser_tab:first-child');
			}
			
			tc.removeClass('teaser_tab-current').css({display: 'none'});
			tn.addClass('teaser_tab-current').css({display: 'block'});
			
			var cc = root.find('.teaser_information_table-current').css({display: 'none'}).removeClass('teaser_information_table-current');
			var cn = root.find('.teaser_information_table-'+oid).css({display: 'block'}).addClass('teaser_information_table-current');
			
		},
		
		toggleCmp5: function(tab_root) {
			var toggler = jq(tab_root).find('.taser_tab_toggler .tab_toggler');
			var frontImg = jq(tab_root).find('.teaser_tab_contents .teaser_tab_content .teaser_layout_col2 .teaser_tab_image-front');
			var sideImg = jq(tab_root).find('.teaser_tab_contents .teaser_tab_content .teaser_layout_col2 .teaser_tab_image-side');
			
			toggler.click(function(){
				if(toggler.hasClass('tab_toggler-front')) {
					toggler.removeClass('tab_toggler-front').addClass('tab_toggler-side');
					frontImg.css({display: 'none'});
					sideImg.css({display: 'block'});
				} else {
					toggler.removeClass('tab_toggler-side').addClass('tab_toggler-front');
					sideImg.css({display: 'none'});
					frontImg.css({display: 'block'});
				}
				
				return false;
			});
			
		},
		
		toggleAllFacts: function(event) {
			var root = jq(event.currentTarget).parent().parent().parent().parent();
			if(root.hasClass('teaser_information_opened')) {
				Teaser.simpleTab.closeAllFacts(root);
			} else {
				Teaser.simpleTab.openAllFacts(root);
			}
		},
		
		openAllFacts: function(root) {
			if(!root || root.length == 0) {
				return;
			}

			var lists = root.find('.teaser_information_table_content ul'); // muszą być dwie
			try {
				jq(lists[0]).css({borderRight: '1px solid #999', width: '279px'});
				jq(lists[1]).css({display: 'block', width: '280px'});
			} catch(e) {
				Application.messageBox('Przepraszam ale nie mogę wykonąć tej akcji, ponieważ: '+e.name+': '+e.message, 'Błąd');
				return;
			}
			
			root.prev().css({visibility: 'hidden'});
			root.find('.teaser_information_table_content').css({position: 'absolute', width: '560px', left: '-300px'});
			root.find('.information_table_footer .information_table_footer_toggler').text('Minimalizuj');
			root.find('.information_table_footer .information_table_footer_toggler_icon').addClass('information_table_footer_toggler_opened');
			root.addClass('teaser_information_opened');			
		},
		
		closeAllFacts: function(root) {

			root = root || jq('.teaser_information_table'); //  jeśli nie określono konkretnego teasera to należy zamknąć wszytkie
			
			var lists = root.find('.teaser_information_table_content ul'); // muszą być dwie
			try {
				jq(lists[0]).css({borderRight: 'none', width: '260px'});
				jq(lists[1]).css({display: 'none'});
			} catch(e) {
				Application.messageBox('Przepraszam ale nie mogę wykonąć tej akcji, ponieważ: '+e.name+': '+e.message, 'Błąd');
				return;
			}
			
			root.prev().css({visibility: 'visible'});
			root.find('.teaser_information_table_content').css({position: 'relative', width: '260px', left: '0px'});
			root.find('.information_table_footer .information_table_footer_toggler').text('Zobacz wszytkie fakty');
			root.find('.information_table_footer .information_table_footer_toggler_icon').removeClass('information_table_footer_toggler_opened');
			root.removeClass('teaser_information_opened');
			
		}
	}
};

//------------------------------------------------------------------------------

// TODO: przechowywanie ostatnio wybranych modeli 
MINIComparator = {
	options: {
		url: '/tools/datasheet/getData.php',
		method: 'POST',
		defaultImage: '/site/_common/_shared_files/product_presentation/mini/one_d/modelcomparison.jpg'
	},
	
	models: null,
	
	defaultHandler: function() {
		if(jq(this).is('a') && jq(this).attr('href') == '#' || jq(this).attr('href') == '/#' || !jq(this).attr('href')) {
			return false;
		}
		return true;
	},
	
	getData: function(action, data) {
		var result = null;
		jq.ajax({
			type: MINIComparator.options.method,
			url: MINIComparator.options.url,
			async: false,
			cache: false,
			data: data || {action: action},
			dataType: data ? 'text' : 'json',
			processData: true,
			success: function(data, textStatus, XMLHttpRequest) {
				result = data;
			}, error: function(XMLHttpRequest, textStatus, errorThrown) {
				Application.messageBox('Status: '+textStatus + '<br />' + 'Błąd: ' + errorThrown, 'MINI - Error');
			}
		});
		return result;
	},
	
	init: function(elem) {
		MINIComparator.models = MINIComparator.getData('getModelList');
		for(i in MINIComparator.models) {
			var option = jq('<option>').attr('value', i).text(i);
			for(n = 1; n <= 3; n++) {
				jq('#body_'+n).append(option.clone(true));
				jq('#body_'+n)[0].internalCombobox.update();
			}
		}
		MINIComparator.setDefaults();
		MINIComparator.compare(jq('#type_1'));
		
		jq('.comparison_quicklinks a').click(MINIComparator.defaultHandler);
		
	},
	
	resetComparisonLinks: function(typeBox) {
		var n = String(jq(typeBox).attr('id')).split('_');
		jq('.model_'+n[1]).find('.details_link').attr('href', '/#');
		jq('.model_'+n[1]).find('.configure_link').attr('href', '/#');
	},
	
	setDefaults: function() {
		var body = jq('#body_1');
		var type = jq('#type_1');
		body.val('MINI');
		body[0].internalCombobox.update();
		body.trigger('onchange');
		type.val('SR31');
		type[0].internalCombobox.update();
	},
	
	populateTypeBox: function(elem, callback) {
		var n = String(jq(elem).attr('id')).split('_');
		var defaultOption = jq('<option>').attr('value', '-1').text('Select a model');
		
		jq('#type_'+n[1]).children().remove();
		jq('#type_'+n[1]).append(defaultOption);
		
		if(elem.value == '-1') {
			jq('#type_'+n[1])[0].internalCombobox.update();
			return;
		}
		
		for(i in MINIComparator.models[elem.value]) {
			var data = MINIComparator.models[elem.value][i];
			var option = jq('<option>').attr('value', data.code).text(data.engine);
			option.data('modelData', data);
			jq('#type_'+n[1]).append(option.clone(true));
		}
		
		jq('#type_'+n[1])[0].internalCombobox.update();
		
		if(typeof(callback) == 'function') {
			callback();
		}
		
		log('MINI Body '+ n[1] + ': ' + elem.value);
	},
	
	buildRequestData: function() {
		var result = new Object();
		result.action = 'comparison';
		for(i = 1; i <= 3; i++) {
			var body = jq('#body_'+i);
			var type = jq('#type_'+i);
			//if(body.val() != '-1' || type.val() != '-1') {
				eval('result.model_'+i+'="' + type.val()+'"');
			//}
		}
		return result;
	},
	
	getImagePath: function(typeBox) {
		return String(jq(typeBox).find('option[value="'+jq(typeBox).val()+'"]').data('modelData').image);
	},
	
	getFSPath: function(typeBox) {
		return String(jq(typeBox).find('option[value="'+jq(typeBox).val()+'"]').data('modelData').finance);
	},
	
	getConfigPath: function(typeBox) {
		return String(jq(typeBox).find('option[value="'+jq(typeBox).val()+'"]').data('modelData').configurator);
	},
	
	compare: function(typeBox) {
		var n = String(jq(typeBox).attr('id')).split('_');
		
		if(jq(typeBox).val() == '-1') {
			MINIComparator.resetComparisonLinks(typeBox);
			return;
		}
		
		log('MINI Type '+ n[1] + ': ' + jq(typeBox).val());
		if(jq('#body_1').val() == '-1' || jq('#type_1').val() == '-1') {
			MINIComparator.setDefaults();
		}
		
		MINIComparator.update(typeBox);
	},
	
	update: function(typeBox) {
		var n = String(jq(typeBox).attr('id')).split('_');
		var html = MINIComparator.getData(null, MINIComparator.buildRequestData());
		
		jq('.comparison_details').find('tbody').html(String(html));
		jq('.comparison_quicklinks').find('.model_'+n[1]).find('.model_image_palceholder').children().remove();
		
		var image = new Image();
		image.onload = function() {
			jq('.comparison_quicklinks').find('.model_'+n[1]).find('.model_image_palceholder').append(this);
		};
		
		log('MINI Photo: ' + MINIComparator.getImagePath(typeBox));
		image.src = MINIComparator.getImagePath(typeBox);
		
		jq('.model_'+n[1]).find('.details_link').attr('href', MINIComparator.getFSPath(typeBox));
		jq('.model_'+n[1]).find('.configure_link').attr('href', MINIComparator.getConfigPath(typeBox));
		
	}
};

//------------------------------------------------------------------------------

MINIGallery = {
	root: null,
	imagePath: '',
	galleryName: '',
	images: null,
	css: {
		leftHotSopt:		'scrollingHotSpotLeft',
		rightHotSpot:		'scrollingHotSpotRight',
		thumbsArea:			'scrollableArea',
		galleryThumb: 		'gallery_thumb_entry',
		thumbnailWrapper:	'gallery_thumb_image',
		thumbnail:			'gallery_thumb',
		thumbLabel:			'gallery_thumb_label',
		scrollWrapper:		'scrollWrapper'
	},
	options: {
		scrollingSpeed: 5,
		mouseDownSpeedBooster: 3, 
		autoScrollDirection: "endlessloop", 
		autoScrollSpeed: 2, 
		visibleHotSpots: "onstart", 
		hotSpotsVisibleTime: 5
	},
	
	init: function(elem, name, galleryItems, galleryPath) {
		MINIGallery.root = jq(elem);
		MINIGallery.imagePath = galleryPath;
		MINIGallery.galleryName = name;
		MINIGallery.parseItems(galleryItems);
		
		MINIGallery.options.displacement = 0;
		MINIGallery.options.fixed_scrollable_area_width = MINIGallery.fixedScrollableAreaWidth() + 'px';
		MINIGallery.root.find('.makeMeScrollable').smoothDivScroll(MINIGallery.options);
		MINIGallery.root.find('.scrollableArea .gallery_thumb_entry:first').css('margin-left','0px');
		
		log('Galeria "'+name+'" gotowa.');
	},
	
	addItem: function(elem) {
		MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).append(elem);
	},
	
	makeThumbEntry: function(fileName, thumbLabel, data) {
		var idx = (MINIGallery.root.find('.'+MINIGallery.css.scrollWrapper).children().length - 1);
		var thumbDiv = jq('<div>').addClass(MINIGallery.css.galleryThumb);
		var thumbnailWrapper = jq('<div>').addClass(MINIGallery.css.thumbnailWrapper);
		var thumbnail = jq('<img>').attr('src', MINIGallery.imagePath + fileName).attr('width', '155').attr('height', '100').attr('alt', MINIGallery.galleryName).attr('rel', 'lightbox');
		var label = jq('<div>').addClass(MINIGallery.css.thumbLabel);
		var textNode = jq('<span>').text(thumbLabel);
		
		thumbnail.hover(function(){MINIGallery.smoothZoomThumbnail(this, true);}, function(){MINIGallery.smoothZoomThumbnail(this, false);});
		thumbnail.click(function(){MINIGallery.zoomImage(this);});
		
		thumbnailWrapper.append(thumbnail);
		label.append(textNode);
		thumbDiv.append(thumbnailWrapper);
		thumbDiv.append(label);
		
		if(data) {
			jq(thumbnail).data('cfg', data)
		}
		
		return thumbDiv;
	},
	
	parseItems: function(items) {
		MINIGallery.images = new Array();
		for(i in items) {
			MINIGallery.addItem(MINIGallery.makeThumbEntry(items[i].thumbnail, items[i].label, items[i]));
			MINIGallery.images.push([MINIGallery.imagePath + items[i].image, items[i].label]);
		}
	},
	
	smoothZoomThumbnail: function(elem, bZoomIn) {
		var data = jq(elem).data('cfg');
		
		if(bZoomIn) {
			
			oldImageWidth = 155;
			newImageWidth = parseInt(oldImageWidth * 1.58);
			
			scrollableAreaWidth = oldScrollableAreaWidth = MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).width();
			
			jq(elem).attr('src', MINIGallery.imagePath + data.small);
			MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).css('width', parseInt(scrollableAreaWidth)-oldImageWidth+newImageWidth + 'px')
			
			jq(elem).parent().parent().animate({width: newImageWidth},{queue:false, duration:500});
			jq(elem).parent().animate({width: newImageWidth},{queue:false, duration:500});
			jq(elem).animate({width: newImageWidth,height: '158'}, {queue:false, duration:500});
			
			if(jq(elem).parent().parent().is(':last-child')) {
				MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).css('width', parseInt(scrollableAreaWidth)-oldImageWidth+newImageWidth + 'px');
				MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).animate({right: newImageWidth-oldImageWidth }, {queue:false, duration:500});
			}
			
			window.setTimeout(function() {return;}, 600);
			
		} else {
			jq(elem).animate({width: oldImageWidth,height: '100'},{queue:false, duration:500 });
			jq(elem).parent().animate({width: oldImageWidth},{queue:false, duration:500});
			jq(elem).parent().parent().animate({width: oldImageWidth},{queue:false, duration:500});
			window.setTimeout(function(){jq('.'+MINIGallery.css.thumbsArea).css("width", scrollableAreaWidth);}, 600);
			jq(elem).attr('src', MINIGallery.imagePath + data.thumbnail);
			if(jq(elem).parent().parent().is(':last-child')) {
				MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).animate({right: 0 }, {queue:false, duration:500});
				MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).css('width', parseInt(oldScrollableAreaWidth) + 'px');
			}
		}
	},
	
	fixedScrollableAreaWidth: function() {
		var newWidth = 0;
		MINIGallery.root.find('.'+MINIGallery.css.thumbsArea).children().each(function(idx, elem) {
			newWidth += parseInt(jq(this).find('img').attr('width')) + 20;
			jq(this).addClass(MINIGallery.css.galleryThumb + '_' + idx);
			jq(this).find('img').addClass('thumb_id-'+idx);
		});
		return newWidth;
	},
	
	zoomImage: function(elem) {
		jq.slimbox(MINIGallery.images, parseInt(String(jq(elem).attr('class')).split('-')[1]), {captionAnimationDuration: 1});
	}
	
};

//------------------------------------------------------------------------------

jq(document).ready(function() {
	
	Application.cssImport('/css/ui-darkness/jquery-ui-darkness.css');
	// Application.iePNGFix();
	
	/*if(jq.browser.msie) {
		switch(parseInt(jq.browser.version)) {
			case 6: {
				Application.cssImport('/css/ie6.css');
				break;
			}
			case 7: {
				Application.cssImport('/css/ie7.css');				
				break;
			}
		}
		
		
	}*/
	
	Application.combobox(jq('.js-combobox'));
	
	if(jq('.teasers_component-comparison').length > 0) {
		MINIComparator.init();
	}
	
	MainMenu.load('#mainMenu');
	Teaser.init();
	ModelSelector.init('#sidebar .modelSelection_menu');
	
	
	SideMenu.init('#sidebar .sidemenu_trigger');
	Application.buildInternalMenus();
	
	jq('.blank').attr('target', '_blank');
	
	if(jq('.table_mini-inclusive').length > 0) {
		jq('.table_mini-inclusive tbody td').hover(
			function(){
				jq(this).parent().find('td').addClass('active_row');
			},
			function(){
				jq(this).parent().find('td').removeClass('active_row');
			}
		);
	}
	
	if(jq('.js-to-hide').length > 0) {
		var config = {
			timeout: 300,
			over: function(event) { jq('.js-to-hide').css('visibility', 'hidden'); },
			out: function(event) { jq('.js-to-hide').css('visibility', 'visible'); }
		};
		jq('#mainMenu').hoverIntent(config);
	}
	
	Application.runFlashContent();	
	
	if(Application.flashQueue.length == 0) {
		jq('#contentOut').css({visibility: 'visible'});
	}
	
	if(!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
		jq("a[rel^='lightbox']").slimbox({}, null, function(el) {
			return (this == el) || ((jq(this).attr('rel').length > 8) && (jq(this).attr('rel') == jq(this).attr('rel')));
		});
	}
	
	// Application.iePNGFix();
	
	Application.fixDimensions('.js-teaser-fix-image', null, true);

	// valid XFBML
	jq.fn.fakeXFBML = function( fb_tag , params ){
		var container = jq(this);
		params = params || {};
		fb_tag = jq("<fb:" + fb_tag + "></fb:" + fb_tag + ">");
		jq.each(params, function( key , value ) {
			fb_tag.attr( key , value );
		});
		fb_tag.appendTo(container);
	};
	
	jq('#topstories').faded();
	
	if(jq('.toggle').length > 0) {
		jq('.toggle').click(function() {
			jq(this).toggleClass('active').next().toggle();
		});
	}
	
});

