//blank
function _blank(url)
{
	window.open(url,"_blank");
}

var moldalControl = {}
moldalControl.show = function(id)
{
	//alert("show - " + id);
	
	//bug Firefox
	if($(id).css("display") != "block")
	{
		$(id).css({display:"block"});
		$(id).hide();		
		$(id).fadeIn("fast");
	}
	
	$(window).resize(function() {moldalControl.realign(id);});
	
	moldalControl.realign(id);
}

moldalControl.realign = function(id)
{
	var left = ($(window).width() - $(id + " .container").width()) / 2;
	var top = ($(window).height() - $(id + " .container").height() - 6 /*BORDER*/) / 2;
	$(id + " .container").css({left:left, top:top});
}

moldalControl.hide = function(id)
{
    $(id).fadeOut("normal");
}

//msgbox
var moldalGallery = {};
moldalGallery.photos = [];
moldalGallery.thumbWidth = 73; //largura + borda + margin
moldalGallery.thumbGroup = 6; //número de thumbs exibidas por vez
moldalControl.isPhotoLoaded = false; //indica se a foto foi carregada

moldalGallery.show = function() //tipo: alerta, confirmacao, carregando
{
    //bug Firefox
    if ($("#moldal-gallery").css("display") != "block") {
        $("#moldal-gallery").css({ display: "block" });
        $("#moldal-gallery").hide();
        $("#moldal-background").css({ display: "block" });
        $("#moldal-background").hide();

        $("#moldal-gallery").fadeIn("fast");
        $("#moldal-background").fadeIn("fast");
    }

    moldalGallery.realign();

    $("#moldal-gallery .container .image-container").load(function() {
        if (moldalGallery.isSlideShow) {
            clearTimeout(moldalGallery.timeSlideShow);
            moldalGallery.timeSlideShow = setTimeout('moldalGallery.nextPhotoSlideShow()', moldalGallery.delaySlideShow);
        }
        moldalGallery.isPhotoLoaded = true;
    });
    moldalGallery.toggleSlideShow();
}

moldalGallery.realign = function()
{
	var left = ($(window).width() - $("#moldal-gallery").width()) / 2;
	var top = ($(window).height() - $("#moldal-gallery").height() - 6 /*BORDER*/) / 2;
	$("#moldal-gallery").css({left:left, top:top});
}

moldalGallery.hide = function() {
    
    $("#moldal-gallery").fadeOut("normal");
    $("#moldal-background").fadeOut("normal");
    if (this.isSlideShow)
        this.toggleSlideShow();
    while (this.pageAtual != 1) {
        this.pagePrev();
    }
}

moldalGallery.addPhoto = function(thumb, large, legend, photoID) {
	moldalGallery.photos.push({thumb:thumb, large:large, legend:legend, photoID:photoID});
}

moldalControl.loadPhotoByID = function(photoID) {
    for (i = 0; i < moldalGallery.photos.length; i++) {
        if (moldalGallery.photos[i].photoID == photoID)
            moldalGallery.loadPhoto(i);
    }
}

moldalGallery.loadPhoto = function(photoIndex) {
    var imageContainer = $("#moldal-gallery .container .image-container");
    var photo = moldalGallery.photos[photoIndex];
    var thumbs = $("#moldal-gallery .footer .thumbs .thumb");
    this.isPhotoLoaded = false;

    //verifica se o moldal está aberto, caso contrário chama o método show()
    if ($("#moldal-gallery").css("display") != "block") {
        $(imageContainer).attr("src", "");
        moldalGallery.show();
    }

    thumbs.removeClass("selected");
    $(thumbs[photoIndex]).addClass("selected");

    if ($(imageContainer).attr("src") != photo.large) {
        $(imageContainer).fadeOut("normal", function() {
            $(imageContainer).attr("src", photo.large);
            $(imageContainer).load(function() { $(this).fadeIn("normal"); });
        });
    }

    //update legend
    imageContainer.attr("alt", photo.legend);
    imageContainer.attr("title", photo.legend);
    $("#moldal-gallery .header h3").text(photo.legend);

    //update counter
    $("#moldal-gallery .header .counter .atual").text(photoIndex + 1);
    $("#moldal-gallery .header .counter .total").text(moldalGallery.photos.length);

    pageOK = Math.ceil((photoIndex + 1) / this.thumbGroup);
    while (pageOK != this.pageAtual) {
        if (pageOK < this.pageAtual)
            this.pagePrev();
        else
            this.pageNext();
    }

    this.bindButtonsPrevNext(photoIndex);
}

