//var theString = "31-12-2007";
//theString = theString.replace(/^([0-2]?[0-9]|[3][12])-([1][012]|[0-9])-(\d{4})$/,"$1/$2/$3 huhu");
//console.info(theString);
//
//var theString = "Lorem ipsum &aacute; &eacute;";
//theString = theString.replace(/(&aacute;)|(&eacute;)/,"ï¿½ ");
//console.info(theString);




var lang='pt';
function changeLang(language){
	lang=language;
}

function ajaxRequest(url) {
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(resp) {
			alert(resp.responseText);
  		}
	});
}


//Update Category position 
function submitCategoryPosition(){
	url='../control/category.php';
	var opts = {
	  method: 'post',
	  postBody: 'action=updatePosition&' + $('sortableListOrder').value,
	  onSuccess: function(response) {
	  	
	  	return true;
	  }
	}
	new Ajax.Request(url, opts);
}


function resetPassword(id){
	var url='../arearestrita/resetPassword.php';
	if(id!=undefined && id!=null){
		var post = 'id='+id;
		sucessFun = function(response){
						if(response.responseText=='ok')
						alert('Uma nova senha foi enviada para o usuário.');
					}
	}else{
		if($('email').value==""){
			 alert('Digite seu email!');
			 $('email').focus();
			 return false;
		}
		var post= 'email='+$('email').value;
		sucessFun = function(response){
			if(response.responseText=='ok') alert('Verifique seu email\n uma nova senha foi enviada.');
			if(response.responseText=='not found') alert('Email não cadastrado.');
		}
	}
	var opts={
		method:'post',
		postBody: post,
		onSuccess: sucessFun,
		onFailure: function(response){
			url= 'arearestrita/resetPassword.php';
			new Ajax.Request(url, opts);
		}
	}
	
	new Ajax.Request(url, opts);
}

function logoff(){	
	url='index.php';
	var opts={
		method:'post',
		postBody: 'action=logoff'
	}
	new Ajax.Request(url, opts);
}


function newWindow(url){
	window.open(url, 'figado', 'width=425,height=400,titlebar=0,scrollbars=1,resizable=1');
//	var opts ={className: "mac_os_x", 
//						title: "Sample",
//						width:200, height:150, 
//						destroyOnClose: true, 
//						recenterAuto:true
//					};
//	var xpto = new Window(opts);
//	xpto.setOpacity(1);
//	
//	var opts1={
//		onSuccess: function(response){
//			xpto.getContent().update(response.responseText); 
//			xpto.showCenter();
//		}
//	};
//	new Ajax.Request(url, opts1);
}
function closeWindow(){
	window.opener.refresh;
	window.close();
}

function exibirImagem(src){ newWindow('imagem.php?src='+src); }

function addImage(type){newWindow('imageFile.php?action=formInsert&type='+type);}
function addFile(){	newWindow('file.php?action=formInsert');}
function addComment(idPost){ newWindow('comment.php?action=formInsert&idPost='+idPost); }
function addPost(){	newWindow('post.php?action=formInsert');}
function addReunion(){ newWindow('reunion.php?action=formInsert');}
function addCategoryLang(idCategory){ newWindow('categoryLang.php?action=formInsert&idCategory='+idCategory+'&keyLanguage='+lang+'&parent=0');}
function addSubCategory(idParentCategory, keyLanguage){ newWindow('categoryLang.php?action=formInsert&parent='+idParentCategory+'&keyLanguage='+keyLanguage);}
function addMedia(){ newWindow('media.php?action=formInsert');}
function addHighlight(keyLanguage){ newWindow('highlight.php?action=formInsert&keyLanguage='+keyLanguage); }
function addScientific(keyLanguage, type){ newWindow('scientific.php?action=formInsert&keyLanguage='+keyLanguage+'&type='+type); }
function addHome(keyLanguage){	newWindow('home.php?action=formInsert&keyLanguage='+keyLanguage);}
function addGlossary(){	newWindow('glossary.php?action=formInsert');}

