// FUNCTIONS
//var buildNavi;
var buildSliders;
var initTripSearch;
var initSelectedTripList;
var showAvailableThemes;
var loadCountryTabsByCookie;

//global settings and variables BEGIN
var flash = 1; // flashCheck;
var cookieTrips = 'gebeco-reiseliste';	// cookie-name for triplist
var cookieTabs = 'gebeco-tab';	// cookie-name for tab
var rows = {}; // for all trip data
var find = {};
var cur = {};
var setRegion;	// for flash-control
var setCountry;	// for flash-control
var tripUrl = '/trips/search.json';	// default trip-JSON
var hotelUrl = '/trips/hotels.json';	// default trip-JSON
var tripUrlSG = '/trips/special_groups.json';	// JSON "Sondergruppenreisen"
var sg = false; // page contains "Sondergruppen"-Content

var useActionTracking = true;
var tripLinkPref = '';
sg = jQuery('#content.specialgroups').length;

var doAllTheNeedfulThings = function(){
	checkLogin();
	handleLogin(); 
	// page countryInfos
	$("#countryInfoTabs").doOnce(function(){loadCountryTabsByCookie(this);});

	// load page-controller (sidebar etc.)
	$.xLazyLoader({js: ['/javascripts/smsG/generalContents.js']});

	// build main-navi
	//buildNavi(); => DEPRECATED	
	$('ul#mainnavi').doOnce(function(){
		buildNaviNEW();
	});
	// more actionTracking
	addActionTracking();
	// load expressFinder
	$('#exFiStyles,#exFiCtr').doOnce(function(){jQuery.xLazyLoader({js: ['/javascripts/smsG/expressFinder.js']});});
	// page trip-styles, themes
	$(".themeContainer").doOnce(function(){showAvailableThemes(this)});
	// trip search
	//initTripSearch();
	// trips of week
	initSelectedTripList();

	buildSliders();
};	

var checkLogin = function(){
	jQuery('#headerLogin').doOnce(function(){
		jQuery.ajax({type:'GET',url:'/sessions/query.json',success:loginUser,dataType:'json'});	
	});
};

var loginUser = function(data){	
	if (data.logged_in && data.type === 'agency_light')	{
		jQuery('#headerLogin .loggedInfo').removeClass('dn').find('span').html(data.user.lastname);
		jQuery('#headerLogin .loggedMenu, #headerLogin .logoutBt').removeClass('dn');
		jQuery('#headerLogin .loginBt').addClass('dn');
		var info = jQuery('#headerServiceMenu');
		info.find('.agency').html(data.user.lastname);
		info.find('.agencyNo').html(data.user.customer_number);
		info.find('.street').html(data.user.street);
		info.find('.city').html(data.user.zip + ' ' + data.user.city);		
	} else {
		jQuery('#headerLogin .loggedInfo').addClass('dn').find('span').html('');
		jQuery('#headerLogin .loggedMenu, #headerLogin .logoutBt').addClass('dn');
		jQuery('#headerLogin .loginBt').removeClass('dn');
		var info = jQuery('#headerServiceMenu');
		info.find('.agency').html('');
		info.find('.agencyNo').html('');
		info.find('.street').html('');
		info.find('.city').html('');
	}
};

