// ---------------------------------------------------------
// ADMIN INIT
// ---------------------------------------------------------
function init () {
	initUI();
	getFilelist(window.config.dir);
	$('.sortthis').remove();
	$('body').click(function(e){
		var target = e.target;
		if (! $(target).closest('#container').length && ! $(target).closest('#metadataControl').length ) {
			forceExitEditMode();
		}
	});
	
	$('.data').live('click',function(e){
		var target = e.target;
		if (! $(target).is('input')) {
			toggleEditMode();
		}
	});
	window.lastfocustype == "INPUT";
	$('input').live('click',function(e){
		window.lastfocustype = e.target.nodeName;
	});
	
	$('.sortthis').live('click',function(e){
		window.lastfocustype = e.target.nodeName;
	});

}


function message(msg) {
		$('#dbAction_message').css({"display":"block"}).text(msg);
		setTimeout(function(){
			$('#dbAction_message').fadeOut(500);
		},3000)
}



function initUI() {
	$('#backup').click(function(){
		backupNow();
		message("Data has been backed up.")
	});
	
	$('#export').click(function(){
		var dir = "../"+window.config.dir
		var url = "php/export.php?directory="+dir
		
		location.href= url;
		message("The data has been or will be downloaded to your computer. Please look for 'exportedData.xls' when process is complete.")

	});
	
	
	
	$('#export2Json').click(function(){
		var dir = "../"+window.config.dir
		var url = "php/export2json.php?directory="+dir
		
		location.href= url;
		message("The data has been or will be downloaded to your computer. Please look for 'exported_JSON_Data.txt' when process is complete.")

	});
	
	
	
	
	
	$('#restoreNow').click(function(){
		restoreNow();
		message("Data has been restored.")
	});
	window.editing = false;
	window.altpressed=false;
	$('#addFieldButton').click(function(){
		addNewField("single");
	});
	
	$('#addFieldButtonAll').click(function(){
		addNewField("all");
	});
	window.lineItemUI = $('.lineitem:first','#readout').clone(true);
	$('.lineitem','#readout').remove();
	window.imageTile = $('.sortthis:first').clone();
	$('.sortthis').remove();
	
	$('#newField').css("display","none");
	
	window.imageZoom = 0;
	window.addFieldInFocus = {"newFieldNameInput":0,"newFieldValueInput":0};
	
	$(document).keydown(function(e){
		var enablezoom
		if (e.altKey) {
			mode = "all"
			enablezoom = 1;
		} else {
			mode = "single"
			enablezoom = 0;
		}
		
		if (e.keyCode == 13) {
			if (window.imageZoom == 1) {
				$('body').trigger('dblclick');
				window.imageZoom = 0;
			} else {
				if (window.addFieldInFocus.newFieldNameInput == 1 || window.addFieldInFocus.newFieldValueInput == 1 ) {
					addNewField(mode);
				} else {
					if (enablezoom == 1) {
						var id = "#img_"+$('#readout').data("fileObject").id;
						$(id).trigger('dblclick');
					} else {
						toggleEditMode();
					}
				}
			}
		}
		
		if (window.imageZoom == 1) {
			if (e.keyCode == 39) {
				
				cyclePic('next');
				return false
			}
			if (e.keyCode == 37) {
				cyclePic('prev');
				return false
			}
		}
		
		if (window.imageZoom == 0 && window.editing == true) {
			if (e.keyCode == 39) {
				if (e.target.tagName != "INPUT") {
					cycleEdit('next');
					return false
				}
			}
			if (e.keyCode == 37) {
				if (e.target.tagName != "INPUT") {
					cycleEdit('prev');
					return false
				}
			}
		}
		
	});


	$('#newFieldNameInput').focusin(function(){window.addFieldInFocus.newFieldNameInput = 1});
	$('#newFieldValueInput').focusin(function(){window.addFieldInFocus. newFieldValueInput = 1});

	$('#newFieldNameInput').focusout(function(){window.addFieldInFocus.newFieldNameInput = 0});
	$('#newFieldValueInput').focusout(function(){window.addFieldInFocus. newFieldValueInput = 0});
	
}

// ---------------------------------------------------------
// LOAD PIC DATA
// ---------------------------------------------------------