moldalGallery.bind = function()
{
	var thumbs = $("#moldal-gallery .footer .thumbs");
	thumbs.html("");
	
	for(i = 0; i < moldalGallery.photos.length ; i++)
	{
		var photo = moldalGallery.photos[i];
		thumbs.append("<img style='background:url(" + photo.thumb + ") no-repeat top center;' src='images/comum/blank.gif' class='thumb button' alt='Click to Enlarge' title='Click to Enlarge' onclick='moldalGallery.loadPhoto(" + i + ")' />");
	}
	
	moldalGallery.updatePageButtons();
	thumbs.css({width:(moldalGallery.thumbWidth * moldalGallery.photos.length + "px")});
	//moldalGallery.loadPhoto(0);
}

moldalGallery.pageAtual = 1;

moldalGallery.pageNext = function()
{
    if (moldalGallery.pageAtual != Math.ceil(moldalGallery.photos.length / moldalGallery.thumbGroup))
	    moldalGallery.pageAtual ++;
	    
	$("#moldal-gallery .footer .thumbs").animate({marginLeft:-(moldalGallery.thumbGroup * moldalGallery.thumbWidth) * (moldalGallery.pageAtual - 1)}, 700);
	moldalGallery.updatePageButtons();
}

moldalGallery.updatePageButtons = function()
{
	if(moldalGallery.pageAtual == 1)
	{
		$("#moldal-gallery .footer .prev").fadeOut("normal");
	}
	else
	{
		$("#moldal-gallery .footer .prev").fadeIn("normal");
	}
	
	if(moldalGallery.pageAtual == Math.round(moldalGallery.photos.length / moldalGallery.thumbGroup))
	{
		$("#moldal-gallery .footer .next").fadeOut("normal");
	}
	else
	{
		$("#moldal-gallery .footer .next").fadeIn("normal");
	}
	
}

moldalGallery.pagePrev = function()
{
    if (moldalGallery.pageAtual != 1) 
	    moldalGallery.pageAtual --;
	$("#moldal-gallery .footer .thumbs").animate({marginLeft:-(moldalGallery.thumbGroup * moldalGallery.thumbWidth) * (moldalGallery.pageAtual - 1)}, 700);
	moldalGallery.updatePageButtons();
}

//Indica se o slide show está ou não ativo
moldalGallery.isSlideShow = false;

//Contabiliza o tempo do slide show
moldalGallery.timeSlideShow = null;

//Tempo de transação do slide show
moldalGallery.delaySlideShow = 4000;

//Armazena o indece da foto que está sendo exibida
moldalGallery.photoIndexActive = 0;

//Procura o index da foto que está ativa
moldalGallery.searchIndexActive = function() {

    var imageContainer = $("#moldal-gallery .container .image-container");
    
    for (i = 0; i < this.photos.length; i++)
        if (this.photos[i].large == imageContainer.attr('src'))
            return i;
}

//Exibe a proxima foto
moldalGallery.nextPhotoSlideShow = function() {

    if (!this.isSlideShow)
        return;
    clearTimeout(this.timeSlideShow);

    //busca a foto que está sendo exibida
    this.photoIndexActive = this.searchIndexActive();

    //Se está na ultima foto
    if (this.photoIndexActive + 1 == this.photos.length) {
        this.photoIndexActive = 0;

    }
    //Se não estpa na ultima foto
    else {
        this.photoIndexActive = this.photoIndexActive + 1;
    }

    this.loadPhoto(this.photoIndexActive);
}

