function moverAba(obj, sentido) {	
	var amp = 5;
	var posPx = obj.css("bottom");
	posPx = (posPx == "auto") ? "0px" : posPx;
	var pos = posPx.slice(0,- 2);	

	obj.stop();
	
	switch (sentido) {
		case "cima":			
			var desl = amp - pos;
			var geral = "+="+desl+"px";
			break;
		case "baixo":			
			var desl = pos - 0;
			var geral = "-="+desl+"px";
			break;
	}	

	obj.animate({bottom: geral}, 200);
}

function parseGetVars(url) {	
	var getVars = new Array();
	if (!url) {
        var qString = unescape(top.location.search.substring(1));
    } else {        
		var qString = url;
    }
	var pairs = qString.split(/\&/);
	for (i = 0; i < pairs.length; i++) {		
		var nameVal = pairs[i].split(/\=/);
		getVars[nameVal[0]] = nameVal[1];		
	}
	return getVars;
}

function params2json(url) {
	if (!url) {
        var qString = unescape(top.location.search.substring(1));
    } else {
        var qString = url;
    }
    if (qString != "") {
        var pairs = qString.split(/\&/);
        saida = "({";
        for (i = 0; i < pairs.length; i++) {
            var nameVal = pairs[i].split(/\=/);
            saida += nameVal[0]+": '"+nameVal[1]+"', ";
        }
        saida = saida.slice(0,-2);
        saida += "})";
    } else {
        saida = "({})";
    }
    saida = eval(saida);
       
	return saida;
}
	
function carregarTudo() { // Callback do Ajax	
	fixpng();
	//formulários
    jQuery.validator.messages["email"] = "Por favor, insira um endereço válido!";
    jQuery.validator.messages["number"] = "Por favor, insira apenas números!";
    jQuery("input[type=text], input[type=password], input[type=file], textarea").focus(function () {jQuery(this).addClass("inputfoco");});
    jQuery("input[type=text], input[type=password], input[type=file], textarea").blur(function () {jQuery(this).removeClass("inputfoco");});
    jQuery.validator.addClassRules({nao_vazio: {required: true}});
    if (jQuery(":checkbox[name='argumento[]']").length > 0) {		
		jQuery.validator.messages["required"] = "É necessário selecionar algum elemento para excluir!";
		jQuery("form").validate({
			errorContainer: "alert"			
		});
	} else {
		jQuery.validator.messages["required"] = "Campo obrigatório!";
		jQuery("form").validate();
	}

	if (!(jQuery.browser.msie && jQuery.browser.version < 7.0)) {
		jQuery(".thumb_container, .produto_container").hover(
			function () {
				jQuery(this).addClass("hover");
			},
			function () {
				jQuery(this).removeClass("hover");
			}
		);
	}
	if (jQuery(":checkbox, :radio").length == 0 ) {
		jQuery("[value=Editar], [value=Excluir]").hide();
	}

	jQuery(".submenu_op").click(function (e) {		
		e.preventDefault();		
		iframe = jQuery(document.createElement("iframe"));
		iframe
			.attr({
				src: jQuery(this).attr("href"),
				frameborder: 0,
				scrolling: "no"
			})
			.width(896)
			.height(600)
			.modal({
				closeHTML: "<a title=\"Fechar galeria\">Fechar</a>",
				overlayId: 'contact-overlay',
				containerId: 'contact-container',
				overlayCss: {
					backgroundColor: '#000',
					cursor: 'wait'
				},
				containerCss: {
					width: 896,
					height: 600
				},
				onOpen: function (dialog) {
					dialog.overlay.fadeIn('slow', function () {
						dialog.container.slideDown('slow', function () {
							dialog.data.fadeIn('slow');
						});
					});
				},				
				onClose: function (dialog) {
					dialog.data.fadeOut('slow', function () {
						dialog.container.slideUp('slow', function () {
							dialog.overlay.fadeOut('slow', function () {
								jQuery.modal.close();
							});
						});
					});
				}
		   });
	});
		
	jQuery("textarea#texto")
		.attr("cols", "57")
		.attr("rows", "12")
		.wysiwyg();	
	jQuery(".sortable").each(function () {
		jQuery(this).attr("id", "id_"+jQuery(this).find("input").attr("value"));
	});
	jQuery(".sortable").parents("form").sortable({
		items: '.thumb_container'
	});
	if (jQuery("textarea#texto").length == 0) {
		jQuery('.thumb_container, form>*:not(.toolbar), .parceiro_container, .depoimento').wrapAll("<div class=\"container_geral\">");
		jQuery('div.container_geral').height(jQuery("div.toolbar, a.enviar_depoimento").length == 0 ? 345 : 308);
	}
	jQuery('[type=file].multi')
		.attr("name", function () {return jQuery(this).attr("name")+"[]"})
		.MultiFile({
			accept:'gif|jpg|png', max:5, STRING: {
				remove:'Remover',
				selected:'Selecionado: $file',
				denied:'Inválido arquivo de tipo $ext!',
				duplicate:'Arquivo já selecionado:\n$file!'
			}
		});	
}