function getFilelist(dir) {
	var path = "../"+dir;
	
	if (window.usermode != "admin") {  // don't check the file system. Go straight to the file
		$.ajax({
		type: "GET",
		url: 'php/readIndex.php',
		data: {"directory":"../"+dir},
		dataType: "json",
		success: function(data){
			window.fileList = data.filelist;
			if (! $.isPlainObject(data) || typeof data.filelist == "undefined" || !data.filelist.length || ! $.isArray(data.filelist) ) {
				alert("Problem with indexfile. Please try again later.");
				return;
			}
			fileListComplete();
			}});
	
	} else {
		$.getJSON('php/json_ImageList.php',
			{"directory":path},function(data){
				
				window.fileList =[];
				var metadata = data;
				$.each(metadata, function(i, val){
					val.dir = dir;
					var fileObject =  new PicData(val);
					fileObject.addProp("dir", dir);
					fileObject.addProp("id", stripIllegal(fileObject.filename));
					window.fileList.push(fileObject);
					if (i == metadata.length-1) {
						getIndexFile (window.fileList);
					}
				});
		});
	}
}

// ---------------------------------------------------------
// ADMIN 
// ---------------------------------------------------------
// ---------------------------------------------------------
// GET IMAGE USING PHP GRAPHICS LIBRARY TO RESIZE
// ---------------------------------------------------------


function admin_generateImg(target, options, fileObject) {
	$(target).append($(window.imageTile).clone());
	$('.sortthis:last .imgdiv:last', '#container').append('<img></img>');
	$('img:last', target).data("id", options.id).data("fileObject", fileObject).data("index",options.index)
		.attr('src', toSrcString(options.dir, options.filename, options.title, options.maxwidth, options.maxheight, window.config.adminthumb_quality))
		.attr('id', "img_"+fileObject.id)
		.hover(
			function(){
				if (window.editing == false) {
					$('#readout').data("activeContainer", "#"+options.id);
					$('#readout').data("fileObject", fileObject).empty();
					$.each($(this).data('fileObject'), function(p, val){
						if (! $.isFunction(val)) {
							$('#readout').append($(window.lineItemUI).clone());
							$('.label:last','#readout').text(p);
							$('.data:last','#readout').text(unescape(val));
						}
					});				
				}
			},
			function(){
				if (window.editing == false) {
					 $('.lineitem').not(':first').remove();
					 $('.lineitem td').empty();
				}
		})
		.click(function(){
			toggleEditMode_onClick(fileObject)
		})
		.dblclick( function() {
			var url = fileObject.url
			showfile(url, options.id)
		});
		$('.sortthis:last', target).attr("id", options.id);
		$('.imgZoom:last', '#container').click(function(){
			var url = $(this).closest('.sortthis').find('img').data("fileObject").url;
			showfile(url, options.id)
		});
		
		$('.imgDelete:last', '#container').click(function(){
			var id = $(this).closest('.sortthis').find('img').data("fileObject").id;
			var url = $(this).closest('.sortthis').find('img').data("fileObject").url;
			var index = $(this).closest('.sortthis').find('img').data("index");
			
			$(this).closest('.sortthis').find('img').replaceWith('<div>Item Removed. Refresh this page to register all changes online.</div>');
			$(this).closest('.imgControl').find('.imgZoom').remove();
			$(this).remove();
			
			//showfile(url, options.id)
			deleteFile("../" + url);
			var deleteIndex;
			$.each(window.fileList, function(fli, flval){
				if (id == flval.id) {
					deleteIndex = fli
				}
				if (fli == fileList.length -1) {
					window.fileList.splice(fli,1);
					updateIndex();
					
				}
			});
		});
}


function deleteFile(url) {
	$.ajax({
		type: "POST",
		url: 'php/deletefile.php',
		data: {"directory":"../"+window.config.dir,
			"file":url
			},
		dataType: "json",
		success: function(data){
			alert(data)
			}
	});
}




function admin_generateAll(target, array, maxwidth, maxheight) {
	$.each(array, function(i, val){
		admin_generateImg(target, {
			"index":i,
			"filename":val.filename,
			"id":val.id,
			"title":val.filename,
			"maxwidth":maxwidth,
			"maxheight":maxheight,
			"dir": val.dir,
			"meta": val
		}, val);
		if (i == array.length-1) { 
			window.dragging = false;
			$("#container").sortable({
				forceHelperSize: true,
				forcePlaceholderSize: true,
				//containment: '#container',
				distance: 5,
				items: '.sortthis',
				tolerance: 'pointer',
				//opacity: 0.6,
				//helper: 'clone',
				stop: function(event, ui){
					setTimeout(function(){window.dragging = false;},50);
					onSlotChange(); // update slotInfo
				},
				start: function(event, ui){
					window.dragging = true;
				}
			});
		}
	});
}


