/******************************************************************************************
*
*	TABLE BUILDER
*
*******************************************************************************************/
   	
   	if (!Atira) var Atira = {}
   
   /**
	* Constructor for the tadetable builder
	*
	* TODO make this prototype ??! 
	* @param analyzerWindowId 		the id of the div that contains the analyzer window, if this is null it will void any analysis functionality
	*/
    Atira.TradeTableBuilder = function(){
   		//this._analyzerWindowId = analyzerWindow;
   	}
   	
   	Atira.TradeTableBuilder.getCSS = function(){
   		return "tradetable.css";
   	}
   	
   	/**
   	*	headers param should look like this:
   	*	var header = [
   	*	{className:"bordered_header", value:"Est. result", sortType:"number", property:"estimatedResult", propertyClass:"", propertyClasses:{positive:'plus', negative:'minus'}},
   	*	]
   	*	className:			class for the header <th>
   	*	value:				the string to be displayed in the header (<th>value</th>)
   	*	sortType:			can be any of the following {number, date, string}
   	*	property:			the identifier name for getting the value of the cells under this header data.options[property] (<td>data.options[property]</td>)
   	*	propertyClass:		if defined this will be the class for the <td class="propertyClass">
   	*	propertyClasses:	if defined this will override the propertyClass param, if inside the data we find the specified class (data.options[property+'Class'] yields the required class) 
   	*	propertyCustomHTML 	if defined as a function this will take the value from the property and apply the function to it (the function should return the html for inside <td> HERE </td>)
   	*	propertyAnalyze 	available values {null, PORTFOLIO, ON_ITS_WAY_UP, PENDING} if defined as not null an onclick event will be placed on the cell enabling the analyze call to the server. 
   							The value referes to where the analyzed engine row values should be taken from.
   	*
   	*	var data = {
   	*			options: {option1: value, option2: value}
   	*	}			 
   	*	
   	*	var legend = (not currently used)
   	*
   	*/
   	Atira.TradeTableBuilder.render = function(headers, data, enumerated, element_id, useClassification){
   	
   		if(data && headers){
	   		return Atira.TradeTableBuilder._renderTable(headers, data, enumerated, element_id, useClassification);
	   	}
	   	
   		return '';
   	}
   
   	Atira.TradeTableBuilder.failed = function(){
   		return '<div style="width: 100%; font-size: 8pt; text-align: center;">Failed to load</div>';
   	}
   	  

/******************************************************************************************
*
*	UTIL
*
*******************************************************************************************/
	
   /**
   	* Analyzes the calculation behind the cell element (uses pagecontroller.analyzerWindow, if this is not present the analyzer will abort)
   	* 
   	* @param property 	the property to analyze (the cell identifier), this can be either a CellPointer or a ExcelIdentifier ei. A1, or CAL_MAX
   	* @param elementId  the id (database id) of the analyzable element to analyze typically this is the shares or the index's id
   	* @param RowType    @see Constants.RowType
   	*
   	* note: all params are required to use this method
   	*/
  	Atira.TradeTableBuilder.analyze = function(property, elementId, RowType){
  		
  		if(!RowType)return;
  		var _window = CountSystem.getInstance().getPageController().analyzerWindow;
  		if(!_window)return;
  		
  		EngineInformationService.analyze(property, elementId, RowType, 
  				function(data){
  					if(data){
	 					_window.setDynamicTitle("Analyzer");
	 					_window.setDynamicContent(Atira.TradeTableBuilder._renderAnalyzeList(data));
	 					_window.show();
 					}
 		});
 		
  	}


