window.easyFairs = {
	event:{
		sideMenu:{
			defaultOpenIndex : 1
		}
	},
	ll:{},
	noLoginForShittyBrowserMsg : "This feature is not available for your browser.\n\nContact easyFairs if you need to modify your catalog or upgrade your browser.",
	cart:null
};

var efOverlay;
var ui; //global UI object (efUI)
window.loginBlockIsOpen = false;

// MOVED CM, needs to be available as soon as possible
//cart
window.easyFairs.cart = new tx_ef_visitorCart();

window.addEvent('domready',function(){

	//init overlay
	efOverlay = new Element('div',{
		'id':'efOverlay',
		'styles':{
			'opacity':0,
			'height': window.getSize().y.toInt()
		}
	}).inject(document.body);
	window.addEvent('resize',function(){efOverlay.setStyle('height',window.getSize().y.toInt())});

	//langMenu-toggler
	var langMenuEl = $('languages-list');
	//$('langMenu-wrap').setStyle('visibility','hidden');
	//var langSlider = new Fx.Slide(langMenuEl);
	//langSlider.hide();

	//langMenuEl.setStyle('visibility','visible');
	if($('langMenu-toggler')){
		$('langMenu-toggler').addEvent('click',function(e){
			new Event(e).stop();
			if(langMenuEl.getStyle('display')=='none'){
				langMenuEl.setStyle('display','');
			}else{
				langMenuEl.setStyle('display','none');
			}
			//langMenuEl.setStyle('display','block');
		});
	}



	//login
	if($('loginBlock-toggler')){
		$('loginBlock-toggler').addEvent('click',function(e){
			new Event(e).stop();
			open_loginBlock();
		});
	}


	//search
	if($('searchbox')){
		$('searchbox').addEvent('submit',function(e){
			new Event(e).stop();
			var langSect = (window.easyFairs && window.easyFairs.lang && window.easyFairs.lang!="") ? '/'+window.easyFairs.lang : '';
			window.location.href=langSect+'/search/'+this.getElement('input[type=text]').value;
		});
	}
	if($('searchbox-inpage')){
		$('searchbox-inpage').addEvent('submit',function(e){
			new Event(e).stop();
			window.location.href='/search/'+this.getElement('input[type=text]').value;
		});
	}

	//search autosuggest
	if(window.location.href.contains('autosuggest')){
		


		var lastSearchValue = $('search').value.trim();
		var lastKeyStroke = 0;
		var autoSuggestRequest = null;
		var lastSearchTyped= lastSearchValue;
		$('search').addEvent('keydown',function(e){
			lastKeyStroke = (new Date()).getTime();

			if(lastSearchTyped!=$('search').value.trim()){
				suggestWrapEl.setStyle('display','block');
				suggestWaitEl.setStyle('display','block');
			}

			lastSearchValue = $('search').value.trim();
		});
		lastKeyStroke = (new Date()).getTime();

		$('search').addEvent('blur',function(e){
			suggestWrapEl.setStyle('display','none');
			suggestWaitEl.setStyle('display','none');
		});

		var checkSearchField = function(){
			var val = $('search').value.trim();
			
			if(val != lastSearchValue && val.length>1 && lastKeyStroke+1000 < (new Date()).getTime()){
				launchAutoSuggest(val);
				lastSearchValue = val;
			}
		};
		checkSearchField.periodical(300,this);

		var launchAutoSuggest = function(value,force){
			force = force || false;

			

			if( (autoSuggestRequest!=null && autoSuggestRequest.isRunning() && force) || (autoSuggestRequest==null) || (autoSuggestRequest!=null &&  !autoSuggestRequest.isRunning()) ){
				console.log('launchAutoSuggest');
				autoSuggestRequest = new Request.JSON({
					'url':'index.php',
					'method':'get',
					'data':{
						'eID':'tx_ef_searchsuggest',
						'q':value,
						'lid':easyFairs.lid,
						'lang':easyFairs.lang
					},
					'onComplete':launchAutoSuggest_onComplete.bind(this)
				}).send();
			}
		};
		var launchAutoSuggest_onComplete = function(r){
			console.log(r);
				
			if(r && !r.error){
				
				if(typeof r.numHits != 'undefined'){
					console.log('Found '+r.numHits+' hits !');

					suggestListEl.empty();
					suggestWaitEl.setStyle('display','none');
					suggestWrapEl.setStyle('display','block');

					if(r.numHits>0){
						for (var i = 0; i < r.hits.length; i++) {
							console.log(r.hits[i].title);

							var thumbHTML = '<img src="'+r.hits[i].thumb+'" class="thumb">';
							if(r.hits[i].thumb=='') thumbHTML='<div class="thumb" style="width:59px;height:59px;border:1px solid #CCC;"></div>';

							new Element('li',{
								'html':thumbHTML+'<a href="'+r.hits[i].url+'" class="title">'+r.hits[i].title+"</a>"
							}).inject(suggestListEl);
							
						};
					}

				}

			}else if(r.error) alert(r.error);
			
		};


		//build autosuggest list
		var suggestWrapEl = new Element('div',{
			'id':'pisearch-suggest-wrap'
		}).inject(document.body);

		var suggestWaitEl = new Element('div',{
			'class':'ajaxLoad-big',
			'styles':{
				'height':60
			}
		}).inject(suggestWrapEl);

		var suggestListEl = new Element('ul',{
			'class':'ef-listing'
		}).inject(suggestWrapEl);


		console.log('autosuggest init OK');
	}


	var Tips1 = new Tips($$('.mootooltip'));

	ui = new efUI();

	//myEf_link
	if($('myEf_link')){
		$('myEf_link').addEvent('click',function(e){
			e.stop();
			/*
			if(Browser.Engine.trident && Browser.Engine.version<=6){
				alert(window.easyFairs.noLoginForShittyBrowserMsg);
				return;
			}
			*/

			var self = this;

			ui.showLoader();

			//check user is logged in
			new Request.JSON({
				url:'index.php',
				data:{eID:'tx_ef-whoami'},
				onComplete:function(user){
					if(user.logged_in){
						ui.loaderEl.set('text','Redirecting...');
						var href = self.getAttribute('href');
						var url = "http://"+window.location.host+'/'+href;
						if(href.contains("http")){//IE <8
							url = href;
						}
						window.location.href = url;
					}else{
						ui.hideLoader();
						open_loginBlock();
						/*
						with(ui.popup){
							title = window.easyFairs.ll.label_access_required;
							content = '<p>'+window.easyFairs.ll.label_sitecontent__myef_needs_login+'</p><div id="loginBlock"><div id="tx-intajaxloginbox-pi1"><p class="ajaxLoadMsg">Loading...</p></div></div>';
							loading = true;
						}
						ui.showPopup();
						int_load_ajaxloginbox();
						ui.hideLoader();
						window.loginBlockIsOpen = true;
						*/
					}
				}
			}).send();

		});
	}

	//home-fader
	if($('home-fader')){
		var home_fader = new efSlideShow($('home-fader'));
	}

	//preload images
	var t = new Image();
	t.src='/fileadmin/templates/efcorp/images/tick.png';
	
	
	
	//collapsable p
	if($("content")) makeCollapsable($("content"));
	
	//click&load links
	//prepare mask anyway
	new Element("div",{id:'clicknLoad-mask',styles:{opacity:0},events:{click:function(e){window.clicknLoad_file_callBack();}}}).inject(document.body);
	window.clicknLoad_file_callBack = function(){
		//alert("clicknLoad_file_callBack");
		$("clicknLoad-mask").fade(0);
		//$("clicknLoad-mask").dispose();
		if(window.clicknLoad_element){
			window.clicknLoad_element.fade(1);
			window.clicknLoad_element = null;
		}
		
	}
	clicknLoadInit(document.body);
	
	
	//custom CSS testing
	/*
	if(window.location.href.match(/style-tweak/)){
		new Element('link',{
			'rel':'stylesheet',
			'type':'text/css',
			'href':'fileadmin/templates/tweak/tweak1.css'
		}).inject(document.body);
	}
	*/

	
	if($('wrap')) {
		//search products box nice url
		var searchDocInputs = $('wrap').getElements('.tx_ef_searchdocs_form');
		if(searchDocInputs.length>0){
			for(var i=0;i<searchDocInputs.length;i++){
				searchDocInputs[i].addEvent('submit',function(e){
					new Event(e).stop();
					var langSect = (window.easyFairs && window.easyFairs.lang && window.easyFairs.lang!="") ? '/'+window.easyFairs.lang : '';
					var searchTypeSegment = 'search-product';
					window.location.href=langSect+'/'+searchTypeSegment+'/'+this.getElement('input[type=text]').value;
				});
				if (searchDocInputs[i].getElement('.isSubmit')) {
					searchDocInputs[i].getElement('.isSubmit').addEvent('click',function(event){this.getParent('form').submit();});
				}
			}
		}
	}
	
});