var handleLogin = function(){
	jQuery('#headerLogin .loginBt a.bt').live('click',function(){
		jQuery(this).toggleClass('open');
		jQuery('#headerLoginForm').toggleClass('dn');
		return false;		
	});
	jQuery('#headerLoginForm form, #loginForm').submit(function(){
		jQuery.ajax({type:'POST',data:jQuery(this).serialize(),url:'/sessions/create.json',success: function(data){
			loginUser(data);
			window.location = location.href.substr(0,location.href.indexOf('#'));
		},dataType:'json'});
		return false;
	});
	jQuery('#headerLogin .logoutBt a.bt').live('click',function(){
		jQuery.ajax({type:'DELETE',url:'/sessions/destroy.json',success: function(data){
			loginUser(data);
			window.location = location.href.substr(0,location.href.indexOf('#'));
		},dataType:'json'});
		return false;
	});
	jQuery('#headerLogin .loggedMenu a.bt').live('click',function(){
		jQuery(this).toggleClass('open');
		jQuery('#headerServiceMenu').toggleClass('dn');
		return false;		
	});
};
buildNaviNEW = function(){
	// set bordered LI to same height
	$('#mainnavi .sub .dottedLeft').parent().each(function(){
		var h = 0;
		$(this).find('>div').each(function(){
			var curH = $(this).height();
			if (h < curH) {h = curH};
		}).height(h);
	});
	// change content depending on trip-amount 
	_.each($('#mainnavi .info:not(#c_ALL) p'), function(el){
		if ($(el).text().match(/^1 Reisen$/)){
			$(el).html("1 Reise");
			return false;
		}
		if ($(el).text().match(/^0 Reisen$/)){
			$(el).html("Keine Reise verf&uuml;gbar.");
			return false;
		}
	});
	// append image of country-info if hovered
	var $countryLinks = $('#mainnavi .countries a').one('mouseover',function(e){
		var $info = $(this).next('.info');
		$('<img/>')
			.attr('src', CONFIG.countryImagePath + $info.attr('id').replace('c_','') + '/navi.jpg')
			.load(function(e){
				$info.find('h3').after(this);
			});
	});
	// set line-heights depending on link-size
	var lineHeight = parseFloat($countryLinks.eq(0).css('line-height'));	 
	_.each($countryLinks,function(a){
		var $a = jQuery(a);
		var height = $a.height();
		if (height == 2*lineHeight) {$a.addClass('two');}
		if (height == 3*lineHeight) {$a.addClass('three');}
	});
	// recalculate height of submenu, depeneding of maximum height of visible elements
	$('#mainnavi .sub li').mouseover(function(e){
		var $li = $(this);
		var $sub = $li.closest('.sub');
		$countries = $li.find('.countries');
		if ($countries.length){
			infoH = $li.find('.h .info').height();
		} else {
			$countries = $li.closest('.countries');
			$info = $li.find('.info');
			infoH = parseInt($info.height());
			if (!$info.find('img').length){
				infoH += 93+2+6+10;
			}
		}
		$sub.css('min-height',_.max([$countries.height(),infoH]));
		return false;
	});
	
	// at extranet: set height of floating UL
	/*$('#mainnavi.extranet .sub').doOnce(function(){
		var h = 0;
		this.find('ul.linkList').each(function(){
			var tmph = $(this).height();
			if (tmph > h) {h = tmph}
		}).height(h);
	});*/
};

//build MainNavi
/*
buildNavi = function(){
	jQuery('.countryList a').each(function(){
		var a = jQuery(this);
		if (a.height() <= 20) {a.addClass('one');}
		else if (a.height() <= 40) {a.addClass('two');} 
		else {a.addClass('three');} 
	});
	
	// handling mainnavi regions+countries
	
	// calculate correct heights of navi-elements
	// regions/countries
	jQuery('.regionList li:last').css('margin-bottom','0');
	jQuery('.countryList li').css('min-height',jQuery('.regionList').height()-4); 
	jQuery('.countryList a').each(function(){
		var a = jQuery(this);
		if (a.height() <= 20) {a.addClass('one');}
		else if (a.height() <= 40) {a.addClass('two');} 
		else {a.addClass('three');} 
	});
	jQuery('.countryList li').hide();
	
	// styles/tags
	jQuery('.teaserList li:last').css('padding-bottom','0');
	
	// helper: set correct label for trip-amount
	var setTripLabel = function(info){
		var amount = info.find('span.amount');
		if (amount){
			var a = parseInt(amount.text());
			switch (a){
				case 0: out = "Keine Reise verfügbar";break;
				case 1: out = "1 Reise";break;
				default: out = a + " Reisen";break;
			}
			amount.removeClass('amount').html(out);
		}		
	};
	
	// hover region
	jQuery('#sMRegion .regionList li').hover(
		function(){
			jQuery('.regionList li.curReg').removeClass('curReg');
			var id = jQuery(this).addClass('curReg').attr('id').replace('r_','');
			jQuery('.countryList li').hide();
			jQuery('.infos .iF').hide();
			
			jQuery('.countryList li#cL_' + id).show();
			var info = jQuery('.infos #i_' + id).show();
			setTripLabel(info);			
		}
	);
	
	// hover country
	jQuery('#sMRegion .countryList a').hover(
		function(){
			var id = jQuery(this).attr('id').replace('c_','');
			jQuery('.infos .iF').hide();
			var info = jQuery('.infos #i_' + id);
			var holder = info.find('.imgHolder');
			setTripLabel(info);
			if (holder.length) {
				var img = jQuery('<img/>').attr('src', holder.attr('rel'));
				img.load(function(e){
					holder.append(this).removeClass('imgHolder');
				});
				info.fadeIn('slow');
			} else {
				info.fadeIn('slow');
			}
		},
		function(e){
			jQuery('.infos .iF').hide();
			if (jQuery('#regionListHover').hasClass('hover')){
				var reg = jQuery('.countryList li:visible').attr('id').replace('cL_','');
				jQuery('.infos #i_' + reg).show();
				
			} else {
				jQuery('.infos #i_default').show();
			}
		}
	);
	
	// hover whole region/country-field
	jQuery('#regionListHover').hover(
		function(){
			jQuery(this).addClass('hover');
		},
		function(){
			jQuery('.regionList li.curReg').removeClass('curReg');
			jQuery('.countryList li').hide();
			jQuery('.infos .iF').hide();
			jQuery('.infos #i_default').show();
			jQuery(this).removeClass('hover');
		}
	);
	
	jQuery('#mainNavi li:not(.png)').mouseenter(function(){
		jQuery('#mainNavi li.cur').removeClass('cur');
		jQuery(this).addClass('cur');
	});
	jQuery('#mainNavi li:not(.png)').mouseleave(function(){
		jQuery(this).removeClass('cur');
	});

	jQuery(".sMCt").hover(
		function(){
			jQuery(this).css({left:'0'});
			jQuery(this).parent().addClass('curH');
		},
		function(e){
			var r = e.currentTarget.getBoundingClientRect();
			if (e.clientX > r.left && e.clientX < r.right && e.clientY > r.top && e.clientY < r.bottom) return;
			jQuery(this).css({left:''});
			jQuery(this).parent().removeClass('curH');
		}
	);
	
	// IE lt 6 only
	if (jQuery.browser.msie && parseInt(jQuery.browser.version.substr(0, 1)) <= 6) {
		// close IE6-Warning
		jQuery('.dontUseThisBrowser .icRem').click(function(){
			jQuery('.dontUseThisBrowser').remove();
		});
		jQuery('#navCtrTabRow li.png').mouseenter(function(){
			jQuery('.liImg').css({backgroundPosition:''});
			jQuery('.liImg a').css({color:''});
			jQuery(this).find('.liImg').css({backgroundPosition: '0 -60px'});
			jQuery(this).find('.liImg a').css({color:'#FFFFFF'});
			var id = jQuery(this).attr('id').replace('navTab','');
			jQuery('#ie6Helper .naviCtrTabCt').hide();
			jQuery('#ie6Helper #' + id).show();
		});
		jQuery('#navCtrTabRow li.png').mouseleave(function(){
			jQuery(this).find('.liImg').css({backgroundPosition:''});
			jQuery(this).find('.liImg a').css({color:''});
		});
		jQuery('#navCtrTabs').mouseleave(function(){
			jQuery('#ie6Helper .naviCtrTabCt').hide();
		});
		jQuery('#ie6Helper .naviCtrTabCt').mouseenter(function(){
			var tab = jQuery('#navTab' + jQuery(this).attr('id') + ' .liImg');
			tab.css({backgroundPosition: '0 -60px'});
			tab.find('a').css({color:'#FFFFFF'});
		});
	}
	
};
*/

