
// ---------------------------------------------------------
// TEST BUILDING NEW METADATA
// ---------------------------------------------------------
// See Notes.txt for info on these functions

function PicData(data) {
	var thisobject = this;
		$.each(data, function(prop, val){
			thisobject[prop] = val;
		});
	if (data.filename) {
		this.id  = data.filename.replace(".","");
	}
	

	
	//if (data.dir) {
		this.url  = window.config.dir+"/"+data.filename;
	//}
	
	
	this.gdImagePath = toSrcString(window.config.dir, data.filename, "ep", 550, 425, window.config.selectedPic_quality);
	
	
	
	this.addProp = function(newProperty, newValue){
		this[newProperty] = escape(newValue);
	};
	this.addProps = function(dataObject){
		var thisobject = this;
		$.each(dataObject, function(prop, val){
			thisobject[prop] = escape(val);
		});
	};
	this.deleteProp = function(prop){
		delete this[prop];
	};
}

//  Alternate method to add properties (or multiple properties) after instantiation

function attachProps(object, dataObject) {
	$.each(dataObject, function(prop, val){
		object[prop] = val;
	});
}


// ---------------------------------------------------------
// COMPARE AND UPDATE LISTS
// ---------------------------------------------------------
//	Check to see if records or files are missing. Update File list. Create copy of fileList, stripped from methods. Write the new index

function getIndexFile (serverList) {
	var numfiles = 0;
	var newlist = [];
	var sList = serverList;
	//var dir = serverList[0].dir;
	var dir = window.config.dir;
	
	$.ajax({ // GET FILEIST FROM SERVER
		type: "GET",
		url: 'php/readIndex.php',
		data: {"directory":"../"+dir},
		dataType: "json",
		success: function(data){
				if (data) {
					//if (! $.isPlainObject(data) || typeof data.filelist == "undefined" || !data.filelist.length || ! $.isArray(data.filelist) ) {
					if (typeof data.filelist == "undefined" || !data.filelist.length || ! $.isArray(data.filelist) ) {
					
						//if (! $.isPlainObject(data)){
						//	alert('not plain object')
						//}
						if (typeof data.filelist == "undefined"){
							alert('data.filelist == undefined')
						}
						if (!data.filelist.length){
							alert('no length of filelist')
						}
					
							if (! $.isArray(data.filelist)){
							alert('not an array')
						}		
					
					
					
						alert("Problem with indexfile. Attempting to reinit indexfile. Unfortunately, metadata is lost. If page does not automatically reload, please reload page.");
						$.getJSON('php/initIndex.php',
							{"directory":"../"+dir},function(data){
							//alert("done initing. page will reload.");
							//location.href = "index.html"
							location.reload();
						});
						return;			
				
				} else {
					//suppress null that occasionally comes
				}

			}
			
			
			
			var newslotnum = data.filelist.length-1
			
			$.each(data.filelist, function(ii, ival){ 
				$.each(sList, function(si, sval){
					if (ival.filename == sval.filename) {
					numfiles++;
						ival.dir = dir;
						ival.url  = dir+"/"+ival.filename;
						newlist.push(ival); // get only records that are on the server, but keep metadata intact
						// update fileList
						$.each(ival,function(prop, propval){
							window.fileList[si][prop] = propval;
						});
					}
					if ((si == sList.length-1) && (ii == data.filelist.length-1)) {
						// now check to see if server has files not in the indexFile
						$.each(sList, function(si2, sval2){	// data from server
							var match = 0;
							$.each(data.filelist, function(ii2, ival2){ 	// data from indexfile
								if (sval2.filename == ival2.filename) {
									match = 1; // there is a match. file is not new
								}
								if (ii2 == data.filelist.length-1) { // done checking serverfileItem against indexFile item
									if (match == 0) { // if still no match, then file IS NEW.
										newslotnum++
										numfiles++;
										sval2.dir = dir;
										sval2.url  = dir+"/"+sval2.filename;
										sval2.slot = newslotnum;
										
										$.each(window.config.defaultFields, function(fi, fval){
											sval2[fi] = fval;
											
										});
										
										
										
										
										newlist.push(sval2);
									}
									// if done looping through everything
									if ((si2 == sList.length-1) && (ii2 == data.filelist.length-1)) {
									
										orderbySlots();
										
										
										
										setTimeout(function(){
												
												fileListComplete(); // go ahead and generate images
										}, 100);
										
										
										
										
										
									}
								}
							});
						});
					}
				});
			});
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("problem with indexfile. Attempting to reinit. Please reload page after initing")
			$.getJSON('php/initIndex.php',
				{"directory":"../"+dir},function(data){
				return
			});
			return
		}
	});
}

// ---------------------------------------------------------
//  METADATA KEYS
// ---------------------------------------------------------

function getKeys(filelist) {
	var keyArray = [];
	$.each(filelist, function(i, val){
		// -------------------------------------
		// build list of all keys in existance
		// -------------------------------------
		$.each(val, function(p, pval){
			if ($.inArray(p, keyArray) == -1) {
				if (! $.isFunction(pval) ) {
					keyArray.push(p)
				}
			}
		});
		
		// -------------------------------------
		// right now just put in global so I can see
		// -------------------------------------	
		if (i == filelist.length-1) {
			window.currentKeys = keyArray;
			//cleanAndAsssignMissingKeys();
		}

	});
}



