// ---------------------------------------------------------
//  INIT
// ---------------------------------------------------------



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


function initViewer(){
	window.uploadIndicator = $(".uploadIndicator").clone();
	$(".uploadIndicator").remove();
	
	$("#legacy_site_link").css("display","none");
	checkContentEditable()
	initViewerEdit_exit();
	registerAdminTooltips();
	
	
	
	if (window.config.generateSplash == true) {
		$("#splashPic").empty();
	}
	
	$('#epName').click(function(){
		location.href="index.html"
	});
	if (window.newdir != null) {
		$('.links a, ').each(function(){
			var href = $(this).attr('href');
			var modhref = href+"?dir="+newdir;
			$(this).attr('href',modhref);
			$('#epName').unbind('click').click(function(){
				location.href = 'index.html?dir='+newdir;
			});
		});
	}
				
	$('#color1').click(function(){
		var bkgd = ("#ffffff");
		 $('#paintingActive').animate({ backgroundColor: bkgd }, 500);
	});
	$('#color2').click(function(){
		var bkgd = $(this).css("backgroundColor");
		$('#paintingActive').animate({ backgroundColor: bkgd }, 500);
	});
	$('#splashpage #subtitle, #paintingsPage .subtitle').text(window.config.mainTitle);
	$('#toc_title').text(window.config.sectionTitle);
	$('#splashTitle').text(window.config.shortTitle);
	bindClickToEnter();
	$('#bio .subtitle').text(window.config.bioTitle);
	$('#contact .subtitle').text(window.config.contactTitle);
	 Cufon.now()
		loginInit();
		
		$('#loginLink').click(function(){
			$('#loginLink').css("display", "none");
			$('#login').css("display", "block");
			$('body').unbind('mousedown').mousedown(function(e){
					if (e.target.id != "password" && e.target.id != "goButton") {
								loginBoxRemove();
					}
			});
			return false
		})
		.qtip({
			content: 'Log in to view prices',
			//position: { target: 'mouse' },
			show: { delay: 0 },
			effect: { length: 50 },
			style: { 
				'font-family': "Arial",
				'font-size': 9,
				padding: 5,
				"color": '#660000',
				textAlign: 'center'
			},
			position: {adjust: { x: -40, y: -40 }}
		});	
}


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);
	if (window.config.generateSplash == true) {
		$("#splashPic").append('<img />');
		$("#splashPic img").attr("src", src );
	}
	$("#splashPic").click(function(){
	//$("#splashPic").empty().append('<img />').click(function(){
	 if (window.newdir != null) {
			location.href = "paintings.html?dir="+window.newdir;
			} else {
				location.href = "paintings.html"
			}
	 });
}


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)
			.attr("id", val.id)
			.click(function(){
				selectPic($(this).data("picIndex"));
			});
		if(i == currentArray.length-1) {
			$("#thumbs").append("<br / class='clear'>")
			selectPic(0);
			if (window.adminallowed == 1) {
				initReorder();
				initDropzone();
			}
		}
	});
}


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", window.config.picWidth, window.config.picHeight, window.config.selectedPic_quality)
	var paintingBox = $("#paintingActive").clone();
	$(".label","#paintingActive").data("id",imageObj.id);
	$("#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" || p == "special" || p == "status") {
								$(".lineItem:last","#paintingActive").addClass("redText");
							}
							
							
							// ---------------------------------------------------------
							// EDIT 
							// ---------------------------------------------------------	
							
							
							$(".lineItem:last","#paintingActive")
								.click(function(){
									if (window.adminallowed == 1) {
										var value = escape($(this).text());
										var pic_id = $(this).closest('.label').data('id')
										var field_id = $(this).attr('id');
										var inputstr =  '<div><input type="text" class="smlInput" /></div>'
										
										
										
										$(this).after(inputstr).css("display","none");
										$(this).next().find('input').data("pic_id",pic_id).data("field_id",field_id).val(unescape(value));
										/*
										$(this).next().mouseleave(function(){
											var newvalue = $(this).find('input').val()
											$(this).prev().text(newvalue).css("display","block")
											$(this).remove();
											
											$.each(window.fileList, function(i, val){
												if (val.id == pic_id) {
													val[field_id] = newvalue
													updateIndex();
												}
											});
										});
										*/
									}
									return false
							});
							
							// ---------------------------------------------------------
							// END EDIT 
							// ---------------------------------------------------------														
							
							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 initViewerEdit_exit() {
	$(document).click(function(e){
		window.test = e.target.className
		if ( e.target.className != "smlInput") {
			newMetadata()
		}
	})
	
	$(document).keypress(function(e){
			if (e.keyCode == 13) {
				if ( e.target.className == "smlInput") {
					newMetadata()
				}
			}
	});
	
}


