<?xml version="1.0" encoding="ISO-8859-1"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:cti_control="CTI.technique.controls.*" xmlns="*" 
	creationComplete="creationComplete()" resize="resize()"
	styleName="CTIView"
	paddingTop="0" paddingBottom="0" paddingRight="0" paddingLeft="0"
	creationPolicy="all">
   <mx:Script>
        <![CDATA[   
		
			import mx.controls.Alert;
			import mx.collections.XMLListCollection;
			import mx.events.CloseEvent
			import mx.collections.Sort;
            import mx.collections.SortField;
			
			import CTI.technique.CTI_Utilitaires;
			import CTI.technique.CTI_ExcelUtilitaires;
			import CTI.print.CTI_Print;
			import CTI.technique.CTI_ExcelUtilitaires;
			import CTI.technique.CTI_PDFUtilitaires;
			import CTI.technique.CTI_ArrayCollection;
			
			public var buildComplete:Boolean = false;
			
			[Embed(source="../../base/swf/CTI/images/24/print.png")]
			public var button_print24:Class;
			
			[Embed(source="../../base/swf/CTI/images/32/help.png")]
            public static var question_class:Class;
			
			// Variables CTI
			public static var softCode:String = "iCTI_activite";
			
			[Bindable]
			public var title:String = "Tables Comptabilité";
			public var titlePrint:String = "Tables Comptabilité";
			
			[Bindable]
			public var hasHelp:Boolean = false;
			
			private var viewName:String;
			private var tableName:String;
			
			[Bindable]
			private var tableCode:String;
			
			[Bindable]
			private var list_collection:XMLListCollection = new XMLListCollection();
			
			public var list_collection_search_mots:Array = new Array();
			
			public var a_regrouper_search_mots:Array = new Array();
			
			[Bindable]
			private var recordUpdated:Boolean = false;
			
			private var currendRecordItem:XML = null;
			
			private var tableList:Object = new Object();
			
			
			
			
			// FONCTIONS
			public function creationComplete():void {
				if (application.currentHelpFile != "") {
					hasHelp = true;
				}
				if (application.name == "CTI") {
				}
				if (application.name == "CTI_1") {
					GUI_titleBar.height = 0
				}
				
				viewName = application.currentViewName;
				tableCode = application.currentSwfData;
				
				tableList["ENC"] = ["encours","Gestion encours","Encours"];
				

				tableName = tableList[tableCode][0];
				title = tableList[tableCode][1];
				titlePrint = tableList[tableCode][2];
				
				getData(true);
			}
			
			public function eventDispatcher(eventCode:String):Boolean {
				return true;
			}
			
			public function getData(firstCall:Boolean = false, updatedOids:String = ""):void {
				// Tri en cours
				var currentSort:Sort = null
				if (list_collection != null) {
					currentSort = list_collection.sort
                } 
			
				// Demande au serveur
				var urlVariables:URLVariables = new URLVariables();
				urlVariables.tableName = tableName;
				if (firstCall) {
					urlVariables.firstCall = "1";
				}
				else {
					urlVariables.firstCall = "0"
				}
				urlVariables.updatedOids = updatedOids
				urlVariables.softCode = softCode;
				CTI_Utilitaires.startRequestHTTP("modules/activite/php/httpService_ACTI_consoManager_getData.php",urlVariables,exec,true,this.parentApplication);
				
				function exec(resultatService:XML):void {
					if (list_collection != null) {
						list_collection.filterFunction = null;
						list_collection.refresh();
					}
					
					if (updatedOids == "") {
						list_collection = new XMLListCollection(resultatService.RECORD);
					
						if (currentSort != null) {
							list_collection.sort = currentSort
						}
					}
					else {
						for each (var updateItem:XML in resultatService.RECORD) {
							for each (var item:XML in list_collection) {
								if (item.@oid.toString() == updateItem.@oid.toString()) {
									for each (var attributeNode:XML in updateItem.@*) {
										var attributeName:String = attributeNode.name().toString()
										if (attributeName != "oid") {
											var attributeValue:String = attributeNode.toString()
											item['@'+attributeName] = attributeValue
										}
									}
									break;
								}
							}
						}
					
					}
					
					if (firstCall) {

						
					}
					
					
					searchChange();
					setTimeout(setBuildComplete, 1000);
						

					
					
				}
			}
			
			private function setBuildComplete():void {
				buildComplete = true;
			}
					
			private function resize():void {
			}
			
			private function searchChange():void {

				list_collection_search_mots = getMots(textSearch_GUI.text)

				if (list_collection.filterFunction == null) {
					list_collection.filterFunction = filterFunction;
				}
				list_collection.refresh();
			}
			
			public function getMots(fromText:String):Array {
				var toMotsArray:Array = new Array()
				
				if (fromText != "") {
					var fromUpperText:String = toUpperCaseWithoutAccent(fromText)
					var mot:String = "";
					
					for (var i:Number = 0; i < fromUpperText.length; i++) { 
						var char:String = fromUpperText.substr(i,1)
						if (char != ' ') {
							mot = mot + char
						}
						else {
							if (mot != "") {
								toMotsArray.push(mot)
								mot = ""
							}
						}
					} 
					if (mot != "") {
						toMotsArray.push(mot)
						mot = ""
					}
				}
				return toMotsArray;
			}
			
			public static function toUpperCaseWithoutAccent(string:String):String {
				
				return noAccent(string).toUpperCase()
				
			}
			
			public static function noAccent(source:String):String {
				source = source.replace(/[àáâãäå]/g, "a");
				source = source.replace(/[ÀÁÂÃÄÅ]/g, "A");
				source = source.replace(/[èéêë]/gi, "e");
				source = source.replace(/[ËÉÊÈ]/g, "E");
				source = source.replace(/[ìíîï]/g, "i");
				source = source.replace(/[ÌÍÎÏ]/g, "I");
				source = source.replace(/[ðòóôõöø]/g, "o");
				source = source.replace(/[ÐÒÓÔÕÖØ]/g, "O");
				source = source.replace(/[ùúûü]/g, "u");
				source = source.replace(/[ÙÚÛÜ]/g, "U");
				source = source.replace(/[ýýÿ]/g, "y");
				source = source.replace(/[ÝÝŸ]/g, "Y");
				source = source.replace(/[ç]/g, "c");
				source = source.replace(/[Ç]/g, "C");
				source = source.replace(/[ñ]/g, "n");
				source = source.replace(/[Ñ]/g, "N");
				source = source.replace(/[š]/g, "s");
				source = source.replace(/[Š]/g, "S");
				source = source.replace(/[ž]/g, "z");
				source = source.replace(/[Ž]/g, "Z");
				source = source.replace(/[æ]/g, "ae");
				source = source.replace(/[Æ]/g, "AE");
				source = source.replace(/[œ]/g, "oe");
				source = source.replace(/[Œ]/g, "OE");
				
				source = source.replace(/Ã©Ã¨/gi, "e");

				return source;
			}

			public function filterFunction(item:XML):Boolean { 
				var result:Boolean = true; 

				result = filterListItem(item, list_collection_search_mots)
				
				return result; 
			} 
			
			public function filterListItem(item:XML, mots:Array):Boolean { 
				var result:Boolean = true; 

				if (mots.length > 0) {
					result = false
					
					var fullText:String = ""
					for each (var attributeNode:XML in item.@*) {
						var attributeName:String = attributeNode.name().toString()
						var attributeValue:String = attributeNode.toString()
						if (attributeName != "oid" && attributeValue.toString() != "") {
							fullText = fullText + ' ' + attributeValue.toUpperCase()
						}
					}

					var resultMot:Boolean = true
					for each (var mot:String in mots) {
						if (fullText.indexOf(mot) < 0) {
							resultMot = false
							break;
						}
					}
					if (resultMot) {
						result = true
					}
					
				}

			
				return result; 
			} 
			
			public function getRecord():void {
				if (recordUpdated == true) {
					return;
				}
				if (list_GUI.selectedIndex < 0) {
					return;
				}
				currendRecordItem = list_GUI.selectedItem as XML;
				showDetail();
			}
			
			public function showDetail():void {
				var i:Number;
				var item:XML;
				if (currendRecordItem == null) {
					return;
				}
				oid_GUI.text = currendRecordItem.@oid.toString();

				code_GUI.text = currendRecordItem.@code.toString();
				texte_GUI.text = currendRecordItem.@texte.toString();
				
				if (tableCode == "ENC") {
					ENC_dateencours_GUI.text = currendRecordItem.@dateencours.toString();
				}

				
				recordUpdated = false;
				detailBox_GUI.visible = true;
				detailBox_GUI.includeInLayout = true;
			}
			
			private function askCancel():void {
				if (recordUpdated == false) {
					hideRecord();
					return;
				}
				Alert.yesLabel = "OUI";
                Alert.noLabel = "NON";
	            var alert:Alert = Alert.show("Les données ont été changées, désirez vous les annuler ?", title, 3, this, alertClickHandler, question_class);
				
	            function alertClickHandler(event:CloseEvent):void {
	                if (event.detail==Alert.YES) {
						hideRecord();
					}
	            }
			}
			
			private function hideRecord():void {
				detailBox_GUI.visible = false;
				detailBox_GUI.includeInLayout = false;
				currendRecordItem = null;
				recordUpdated = false;
			}

			private function askDelete():void {
				Alert.yesLabel = "OUI";
                Alert.noLabel = "NON";
	            var alert:Alert = Alert.show("Désirez vous vraiment supprimer " + texte_GUI.text + " ?", title, 3, this, alertClickHandler, question_class);
				
				
	            function alertClickHandler(event:CloseEvent):void {
	                if (event.detail==Alert.YES) {
						deleteRecord()
					}
	            }
			}
			
			public function deleteRecord():void {
				updateRecord("delete");
			}
			
			public function copyRecord():void {
				updateRecord("copy");
			}
			
			public function saveRecord():void {
				updateRecord("save");
			}
			
			public function updateRecord(action:String):void {
				var urlVariables:URLVariables = new URLVariables()
				urlVariables.tableName = tableName;
				urlVariables.action = action;
				urlVariables.softCode = softCode;
				var recordNode:XML = new XML(<RECORD />);
				recordNode.@oid = oid_GUI.text;
				recordNode.@code = code_GUI.text;
				recordNode.@texte = texte_GUI.text;
				
				if (tableCode == "ENC") {
					recordNode.@dateencours = ENC_dateencours_GUI.text;
				}


				urlVariables.recordNode = recordNode.toXMLString();
				CTI_Utilitaires.startRequestHTTP("modules/activite/php/httpService_ACTI_consoManager_setData.php",urlVariables,exec,true,this.parentApplication)	
				function exec(resultatService:XML):void {
				
					var returnCode:String = resultatService.@returnCode;
					var returnTexte:String = resultatService.@returnTexte;
					if (returnCode == "KO") {
						CTI_Utilitaires.alert_error("Mise à jour", "Mise à jour non effectuée : " + returnTexte);
					}
					else {
						var updatedOids:String = resultatService.@updatedOids.toString();
						
						getData(false,updatedOids);
						
						currendRecordItem = null;
						recordUpdated = false;
						detailBox_GUI.visible = false;
						detailBox_GUI.includeInLayout = false;
					}
					
				}
			}
			
			public function print():void {
				var printReport:CTI_Print = new CTI_Print();
				if (printReport.start("ECO_TablesManager", titlePrint) == false) {
					return;
				}
				printReport.addDataGrid(list_GUI)
				printReport.print();
			}
			
			public function exportExcel():void {
				var xml:XML = new XML(<EXCELEXPORT />);
				var ongletNode:XML;
				var similiTabNode:XML;
				var selectionsNode:XML;
				var datagridNode:XML;
				var columnNode:XML;
				var dataNode:XML;
				var rowNode:XML;
				xml.@viewName = this.viewName;
				xml.@title = this.title;
				selectionsNode = new XML(<SELECTIONS />);
				selectionsNode.displayText = "";
				if (textSearch_GUI.text != "") {
					selectionsNode.@displayText = selectionsNode.displayText + "(Filtre : " + textSearch_GUI.text + ")  ";
				}
				xml.appendChild(selectionsNode);
				ongletNode = new XML(<ONGLET />);
				ongletNode.@excelLabel = tableCode;
				xml.appendChild(ongletNode);
				similiTabNode = new XML(<SIMILITAB />);
				similiTabNode.@excelLabel = "Liste";
				ongletNode.appendChild(similiTabNode);
				datagridNode = new XML(<DATAGRID />);
				datagridNode.@total = "false";
				ongletNode.appendChild(datagridNode);
				for each (var column:DataGridColumn in list_GUI.columns) {
					columnNode = new XML(<COLUMN />);
					columnNode.@dataField = column.dataField;
					columnNode.@headerText = column.headerText;
					columnNode.@type = "Char";
					columnNode.@textAlign = column.getStyle("textAlign");
					datagridNode.appendChild(columnNode);
				}
				dataNode = new XML(<DATA />);
				similiTabNode.appendChild(dataNode);
				for each (var itemNode:XML in list_collection) {
					if (itemNode.@oid != "-1") {
						rowNode = new XML(<ROW />)
						var c:int = 0;
						for each (column in list_GUI.columns) {
							c++;
							rowNode.@["c" + c.toString()] = itemNode[column.dataField]
						}
						dataNode.appendChild(rowNode);
					}
				}
				CTI_ExcelUtilitaires.exportExcel(xml);
			}
			
			public function exportPDF():void {
				var xml:XML = new XML(<PDFEXPORT />);
				var ongletNode:XML;
				var selectionsNode:XML;
				var datagridNode:XML;
				var columnNode:XML;
				var dataNode:XML;
				var rowNode:XML;
				xml.@viewName = this.viewName;
				xml.@title = this.title;
				selectionsNode = new XML(<SELECTIONS />);
				selectionsNode.displayText = "";
				if (textSearch_GUI.text != "") {
					selectionsNode.displayText = selectionsNode.displayText + "(Filtre : " + textSearch_GUI.text + ")  ";
				}
				xml.appendChild(selectionsNode);
				ongletNode = new XML(<ONGLET />);
				ongletNode.@excelLabel = tableCode;
				xml.appendChild(ongletNode);
				datagridNode = new XML(<DATAGRID />);
				datagridNode.@total = "false";
				ongletNode.appendChild(datagridNode);
				for each (var column:DataGridColumn in list_GUI.columns) {
					columnNode = new XML(<COLUMN />);
					columnNode.@dataField = column.dataField;
					columnNode.@headerText = column.headerText;
					columnNode.@type = "Char";
					columnNode.@textAlign = column.getStyle("textAlign");
					datagridNode.appendChild(columnNode);
				}
				dataNode = new XML(<DATA />);
				ongletNode.appendChild(dataNode);
				for each (var itemNode:XML in list_collection) {
					if (itemNode.@oid != "-1") {
						rowNode = new XML(<ROW />)
						var c:int = 0;
						for each (column in list_GUI.columns) {
							c++;
							rowNode.@["c" + c.toString()] = itemNode[column.dataField]
						}
						dataNode.appendChild(rowNode);
					}
				}
				CTI_PDFUtilitaires.exportPDF(xml);
				xml = null;
			}
			
						
			
			
        ]]>
    </mx:Script>

	<mx:VBox width="100%" height="100%">
		<cti_control:CTIViewTitle id="GUI_titleBar" label="{title}" width="100%" height="25" />
		<mx:Canvas width="100%" height="28" >
			<mx:HBox id="GUI_buttonBar" width="100%">
				<mx:Button height="28" width="28"
					visible="{detailBox_GUI.visible == false}"
					toolTip="Imprimer" icon="@Embed('../../base/swf/CTI/images/24/print.png')" labelPlacement="right" click="print()"/>
				<mx:Button height="28" width="28" 
					visible="{detailBox_GUI.visible == false}"
					toolTip="Réafficher" icon="@Embed('../../base/swf/CTI/images/24/view-refresh.png')" labelPlacement="right" click="getData()" />
				<mx:Button height="28" width="28" 
					visible="{detailBox_GUI.visible == false}"
					toolTip="Exporter vers Excel" icon="@Embed('../../base/swf/CTI/images/24/excel.png')" labelPlacement="right" click="exportExcel()"/>
				<mx:Spacer />
				<!--<mx:Button height="28" width="28" toolTip="Ajouter" icon="@Embed('../../base/swf/CTI/images/24/list-add.png')" labelPlacement="right" click="addRecord()" visible="false" />
				<mx:Spacer />-->
				<mx:Button height="28" width="28" toolTip="Aide" icon="@Embed('../../base/swf/CTI/images/24/help.png')" labelPlacement="right" click="application.displayHelp()" visible="{hasHelp}" />
				<mx:Button height="28" width="28" toolTip="A propos" icon="@Embed('../../base/swf/CTI/images/24/information.png')" labelPlacement="right" click="application.showApropos_view()"  />
				<mx:Spacer width="100%" />
				<mx:HBox  >
					<mx:Label text="Filtre" />
					<mx:TextArea width="100%" height="18" id="textSearch_GUI" change="searchChange()"/>
					
				</mx:HBox>
			</mx:HBox>
		</mx:Canvas>
		<mx:Canvas width="100%" height="100%">
			<mx:VDividedBox id="mainBox" width="100%" height="100%" visible="true">
				<mx:DataGrid id="list_GUI" rowHeight="20" headerHeight="40"
					rowCount="{list_collection.length + 1}" height="100%" width="100%"
					wordWrap="false" dataProvider="{list_collection}"
					fontFamily="tahoma" fontSize="11"
					itemClick="getRecord()"
					selectable="{!recordUpdated}">
					<mx:columns>
						<mx:DataGridColumn dataField="@code" headerText="Environnement" width="110"  editable="false" headerWordWrap="true"/>
						<mx:DataGridColumn dataField="@texte" headerText="Texte" minWidth="400"  editable="false" headerWordWrap="true"/>

						<mx:DataGridColumn dataField="@dateencours" headerText="Jour clôture" width="400"  editable="false" headerWordWrap="true"/>
						<mx:DataGridColumn dataField="@encoursnow" headerText="Derniers encours calculés" width="400"  editable="false" headerWordWrap="true"/>
					</mx:columns>
				</mx:DataGrid>
				<mx:VBox id="detailBox_GUI" width="100%" 
					visible="false"
					includeInLayout="false"
					height="300" backgroundColor="0xFFFFFF">
					<mx:HBox>
						<mx:Canvas>
							<mx:Button height="28" label="Annuler" toolTip="Annuler les modifications" icon="@Embed('../../base/swf/CTI/images/24/window-close.png')" labelPlacement="right" click="askCancel()" visible="{recordUpdated == true}" />
							<mx:Button height="28" label="Masquer" toolTip="Masquer la fiche" icon="@Embed('../../base/swf/CTI/images/24/go-up.png')" labelPlacement="right" click="hideRecord()" visible="{recordUpdated == false}" />
						</mx:Canvas>
						<mx:Canvas>
							<mx:Button height="28" label="Enregistrer" toolTip="Enregistrer les modifications" icon="@Embed('../../base/swf/CTI/images/valider24.png')" labelPlacement="right" click="saveRecord()" visible="{recordUpdated == true &amp;&amp; code_GUI.text != ''}" />
						</mx:Canvas>
					</mx:HBox>
					<mx:HBox width="100%" height="100%" >
						<mx:VBox width="100%" height="100%" >
							<mx:HBox>
								<mx:Label width="150" text="Code environnement" />
								<mx:TextArea width="100" height="18" id="code_GUI" change="recordUpdated = true" editable="false"/>
							</mx:HBox>
							
							<mx:HBox width="100%">
								<mx:Label width="150" text="Texte" />
								<mx:TextArea width="100%" height="18" id="texte_GUI" change="recordUpdated = true" fontWeight="bold" editable="false"/>
							</mx:HBox>
							
							
							<mx:HBox width="100%">
								<mx:Label width="150" text="Jour clôture" />
								<mx:TextArea width="50" height="18" id="ENC_dateencours_GUI" change="recordUpdated = true" fontWeight="bold" editable="true"/>
							</mx:HBox>
							
							
							<mx:HBox visible="false" includeInLayout="false">
								<mx:Label width="150" text="Oid" />
								<mx:TextArea width="300" height="18" id="oid_GUI" change="recordUpdated = true" editable="false"/>
							</mx:HBox>

						</mx:VBox>
						
						
						
						
					</mx:HBox>
					
				</mx:VBox>
			</mx:VDividedBox>
		</mx:Canvas>
	</mx:VBox>
</mx:Application>