function salvarOrdem() {	
	var newQuery = location.hash.indexOf("?") != -1 ? location.hash.split("?")[1] : "";
	var urlHash = parseGetVars(newQuery);
	cat = urlHash["categoria"];	
	var sessid = jQuery.url.param("SESSID");	
	jQuery.get("salvarOrdem.php?SESSID="+sessid+"&categoria="+cat+"&"+jQuery("form").sortable('serialize'), function (data) {if (data) {alert("Erro: "+data)} else {alert("Nova ordem salva com sucesso!")}});
}
	
function alertarMsg() {
	var url = parseGetVars();
	var newQuery = location.hash.indexOf("?") != -1 ? location.hash.split("?")[1] : "";	
	var urlHash = parseGetVars(newQuery);	
	var arr = new Array();
	arr["erro"] = "Erro na operação!";
	arr["login"] = "Senha incorreta. Por favor, tente novamente!";
	arr["sucesso"] = "Operação realizada com sucesso!";
	arr["categoriaEmUso"] = "Você não pode excluir uma categoria que contém itens!";
    arr["categoriaPai"] = "A categoria possui subcategorias. Exclua estas primeiro.";
	arr["categoriaPai2"] = "A categoria possui subcategorias, portanto não pode ser vinculada a outra.";
    arr["imgInvalida"] = "O formato da imagem não é válido! (somente JPEG, GIF ou PNG)";
	arr["arqInvalido"] = "Formato de arquivo inválido!";
	if (url["msg"] && arr[url["msg"]]) {
		alert(arr[url["msg"]]);
	}
	if (urlHash["msg"] && arr[urlHash["msg"]] && urlHash["msg"] != "login") {
		alert(arr[urlHash["msg"]]);
	}
}

function paginaInicial() {	
	if (jQuery.url.param("adm")) {
        //return "conteudo.php"+unescape(getUrl());
		jQuery("#conteudo").load("conteudo.php"+unescape(getUrl()),carregarTudo);
    } else if (!location.hash && jQuery.url.param("SESSID")) {
		//return "";
		jQuery("#conteudo").html("<img class=\"imgH1\" alt=\"Fotos\" src=\"imagens_php/titulo.php?texto=Bem-vinda, Graziela\"/><p>Modifique seu site através das opções acima!</p><p><strong>Dificuldades no uso?</strong> Clique <a href=\"manual_site.doc\">aqui</a> para ler o manual!</p><p>Caso o site apresente problemas, envie um email para <a href=\"mailto:jpbcosta@yahoo.com\">jpbcosta@yahoo.com</a></p>");
	} else {		
		//return "conteudo.php?pg=1";
		//jQuery("#conteudo").load("conteudo.php?pg=1");		
        jQuery(".history.home").trigger("click"); //para começar na página inicial qdo não há hash
    }
}

function fixpng() {	
	if (jQuery.browser.msie && jQuery.browser.version < 7.0) {		
		jQuery('#conteudo img').ifixpng();
	}
}
	
jQuery(document).ready(function() {		
	jQuery(document).bind("contextmenu",function(e){
		return false;
	});
	jQuery("#slideshow").cycle();
	if (typeof(jQuery.url.param("SESSID")) == "undefined") {
		jQuery(".mbutton_fundo a").floatSubmenu({ajaxQuery: false});
	}
    jQuery(".history").remote('#conteudo', null, carregarTudo);
	jQuery(".history").click(function () {
		jQuery("#conteudo").html("<div class=\"loading\"></div>");
	});
	jQuery.ajaxHistory.initialize(paginaInicial);	
	jQuery(".mbutton_fundo").hover(
		function () {
			moverAba(jQuery(this), "cima");
		},
		function () {
			moverAba(jQuery(this), "baixo");
		}
	);	
	alertarMsg();
});