function onSlotChange() {
	window.newSlots = $("#container").sortable( "toArray" );
	$.each(window.newSlots, function(i, val){
		$.each(window.fileList, function(fi, fval){
			if (fval.id == val) {
				fval.addProp("slot", i)
			}
			if (i == window.newSlots.length-1 && fi==window.fileList.length-1) {
				orderbySlots()
			}
		});
	});
}

function orderbySlots(){
	
	$.each(window.fileList, function(i, val){
		if (val.slot == "undefined") {
			val.slot = window.fileList.length-1;
		}
		if (i ==  window.fileList.length-1) {
			window.fileList = window.fileList.sort(function(a, b){ return a.slot-b.slot});
			updateIndex();
		}
	});
}



// ---------------------------------------------------------
// SETUP PAGES 
// ---------------------------------------------------------

function setupPages(itemLimit) {
	// create array of arrays
	var pages = [];
	var numPages = 0;
	$.each(window.fileList, function(i, val){
		if (i == 0) {
			numPages++
			pages.push([]);
		}
		if (i< itemLimit * numPages) {
			pages[numPages-1].push(val);
		} else {
			numPages++
			pages.push([]);
			pages[numPages-1].push(val);
		}
		if (i== window.fileList.length-1) {
			window.pages = pages;
			drawPager()
		}
	});
}


function drawPager() {
	window.activePageIndex = 0;
	var pageitem = $('#pager .page:first').clone();
	$('#pager .page').remove();
	$.each(window.pages, function(i, val){
		$('#pager').append($(pageitem).clone());
		$('#pager .page:last')
			.text(i+1)
			.data("pageIndex", i)
			.click(function(){
				var activePage = $(this).data("pageIndex");
				//alert(activePage)
				window.activePageIndex = activePage;
				populateThumbs(window.activePageIndex);
			});
		if (i == window.pages.length-1) {
			if (window.pages.length == 1) {
					$('#pager').css("display","none");
			}
			
			
			if (window.usermode == "splash") {
				populateSplash ()
			} else {
				populateThumbs(window.activePageIndex);
			}
			
		}
	});
}


function populateSplash () {
	var picObj = window.pages[0][0];
	var src = toSrcString(picObj.dir, picObj.filename, "title", 700, 500, window.config.splash_quality);
	 $("#splashPic").empty().append('<img />').click(function(){
	 
	 if (window.newdir != null) {
			location.href = "paintings.html?dir="+window.newdir;
	} else {
		location.href = "paintings.html"
	}
	 	
	 });
	 
	 /*.qtip({
			content: 'Click to view work',
			//position: { target: 'mouse' },
			show: { delay: 0 },
			effect: { length: 50 },
			style: { 
				'font-family': "Arial",
				'font-size': 9,
				padding: 5,
				// background: '#A2D959',
				"color": '#660000',
				textAlign: 'center'
			},
			position: {adjust: { x: -40, y: -40 },  target: 'mouse' }
   		
		
	});	
	*/
	$("#splashPic img").attr("src", src );
}


function populateThumbs(activePage){
	highlightPageLink()
	var thumbnail = $('.thumb:first', "#thumbs").clone();
	 $("#thumbs").empty();
	var currentArray = window.pages[activePage];
	$.each(currentArray, function(i, val){
		$("#thumbs").append($(thumbnail).clone());
		var phpString = toSrcString(val.dir, val.filename, "title", 80, 80, window.config.thumb_quality);
		var imgURLString = "url("+phpString+")"
		$('.thumb:last', "#thumbs")
			.css("backgroundImage", imgURLString)
			.data("picIndex", i)
			.click(function(){
				selectPic($(this).data("picIndex"));
			});
		if(i == currentArray.length-1) {
			$("#thumbs").append("<br / class='clear'>")
			selectPic(0);
		}
	});
}



function highlightPageLink() {
	$('.page', "#pager").removeClass('pageHighlight');
	$('.page', "#pager").eq(window.activePageIndex).addClass("pageHighlight");
}



