dojo.provide("umat.data.ItemFileReadStore");

dojo.require("dojo.data.ItemFileReadStore");

// Treure accents, treballem en ISO-8859-1, per� el fitxer est� codificat en UTF8
String.prototype.removeAccents = function ()
{
	var __r = {
			'À':'A','Á':'A',
			'È':'E','É':'E',
			'Ì':'I','Í':'I','Ï':'I',
			'Ò':'O','Ó':'O',
			'Ù':'U','Ú':'U','Ü':'U',
			'Ñ':'N'};
	
	return this.replace(/[ÀÁÈÉÌÍÏÒÓÙÚÜ]/gi, function(m){
		var ret = __r[m.toUpperCase()];
					
		if (m === m.toLowerCase())
			ret = ret.toLowerCase();

		return ret;
	});
};

dojo.declare(
	"umat.data.ItemFileReadStore",
	[dojo.data.ItemFileReadStore],
	{

		// @Override example
//		_openResultList: function(/*Object*/ results, /*Object*/ dataObject){
//   			// do my stuff, then...
//   			this.inherited("_openResultList", arguments);
//		},

		containsValue: function(/* item */ item, 
								/* attribute-name-string */ attribute, 
								/* anything */ value){
			//	summary: 
			//		See dojo.data.api.Read.containsValue()
			var regexp = undefined;
			if(typeof value === "string"){
				regexp = dojo.data.util.filter.patternToRegExp(value, false);
			}
			return this._containsValue(item, attribute, value, regexp); //boolean.
		},
	
		_containsValue: function(	/* item */ item, 
									/* attribute-name-string */ attribute, 
									/* anything */ value,
									/* RegExp?*/ regexp){
			//	summary: 
			//		Internal function for looking at the values contained by the item.
			//	description: 
			//		Internal function for looking at the values contained by the item.  This 
			//		function allows for denoting if the comparison should be case sensitive for
			//		strings or not (for handling filtering cases where string case should not matter)
			//	
			//	item:
			//		The data item to examine for attribute values.
			//	attribute:
			//		The attribute to inspect.
			//	value:	
			//		The value to match.
			//	regexp:
			//		Optional regular expression generated off value if value was of string type to handle wildcarding.
			//		If present and attribute values are string, then it can be used for comparison instead of 'value'


			return dojo.some(this.getValues(item, attribute), function(possibleValue){
				if(possibleValue !== null && !dojo.isObject(possibleValue) && regexp){
					if(possibleValue.toString().removeAccents().match(regexp)){
						return true; // Boolean
					} else if(possibleValue.toString().match(regexp)){
						return true; // Boolean
					}
				} else if(value === possibleValue.removeAccents()){
					return true; // Boolean
				} else if(value === possibleValue){
					return true; // Boolean
				}
			});
		},
		
		_forceLoad: function(){
			alert("ForceLoad");
		},

	_fetchItems2: function(	/* Object */ keywordArgs, 
							/* Function */ findCallback, 
							/* Function */ errorCallback){
							
		//	summary: 
		//		See dojo.data.util.simpleFetch.fetch()
		var self = this;
		var filter = function(requestArgs, arrayOfItems){
			var items = [];
			if(requestArgs.query){
				var ignoreCase = requestArgs.queryOptions ? requestArgs.queryOptions.ignoreCase : false; 

				//See if there are any string values that can be regexp parsed first to avoid multiple regexp gens on the
				//same value for each item examined.  Much more efficient.
				var regexpList = {};
				for(var key in requestArgs.query){
					var value = requestArgs.query[key];
					if(typeof value === "string"){
						regexpList[key] = dojo.data.util.filter.patternToRegExp(value, ignoreCase);
					}
				}

				for(var i = 0; i < arrayOfItems.length; ++i){
					var match = true;
					var candidateItem = arrayOfItems[i];
					if(candidateItem === null){
						match = false;
					}else{
						for(var key in requestArgs.query) {
							var value = requestArgs.query[key];
							if (!self._containsValue(candidateItem, key, value, regexpList[key])){
								match = false;
							}
						}
					}
					if(match){
						items.push(candidateItem);
					}
				}
				findCallback(items, requestArgs);
			}else{
				// We want a copy to pass back in case the parent wishes to sort the array. 
				// We shouldn't allow resort of the internal list, so that multiple callers 
				// can get lists and sort without affecting each other.  We also need to
				// filter out any null values that have been left as a result of deleteItem()
				// calls in ItemFileWriteStore.
				for(var i = 0; i < arrayOfItems.length; ++i){
					var item = arrayOfItems[i];
					if(item !== null){
						items.push(item);
					}
				}
				findCallback(items, requestArgs);
			}
		};

		if(this._loadFinished){
			filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
		}else{

			if(this._jsonFileUrl){
				//If fetches come in before the loading has finished, but while
				//a load is in progress, we have to defer the fetching to be 
				//invoked in the callback.
				if(this._loadInProgress){
					this._queuedFetches.push({args: keywordArgs, filter: filter});
				}else{
					this._loadInProgress = true;
					var getArgs = {
							url: self._jsonFileUrl, 
							handleAs: "json-comment-optional"
						};

        OX.AJAST.call(
//          'http://babylon/web/umat/carrers/carrers.php?action=llista'
		  self._jsonFileUrl,
          'callback',
          function(success, data){
          	if (success) {
						try{
							self._getItemsFromLoadedData(data);
							self._loadFinished = true;
							self._loadInProgress = false;
							
							filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions));
							self._handleQueuedFetches();
						}catch(e){
							self._loadFinished = true;
							self._loadInProgress = false;
							errorCallback(e, keywordArgs);
						}
			} else {
						self._loadInProgress = false;
						alert('error: ');
//						errorCallback(error, keywordArgs);
						errorCallback(new Error("umat.data.ItemFileReadStore: error fetching items."), keywordArgs);
			}
					});
/*
					var getHandler = dojo.xhrGet(getArgs);
					getHandler.addCallback(function(data){
						try{
							self._getItemsFromLoadedData(data);
							self._loadFinished = true;
							self._loadInProgress = false;
							
							filter(keywordArgs, self._getItemsArray(keywordArgs.queryOptions));
							self._handleQueuedFetches();
						}catch(e){
							self._loadFinished = true;
							self._loadInProgress = false;
							errorCallback(e, keywordArgs);
						}
					});
					getHandler.addErrback(function(error){
						self._loadInProgress = false;
						errorCallback(error, keywordArgs);
					});
*/
				}
			}else if(this._jsonData){
				try{
					this._loadFinished = true;
					this._getItemsFromLoadedData(this._jsonData);
					this._jsonData = null;
					filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
				}catch(e){
					errorCallback(e, keywordArgs);
				}
			}else{
				errorCallback(new Error("dojo.data.ItemFileReadStore: No JSON source data was provided as either URL or a nested Javascript object."), keywordArgs);
			}
		}
	},
			
		setOpcions: function(data){
			this._loadFinished = true;
			this._getItemsFromLoadedData(data);
			this._jsonData = null;
			filter(keywordArgs, this._getItemsArray(keywordArgs.queryOptions));
			this._loadInProgress = false;

//			this._getItemsFromLoadedData(data);
			alert("noves dades carregades");
		},
		
		setUrl: function(url) {
			this._jsonFileUrl = url;
		}


	}
);