/******************************************************************************************
*
*	STATELESS RENDERING METHODS  
*
*******************************************************************************************/
	Atira.TradeTableBuilder._renderAnalyzeList = function(list){
		
		var html = '';	
		
		if(list && list.length > 0){
			for(var i = 0; i < list.length; i++ ){
				var option = list[i];
				var optionType = option.optionType;
				if(optionType == 'cellOption'){
					html += '<div class="cellOption">' +i +':' + option.options['stringValue'] + '</div>';
				}
				
				var childList = option.options['childOptions'];
				html += Atira.TradeTableBuilder._renderChildOptions(childList);
				
			}
		
		}
	
		return html;
	}
	
	Atira.TradeTableBuilder._renderChildOptions = function(childList){
	
		var html = '';
			
		if(childList && childList.length > 0){
			
			for(var j = 0; j < childList.length; j++ ){
				var childOption = childList[j]; 
				var childOptionType = childOption.optionType;
				
				if(childOptionType == 'cellReferenceOption'){
					html += Atira.TradeTableBuilder._renderCellReferenceOption(childOption);
				}
			}
		}
		return html;
	}
	
	Atira.TradeTableBuilder._renderCellReferenceOption = function(option){
		
		html = '';
		
		if(option){
			var value = option.options['stringValue'];
			html += '<div class="cellReferenceOption"><a onclick="if(this.parentNode.childNodes[2].style.display == \'none\'){this.parentNode.childNodes[2].style.display = \'\'}else{this.parentNode.childNodes[2].style.display = \'none\'};" >'+option.options['excelIdentifier'] +'</a>';
			html += ' : ' + value;
			html += '<div style="display: none;">';
			
			var childList = option.options['childOptions'];
			if(childList){
				html += Atira.TradeTableBuilder._renderChildOptions(childList);
			}

			
			html += '</div>';
			html += '</div>';
		
		}
		
		return html;
	}
	
	/**
	* Renders the table
	*
	* @return 			a html string
	*/
	Atira.TradeTableBuilder._renderTable = function(headers, values, enumerated, element_id_identifier, useClassification){
		
		//defaults to shareId
		var id_identifier = element_id_identifier || 'shareId';
		
		var html = '';	
		var atleastOne = false;
			
			//TRADE TABLE
			html+= 		'<div class="TradeTable">';
					html+=	'<table>';
										if(headers){
											atleastOne = true;
											html+= '<thead>';
											html+= '<tr>';
											for(var i = 0; i < headers.length; i++ ){	
												
												var header = headers[i];
												var className = header.className;
												var value = header.value;
												var sortType = header.sortType;
												
												html+= '<th class="'+className+'" sort="'+sortType+'">'+value+'</th>';
											}			
											html+=	'</tr>';
											html+=	'</thead>'; 
											
											if(values){
												atleastOne = true;
												html+=	'<tbody>'; 
												
												var _isEmpty = true;
												
												if(values.length != 0){
													
													for(var j = 0; j < values.length; j++ ){	
														
														var option = values[j];
														var optionType = option.optionType;
														var optionClassification = option.classification;
													
														//values
														if(optionType == 'valueOption'){
															_isEmpty = false;
															
															//TODO val == null?
															var val = option.options;
															
															//tr properties
															if(useClassification && optionClassification){
																html+= '<tr class="hoverable_'+optionClassification+'">';
															}else{
																//default tr class
																html+= '<tr class="hoverable">';
															}
															
															for(var i = 0; i < headers.length; i++ ){
																
																var header = headers[i];
																var property = header.property;
																var propertyClass = header.propertyClass;
																var propertyClasses = header.propertyClasses;
																var propertyCustomHTML = header.propertyCustomHTML;
																var propertyAnalyze = header.propertyAnalyze;
																
																//determine td class
																if(propertyClasses){
																	var classIdentifier = '';
																	var valueClassIdentifier = property + 'Class';
																	var valueClass = val[valueClassIdentifier];
																	
																	if(valueClass){
																		classIdentifier = valueClass;
																	}
																	propertyClass = header.propertyClasses[classIdentifier];
																}
																if(!propertyClass){propertyClass = '';}
																
																//determine td html
																if(propertyCustomHTML){
																	if(typeof(propertyCustomHTML) == 'function'){
																		if(property){
																			
																			if(typeof(property) == 'object' && property.length){
																				//incase we have an array
																				var params = new Array();
																				for(var index=0; index<property.length; index++) {
																					var _prop = property[index];
																					var propertyValue = val[_prop];
																					if(!propertyValue){propertyValue = '';}
																					params.push(propertyValue);			
																				}
																				
																				if(!propertyAnalyze){
																					html+='<td class="'+propertyClass+'">'+propertyCustomHTML(params)+'</td>';
																				}else{
																					var element_id = val[id_identifier];
																					html+='<td onclick="Atira.TradeTableBuilder.analyze(\''+property+'\', '+element_id+', \''+propertyAnalyze+'\'); return false;" class="'+propertyClass+'"><div class="analyze">'+propertyCustomHTML(params)+'</div></td>';
																				}
																				
																			}else{
																				//simple value																				
																				var cellValue = val[property];
																				if(!cellValue){cellValue = '';}
																				
																				if(!propertyAnalyze){
																					html+='<td class="'+propertyClass+'">'+propertyCustomHTML(cellValue)+'</td>';
																				}else{
																					var element_id = val[id_identifier];
																					html+='<td onclick="Atira.TradeTableBuilder.analyze(\''+property+'\', '+element_id+', \''+propertyAnalyze+'\'); return false;" class="'+propertyClass+'"><div class="analyze">'+propertyCustomHTML(cellValue)+'</div></td>';
																				}
																			}
																		
																		}else{
																			//empty property
																			html+='<td class="'+propertyClass+'">'+propertyCustomHTML()+'</td>';
																		}
																	}else{
																		var element_id = val[id_identifier];
																		//TODO fix this
																		var share_name = val['shareName'];
																		html+=	'<td class="edit"><a href="#" onclick="CountSystem.getInstance().getPageController().editShare('+element_id+', \''+share_name+'\' , this); return false;">Edit</a></td>';
																	}
																}else if(property){
																	var element_id = val[id_identifier];
																	var cellValue = val[property];
																	if(!cellValue){cellValue = '';}
																	
																	if(!propertyAnalyze){
																		html+='<td class="'+propertyClass+'">'+cellValue+'</td>';
																	}else{
																		html+='<td onclick="Atira.TradeTableBuilder.analyze(\''+property+'\', '+element_id+', \''+propertyAnalyze+'\'); return false;" class="'+propertyClass+'"><div class="analyze">'+cellValue+'</div></td>';
																	}
																	
																}else{
																	html+='<td class="'+propertyClass+'"></td>';
																}
															}
															html+= '</tr>';
														
														}else if(optionType == 'sumOption' && !_isEmpty){
															var val = option.options;
															html+= '<tr class="last">';
															
															for(var i = 0; i < headers.length; i++ ){
																var header = headers[i];
																var property = header.property;
																var propertySumClass = header.propertySumClass;
																if(!propertySumClass){propertySumClass = '';}
																
																if(property){
																	var cellValue = val[property];
																	if(!cellValue){cellValue = '';}
																	html+='<td class="'+propertySumClass+'">'+cellValue+'</td>';
																}else{
																	html+='<td class="'+propertySumClass+'"></td>';
																}	
															}
															html+= '<tr>';
														}
														
													}
												}
												
												if(_isEmpty){
													if(headers.length > 0){
														if(enumerated){
															var cols = headers.length - 1;
															html+= '<tr><td class="enum"></td><td class="full" colspan="'+cols+'">Empty</td></tr>';
														}else{
															var cols = headers.length;
															html+= '<tr><td class="full" colspan="'+cols+'">Empty</td></tr>';
														}
													}else{
														html+= '<tr><td class="full">Empty</td></tr>';
													}
												}
												
												html+=	'</tbody>'; 
											}
										}
					html+= '</table>';
			html+= 		'</div>';
		
		if(atleastOne){
			return html;	
		}else{
			return '';
		}
	}