(function(){

angular
.module('izApp')
.directive('freeModule',freeModuleDirective);

function freeModuleDirective(){
  return {
	restrict: 'E',
	scope: {index: '@index'},
	replace:true,
	controller: freeModuleDirectiveController,
	template: '<div bind-html-compile="module.templateRendered" class="row freeModule" id="{{module.title}}"></div>'
  };
}

freeModuleDirectiveController.$inject=["$scope","$window","LocationService","UtilService","MODULE_TEMPLATE_IDS"];
function freeModuleDirectiveController($scope,$window,LocationService,UtilService,MODULE_TEMPLATE_IDS){
	  $scope.module = $scope.$parent.freeModules[$scope.index];
	  $scope.veranstaltung = $scope.$parent.$parent.veranstaltung;
      $scope.noOfContentBoxes = $scope.module.contentboxes.length;
  
	  $scope.mapLoaded = mapLoaded; 
	  $scope.hyphenateText = UtilService.hyphenateText;
  	  $scope.displayRabattText = displayRabattText; 
  		$scope.stripHTMLforRabattText=stripHTMLforRabattText;
  
  	  var chunkArray = UtilService.chunkArray;	
  
   
  	  function mapLoaded(mapContainerId){
		if(!mapContainerId){
			    $scope.module.mapError = true;
				return console.log("[$scope.mapLoaded] Undefined mapContainerId");
		}
 			
		//var addressMarkups = document.getElementsByClassName("address-markup");
		
		var cssSelector = "#"+$scope.module.title;
		cssSelector += " .address-markup";
		var addressMarkups = document.querySelectorAll(cssSelector);

		/*
		 for (var i = 0; i < addressMarkups.length; i++) {
    		addressMarkups[i].addEventListener('click', function(event){
			  	$window.open( "https://www.google.de/maps/place/" + this.innerHTML );
			}, false);
		 }
		*/
			if($scope.module.templateId == MODULE_TEMPLATE_IDS.LOCATION){
			  
			  
			  // checke ob das Wort "hotel" in den Contentboxen vorkommt
			  
			    var fullModuleText = "";
			    var cbTitle = angular.copy($scope.module.contentboxes[0].title);
			  	
			   
			  $scope.module.contentboxes.forEach(function(contentBox){
				fullModuleText += " ";
				fullModuleText += contentBox.text;
			  });
			  var isHotelPresentInDesc = false;
			  if(fullModuleText){
			  	isHotelPresentInDesc = ( fullModuleText.toLowerCase().indexOf("hotel") !== -1 ) ? true : false;
			  }
			 
			  
			  
			  
			  if(!addressMarkups.length){
				$scope.module.mapError = true;
			  	console.log("Address markup cannot be found in the location module, hence no map can be generated");
				return;
			  }
			  
			  	var addressString = "";
			  	var excludeTitleWords = ["veranstaltungsort","location"];
			  	if( cbTitle.toLowerCase().indexOf("hotel") > -1){
				  	console.log("should append to address ...",cbTitle);
					 //addressString = "hotel";
				}
			  
			   

			  	for(var i=0; i < addressMarkups.length; i++){
				    if(addressString.length){
						//addressString += " - ";
					}
					addressString += addressMarkups[i].innerText;
				}
					
				
			    //var addressElementString = addressMarkups[0].innerText;
			
			    var addressPurifed = addressString.trim();
			    /*
			     if(isHotelPresentInDesc){
				 	addressPurifed += "-hotel";
				 }
				 */
			  	console.log("Rendere Karte in DOMID:",mapContainerId);
			  	LocationService.renderEmbededMap(mapContainerId,addressPurifed);
				//LocationService.initMap(mapContainerId);
			    //LocationService.geocodeAndPinToGmap(mapContainerId,addressPurifed);
	  		}
	  }
  
	 function shouldDisplayOffsetColumn(chunkLength,targetCellWidth){
		// 08.06.2016, barwicki@iz.de : for constant separation width between elements
		// returns false if grid column should be not displayed before the $index-th, offset width if it should
		// !targetCellWidth :  6 pr 4 block col-sm-2 grid or col-sm-3 

		return 6-chunkLength;  
	  };

	 
	
	  $scope.module.contentboxesChunks = [];
   	  var noOfElementsInRow = 3;
      if ( $scope.module.templateId == MODULE_TEMPLATE_IDS.LOCATION ) {
	  	noOfElementsInRow = 2;
	  } else if ( $scope.module.templateId == MODULE_TEMPLATE_IDS.TICKETS ) {
		noOfElementsInRow = 3;
	  } else if ( $scope.module.templateId == MODULE_TEMPLATE_IDS.RABBATS ) {
		noOfElementsInRow = 6;
	  }	
	 
	  chunkArray($scope.module.contentboxes,noOfElementsInRow).forEach(function(boxchunk){
		var isEven = ( boxchunk.length % 2 ) ? false : true;
		var targetCellWidth = isEven ? 2 : 3;
		var rowOffset = shouldDisplayOffsetColumn(boxchunk.length,targetCellWidth);

		$scope.module.contentboxesChunks.push({
		  data:boxchunk, 
		  nodeClasses: "col-sm-2", //+targetCellWidth, 
		  rowOffset : rowOffset
		});
	  });




	  function checkIfRabattFormatUsed(cbHtmlText){
		// 06.06.2016, barwicki@iz.de : we want to check if a tinycms format 'Rabattformat' has been used in the cbHtmlText
		// if is used, the function returns the text to which the format has been applied, otherwise false
		var tmp = document.createElement("DIV");
		tmp.innerHTML = cbHtmlText;
		var rabattFormatElements = tmp.getElementsByTagName("h3");
		var textFromFormatElement;
		if(rabattFormatElements&&rabattFormatElements.length){
		  textFromFormatElement = rabattFormatElements[0].innerHTML;
		}
		return textFromFormatElement ? textFromFormatElement : false;
	  }



	  function calculateColumnWidth(arrayLength,$index){
		// 07.06.2016 barwicki@iz.de : calculates the width columnWidth of bootstrap column col-sm-columnWidth 
		// 08.06.2016 : for symmetrical alignment
		
		if(arrayLength==5){
		  return $index > 2 ? 6 : 4;
		}

		if(arrayLength==6){
		  return 4;
		}
		return (arrayLength<4) ? ( 12/(arrayLength%4) ) : ( $index > ( arrayLength - arrayLength%4 - 1 ) ) ? 12/(arrayLength%4) : 3;

	  }


	  
  
      function displayRabattText(cbHtmlText){
		var rabattFormatText = checkIfRabattFormatUsed(cbHtmlText);
		if(rabattFormatText){
		  return rabattFormatText;
		} else {
		  return cbHtmlText;
		}
	  }	

	  function stripHTMLforRabattText(cbHtmlText){
		var tmp = document.createElement("DIV");
		tmp.innerHTML = cbHtmlText;
		var contentText = (tmp.textContent || tmp.innerText || "" );  
		var rabattFormatText = checkIfRabattFormatUsed(cbHtmlText);
		if(rabattFormatText){
		  return { rabattTitle : rabattFormatText, text: contentText.replace(rabattFormatText, '') };
		}else{
		  return { rabattTitle : "Rabatt", text : contentText.replace(rabattFormatText, '') };	
		}
	  }
	  // Berechnungen hier einfügen
	  //// $scope.module.contentboxes.length
	  //// $scope.offset = 50;
}

}());