function cleanAndAsssignMissingKeys() {
	var clean = []
	window.functionprops = {}
	$.each(window.fileList, function(i, val){
		var newObj = {};
		$.each(val, function(p, pval){
			if ($.isFunction(pval) ) {
				functionprops[p] = pval;
			} else {
				newObj[p]=pval;
			}
		});
		clean.push(newObj);
		if (i == window.fileList.length-1) {
			execAsssignMissingKeys(clean)
		}
	});
}


function execAsssignMissingKeys(cleanlist) {
	if (! window.newfieldorder) {
		window.newfieldorder = 	window.currentKeys;
	}

	$.each(cleanlist, function(i, val){
		var thiskeylist = [];
		var propcount = 0;
		var numprops = $.param(val).split('&').length;     // this craps out right now because there are props that are functions.
		
		// build local keylist and add new keys to objects
		// that are found to not have keys
		
		$.each(val, function(p, pval){
			propcount++;
			thiskeylist.push(p);
			if (propcount == numprops) {
				// done building local keylist
				
				// now check if global keylist has some keys not
				// in local keylist
				var neworderedObject = {};
				$.each(window.newfieldorder, function(a, aval){
					if ($.inArray(aval, thiskeylist) == -1) {
						// add the key to the object
						//val[aval] = "EMPTY"
						neworderedObject[aval] = aval+"_undefined"
					} else {
						//delete neworderedObject[aval];
						neworderedObject[aval] = val[aval];
					}
					
					if (a == window.newfieldorder.length-1) {
						cleanlist[i] = neworderedObject;
					}
					
					if (i == cleanlist.length - 1 && a == window.newfieldorder.length-1) {
						// do something like write the new filelist to file
						//window.testnewkeylistwithnewentries = cleanlist;
						// addback the props
						
						
						$.each(cleanlist, function(cli, clval){
							// add back the props that are functions	
							$.each(window.functionprops, function(fpi, fpval){
								clval[fpi] = fpval;
							});
							 $('.sortthis', '#container').eq(cli).find('.imgdiv').find('img').data("fileObject", clval);
						});
						
						window.fileList = cleanlist
						window.testtelksjdlfsjdlkfj = neworderedObject;
						updateIndex();
						
						
						message("The data has been normalized.")
						
					}
				});
			}
		});	
	});
}



function reorderKeys_single(element) {
	var fileobject = $('#readout').data("fileObject");
	
	var index = fileobject.slot;
	var newFileObject = {}
	var functionprops = {}
	$.each(fileobject, function(p, pval){
		if ($.isFunction(pval) ) {
			functionprops[p] = pval;
		}
	});
	
	
	
 	$.each(window.newfieldorder, function(i, val){
 		newFileObject[val] = fileobject[val]
 		if (i == window.newfieldorder.length-1) {
 			$.each(functionprops, function(fp, fpval){
 				newFileObject[fp] = fpval;
 			});
 			 $('#readout').data("fileObject", newFileObject);
 			  $('.sortthis', '#container').eq(index).find('.imgdiv').find('img').data("fileObject", newFileObject);
 			  
 			 // window.wtf =  $('#readout').data("fileObject");
 			 window.fileList[index] = newFileObject;
 			updateIndex();
 		}
 		
 	});
 
 
 

	
 
}


// ---------------------------------------------------------
// READ WRITE INDEX FILE
// ---------------------------------------------------------

function getIndex(dir) {
	$.getJSON('php/readIndex.php',
		{"directory":"../"+dir},function(data){
			if (data.inited == "false") {
				testjson = [{"lorem":"lorem"}];
			}
	});
}

function writeIndex(dir, newJsonData) {
	var newdata = {}
	newdata.filelist = {"filelist":newJsonData};
	newdata.dir = "../"+dir;
	$.post('php/writeIndex2.php', newdata, function(data, textStatus) {
  			//data contains the JSON object
  		//textStatus contains the status: success, error, etc
  		
  		
  		debug('foofoofoo!')
  		
  		
  		
  		if (data) {
			if (data.status == "done") {
				debug('jsonstatus=done!')
				 if (window.hasuploaded == 1) {
					location.href = 'paintings.html'
				} 
			} else {
				alert("failed to write index in writeIndex()")
			}
  		} else {
  			alert('writeIndex2.php returns null')
  			
  		}
	}, "json");
}


function updateIndex() {
	var fileListCopy = [];
	$.each(window.fileList, function(i, val){
		var newObject = {};
		$.each(val, function (p, pval){
			if (! $.isFunction(pval) ) {
				newObject[p] = pval;
			}
		});
		fileListCopy.push(newObject);
		if (i == window.fileList.length-1) {
			writeIndex(window.config.dir, fileListCopy);
		}
	});
}

// ---------------------------------------------------------
// UTILITY
// ---------------------------------------------------------


function stripIllegal(text){
	text =  text.replace(/ /gi,"");
	text =  text.replace(/_/gi,"");
	text =  text.replace(/-/gi,"");
	return text.replace(/\./gi,"");
}