loadCountryTabsByCookie = function($tabs){
	var tabCookie = jQuery.cookie(cookieTabs);
	var tab = 0;
	// try to get tab to select from cookie
	if (!_.isNull(tabCookie) && tabCookie.length) {
		var code = $tabs.eq(0).attr('rel');		
		var pages = tabCookie.split('@@');
		for (var i=0; i<pages.length; i+=1){
			var tmp = pages[i].split('::');
			if (tmp[0] == 'C' + code.toUpperCase()) {
				tab = tmp[1];
				break;
			} 
		}
	}
	// init tabs
	jQuery("#countryInfoTabs").tabs({
		selected:tab,
		cookie:null,
		select: function(event,ui) {
			updateTabCookie(ui.index,$(this).attr('rel').toUpperCase(),'C');}	
	});
};

showAvailableThemes = function(that){
	for (var i=0;i<DATA.meta.styles.length;i+=1){
		jQuery(that).find('.teaserTheme.' + DATA.meta.styles[i].c).removeClass('dn');
	}
};

buildSliders = function(){
	// Slider Styles	
	jQuery('#sliStyles').doOnce(function(){
		this.find('.sliderItem:last').addClass('lastItem');
		this.slidebar({stepWidth:300});
		// Tooltips Style-Slider
		this.find('.sliderItem').mouseenter(function(){
			jQuery('.slyHover').remove();
			var info = jQuery(this).find('a span').text();
			var pos = jQuery(this).position();
			var left = jQuery('#sliStyles .sliderItems').css('left');
			var v = ((typeof(left)===undefined || left==='auto') ? 0 : parseInt(left.replace('px','')));			
			jQuery('#sliStyles')
				.append(
					jQuery('<span/>')
						.addClass('slyHover')
						.css('left',(pos.left+30+v)+'px')
						.html(info)
						.show()
				);			
		});
		this.find('.sliderItem').mouseleave(function(){jQuery('.slyHover').remove();});		
	});
	
	jQuery('#sliPushHome').doOnce(function(){
		this.galleryView({
		    panel_width: 217,
		    panel_height: 92,
		    frame_width: 0,
		    frame_height: 0,
			transition_interval: 3500,
		    border: 'none',
		    pause_on_hover: true
		});
	});	
	jQuery('.galleryview .nav-overlay').remove();
	jQuery('.galleryview .nav-prev').attr({src: '/images/sms/e/icPREV_23x23.png'});
	jQuery('.galleryview .nav-next').attr({src: '/images/sms/e/icNEXT_23x23.png'});
	
};
/*
initTripSearch = function(){
	// load all trip-data and libs to search and render
	HELPER.loadTripsAndHotels(function(){
		rows.travels = DATA.trips;
		rows.hotels = DATA.hotels;
		jQuery.xLazyLoader({
			js: [
				'/javascripts/smsG/renderLists.js',
				'/javascripts/smsG/tripSearch.js'
			],
			success: function(){
				prepareAdvancedSearch();
				initSearch();
				updateJSON(find);
			}
		});
	});
};
*/
initSelectedTripList = function(){
	jQuery('#selectedTrips').doOnce(function(){
		var type = jQuery(this).attr('rel');
		jQuery.ajax({
			url:tripUrl,
			type:'GET',
			dataType:'text',			
			success: function(data){
				rows.travels = data;
				cur.travels = [];
				var search_callback = function(data){
					var i;var l=data.length;
					switch (type) {
						case 'ReisenDerWoche':
							for(i=0;i<l;i+=1){if (data[i].push === true) {cur.travels.push(data[i]);}}
							break;
						case 'EigeneReiseliste':
							var nr = ownTrips.replace(' ','').split(',');
							for(i=0;i<l;i+=1){
								if (jQuery.inArray(data[i].nr, nr) >= 0) {cur.travels.push(data[i]);}}
							break;
						case 'PartnerReisen':
							for (i = 0; i < l; i += 1) {
								cur.travels.push(data[i]);
							}
								//if (jQuery.inArray(data[i].nr, nr) >= 0) {cur.travels.push(data[i]);}}
							break;
						// Stile/Tags
						default:
							if (availableStyles && jQuery.inArray(type,availableStyles) >= 0){
								for(i=0;i<l;i+=1){if (jQuery.inArray(type, data[i].es) >= 0) {cur.travels.push(data[i]);}}	
							}
							break;
					}
					
				};
				eval(data);
				jQuery.xLazyLoader({
					js: ['/javascripts/smsG/renderLists.js'],
					success: function(){
						renderJSON(1);
					}
				});
			}
		});
	});
};

