var Pictures = {
	form          : null,
	parent        : null,
	iterator      : 0,
	limit         : 6,
	id            : null,
	oncomplete    : null,
	dAlignX       : ((document.documentElement.offsetWidth/2) - (200/2)),
	dAlignY       : (((document.documentElement.offsetHeight+document.documentElement.scrollTop)/2)-100),
	pictureslist  : new Array(),
	listpath      : "",
	httphost      : "",
	pagination    : null,
	categoryCombo : null,
	catloaded     : false,
	toAdd         : false,
	info          : true,
	site          : "",
	
	request : function () {
		if(Pictures.categoryCombo.value.trim() == "" || Pictures.categoryCombo.value == 0) {
			alert("Selecione uma Categoria.");
			return;
		}
		
		if(!Pictures.checkExists()) {
			if(Pictures.oncomplete != null)
				eval(Pictures.oncomplete);
				
			return;
		}
		
		if(Pictures.id != null)
			insertHTML(Pictures.form, "beforeEnd", '<input type="hidden" name="id" id="id" value="'+Pictures.id+'"/>');
		
		Pictures.waiting();
		Pictures.form.submit();
	},
	
	waiting : function (state) {
		Loading.show("Enviando Imagens", "Aguarde enquanto o sistema grava as imagens.", Pictures.dAlignX, Pictures.dAlignY, true);
	},
	
	response : function (reason) {
		Loading.hide();
		
		var phrases = {0 : { icon : 'success', title : 'Sucesso', text : 'Imagens gravadas com sucesso !'}, 
					   1 : { icon : 'error', title : 'Problemas na gravação das images.', text : 'Ocorreu um erro ao gravar as imagens.' }};
		
		if(reason > 0)
			reason = 1;
		
		createDialog('joinerror', document.body, false);
		joinerror.setTitleText(phrases[reason].title);
		preloader('images/icons/'+phrases[reason].icon+'.gif');
		joinerror.setTitleIcon('images/icons/'+phrases[reason].icon+'.gif');
		joinerror.setX((document.documentElement.offsetWidth/2) - (300/2));
		joinerror.setY(document.documentElement.scrollTop+100);
		
		joinerror.setW(300);
		joinerror.setH(10);
		joinerror.setContent('<div class="NewsAdd"><div class="titleerror">'+phrases[reason].text+'</div></div>');
		joinerror.setCloseButton(true);
		joinerror.setButtonsBar('<center><input type="button" onclick="joinerror.hide(); Pictures.sendClear()" value="OK" /></center>');
		joinerror.setCloseByESC(true);
		
		if(Pictures.oncomplete != null)
			joinerror.setActionOnHide(Pictures.oncomplete);
		
		joinerror.setCloseAndDestroy(true);
		joinerror.setTransparency(0.95);
		joinerror.setMovable(true);
		joinerror.setModal(true);
		joinerror.show();	
	},

	requestCategory : function () {
		if(!Pictures.checkCategoryExists()) {
			if(Pictures.oncomplete != null)
				eval(Pictures.oncomplete);
				
			return;
		}
		
		Pictures.waitingCategory();
		Pictures.form.submit();
	},
	
	waitingCategory : function (state) {
		Loading.show("Criando Categorias", "Aguarde enquanto o sistema cria as categorias.", Pictures.dAlignX, Pictures.dAlignY, true);
	},
	
	responseCategory : function (reason) {
		Loading.hide();
		
		var phrases = {0 : { icon : 'success', title : 'Sucesso', text : 'Categorias criadas com sucesso !'}, 
					   1 : { icon : 'error', title : 'Problemas na criação das categorias.', text : 'Ocorreu um erro ao criar as categorias.' }};
		
		if(reason > 0)
			reason = 1;
		
		createDialog('joinerror', document.body, false);
		joinerror.setTitleText(phrases[reason].title);
		preloader('images/icons/'+phrases[reason].icon+'.gif');
		joinerror.setTitleIcon('images/icons/'+phrases[reason].icon+'.gif');
		joinerror.setX((document.documentElement.offsetWidth/2) - (300/2));
		joinerror.setY(document.documentElement.scrollTop+100);
		
		joinerror.setW(300);
		joinerror.setH(10);
		joinerror.setContent('<div class="NewsAdd"><div class="titleerror">'+phrases[reason].text+'</div></div>');
		joinerror.setCloseButton(true);
		joinerror.setButtonsBar('<center><input type="button" onclick="joinerror.hide(); Pictures.sendCategoryClear()" value="OK" /></center>');
		joinerror.setCloseByESC(true);
		
		if(Pictures.oncomplete != null)
			joinerror.setActionOnHide(Pictures.oncomplete);
		
		joinerror.setCloseAndDestroy(true);
		joinerror.setTransparency(0.95);
		joinerror.setMovable(true);
		joinerror.setModal(true);
		joinerror.show();
	},
	
	clearCombo : function () {
		obj = Pictures.categoryCombo;
		obj.disabled = true;
		var count = obj.options.length;
		for(var i=count-1; i>0; i--) {
			obj.options[i] = null;
		}
		obj.options[0].selected = true;
	},	
	
	requestCotegoriesList : function (path, pValue) {
		var value = (typeof pValue != "undefined" ? pValue : "");
		Pictures.clearCombo();
		Ajax.loadXMLDoc('engine/picture.category.list.php', "path="+escape(path), 'POST', {fn : 'Pictures.responseCotegoriesList', params : value}, true, {fn : 'Pictures.waitingResponseCotegoriesList'});
	},
	
	waitingResponseCotegoriesList : function (state) {
		obj = Pictures.categoryCombo;		
		obj.options[0].text = 'Carregando Categorias. Aguarde...';
		obj.options[0].value = 0;
		if(state == 4) {
			obj.disabled = false;			
			obj.options[0].text = ':: Selecione';
		}
	},
	
	responseCotegoriesList : function (xmldoc, textdoc, status, value) {
		if(status != 200)
			return;
		
		if(!xmldoc)
			return;
		
		var child;
		var obj = Pictures.categoryCombo;
		
		obj.disabled = false;
		var y=1;
		for(var i=0; i<xmldoc.childNodes.length; i++) {
			child = xmldoc.childNodes[i];
			if(child.nodeType != 1)
				continue;
			
			var name = child.getAttribute('name');
			name = name.split("[")[0];

			obj.options[y] = new Option(name);
			obj.options[y].value = child.getAttribute('name');
			if(value == child.getAttribute('name'))
				obj.options[y].selected = true;
				
			y++;
		}
		
		Pictures.catloaded = true;
		if(Pictures.toAdd)
			Pictures.add();
	},	
	
	setCategoryCombo : function (pCombo) {
		if(typeof pCombo != "object")
			pCombo = document.getElementById(pCombo);
		
		Pictures.categoryCombo = pCombo;
	},
	
	sendCategoryClear : function () {
		if(this.parent)
			this.parent.innerHTML = "";
		
		this.iterator = 0;
		this.addCategory();
	},	
	
	sendClear : function () {
		if(this.parent)
			this.parent.innerHTML = "";
		
		this.iterator = 0;
		this.add();
	},
	
	requestRemove : function (path, id) {
		if(!confirm("Confirma a exclusão da desta foto ?"))
			return;
		
		var params = "image="+path;
		Ajax.loadXMLDoc('engine/picture.remove.php', params, 'POST', {fn : 'Pictures.responseRemove', params : id}, true, {fn : 'Pictures.waitingResponseRemove'});
	},
	
	waitingResponseRemove : function (state) {
		if(state < 4)
			Loading.show("Removendo Imagem", "Aguarde enquanto o sistema remove a imagem.", Pictures.dAlignX, Pictures.dAlignY, true);
		else
			Loading.hide();
	},
	
	responseRemove : function  (xmldoc, textdoc, status, id) {
		if(status != 200) {
			alert("Erro ao remover imagem.")
			return;
		}
		
		var element = document.getElementById("picture("+id+")");
		try {
			element.parentNode.removeChild(element);
			for(var i=0; i<Pictures.pictureslist.length; i++) {
				if(Pictures.pictureslist[i].src == id) {
					Pictures.pictureslist.splice(i, 1);
					break;
				}
			}
			
			if(Pictures.pictureslist.length == 0)
				Pictures.showEmptyPhrase();
		}
		catch(o){}
		//Pictures.list(Pictures.listpath);
	},
	
	requestRemoveCategory : function () {
		var category = Pictures.categoryCombo.value;
		if(category == "" || category == 0)
			return;
		
		if(!confirm("Confirma a exclusão desta categoria?\nATENÇÃO: Serão apagadas todas as fotos que estão dentro desta categoria."))
			return;
		
		Pictures.categoryCombo.disabled = true;
		var params = "category="+encodeURIComponent(category);
		Ajax.loadXMLDoc('engine/picture.category.remove.php', params, 'POST', {fn : 'Pictures.responseRemoveCategory', params : category}, true, {fn : 'Pictures.waitingResponseRemoveCategory'});
	},
	
	waitingResponseRemoveCategory : function (state) {
		obj = Pictures.categoryCombo;		
		obj.options[0].text = 'Removendo Categoria. Aguarde...';
		obj.options[0].value = 0;
		if(state == 4) {
			obj.disabled = false;			
			obj.options[0].text = ':: Selecione';
		}
	},
	
	responseRemoveCategory : function  (xmldoc, textdoc, status, category) {
		if(status != 200) {
			alert("Erro ao remover categoria.")
			return;
		}
		
		for(var i=0; i<Pictures.categoryCombo.options.length; i++) {
			if(Pictures.categoryCombo.options[i].value == category)
				Pictures.categoryCombo.options[i] = null;
		}
		
		Pictures.categoryCombo.disabled = false;
	},	
	
	showEmptyPhrase : function () {
		if(!Pictures.parent)
			return;
		Pictures.parent.innerHTML = "Não exitem fotos cadastradas.";			
	},
	
	list : function (category, path, prefix, engine) {
		if(category == 0)
			return;
		
		this.listpath = path+category;
		this.requestPictures(this.listpath, prefix, (typeof engine != "undefined" ? engine : null));
	},
	
	requestPictures : function (path, prefix, engine) {
		Pictures.pictureslist = new Array();
		this.clearArea();
		var params = "path="+escape(path)+"&prefix="+encodeURIComponent(prefix);
		Ajax.loadXMLDoc((engine != null ? engine :'engine/picture.list.php'), params, 'POST', {fn : 'Pictures.responsePictures'}, true, {fn : 'Pictures.waitingResponsePictures'});
	},
	
	waitingResponsePictures : function (state) {
		if(typeof Loading != "undefined") {
			if(state < 4)
				Loading.show("Carregando Imagens", "Aguarde enquanto o sistema carrega as imagens.", Pictures.dAlignX, Pictures.dAlignY, true);
			else
				Loading.hide();
		}
	},
	
	responsePictures : function  (xmldoc, textdoc, status) {
		if(status == 404) {
			Pictures.showEmptyPhrase();
			return;
		}
		
		if(status != 200 || !xmldoc) {
			alert("Erro ao carregar imagens.")
			return;
		}
		
		var childs = xmldoc.childNodes;
		for(var i=0; i<childs.length; i++) {
			var child = childs[i];
			if(child.nodeType != 1)
				continue;
			
			Pictures.pictureslist.push({bsrc:child.getAttribute("bsrc"), src:child.getAttribute("src"), caption:child.getAttribute("caption")});
		}
		
		if(!Pictures.pagination) {
			createPagination('Pictures.pagination', document.getElementById('picturespgarea'));
			Pictures.pagination.setStack(Pictures.pictureslist);
			Pictures.pagination.setUpdateAction('Pictures.update');
			Pictures.pagination.setNumberOfLinks(5);
			Pictures.pagination.setNumRegsByPage(16);
			Pictures.pagination.paint();
			Pictures.update();
		}
		else
			Pictures.paintPictures();
	},
	
	update : function () {
		Pictures.parent.innerHTML = Pictures.listToHTML();
		Pictures.pagination.updateNavigation();
		initLightbox();
	},	
	
	paintPictures : function () {
		if(!Pictures.parent)
			return;
		
		insertHTML(Pictures.parent, "beforeEnd", this.listToHTML());
		initLightbox();
	},
	
	listToHTML : function () {
		var control = 0;
		var html = "";
		//for(var i=0; i<Pictures.pictureslist.length; i++) {
		for(var i=(Pictures.pagination && typeof Pictures.pagination.getStart != 'undefined' ? Pictures.pagination.getStart() : 0); i<=(Pictures.pagination && typeof Pictures.pagination.getEnd != 'undefined' ? Pictures.pagination.getEnd() : Pictures.stack.length); i++) {	
			var pic = Pictures.pictureslist[i];
			if(!pic)
				continue;
			
			control++;
			var absource = pic.src.split("../intranet");
			absource = absource[absource.length-1];
			html
			  +='<div style="margin:5px 0px 0px 5px; float:left" id="picture('+pic.src+')">'
			    + '<div>'
				  +'<a href="'+pic.bsrc+'" rel="lightbox" title="'+pic.caption+'"><img src="'+pic.src+'" border="0" /></a>'
			    + '</div>';
				if(this.info) {
					html
					+='<div>'
					  +'<input type="text" size="42" value="'+this.httphost+'/'+absource+'" onclick="this.select()" readonly />'
					+ '</div>'				
					+ '<div>'
					  + '| <a href="javascript:Pictures.requestRemove(\'../'+pic.src+'\', \''+pic.src+'\')">Excluir</a> |'
					+ '</div>';
				}
			html
			  +='</div>';

			if(control == 2) {
				html += '<br clear="all" />';
				control = 0;
			}
		}
		html += '<br clear="all" /><br />';
		return html;
	},
	
	clearArea : function () {
		if(!Pictures.parent)
			return;
		
		Pictures.parent.innerHTML = "";
	},
	
	setHTTPHost : function (str) {
		this.httphost = str;
	},
	
	setIterator : function (pInt) {
		Pictures.iterator = pInt;
		Pictures.updateButtons();
	},
	
	setLimit : function (pInt) {
		Pictures.limit = pInt;
		Pictures.updateButtons();
	},
	
	setOnComplete : function (pFn) {
		Pictures.oncomplete = pFn;
	},
	
	setID : function (pId) {
		Pictures.id = pId;
	},
	
	setInfo : function (p) {
		this.info = p;
	},
	
	setSite : function (p) {
		this.site = p;
	},	
	
	setAdd : function (pBool) {
		Pictures.toAdd = pBool;
	},
	
	setForm : function (pForm) {
		if(typeof pForm != "object")
			pForm = document.getElementById(pForm);
		
		Pictures.form = pForm;
	},
	
	setParent : function (pParam) {
		if(typeof pParam != "object")
			pParam = document.getElementById(pParam);
		
		Pictures.parent = pParam;
	},
	
	checkExists : function () {
		var fields = document.getElementsByName("pictures[]");
		var found = false;
		for(var i=0; i<fields.length; i++) {
			if(fields[i].value.trim().length > 0) {
				found = true;
				break;
			}
		}
		
		return found;
	},

	checkCategoryExists : function () {
		var fields = document.getElementsByName("category[]");
		var found = false;
		for(var i=0; i<fields.length; i++) {
			if(fields[i].value.trim().length > 0) {
				found = true;
				break;
			}
		}
		
		return found;
	},
	
	updateButtons : function () {
		var btnadd = document.getElementById("btnaddpicture");
		var btnremove = document.getElementById("btnremovepicture");
		
		if(btnadd) {
			if(Pictures.iterator < Pictures.limit)
				btnadd.style.display = "";
			else
				btnadd.style.display = "none";
		}
		
		if(btnremove) {
			if(Pictures.iterator > 1)
				btnremove.style.display = "";
			else
				btnremove.style.display = "none";
		}
	},
	
	remove : function () {
		if(Pictures.iterator <= 0)
			return;
		
		Pictures.iterator--;
		
		var element = document.getElementById('picture('+Pictures.iterator+')');
		if(!element)
			return;
			
		element.parentNode.removeChild(element);
		
		Pictures.updateButtons();
	},
	
	add : function () {
		if(!Pictures.catloaded) {
			alert("Não há categorias cadastradas");
			return;
		}
		
		if(!Pictures.parent)
			return;
			
		if(Pictures.iterator >= Pictures.limit)
			return;

		insertHTML(Pictures.parent, "beforeEnd", Pictures.toHTML(Pictures.iterator));
		Pictures.iterator++;
		
		Pictures.updateButtons();
	},
		
	toHTML : function (pIndex) {
		var html
		= '<div id="picture('+pIndex+')" style="border-bottom:1px solid #CCC; padding-bottom:10px; margin-right: 10px;">'
		  + 'Imagem '+(pIndex+1)+':<br />'
		  + '<input name="pictures[]" nc="yes" type="file" size="50" /><br />'
		  + 'Descrição:<br />'
		  + '<input name="captions[]" type="text" size="80" maxlength="200" />'
		+ '</div>';
	
		return html;
	},
	
	removeCategory : function () {
		if(Pictures.iterator <= 0)
			return;
		
		Pictures.iterator--;
		
		var element = document.getElementById('category('+Pictures.iterator+')');
		if(!element)
			return;
			
		element.parentNode.removeChild(element);
		
		Pictures.updateButtons();
	},
	
	addCategory : function () {
		if(!Pictures.parent)
			return;
			
		if(Pictures.iterator >= Pictures.limit)
			return;

		insertHTML(Pictures.parent, "beforeEnd", Pictures.categoryToHTML(Pictures.iterator));
		Pictures.iterator++;
		
		Pictures.updateButtons();
	},
		
	categoryToHTML : function (pIndex) {
		var html
		= '<div id="category('+pIndex+')" style="border-bottom:1px solid #CCC; padding-bottom:10px; margin-right: 10px;">'
		  + 'Nome:<br />'
		  + '<input name="category[]" type="text" size="80" maxlength="50" />'
		  + '<input name="site" type="hidden" value="'+this.site+'" />'
		+ '</div>';
	
		return html;
	},	
	
	init : function () {
		insertHTML(document.body, "beforeEnd", '<iframe name="pictureUpload" id="pictureUpload" src="dummy.html" style="display:none; width:300px; height:300px"></iframe>');
	}
}