//Ativa e desativa o slide show
moldalGallery.toggleSlideShow = function() {
    button = $("#moldal-gallery .header .button.slideshow").get(0);

    if (this.isSlideShow) {

        button.src = button.src.replace('btn_slide_show_active', 'btn_slide_show');

        clearTimeout(this.timeSlideShow);
        this.timeSlideShow = null;
        this.isSlideShow = false;
    }
    else {
        button.src = button.src.replace('btn_slide_show', 'btn_slide_show_active');

        if (this.isPhotoLoaded) {
            clearTimeout(moldalGallery.timeSlideShow);
            this.timeSlideShow = setTimeout('moldalGallery.nextPhotoSlideShow()', this.delaySlideShow);
        }
        this.isSlideShow = true;
    }
}

moldalGallery.nextPhoto = function() {

    clearTimeout(this.timeSlideShow);

    //busca a foto que está sendo exibida
    this.photoIndexActive = this.searchIndexActive();

    //Se está na ultima foto
    if (this.photoIndexActive + 1 == this.photos.length) {
        this.photoIndexActive = 0;
    }
    //Se não estpa na ultima foto
    else {
        this.photoIndexActive = this.photoIndexActive + 1;
    }

    this.loadPhoto(this.photoIndexActive);
}

moldalGallery.previousPhoto = function() {

    clearTimeout(this.timeSlideShow);
    
    //busca a foto que está sendo exibida
    this.photoIndexActive = this.searchIndexActive();
    
    //Se está na primeira foto
    if (this.photoIndexActive == 0) {
        this.photoIndexActive = this.photos.length - 1;
    }
    //Se não estpa na primeira foto
    else {
        this.photoIndexActive = this.photoIndexActive - 1;

        //Passa para a proxima página
//        if (Math.ceil((this.photoIndexActive + 1) / this.thumbGroup) != this.pageAtual)
//            this.pagePrev();
    }

    this.loadPhoto(this.photoIndexActive);
}

moldalGallery.bindButtonsPrevNext = function(photoIndex) {

    stylePrev = styleNext = 'visible';

    if (photoIndex == 0)
        stylePrev = 'hidden';

    if (photoIndex == this.photos.length - 1)
        styleNext = 'hidden';

    $('#moldal-gallery .container .previous').css('visibility', stylePrev);
    $('#moldal-gallery .container .next').css('visibility', styleNext);
}



$(window).resize(function() {moldalGallery.realign();});


//VALIDATION
var ValidationType = new Object();
ValidationType.NOME = "nome";
ValidationType.EMAIL = "email";
ValidationType.LENGTH = "length";

var Validation = new Object();
Validation.fields = [];

Validation.addField = function(id, type, args)
{
   var field = new Object();
   field.id = id;
   field.type = type;
   field.args = args;
   
   Validation.fields.push(field);
}

Validation.clearFields = function() { Validation.fields = []; }

Validation.validate = function()
{
    var _return = true;
    
    for(i = 0 ; i < Validation.fields.length ; i++)
    {
        var field = Validation.fields[(Validation.fields.length - 1) -i];
        if(!validateField(field.id, field.type, field.args)) _return = false;
    }
    
    Validation.clearFields();
    return _return;
}

function validateField(id, type, args)
{
    var field = $(id);
    
    switch(type)
    {
        case ValidationType.EMAIL:
            if(field.val().match(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/)==null)
            {
                markAsInvalid(field);
                return false;
            }
            else
            {
                markAsValid(field);
                return true;
            }
            
        break;
        
        case ValidationType.NOME:            
            if(field.val().length <= 2)
            {
                markAsInvalid(field);
                return false;    
            }
            else
            {
                markAsValid(field);
                return true;
            }
        break;
		
		case ValidationType.LENGTH:
			if(field.val().length < args)
            {
                markAsInvalid(field);
                return false;    
            }
            else
            {
                markAsValid(field);
                return true;
            }
		break;
    }
}

function markAsValid(field) {field.removeClass("invalid");}
function markAsInvalid(field) {field.addClass("invalid");field.focus();}