function updateReunion(id){	newWindow('reunion.php?action=formUpdate&id='+id);}
function updatePost(idPost){newWindow('post.php?action=formUpdate&id='+idPost);}
function updateCategoryLang(idCategory, keyLanguage){ newWindow('categoryLang.php?action=formUpdate&idCategory='+idCategory+'&keyLanguage='+keyLanguage); }
function updateMedia(idMedia){ newWindow('media.php?action=formUpdate&id='+idMedia); }
function updateHighlight(id){ newWindow('highlight.php?action=formUpdate&id='+id); }
function updateScientific(id){ newWindow('scientific.php?action=formUpdate&id='+id); }
function updateGlossary(id){ newWindow('glossary.php?action=formUpdate&id='+id); }

function jump(el,fo){
	oc = $(el);
	if (fo != 'up') {
		ocs = oc.previousSiblings()[0];
		if(!ocs || !ocs.hasClassName('category')) return;
		Insertion.Before(ocs, oc);
	}
	else {
		ocs = oc.nextSiblings()[0];
		if(!ocs || !ocs.hasClassName('category')) return;
		Insertion.After(ocs, oc);
	}
}

function deleteUser(id){
	if(confirm('Deseja realmente ecluir?'))
		window.location = "user.php?action=delete&id="+id;
}

function deletePost(id){
	if(confirm('Deseja realmente ecluir o post?'))
		window.location = "post.php?action=delete&id="+id;
}

function deleteMedia(id){
	if(confirm('Deseja realmente excluir essa imagem?')){
		var url='media.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				window.location.reload();	
			}
		}
		new Ajax.Request(url, opts);
	}
}

function deleteImage(id){
	if(confirm('Deseja realmente excluir esse arquivo?')){
		var url='imageFile.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				window.location.reload();	
			}
		}
		new Ajax.Request(url, opts);
	}
}
function deleteComment(id){
	if(confirm('Deseja realmente excluir esse commentário?')){
		var url='comment.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				if(response.responseText=='ok')
				window.location.reload();
				else alert('O comentário não foi apagado');
			}
		}
		new Ajax.Request(url, opts);
	}
}
function deleteReunion(id){
	if(confirm('Deseja realmente ecluir?')){
		var url='reunion.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				window.location.reload();	
			}
		}
		new Ajax.Request(url, opts);
	}
}

function deleteCategoryLang(idCategory, keyLanguage, idParent){
	var msg = 'Deseja realmente excluir essa categoria?';
	if(idParent==0 || idParent==null)
		msg = 'Deseja realmente excluir essa categoria?\n' +
				' Todas as subcategorias correspondentes também serão excluídas.\n' +
				' Essa ação não poderá ser refeita.';
	if(confirm(msg)){
		var url='categoryLang.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&idCategory='+idCategory+'&keyLanguage='+keyLanguage,
			onSuccess: function(response){
				msg = (idParent==0)? 'Categoria excluida' : 'Sub-Categoria excluida';
				alert(msg);
				window.close();	
				opener.location.reload();
			}
		}
		new Ajax.Request(url, opts);
	}
}


function deleteHighlight(id, keyLanguage){
	var msg = 'Deseja realmente excluir esse destaque?';
	if(confirm(msg)){
		var url='highlight.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				msg = 'Destaque excluido';
				alert(msg);
				window.close();	
				opener.location='highlight.php?action=listAll&keyLanguage='+keyLanguage;
			}
		}
		new Ajax.Request(url, opts);
	}
}

function deleteScientific(id, keyLanguage, type){
	var msg = 'Deseja realmente excluir?';
	if(confirm(msg)){
		var url='scientific.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				alert('Registro excluido');
				window.close();	
				opener.location='scientific.php?action=listAll&keyLanguage='+keyLanguage+'&type='+type;
			}
		}
		new Ajax.Request(url, opts);
	}
}
function deleteGlossary(id){
	var msg = 'Deseja realmente excluir?';
	if(confirm(msg)){
		var url='glossary.php';
		var opts ={
			method: 'post',
			postBody: 'action=delete&id='+id,
			onSuccess: function(response){
				alert('Registro excluido');
				window.close();	
				opener.location='glossary.php?action=listAll';
			}
		}
		new Ajax.Request(url, opts);
	}
}