function selectPic(picIndex) {
	var imageObj = window.pages[window.activePageIndex][picIndex]
	var image = toSrcString(imageObj.dir, imageObj.filename, "ep", 550, 425, window.config.selectedPic_quality)
	var paintingBox = $("#paintingActive").clone();
	$("#paintingActive").fadeOut(100, function() {
		var lineItem = $(".lineItem:first","#paintingActive").clone();
		 $(".label","#paintingActive").empty();
		 var numImgObjPropCount = 0
		$.each(imageObj, function (p, val){
			numImgObjPropCount++
			var numImgObjProps = $.param(imageObj).split('&').length;
			var adminFields = window.config.adminFields
			
			var numprops = $.param(adminFields).split('&').length;
			var count = 0;
			var pDataType = "normal";
			
			if (! $.isFunction(val) ) {
				 $.each(adminFields, function(i, ival){
				 	count++;
				 	if (p == i) {
				 		if (ival == "hidden") {
				 			pDataType = "hidden";
				 		}
				 		if (ival == "omit") {
				 			pDataType = "omit";
				 		}
				 	}
				 	
				 	if (count == numprops) {
				 		if (pDataType != "omit") {
				 			$(".label","#paintingActive").append($(lineItem).clone());
							$(".lineItem:last","#paintingActive").text(unescape(val)).attr("id", p);
							if (pDataType == "hidden") {
								$(".lineItem:last","#paintingActive").addClass("noshow");
							}
							if (p == "discount") {
								$(".lineItem:last","#paintingActive").addClass("redText");
							}
							if (window.login == false ) {
				 					$(".noshow").css({"display":"none"});
							}
							
							
								
				 		}
				 	}
				 });
			}
			if (numImgObjPropCount == numImgObjProps) {
				if (! $(".lineItem","#paintingActive").length) {
						$(".label","#paintingActive").append($(lineItem).clone());	
						$("#title").text('Undefined Title');	
				}
			
			}
		});
		
		$(".image","#paintingActive").html('<img/>');
		$("img","#paintingActive").unbind('load').bind("load", function(){
			$("#paintingActive").fadeIn(100);
		});
		$("img","#paintingActive").attr('src', image );
		$(".zoom, img","#paintingActive")
			.data("url", imageObj.url)
			.unbind('click').click(function(){
				zoom($(this).data("url"));
			});
		$(".zoom","#paintingActive").css("display","block");
	});
	highlightThumb(picIndex);
}





function highlightThumb(picIndex) {
		$('.thumb', '#thumbs').removeClass("thumbHightlight").eq(picIndex).addClass("thumbHightlight");
}


// ---------------------------------------------------------
// VIEWER 
// ---------------------------------------------------------

function zoom(url) {
	$('#clickToReturn').remove();
			$('#mainborder').fadeOut("fast", function(){
			$('#bkgdChooser').css("display","none");
				$('body').css("background-color","#333333").append('<div id="previewArea"><div id="preview"><img id="previewImg"></img></div></div>');
				$('#preview').draggable();
				$('#previewImg').attr("src", url);
				$('body').append('<div id="clickToReturn">Click anywhere to return</div>');
				
				$('#clickToReturn').center();
				setTimeout(function(){
					$('#clickToReturn').fadeOut(2400, function(){
						
						$(this).remove();
					});
				},500); 
				
				$('body').click( function() {
					
					$('#clickToReturn').remove();
					$('#previewArea').fadeOut("fast", function(){
						$('#bkgdChooser').css("display","block");
						$('body').css("background-color","#211D11");
						$('#previewArea').remove();
						$('#mainborder').fadeIn("fast");
						$('body').unbind('click');
					});
				});
			});
}



function fadeClickToReturn() {
	//
}



jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

// ---------------------------------------------------------
// PIC FUNCTIONS 
// ---------------------------------------------------------


function fileListComplete() { // called from a timeout. Don't want the code on the metadata page.
	if (!window.usermode || window.usermode != "admin") {
		setupPages(14)
	} else {
		admin_generateAll('#container', window.fileList, 150, 100)
	}
}

function returnObject(id) {
	$.each(window.fileList, function(i, val){
		if (id == val.id) {
			return val;
		}
	});
}




function toSrcString(dir, filename, title, maxwidth, maxheight, quality) {
	var script = 'php/getThumb.php?';
	var path = 'imagePath=../'+escape(dir)+'/'+escape(filename);
	var srcTitle = "&title=" + escape(title);
	var maxwidth = "&maxwidth=" + maxwidth;
	var maxheight = "&maxheight=" + maxheight;
	var quality = "&quality=" + quality;
	var src = script+path+srcTitle+maxwidth+maxheight+quality;
	return src;
}


