/*
    Copyright (C) 2008  Ivo Toby, Internet Voor Ondernemers, http://www.i-v-o.nl / http://syntacticsugar.nl 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

	Crudder Version : 0.50b
 */


	var crudderNavigator = Class.create({
		
		initialize : function(rowCount, currPage, itemsPerPage, maxShownPages){
			this.instID = 'crudderNavigator.' + parseInt(Math.random()*1000000);
			this.rowCount = rowCount;
			this.page = currPage;
			this.itemsPerPage = itemsPerPage;
			this.maxPages = 10;
			if (maxShownPages) this.maxPages = maxShownPages;
		},
		
		drawNavigator : function(container){
			container.update("");
			var div = new Element('div', {className:'crudderNavigator', id:this.instID +"_navigator"});
			container.appendChild(div);
			
			if (!this.itemsPerPage ) this.itemsPerPage = 20;
			var pages = Math.ceil( ( parseInt(this.rowCount) / this.itemsPerPage)  );

			// we can show max. 15 items, cut the counter into parts if 15 items are exceeded
			if (pages <= (this.maxPages)){
				pages.times(
						(function(pageNum){
							div.insert(this.drawNavItem(pageNum, pages, div));
						}).bind(this)
					)
			}else{
				if (this.page > this.maxPages){
					var half = Math.floor( (this.maxPages/2));
					var start = (((this.page -half)))
					var end = (start + this.maxPages);
					if (end > pages) {
						end = pages;
						start = pages - this.maxPages;
					}
					
					// build select thingy before list:
					var select = new Element('select', {className:'crudderNavigatorSelect'});
					select.insert(new Element('option'));
					div.insert(select);
					select.observe('change', this.navigateFromSelect.bindAsEventListener(this));
					for (var i=0;i<start;i++){
						var option = new Element('option', {value:i}).update((i+1));
						select.insert(option);
					}
					div.insert('-');
					// build normal numeric links
					for (var i=start;i<(end-1);i++){
						div.insert(this.drawNavItem(i, pages, div));
					}
					
					// build closing select thingy:
					if (end < pages){
						var select = new Element('select', {className:'crudderNavigatorSelect'});
						select.insert(new Element('option'));
						div.insert(select);
						select.observe('change', this.navigateFromSelect.bindAsEventListener(this));
						for (var i=end;i<=pages;i++){
							var option = new Element('option', {value:i}).update((i+1));
							select.insert(option);
						}
					}

				}else{
					var select = new Element('select', {className:'crudderNavigatorSelect'});
					select.insert(new Element('option'));
					pages.times(
							(function(pageNum){
								if (pageNum > this.maxPages){
									var option = new Element('option', {value:pageNum}).update(pageNum + 1);
									select.insert(option);
								}else{
									div.insert(this.drawNavItem(pageNum, pages, div));
								}
							}).bind(this)
						)
					if (select.options.length > 1){
						div.insert(select);
						select.observe('change', this.navigateFromSelect.bindAsEventListener(this));
					}
				}
			}
			if (this.callBackItemsPerPage && (this.rowCount > this.itemsPerPage)){
				var select = new Element('select', {className:'crudderNavigatorSelect', style:"margin-left:10px;"});
				select.insert(new Element('option', {value:''}).update(''));
				[10,20,50,100,200,500,1000].each(
					(function(num){
						var option = new Element('option', {value:num}).update(num);
						select.insert(option);
						if (num == this.itemsPerPage) option.selected = true;
					}).bind(this)
				)
				div.appendChild(select);
				select.observe('change', this.setItemsPerPage.bindAsEventListener(this));
			}
			if (this.searchCallBack){
				var input = new Element('input', {type:'text', value:"", id:this.instID + "searchInput", className:'crudderSearch', style:'margin-left:10px;'});
				div.insert(input);
				var button = new Element('button', {className:'crudderSearch'}).update(this.controller.lang.get('searchButton'));
				button.srcElem = input;
				div.insert(button);
				button.observe('click', this.search.bindAsEventListener(this));

//				this.cancelSearchButton = new Element('button', {id:this.instID+'_cancel',className:'crudderSearch'}).update(this.controller.lang.get('cancelButton'));
//				div.insert(this.cancelSearchButton);
//				this.cancelSearchButton.hide();
//				console.log(this.cancelSearchButton);
//				button.observe('click', this.search.bindAsEventListener(this));

				
			}
			if (this.exportCallBack){
				var button = new Element('button', {className:'crudderExportButton'}).update(this.controller.lang.get('exportButton'));
				button.srcElem = input;
				div.insert(button);
				button.observe('click', this.exportData.bindAsEventListener(this));
			}
			return div;
		},
		
		exportData : function(event){
			var container = event.element().parentNode;
			// draw export-interface:
			if ($(this.instID + "_exportDiv")) $(this.instID + "_exportDiv").remove(); 
			var exportDiv = new Element('div', {className:'exportControls', id:this.instID + "_exportDiv"});
			container.insert(exportDiv);
			
			var exportCloser = new Element('span', {className:'exportClose', style:'cursor:pointer;'}).update(this.controller.lang.get("closeExport"))
			exportDiv.insert(exportCloser);
			exportCloser.observe('click', function(e){
				new Effect.BlindUp(e.element().parentNode)
			});
			
//			// import & export selection:
//			var select = new Element('select', {className:'exportSelection'});
//			select.insert(new Element('option').update(''));
//			select.insert(new Element('option', {value:'export'}).update('Export'));
////			select.insert(new Element('option', {value:'import'}).update('Import'));
//			exportDiv.insert(this.controller.lang.get('exportPreSelect'))
//			exportDiv.insert(select);
//			
//			select.observe('change', (function(e){
//				$(this.instID + "_export").hide();
//				$(this.instID + "_import").hide();
//				$(this.instID + "_" + e.element().getValue()).show();
//			}).bind(this));
			
			// create export-controls:
			
			// EXPORT:
			var exportLayer = new Element('div', {className:'exportLayer', id:this.instID+"_export", style:'display:none;'});
			exportDiv.insert(exportLayer);
			exportLayer.show();
			this.drawExportControls(exportLayer, 'export');
			
			// Linked tables:
			var fieldDiv = new Element('div', {className:'exportField'});
			exportLayer.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get('exportLinkedFields'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_exportLinked"});
			select.insert(new Element('option', {value:'1'}).update(this.controller.lang.get('exportLinkedFieldsYes')));
			select.insert(new Element('option', {value:'0'}).update(this.controller.lang.get('exportLinkedFieldsNo')));
			fieldDiv.insert(select);

			// what:
			var fieldDiv = new Element('div', {className:'exportField'});
			exportLayer.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get('exportdataSelect'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_exportWhat"});
			select.insert(new Element('option', {value:'currPage'}).update(this.controller.lang.get('exportCurrPage')));
			select.insert(new Element('option', {value:'allPage'}).update(this.controller.lang.get('exportAllPage')));
			fieldDiv.insert(select);
			
			var exportButton = new Element('button', {className:"crudderExportButton"}).update(this.controller.lang.get("startExport"));
			exportLayer.insert(exportButton);
			exportButton.observe('click', this.doExport.bind(this));
			
			
			
			
			// IMPORT
			var importLayer = new Element('div', {className:'exportLayer', id:this.instID+"_import", style:'display:none;'});
			exportDiv.insert(importLayer);
			this.drawExportControls(importLayer, 'import');

			var fieldDiv = new Element('div', {className:'exportField'});
			importLayer.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get('importdataSelect'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_importWhat"});
			select.insert(new Element('option', {value:'importNew'}).update(this.controller.lang.get('importDataSelectNewRecord')));
			select.insert(new Element('option', {value:'importSmart'}).update(this.controller.lang.get('importDataSelectSmart')));
			fieldDiv.insert(select);

			
			var exportButton = new Element('button', {className:"crudderExportButton"}).update(this.controller.lang.get("startImport"));
			importLayer.insert(exportButton);
			exportButton.observe('click', this.doExport.bind(this));
			

			
//			if (this.exportCallBack){
//				this.exportCallBack();
//			}
		},
		
		doExport : function(){
			//  gather values and let the dataFactory export the whole shebang;
			var args = $H({});
			args.set('fieldDelim', $(this.instID + "_export_fieldDelim").getValue());
			args.set('textDelim', $(this.instID + "_export_textDelim").getValue());
			args.set('decimalSign', $(this.instID + "_export_decimalSign").getValue());
			args.set('fieldNames', $(this.instID + "_export_fieldNames").getValue());
			args.set('exportLinkedFields', $(this.instID + "_exportLinked").getValue());
			args.set('what', $(this.instID + "_exportWhat").getValue());
			this.controller.factory.exportData(args);
			
		},
		
		drawExportControls:function(container,type){
			// field delim:
			var fieldDiv = new Element('div', {className:'exportField'});
			container.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get(type + 'fieldDelim'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_" + type + "_fieldDelim"});
			select.insert(new Element('option', {value:','}).update(','));
			select.insert(new Element('option', {value:';'}).update(';'));
			select.insert(new Element('option', {value:'tab'}).update('tab'));
			fieldDiv.insert(select);
			
			// text-delim:
			var fieldDiv = new Element('div', {className:'exportField'});
			container.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get(type + 'textDelim'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_" + type + "_textDelim"});
			select.insert(new Element('option', {value:'"'}).update('"'));
			select.insert(new Element('option', {value:"'"}).update("'"));
			fieldDiv.insert(select);
			
			// decimal-sign:
			var fieldDiv = new Element('div', {className:'exportField'});
			container.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get(type + 'decimalSign'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_" + type + "_decimalSign"});
			select.insert(new Element('option', {value:'.'}).update('.'));
			select.insert(new Element('option', {value:","}).update(","));
			fieldDiv.insert(select);
			
			// Fieldnames:
			var fieldDiv = new Element('div', {className:'exportField'});
			container.insert(fieldDiv);
			var label =  new Element('label', {className:'exportFieldLabel'}).update(this.controller.lang.get(type + 'fieldNames'));
			fieldDiv.insert(label);
			var select = new Element('select', {className:'exportSelection', id:this.instID + "_" + type + "_fieldNames"});
			select.insert(new Element('option', {value:'1'}).update(this.controller.lang.get('fieldNamesYes')));
			select.insert(new Element('option', {value:'0'}).update(this.controller.lang.get('fieldNamesNo')));
			fieldDiv.insert(select);
			
		},
		
		search : function(event){
			var searchFor = $(event.element().srcElem).getValue();
			if (this.searchCallBack){
				this.searchCallBack(searchFor);
			}
		},
		
		setItemsPerPage : function(event){
			if (this.callBackItemsPerPage){
				this.page = 0;
				this.itemsPerPage = event.element().getValue();
				this.callBackItemsPerPage(event.element().getValue());
//				this.refresh();
			}
		},
		
		drawNavItem : function(pageNum, pages, container){
			if (pageNum != pages){
				var text = (pageNum + 1 ) + ' - ';
			}else{
				var text = (pageNum + 1 );
			}

			var spanner = new Element('span', {className:'crudderNavigatorItem'}).update(text);
			if (pageNum == this.page) spanner.addClassName('on');
			spanner.pageNum = pageNum;
			container.insert(spanner);
			spanner.observe('click', this.navigate.bind(this))
		},

		navigateFromSelect : function(event){
			var element = event.element();
			this.page = parseInt(element.getValue());
			if (this.callBack){
				this.callBack(this.page);
			}
//			this.refresh();
		},
		
		navigate : function(event){
			var element = event.element();
			if (element.pageNum === '') return;
			this.page = parseInt(element.pageNum);
			if (this.callBack){
				this.callBack(this.page);
			}
//			this.refresh();
		},
		
		refresh : function(){
			var parent = $(this.instID +"_navigator").parentNode;
//			$(this.instID +"_navigator").remove();
			this.drawNavigator(parent);
		}

	})