function http_build_query( formdata, numeric_prefix, arg_separator ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: urlencode
    // *     example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&amp;');
    // *     returns 1: 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    // *     example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_');
    // *     returns 2: 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk'
 
    var key, use_val, use_key, i = 0, j=0, tmp_arr = [];
 
    if (!arg_separator) {
        arg_separator = '&';
    }
 
    for (key in formdata) {
        use_val = urlencode(formdata[key].toString());
        use_key = urlencode(key);
 
        if (numeric_prefix && !isNaN(key)) {
            use_key = numeric_prefix + j;
            j++;
        }
        tmp_arr[i++] = use_key + '=' + use_val;
    }
 
    return tmp_arr.join(arg_separator);
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

/* GALERIA */
function getUrl(vetor, url) {
    saida = "({";    
    if (!url) {
        qString = unescape(top.location.search.substring(1));
    } else {
        qString = url;
    }    

	gets = params2json(qString);

	if (location.hash) {
        gets.pg = getAppId();
    }

	if (vetor) {
        for (i = 0; i < vetor.length; i++) {
            if (vetor[i][1] != null) {
                eval("gets."+vetor[i][0]+" = '"+vetor[i][1]+"';");
            } else {
                eval("delete gets."+vetor[i][0]);
            }
        }

    }

    delete gets.msg // evitando alerts
    saida = "?"+http_build_query(eval(gets));	
    return saida;
}

function cancelar() {    
	retorno = getHash("query") == "" ? "" : getHash();
	location.hash = retorno;
}

function limparSessao() {
    location.href = getUrl([["SESSID", null],["adm", null]]);
}

function getAppId() {
    if (!location.hash) {
        id = "";
    } else {        
		id = jQuery.url.attr("source");
        id = id.split("-");
        id = id[0];
    }
    return id;
}

function novoConteudo(url) {
    jQuery("#conteudo").load("conteudo.php"+url,carregarTudo);
}

function inserirFoto() {
	jQuery.url.setUrl(jQuery.url.attr("anchor"));
	album = jQuery.url.param("categoria");	
	applyNewQuery("cenario=inserirPorCategoria&titulo=Fotos+-+Inserir&categoria="+album);
}

function funcao_aplicacao(prm, titulo) {
    titulo = titulo ? "&titulo="+titulo : "";	
	switch (prm) {
        case "inserir":
			applyNewQuery("cenario=inserir"+titulo);
            break;
        case "editar":
            if (jQuery(":checked").length == 0) {
                alert("É necessário selecionar algum elemento para alterar!");
            } else if (jQuery(":checked").length > 1) {
                alert("Só é possível editar um elemento por vez!");
            } else {
				applyNewQuery("cenario=atualizar&argumento="+jQuery(":checked").val()+titulo);
            }
            break;
        default:
            alert('não programado!');
            break;
    }
}

function verificarDepoimento() {	
	if (jQuery(":checked").length == 0) {
		alert("É necessário selecionar algum elemento para alterar!");
	} else if (jQuery(":checked").length > 1) {
		alert("Só é possível editar um elemento por vez!");
	} else if (jQuery(":checked").parents("div.publicado.depoimento").length > 0) {
		confirmar = window.confirm("O depoimento já possui foto e está publicado. Deseja enviar nova foto?");
		if (confirmar) {
			applyNewQuery("cenario=atualizar&argumento="+jQuery(":checked").val()+"&titulo=Depoimentos+-+Publicar");
		}
	} else {
		applyNewQuery("cenario=atualizar&argumento="+jQuery(":checked").val()+"&titulo=Depoimentos+-+Publicar");
	}
}

function editarCategoria() {
	if (jQuery(":checked").length == 0) {
		alert("É necessário selecionar algum elemento para alterar!");
    } else if (jQuery(":checked").length > 1) {
        alert("Só é possível editar um elemento por vez!");
    } else {
		applyNewQuery("cenario=atualizar_categoria&argumento="+jQuery(":checked").val());
    }
}

function verAlbum(cat, nome) {
	applyNewQuery("cenario=excluir&titulo="+nome+"&categoria="+cat);
}

function getHash(prm) {
	var anchor = typeof(location.hash) == "undefined" ? "#" : location.hash;
	anchor = anchor.replace("#","");
	var query = "";
	var page;

	if (anchor.indexOf("?") != -1) {
		splitAnchor = anchor.split("?");
		query = splitAnchor[1];
		page = splitAnchor[0];
	} else {		
		page = anchor;
	}

	switch (prm) {
		default:
		case "page":			
			return page;
			break;
		case "query":			
			return query;
			break;
	}
}

function applyNewQuery(query) {	
	location.hash = getHash() + "?" + query;
	if (jQuery.browser.msie && jQuery.browser.version < 7.0) {
		location.reload();
	}
}

function paginacao(prm) {	
	var query = getHash("query");	
	if (query != "") {		
		var get_vars = parseGetVars(query);
		if (!isNaN(get_vars["min"])) {
			min = get_vars["min"];
		} else {
			min = 0;
		}
	} else {
		min = 0;
	}	
    switch (prm) {
        case "menos":
            if (min != 0) {
				min--;
			}
            break;
        case "mais":
            min++;
            break;
    }	

	if (isNaN(min))  {
		alert(query+" não gerou número!\n"+get_vars["min"]);
		return;
	}    
	applyNewQuery("min="+min);
}
