/**
 * NEXT_FOKUS
 *
 * Wording:
 * Focus-Area: dargestellt durch pi1, oben - 1 grosses post
 * Posts-Area: dargestellt durch pi2, unten wo die posts dargestellt werden.
 * Position(s): ein einzelner Slot im Posts Bereich.
 * Post: Der Inhalt vom FCE das im Focus/Posts-Bereich dargestellt wird.
 */

var next_fokus = (function($){
	// -----------------------------------------------------
	// private variables
	// -----------------------------------------------------
	
	// strategy 2: focus post and reorder other posts
	currentFocus = 1;
	list = {1:2,2:3,3:4};
	obscureRunning = false;
	
	// configuration
	configuration = {pid: 0, extkey: 'next_fokus', itemsPerRow: 3, rows: 1, startWithPostInFocus: 1, pagingRows: 1, tags: [], suchMaske: false};
	
	not_obscure_posts = {};
	requests = {};
	kompetenzen_branche_prev_element = 0;
	kompetenzen_branche_prev_tagId = 0;
	
	/**
	 * Strategy 1: switch focus and post
	 * Remember which post is in focus area.
	 * Remember which post is in whic position.
	 */
	mapping = {
		//length = 3,
		fokusPost : 1,
		previousFokusPost : 0,
		positions : {},
		init : function() {
			previousFokusPost = 0;
			if(1!==configuration.startWithPostInFocus) {
				currentFocus = 0;
				fokusPost = 0;
			} else {
				currentFocus = 1;
				fokusPost = 1;
			}
			this.resetPositions();
		},
		resetPositions : function() {
			for(var i = 1; i<=(paging.itemsPerPage()); i=i+1) {
				this.positions[i] = paging.firstPostNrOfCurrentPage() + i;
			}
		},
		setFokusPost : function(newNr) {
			this.previousFokusPost = this.fokusPost;
			this.fokusPost = newNr;
			return this.previousFokusPost;
		},
		switchFocusTo : function(positionId) {
			var postIdOfNewFocusPost = mapping.positions[positionId];
			mapping.setFokusPost(postIdOfNewFocusPost);
			mapping.positions[positionId] = mapping.previousFokusPost;
			
			return postIdOfNewFocusPost;
		}
	};
	
	/**
	 * Helper functions for paging.
	 */
	paging = {
		currentPage : 0,
		/**
		 * Calculate number of possible positions depending on col and row count.
		 */
		itemsPerPage : function() {
			return configuration.itemsPerRow * configuration.rows;
		},
		/**
		 * Depending on active page, the nr of the post that sould be displayed.
		 */
		firstPostNrOfCurrentPage : function() {
			return this.currentPage * this.itemsPerPage() + configuration.startWithPostInFocus;
		}
	};
	
	// -----------------------------------------------------
	// private functions
	// -----------------------------------------------------
	
	/**
	 * Update Text&Image in Focus Box.
	 * Keep this simple.
	 */
	updateFocus = function(element) {
		$('#contentsection').fadeOut('slow', function() {
			// Fade out is complete
			
			if(configuration.suchMaske){
				next_fokus.hideSuche(element.style);
			}
			
			//if(configuration.modus == 'Kompetenzfinder'){
			if(true){
				$('#fokusbox').removeClass('news referenzen mitarbeiter');
				$('#fokusbox').addClass(element.style);
				if(element.style == 'referenzen'){
					$('#fokusboxtitel').click(function(event) {
						next_fokus.showDetail();
					});
					$('#fokusboxbild').click(function(event) {
						next_fokus.showDetail();
					});
					$('#fokusboxtext').click(function(event) {
						next_fokus.showDetail();
					});
					$('#showdetaillink').click(function(event) {
						next_fokus.showDetail();
					});
					$('#fokusboxtitel').css("cursor", "pointer");
					$('#fokusboxbild').css("cursor", "pointer");
					$('#fokusboxtext').css("cursor", "pointer");
					$('#addthis_toolbox').show();
				} else {
					$('#fokusboxtitel').unbind('click');
					$('#fokusboxbild').unbind('click');
					$('#fokusboxtext').unbind('click');
					$('#fokusboxtitel').css("cursor", "default");
					$('#fokusboxbild').css("cursor", "default");
					$('#fokusboxtext').css("cursor", "default");
					$('#addthis_toolbox').hide();
				}
			}
			
			// Set new title/image/text
			
			$('#fokusboxtitle').empty().html(element.focus_title);
			if(element.focus_image_url == "uploads/tx_templavoila/" || element.focus_image_url == ""){
				$('#fokusboximg').hide();
			} else {
				$('#fokusboximg').get(0).src=element.focus_image_url;
				$('#fokusboximg').show();
			}
			$('#fokusboxtext').empty().html(element.focus_text);
			$('#detailboxcontent').empty().html(element.detail_html);
			
			// Redo special fonts
			refreshCufon();
			
			// Fade in
			$('#contentsection').scrollTo(0,0);
			$('#contentsection').fadeIn('slow');
		});
	};
	
	/**
	 * Update Text&Image in specified Post.
	 * Keep this simple.
	 */
	updatePost = function(positionId, element, size) {
		if(typeof(element)=='undefined') {
			// element is "null" - hide this post
			$('#next_fokus_position_'+positionId).hide();
			return false;
		} else {
			$('#next_fokus_position_'+positionId).show();
		}
		var image_url = element.post_small_image_url;
		if(configuration.modus == 'Kompetenzfinder'){
			image_url = "phpthumb/phpThumb.php?src=/" + element.post_small_image_url + "&w=67&h=67&zc=1";
		}
		var size_string = 'small';
		/*
		if(size!='small') {
			image_url = element.post_big_image_url;
			size_string = 'big';
		}
		*/
		if($('#next_fokus_position_'+positionId).attr('class') == 'post_img'){
			$('#next_fokus_position_'+positionId+' img').get(0).src=image_url;
		} else {
			if($('#next_fokus_position_'+positionId).attr('class') == 'post_big'){
				image_url = element.post_big_image_url;
				size_string = 'big';
			}
			$('#next_fokus_position_'+positionId+' .post_'+size_string+'-titel').empty().html(element.post_title);
			$('#next_fokus_position_'+positionId+' .post_'+size_string+'-bild img').get(0).src=image_url;
			$('#next_fokus_position_'+positionId+' .post_'+size_string+'-text').empty().html(element.post_text);
		}
		if(obscureRunning){
			if(in_array(element.uid, not_obscure_posts)){
				$('#next_fokus_position_' + positionId).fadeTo('slow', 1);
			} else {
				$('#next_fokus_position_' + positionId).fadeTo('slow', 0.3);
			}
		}
	};
	
	/**
	 * Update focus - knows about mappings and paging
	 * mappings are used for remembering which post is in which position/focus.
	 */
	updateFocusFromPosition = function(positionId) {
		mapping.switchFocusTo(positionId);
		updateFocus(next_fokus_posts['p'+mapping.fokusPost]);
		//console.log("Old Focus: " + mapping.previousFokusPost + ", New Focus: " + mapping.fokusPost + ", Event from PostID " + positionId);
	};
	
	// -----------------------------------------------------
	// private functions - published in API
	// -----------------------------------------------------
	/**
	 * Move content of post to focus-area.
	 * Use this for "Kompetenzfinder".
	 * Doesn't Supports paging
	 */
	updateFocusKompetenzfinder = function(options) {
		$("#contentstart").stop(true, true);
		$("#contentstart").effect("highlight", {color: '#95e6ff'}, 1000);
		
		updateFocus(next_fokus_posts['p'+options.positionId]);
		// '/artikel/'.$element['uid'].'/referenz/'.str_replace(" ", "-", strtolower(preg_replace("/[^a-zA-Z0-9 -]/", "", $element['share_title']))).'/';
		var urltitle = next_fokus_posts['p'+options.positionId].share_title;
		urltitle = urltitle.toLowerCase().replace(/ü/g, "ue").replace(/ä/g, "ae").replace(/ü/g, "oe").replace(/[^a-zA-Z0-9 -]/i, "").replace(/ /g, "-");
		
		addthis_share.url = configuration.directUrl + 'artikel/' + next_fokus_posts['p'+options.positionId].uid + '/referenz/' + urltitle + '/';
		addthis_share.title = next_fokus_posts['p'+options.positionId].share_title;
		addthis_share.description = next_fokus_posts['p'+options.positionId].share_descr;
		if(typeof(addthis) != "undefined"){
			addthis.toolbox('#addthis_toolbox', addthis_share);
		}
		
		$('#next_fokus_position_'+options.positionId).stop(true, true);
		$('#next_fokus_position_'+options.positionId).effect('95e6ff', {color: '#95e6ff'}, 1000);
		refreshCufon();
		
		highlightPost(options.positionId);
	};
	
	// -----------------------------------------------------
	// private functions - published in API
	// -----------------------------------------------------
	/**
	 * Move content of post to focus-area and move focus-area content to post-area.
	 * Use this for "Mitarbeiter".
	 * Supports paging
	 */
	switchThisPostAndFocus = function(options) {
		$("#contentstart").stop(true, true);
		$("#contentstart").effect("highlight", {color: '#95e6ff'}, 1000);
		
		updateFocusFromPosition(options.positionId);
		updatePost(options.positionId, next_fokus_posts['p'+mapping.previousFokusPost], options.positionSize);
		
		$('#next_fokus_position_'+options.positionId).stop(true, true);
		$('#next_fokus_position_'+options.positionId).effect('95e6ff', {color: '#95e6ff'}, 1000);
		refreshCufon();
	};
	/**
	 * Move content of post to focus-area. Update postcontent depending on post order.
	 * Max posts incl. focus: 4
	 * No paging support!
	 */
	focusThisPostAndUpdateOrder = function(options) {
		$("#contentstart").stop(true, true);
		$("#contentstart").effect("highlight", {color: '#95e6ff'}, 1000);
		
		var positionEl = (parseInt(options.positionId) - parseInt(configuration.startWithPostInFocus) + paging.firstPostNrOfCurrentPage());
		if(currentFocus != 0 && positionEl >= currentFocus){
			positionEl++;
		}
		updateFocus(next_fokus_posts['p'+positionEl]);
		//currentFocus = options.positionId;
		
		// '/artikel/'.$element['uid'].'/referenz/'.str_replace(" ", "-", strtolower(preg_replace("/[^a-zA-Z0-9 -]/", "", $element['share_title']))).'/';
		var urltitle = next_fokus_posts['p'+positionEl].share_title;
		urltitle = urltitle.toLowerCase().replace(/ü/g, "ue").replace(/ä/g, "ae").replace(/ü/g, "oe").replace(/[^a-zA-Z0-9 -]/i, "").replace(/ /g, "-");
		
		addthis_share.url = configuration.directUrl + 'artikel/' + next_fokus_posts['p'+positionEl].uid + '/referenz/' + urltitle + '/';
		// addthis_share.url = configuration.directUrl + next_fokus_posts['p'+positionEl].uid;
		addthis_share.title = next_fokus_posts['p'+positionEl].share_title;
		addthis_share.description = next_fokus_posts['p'+positionEl].share_descr;
		if(typeof(addthis) != "undefined"){
			addthis.toolbox('#addthis_toolbox', addthis_share);
		}
		
		currentFocus = positionEl;
		
		$('#next_fokus_position_'+options.positionId).stop(true, true);
		$('#next_fokus_position_'+options.positionId).effect('highlight', {color: '#95e6ff'}, 1000);
		
		var postsEl = paging.firstPostNrOfCurrentPage() - parseInt(configuration.startWithPostInFocus);
		for(var i = 1; i <= paging.itemsPerPage(); i++){
			postsEl++;
			if(postsEl == currentFocus){
				postsEl++;
			}
			//console.log(postsEl + ' (' + currentFocus + ')');
			updatePost(i, next_fokus_posts['p'+postsEl], options.positionSize);
			refreshCufon();
		}
	};
	
	showFocusExtId = function(fid){
		fid = parseInt(fid, 10);
		var isValid = false;
		var page = 0;
		var box = 1;
		jQuery.each(next_fokus_posts, function(index, value){
			if(value.uid == fid){
				box = parseInt(index.substr(1)) - parseInt(configuration.startWithPostInFocus);
				isValid = true;
			}
		});
		if(isValid && box != 0){
			if(configuration.focusdirect == "komp"){
				updateFocusKompetenzfinder({positionId: box, positionSize: "small"});
			} else if(configuration.focusdirect == "keep"){
				pagingTo(page);
				focusThisPostAndUpdateOrder({positionId: box, positionSize: "small"});
			} else {
				pagingTo(page);
				switchThisPostAndFocus({positionId: box, positionSize: "small"});
			}
		}
	}
	
	
	/**
	 * Reapply special fonts.
	 */
	refreshCufon = function() {
	
		Hyphenator.run();
		
		Cufon.replace('.post_small .post_small-titel h2', { fontFamily: 'FrutigerNext-Black' });
		Cufon.replace('.post_big .post_big-titel h2', { fontFamily: 'FrutigerNext-Black' });
		
		Cufon.refresh('.fokusbox .fokusbox-titel');
		Cufon.refresh('.fokusbox .fokusbox-text h2');
		
		/* Mitarbeiter, Default */
		Cufon.refresh('#mitarbeiter .fokusbox .fokusbox-text h2', { fontFamily: 'FrutigerNext-Black' });
		Cufon.replace('#kompetenzfinder .fokusbox.mitarbeiter .fokusbox-text h2', { fontFamily: 'Frutiger-Bold' });
		
		/* Referenzen */
		Cufon.refresh('#referenzen .fokusbox .fokusbox-text h2', { fontFamily: 'Frutiger-Bold' });
		Cufon.replace('#kompetenzfinder .fokusbox.referenzen .fokusbox-text h2', { fontFamily: 'Frutiger-Bold' });
		Cufon.replace('#detailbox h1', { fontFamily: 'FrutigerNext-Black' });
		Cufon.replace('#detailbox h2', { fontFamily: 'FrutigerNext-Black' });
		Cufon.replace('#showdetaillink', { fontFamily: 'FrutigerNext-Black', hover: true });
	};
	/**
	 * Update Paging Class after Selection
	 */
	updatePagingSelected = function(pageNr) {
		for(var i = 0; i < configuration.pagingRows; i++){
			if(pageNr == i){
				$("#pagingRow" + i).addClass("selected")
			} else {
				$("#pagingRow" + i).removeClass("selected")
			}
		}
	};
	/**
	 * Hide Paging after Selection
	 */
	updatePaging = function(rows) {
		if(rows < configuration.pagingRows){
			for(var i = rows; i < configuration.pagingRows; i++){
				$("#pagingRow" + i).hide();
			}
		} else {
			for(var i = configuration.pagingRows; i < rows; i++){
				$("#pagingRow" + i).show();
			}
		}
	};
	/**
	 * Switch to another "page".
	 */
	pagingTo = function(pageNr) {
		//console.log("pagingTo: " + pageNr);
		paging.currentPage = pageNr;
		mapping.resetPositions();
		
		//console.log("itemsPerPage: " + paging.itemsPerPage());
		for(var i=1; i<=paging.itemsPerPage(); i=i+1) {
			var nextEl = paging.firstPostNrOfCurrentPage() + i - parseInt(configuration.startWithPostInFocus);
			if(currentFocus != 0 && nextEl >= currentFocus){
				nextEl++;
			}
			updatePost(i, next_fokus_posts['p'+(nextEl)], 'small');
		}
		
		updatePagingSelected(pageNr);
		
		refreshCufon();
	};
	/**
	 * Get/set configuration options
	 */
	conf = function(options) {
		$.extend(configuration,options);
		//console.log("New Config");
		//console.log(configuration);
		mapping.init();
		return configuration;
	};
	
	filter = function(pid, extkey){
		var tstamp = new Date().getTime();
		if(requests.filter != undefined){
			requests.filter.abort();
		}
		requests.filter = $.post('index.php?id=' + pid + '&eID=' + extkey + '&t=' + tstamp, configuration, function(data) {
			next_fokus_posts = data.posts;
			updatePaging(data.pagingRows);
			configuration.pagingRows = data.pagingRows;
			pagingTo(0);
		}, 'json');
	};
	
	obscure = function(pid, extkey){
		var tstamp = new Date().getTime();
		if(requests.obscure != undefined){
			requests.obscure.abort();
		}
		requests.obscure = $.post('index.php?id=' + pid + '&eID=' + extkey + '&t=' + tstamp, configuration, function(data) {
			not_obscure_posts = data.posts;
			obscurePosts();
		}, 'json');
		obscureRunning = true;
	};
	
	obscurePosts = function(){
		for(var i=1; i<=paging.itemsPerPage(); i=i+1) {
			var nextEl = paging.firstPostNrOfCurrentPage() + i - parseInt(configuration.startWithPostInFocus);
			if(currentFocus != 0 && nextEl >= currentFocus){
				nextEl++;
			}
			
			if(typeof(next_fokus_posts['p'+(nextEl)])!='undefined'){
				if(in_array(next_fokus_posts['p'+(nextEl)].uid, not_obscure_posts)){
					$('#next_fokus_position_' + i).fadeTo('slow', 1);
				} else {
					$('#next_fokus_position_' + i).fadeTo('slow', 0.3);
				}
			}
		}
	};
	
	highlightPost = function(positionId){
		for(var i=1; i<=paging.itemsPerPage(); i=i+1) {
			var nextEl = paging.firstPostNrOfCurrentPage() + i - parseInt(configuration.startWithPostInFocus);
			if(currentFocus != 0 && nextEl >= currentFocus){
				nextEl++;
			}
			
			if(typeof(next_fokus_posts['p'+(nextEl)])!='undefined'){
				if(nextEl == positionId){
					$('#next_fokus_position_' + i).addClass('postselected');
				} else {
					$('#next_fokus_position_' + i).removeClass('postselected');
				}
			}
		}
	};
	
	
	in_array = function(item,arr) {
		for(p=0;p<arr.length;p++) {
			if (item == arr[p]) {
				return true;
			}
		}
		return false;
	};
	
	toggleTag = function(el, tagId){
		if($(el).parent().parent().parent().hasClass('kompetenzen_spalte1')) {
			// Element ist aus der Kategorie "Branchen" des Kompetenzfinders
			
			if(kompetenzen_branche_prev_element!=0) {
				// highlighting von vorheriger auswahl entfernen
				$(kompetenzen_branche_prev_element).removeClass("selected");
				
				// alte tag id von liste entfernen
				configuration.tags = jQuery.grep(configuration.tags, function(value) {
					return value != kompetenzen_branche_prev_tagId;
				});
			}
			
			// Ist "der alte Tag" = "der neue Tag" - dann wird der 
			// Tag abgewählt und nicht mehr zur Liste hinzugefügt
			if(tagId != kompetenzen_branche_prev_tagId) {
				// element und tagId speichern
				kompetenzen_branche_prev_element = el;
				kompetenzen_branche_prev_tagId = tagId;
				
				// auswahl highlighten
				$(el).addClass("selected");
				
				// neue tag id zu liste hinzufügen
				configuration.tags.push(tagId);
			} else {
				// element und tagId speichern
				kompetenzen_branche_prev_element = '';
				kompetenzen_branche_prev_tagId = '';
			}
			
		} else if($.inArray(tagId, configuration.tags) >= 0){
			configuration.tags = jQuery.grep(configuration.tags, function(value) {
					        return value != tagId;
					      });
			$(el).removeClass("selected");
		} else {
			configuration.tags.push(tagId);
			$(el).addClass("selected");
		}
		//console.log(configuration.tags);
		// search...
		if(configuration.modus === "Kompetenzfinder"){
			this.obscure(configuration.pid, configuration.extkey);
		} else {
			this.filter(configuration.pid, configuration.extkey);
		}
	};
	
	showSuche = function(){
		$('#searchbutton').hide();
		currentFocus = 0;
		if(configuration.dontswitch != true){
			pagingTo(paging.currentPage);
		}
		$('#fokusbox').fadeOut('slow');
		$('#filterbox').fadeIn('slow', function(){
			$('#addthis_toolbox').hide();
		});
	};
	
	hideSuche = function(style){
		$('#filterbox').hide();
		$('#fokusbox').fadeIn('slow', function(){
			if(style == 'referenzen'){
				$('#addthis_toolbox').show();
			}
			$('#searchbutton').empty().html('<a href="#" onclick="next_fokus.showSuche(); return false;">zurück zur Auswahl.</a>').show();
			Cufon.refresh('#searchbutton');
		});
	};
	
	showDetail = function(){
		$('#detailbox').fadeIn('slow');
		$(".rzcolorbox").colorbox({current:"Image {current} of {total}",opacity:"0.85",transition:"elastic",speed:350,slideshowSpeed:2500,previous:"previous",next:"next",close:"close"});
		refreshCufon();
	},
	
	hideDetail = function(){
		$('#detailbox').fadeOut('slow');
	};
	
	printref = function(){
		var tstamp = new Date().getTime();
		var url = 'index.php?id=' + configuration.pid + '&eID=' + configuration.extkey + '&t=' + tstamp + '&c=' + next_fokus_posts['p'+currentFocus].uid;
		var title = next_fokus_posts['p'+currentFocus].share_title;
		var printwindow = window.open(url, 'referenz_print','height=400,width=700');
		if (window.focus) {
			printwindow.focus()
		}
		return false;
	};
	
	pdf = function(){
		console.log("pdfing...");
	};
	
	afterLoading = function(){
		var element = next_fokus_posts['p'+currentFocus];
		if(element != null){
			$('#fokusbox').removeClass('news referenzen mitarbeiter');
			$('#fokusbox').addClass(element.style);
			if(element.style == 'referenzen'){
				$('#fokusboxtitel').click(function(event) {
					next_fokus.showDetail();
				});
				$('#fokusboxbild').click(function(event) {
					next_fokus.showDetail();
				});
				$('#fokusboxtext').click(function(event) {
					next_fokus.showDetail();
				});
				$('#showdetaillink').click(function(event) {
					next_fokus.showDetail();
				});
				$('#fokusboxtitel').css("cursor", "pointer");
				$('#fokusboxbild').css("cursor", "pointer");
				$('#fokusboxtext').css("cursor", "pointer");
				$('#addthis_toolbox').show();
				$('#detailboxcontent').empty().html(element.detail_html);
			}
		}
	}
	
	mapping.init();
	
	// -----------------------------------------------------
	// public API
	// -----------------------------------------------------
	return {
		//focusThisPost : focusThisPost,
		//focusThisPost : focusThisPost,
		switchThisPostAndFocus : switchThisPostAndFocus,
		focusThisPostAndUpdateOrder : focusThisPostAndUpdateOrder,
		updateFocusKompetenzfinder: updateFocusKompetenzfinder,
		showFocusExtId : showFocusExtId,
		pagingTo: pagingTo,
		conf: conf,
		mapping: mapping,
		paging: paging,
		filter: filter,
		obscure: obscure,
		toggleTag: toggleTag,
		showDetail: showDetail,
		hideDetail: hideDetail,
		showSuche: showSuche,
		hideSuche: hideSuche,
		print: printref,
		pdf: pdf,
		afterLoading: afterLoading
	};
})($);