/**
 * Remove a imagem do post.
 */
function removeImage(){
	if(confirm('Deseja Excluir a imagem?')){
		$('fileName').value="";
		$('postImage').innerHTML="";
		var url = 'post.php';
		var opts={
			method:'post',
			postBody: 'action=deleteImage&id='+$('id').value
		}
		new Ajax.Request(url, opts);
	}
}

function amplifyImage(idImage){
	newWindow('imageFile.php?action=detail&id='+idImage);
}

function amplifyMedia(id){
	newWindow('media.php?action=detail&id='+id);
}

opts={duration: 0.5}
function hide(id){
	new Effect.SlideUp(id, opts);
}
function show(id){
  	new Effect.SlideDown(id, opts);
}

//show OR hide funtion depends on if element is shown or hidden
function shoh(id) {
	if (document.getElementById) {
		if ($(id).style.display == 'none'){ 
			show(id);
			return true;
		}
		else hide(id);
		return false;
	}
	else{
		if (document.layers) {	
			if (document.id.display == "none"){
				show(id);
				return true;
			}
			else hide(id);
			return false;
		} else {
			if(document.all.id.style.visibility == "none"){
				show(id);
				return true;
			}
			else hide(id);
			return false;
		}
	}			
}

function shohPost(id, img){
	if(shoh(id))
	img.setAttribute('src', '../icons/icon_menos.gif');
	else
	img.setAttribute('src', '../icons/icon_mais.gif');
}

function chageLink(idLink){

	if($(idLink)!=null){
		$(idLink).addClassName('subitemon');
		var parentN='';
		var parentOld='';
		var nodes = $(lastLink).parentNode.parentNode.childNodes;
		for(i=0; i<nodes.length; i++){
			if(nodes[i].tagName=="A"){
				parentOld = $(nodes[i]).id;
				$(parentOld).removeClassName("itemon");
				break;
			}
		}
		if(lastLink!=parentN){
			$(lastLink).removeClassName('subitemon');
			$(lastLink).removeClassName('itemon');
		}
		
		nodes = $(idLink).parentNode.parentNode.childNodes;
		for(i=0; i<nodes.length; i++){
			if(nodes[i].tagName=="A"){
				parentN = $(nodes[i]).id;
				$(parentN).addClassName("itemon");
				break;
			}
		}
		if(parentN==''){
			$(idLink).removeClassName('subitemon');
			$(idLink).addClassName('itemon');
		}
		
		lastLink=idLink;
	}
}

function formatHour(element) {
	var v = element.value;
	var newValue = ((v.replace(/\D/g,"")).replace(/(\d{2})(\d)/,"$1:$2"));
	element.value = newValue;
}

function formatDate(element) {
	var v = element.value;
	var newValue = v.replace(/^\D+$/g,"");
	newValue = newValue.replace(/^([0-2][0-9]|[3][12])([1][012]|[0][0-9])(\d{4})$/,"$1/$2/$3")
	element.value = newValue;
}



/**
 * sort list
 * 
 */

function createNewSection(name) {
	var name = $F('sectionName');
	if (name != '') {
		var newDiv = Builder.node('div', {id: 'group' + (sections.length + 1), className: 'section', style: 'display:none;' }, [
			Builder.node('h3', {className: 'handle'}, name)
		]);
	
		sections.push(newDiv.id);
		$('page').appendChild(newDiv);
		Effect.Appear(newDiv.id);
		destroyLineItemSortables();
		createLineItemSortables();
		createGroupSortable();
	}
}