function open_efOverlay(){
	ui.showOverlay();
}
function adjust_efOverlay(){efOverlay.setStyle('height',window.getScrollSize().y.toInt());}

function open_loginBlock(noRedirect,callBack,thelogintype,popupTitle){
	/*
	if(Browser.Engine.trident && Browser.Engine.version<=6){
		alert(window.easyFairs.noLoginForShittyBrowserMsg+' ('+Browser.Engine.trident+Browser.Engine.version+')');
		return;
	}*/

	with(ui.popup){
		title = (popupTitle?popupTitle:$("loginBlock-toggler").getElement('span').get('text'));
		content = '<div id="loginBlock"><div id="ajaxTarget-login"><p class="ajaxLoadMsg">Loading...</p></div></div>';
		loading = true;
	}

	ui.showPopup();

	//int_load_ajaxloginbox();
	new Request.HTML({
		url:'index.php',
		method:'get',
		evalScripts: true,
		data:{
			id:(noRedirect?window.easyFairs.dest_login_noRedirect:window.easyFairs.dest_login),
			L:window.easyFairs.lid,
			isAjax:1,
			logintype:(thelogintype?thelogintype:''),
			nc:Math.random()
		},
		update:$('ajaxTarget-login'), 
		onSuccess:function(){
			ui.popup_hideLoad();
			ui.popup_ajaxize(callBack,0);
			if(callBack) callBack();
		}
	}).send();

	window.loginBlockIsOpen = true;
}