var addActionTracking = function(){
	if (useActionTracking){		
		// Teaserboxen Home
		jQuery('#teaserHome').doOnce(function(){
			jQuery('.teasTb a, .hpTbCt a').live('click',function(){
				// Slider Home
				if (jQuery(this).parents('.slideshow').length){
					_gaq.push(['_trackEvent', 'teaser', 'home_slider', jQuery(this).attr('href')]);
					return true;	
				}
				_gaq.push(['_trackEvent', 'teaser', 'home_teaser', jQuery(this).attr('href')]);
			});
		});
		// MainNavi
		jQuery('#mainNavi').doOnce(function(){
			// Hauptlinks
			this.find('#mNReg .mNLi, #mainNavi #mNStyle .mNLi, #mainNavi #mNService .mNLi').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_mainLinks', jQuery(this).find('span').text()]);			
			});
			// Regionen
			this.find('#navCtrTabs .regionList a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_region', jQuery(this).text()]);			
			});
			// Länder
			this.find('#navCtrTabs .countryList a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_country', jQuery(this).text()]);
			});
			// Stile (Icons)
			this.find('#sMType a.icon').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_tag', jQuery(this).attr('title')]);
			});
			// Stile (Text-Links)
			this.find('#sMType .linkList a, #mainNavi #sMType .iconList a.text').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_tag', jQuery(this).text()]);
			});
			// Stile (Teaser - Image)
			this.find('#sMType .teaserList .img a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_tag', jQuery(this).find('img').attr('title')]);
			});
			// Stile (Teaser - Text)
			this.find('#sMType .teaserList .text a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_tag', jQuery(this).find('h3').text()]);
			});
			// Service (Text-Links)
			this.find('#sMService .linkList a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_service', jQuery(this).text()]);
			});
			// Service (Teaser - Image)
			this.find('#sMService .teaserList .img a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_service', jQuery(this).find('img').attr('title')]);
			});
			// Service (Teaser - Text)
			this.find('#sMService .teaserList .text a').live('click',function(){
				_gaq.push(['_trackEvent', 'menu', 'mainnavi_service', jQuery(this).find('h3').text()]);
			});
		});
		// Slider Sidebar
		jQuery('#bbPUSH').doOnce(function(){
			this.find('.frame a').live('click',function(){
				_gaq.push(['_trackEvent', 'sidebar', 'pushSlider', jQuery(this).attr('href')]);
			});
		});
	}
};