function createLineItemSortables() {
	for(var i = 0; i < sections.length; i++) {
		Sortable.create(sections[i],{tag:'div',dropOnEmpty: true, containment: sections,only:'lineitem'});
	}
}

function destroyLineItemSortables() {
	for(var i = 0; i < sections.length; i++) {
		Sortable.destroy(sections[i]);
	}
}

function createGroupSortable() {
	Sortable.create('page',{tag:'div',only:'section',handle:'handle'});
}

/*
Debug Functions for checking the group and item order
*/
function getGroupOrder() {
	var sections = document.getElementsByClassName('section');
	var alerttext = '';
	sections.each(function(section) {
		var sectionID = section.id;
		var order = Sortable.serialize(sectionID);
		alerttext += sectionID + ': ' + Sortable.sequence(section) + '\n';
	});
	alert(alerttext);
	return false;
}

/**
 * salva no banco a ordem.
 */
function saveOrder(lc){
	arr = []; $(lc).getElementsBySelector('[class="category"]').each(function(item) {arr.push(item.id)});
	ajaxRequest("category.php?action=order&categories="+arr.toString()+"&language="+lc);
	showOrder(lc, false);
}

/**
 * mostra/esconde os botï¿½es de ordenaï¿½ï¿½o
 */	
function showOrder(lang, rel, idParent){
	var objs = $$('a.order');
	objs.each(function (a, i){
		if(lang == a.id.substring(0, 2))
		a.toggle();
	});
	
	var btn = $(lang+'Order');
	$(lang+'CancelOrder').toggle();
	btn.toggle();
	
	if(btn.style.display=="none"){
		$(lang+'action').update('Listagem');
		if(rel)
		window.location='category.php?action=listAll&keyLanguage='+lang+'&parent='+idParent;
	}else
		$(lang+'action').update('Ordenar');
}

function saveHighlightOrder(lc){
	arr = []; $(lc).getElementsBySelector('[class="category"]').each(function(item) {arr.push(item.id)});
	ajaxRequest("highlight.php?action=order&highlights="+arr.toString()+"&language="+lc);
	showOrder(lc, false);
}

function showHighlightOrder(lang, rel){
	var objs = $$('a.order');
	objs.each(function (a, i){
		if(lang == a.id.substring(0, 2))
		a.toggle();
	});
	
	var btn = $(lang+'Order');
	$(lang+'CancelOrder').toggle();
	btn.toggle();
	
	if(btn.style.display=="none"){
		$(lang+'action').update('Listagem');
		if(rel)
		window.location='highlight.php?action=listAll&keyLanguage='+lang+'&parent='+idParent;
	}else
		$(lang+'action').update('Ordenar');
}

function showScientificOrder(lang, rel, type){
	var objs = $$('a.order');
	objs.each(function (a, i){
		if(lang == a.id.substring(0, 2))
		a.toggle();
	});
	
	var btn = $(lang+'Order');
	$(lang+'CancelOrder').toggle();
	btn.toggle();
	
	if(btn.style.display=="none"){
		$(lang+'action').update('Listagem');
		if(rel)
		window.location='scientific.php?action=listAll&keyLanguage='+lang+'&type='+type;
	}else
		$(lang+'action').update('Ordenar');
}

function saveScientificOrder(lc){
	arr = []; $(lc).getElementsBySelector('[class="category"]').each(function(item) {arr.push(item.id)});
	ajaxRequest("scientific.php?action=order&scientifics="+arr.toString()+"&language="+lc);
	showOrder(lc, false);
}

function utf8_encode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    str_data = str_data.replace(/\r\n/g,"\n");
    var utftext = "";
 
    for (var n = 0; n < str_data.length; n++) {
        var c = str_data.charCodeAt(n);
        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
 
    return utftext;
}

function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    var string = "", i = 0, c = c1 = c2 = 0;
 
    while ( i < str_data.length ) {
        c = str_data.charCodeAt(i);
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if((c > 191) && (c < 224)) {
            c2 = str_data.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return string;
}