function close_loginBlock(){
	ui.hidePopup();
	window.loginBlockIsOpen = false;
}



function openEfPopup(url,theTitle,callBack,onCloseCallBack,addData,mayNotClose){
	if(!addData) addData = {};
	with(ui.popup){
		title = theTitle;
		content = '<div id="loginBlock"><div id="genericPopupAjaxTarget"></div></div>';
		loading = true;
		mayClose = (mayNotClose?false:true);
	}
	new Request.HTML({
		url:url,
		method:"get",
		data:addData,
		update:'genericPopupAjaxTarget',
		onSuccess: callBack
	}).send();
	ui.showPopup(false,onCloseCallBack);
	return false;
}

function closeEfPopup(){
	ui.hidePopup();
}

var formValidator = {};
formValidator.isEmail = function(string){
	emailRegExp = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.([a-zA-Z]){2,4})$/
	return emailRegExp.test(string);
}
formValidator.notEmpty = function(string){return /\S/.test(string);};

function makeCollapsable(container){

	if(container){
		var maxLine = 5;
		var lineHeight,numLine,elHeight;
		var pEls = $(container).getElements("p.collapsable");
		if(pEls.length>0){
			var p;
			for(var i=0,j=pEls.length;i<j;i++){
				p = pEls[i];
				if(i==0) lineHeight = p.getStyle("line-height").toInt();
				if(p.innerHTML.trim()=="") continue;
				elHeight = p.getHeight().toInt();
				numLine = elHeight/lineHeight;
				if(numLine > maxLine){
					p.store("originalHeight",elHeight);
					p.store("collapsedHeight",97);/*(maxLine*lineHeight)*/
					p.setStyles({"overflow":"hidden","height":97});
					new Element("a",{
						"href":"#",
						"text":window.easyFairs.ll.label_more_text,
						"class":"collapsable-btn",
						"events":{
							"click":function(e){
								e.stop();
								var p = this.getPrevious("p");
								var oriHeight = p.retrieve("originalHeight");
								if(p.getHeight().toInt()==oriHeight){
									p.tween("height",p.retrieve("collapsedHeight"));
									this.set("text",window.easyFairs.ll.label_more_text);
									this.removeClass("close");
								}else{
									p.tween("height",oriHeight);
									this.set("text",window.easyFairs.ll.label_less_text);
									this.addClass("close");
								}
								this.blur();
							}
						}
					}).inject(p,"after");
				}
			}
		}
	}
}

function clicknLoadInit(container){
	var clicknLoadEls = $(container).getElements(".clicknLoad");
	console.log(clicknLoadEls); 
	
	//console.log(clicknLoadEls);
	if(clicknLoadEls !== undefined && clicknLoadEls.length>0){
		
		for(var i=0,j=clicknLoadEls.length;i<j;i++){
			clicknLoadEls[i].addEvent('click',function(e){
				window.clicknLoad_element = this;
				var pos = this.getPosition();
				var size = this.getSize();
				$("clicknLoad-mask").setStyles({
					'left':pos.x.toInt(),
					'top':pos.y.toInt(),
					'width':size.x.toInt(),
					'height':size.y.toInt()
				}).fade(1);
				this.fade(.6);
				this.blur();
				
				
				
				
				if(this.hasClass("clicknLoad_file")){
					e.stop();
					var cnl = Math.random();
					
					var url = this.href+"&cnl="+cnl;
					
					
					var interv = (function(){
						new Request({
							url:'index.php',
							method:'get',
							data:{
								eID:'tx_ef_clicknLoad',
								cnl:cnl,
								rand:Math.random()
							},
							onComplete:function(r){
								if(r && r.trim()=="finished"){
									window.clicknLoad_file_callBack();
									$clear(interv);
								}
							}
						}).send();
					}).periodical(3000);
					/*
					(function(){
						window.clicknLoad_file_callBack();
						$clear(interv);
					}).delay(60000);
					*/
					
					new Element("iframe",{
						src:url,
						frameborder:0,
						id:"clicknLoad-iframe",
						styles:{width:0,height:0}
					}).inject(document.body);
					
					
					
					
					
					
					
					/*
					if(Browser.Engine.trident || Browser.Engine.webkit){
						
						
						//fucking IE. not supporting dynamic iframe onload. rot in hell
						function ieIframeReadyHandler() { 
							var iframe = $("clicknLoad-iframe");
							//$("clicknLoad-mask").set('text',iframe.readyState);
						    if( iframe.readyState=="complete" || iframe.readyState=="interactive" ) {
						           //alert("complete!");
						           clicknLoad_file_callBack();
						    } else {
						        setTimeout(ieIframeReadyHandler, 2000);
						    }
						}
						setTimeout(ieIframeReadyHandler, 2000);
						
					}
					*/
					
				}
				
			});
		}
	}
}