function newMetadata() { // fires on document click
		var num = $('.smlInput', '#paintingActive').length;
		$('.smlInput', '#paintingActive').each(function(ind, elem){
			var pic_id = $(this).data('pic_id')
			var field_id = $(this).data('field_id')
			var newvalue = escape($(this).val());
			$(this).parent().prev().text(unescape(newvalue)).css("display","block")
			$(this).parent().remove();
			$.each(window.fileList, function(i, val){
				if (val.id == pic_id) {
					val[field_id] = newvalue
				}
			});
			if (ind == num-1) {
				updateIndex();
			}
		});
}



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


// ---------------------------------------------------------
// ZOOM 
// ---------------------------------------------------------

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');
					});
				});
			});
}





// ---------------------------------------------------------
// SLOT 
// ---------------------------------------------------------



function initReorder() {
	$("#thumbs").sortable({
				forceHelperSize: true,
				forcePlaceholderSize: true,
				//containment: '#container',
				distance: 5,
				items: '.thumb',
				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 = $("#thumbs").sortable( "toArray" );
	$.each(window.newSlots, function(i, val){
		$.each(window.fileList, function(fi, fval){
			if (fval.id == val) {
				pagelength = window.pages[0].length;
				slotOffset = pagelength * activePageIndex;
				fval.slot = i + slotOffset;
			}
			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();
		}
	});
}


// ---------------------------------------------------------
// upload 
// ---------------------------------------------------------

function initDropzone() {
window.numfilesfinished = 0;
		$('#paintingsPage').filedrop({
						url: 'php/upload.php',              // upload handler, handles each file separately
						paramname: 'user_file',          // POST parameter name used on serverside to reference file
						
						data: { 
							//directory: "../"+(window.config.dir)+"/"           // send POST variables
							
							
							//directory: "../2010/"     // send POST variables
							"dir": "../"+(window.config.dir)+"/",     // send POST variables
							//param2: "empty"
							
							//directory: function(){
							//	return "../"+(window.config.dir)+"/"; // calculate data at time of upload
							//}
						},
						
						
						error: function(err, file) {
							switch(err) {
								case 'BrowserNotSupported':
									alert('browser does not support html5 drag and drop')
									break;
								case 'TooManyFiles':
									// user uploaded more than 'maxfiles'
									alert('TooManyFiles')
									break;
								case 'FileTooLarge':
									alert('FileTooLarge')
									// program encountered a file whose size is greater than 'maxfilesize'
									// FileTooLarge also has access to the file which was too large
									// use file.name to reference the filename of the culprit file
									break;
								default:
									break;
							}
						},
						maxfiles: 25,
						maxfilesize: 20,    // max file size in MBs
						dragOver: function() {
							// user dragging files over #dropzone
						},
						dragLeave: function() {
							// user dragging files out of #dropzone
						},
						docOver: function() {
							// user dragging files anywhere inside the browser document window
						},
						docLeave: function() {
							// user dragging files out of the browser document window
						},
						drop: function() {
							// user drops file
							$('#uploadingMessage').css("display","block").text('Uploading...').append('<br/>');
							debug("init numfilesfinished.....");
							window.numfilesfinished = 0;
						},
						uploadStarted: function(i, file, len){
						
							//window.test = [];
							// a file began uploading
							// i = index => 0, 1, 2, 3, 4 etc
							// file is the actual file of the index
							// len = total files user dropped
							
							
							window.numfilesDropped = len;
							//$('#dropzone').text("Currently uploading "+numfilesfinished+" files.");
							
							
							
							// move to plugin
							//for(var li=0; li< len; li++) {
							//	uploadProgressInit(li, file);
							//}
						},
						
						uploadFinished: function(i, file, response, time) {
							// response is the data you got back from server in JSON format.
							
							
							//window.test.push(file)
							
							$('#uploadingMessage').append('<br/>')
									.append('Finished uploading file: ' +file.fileName).append('<br/>')
									.append('Time: '+time+'ms').append('<br/>')
									.append('Size: '+file.size+'bytes').append('<br/>')
									.append('Type: '+file.type).append('<br/>')
									
							debug("incrementing numfilesfinished.....");
							//window.numfilesfinished = window.numfilesfinished + 1;
							window.numfilesfinished = i+1
							if (window.numfilesDropped == window.numfilesfinished) {
								//alert ("Uploaded "+numfilesfinished+" files.")
									//$('#dropzone').text("Sucessfully Uploaded "+numfilesfinished+" files.");
								//	$('.sortthis', "#container").remove();
								
								return
								$('#uploadingMessage').append('<br/>')
									.append('"Finished last upload! Reloading page now."')
									.delay(2000)
									.fadeOut(200);
									
								debug("Finished last upload!!")
								
								
									// give php some time to move file?
									setTimeout (function(){
										delayed_json_imageList();
									}, 500);
							}
						},
						progressUpdated: function(i, file, progress) {
							// this function is used for large files and updates intermittently
							// progress is the integer value of file being uploaded percentage to completion
							uploadProgress(i, file, progress);
						},
						speedUpdated: function(i, file, speed) {
							// speed in kb/s
						}
				});
		}
// ---------------------------------------------------------
// ADD UPLOAD PROGRESS
// ---------------------------------------------------------


function uploadProgressInit(i, file){
	var id = 'upload'+i;
	var jqid = "#"+id;
	$('#uploadingMessage').append($(window.uploadIndicator).clone());
	$('.uploadIndicator:last','#uploadingMessage').attr("id",id);
	$(".uploadReadout",jqid).text(file);
	window.myfile =  file;
}


function uploadProgress(i, file, progress){

	var id = 'upload'+i;
	var jqid = "#"+id;
	
	
	
	var totalWidth = $(jqid).innerWidth(true);
	
	var percent = (Math.floor((totalWidth / 100)* progress)) + 'px'
	debug(progress+"<br / >")
	debug(percent+"<br / >")
	
	
	$(".progressBar",jqid).css('width',percent);
}


// ---------------------------------------------------------
// DELAY GET IMAGELIST 
// ---------------------------------------------------------
function delayed_json_imageList() {
	// give php some time to move file?
	var path = "../"+window.config.dir;
			$.getJSON('php/json_ImageList.php',
				{"directory":path},function(data){
					
					window.fileList =[];
					var metadata = data;
					$.each(metadata, function(i, val){
						val.dir = window.config.dir;
						var fileObject =  new PicData(val);
						fileObject.addProp("dir", window.config.dir);
						fileObject.addProp("id", stripIllegal(fileObject.filename));
						window.fileList.push(fileObject);
						if (i == metadata.length-1) {
							window.hasuploaded = 1;
							debug("set hasuploaded to 1!");
							getIndexFile (window.fileList) 
								
						}
					});
			});

}


// ---------------------------------------------------------
// UTIL 
// ---------------------------------------------------------





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;
}



