var dest = new Array();
dest[0] = 'disenyo-web';
dest[1] = 'tiendas-online';
dest[2] = 'weblogs';

function isValidEmail(str) {
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

function captify() {
    $('img.captify').captify({
        // speed of the mouseover effect
        speedOver: 'fast',
        // speed of the mouseout effect
        speedOut: 'normal',
        // how long to delay the hiding of the caption after mouseout (ms)
        hideDelay: 500,
        // 'fade', 'slide', 'always-on'
        animation: 'slide',
        // text/html to be placed at the beginning of every caption
        prefix: '',
        // opacity of the caption on mouse over
        opacity: '0.7',
        // the name of the CSS class to apply to the caption box
        className: 'caption-bottom',
        // position of the caption (top or bottom)
        position: 'bottom',
        // caption span % of the image
        spanWidth: '100%'
    });

}

function imagehover() {
    $('.proyectos img').mouseenter(function() {
        $('.proyectos img, #portfolio_image').stop(true, true).fadeIn();
        var img = $(this).attr('src');
        var portfolio = img.replace('.png', '_portfolio.jpg');
        var caption = img.replace('images/', 'caption-');
        caption = caption.replace('.png', '');
        $('.caption-bottom:last').html($('#' + caption).html());
        $('#' + caption).removeClass('hidden');
        //captify();
        $('#portfolio_image').fadeTo(0, 0, function() {
            $('#portfolio_image img').attr('src', portfolio);
            $('#portfolio_image').fadeTo(0, 1, function() {
                $('.captify').trigger('mouseenter');
            });
        });
    }).mouseout(function() {
        $('.captify').trigger('mouseout');
    });

    $.each($('.proyectos li'), function(index, value) {
        var comentario = $(this).find('.comentario').html();
        $('img', this).attr('alt', comentario);
    });

    $('.proyectos img').tipTip({
        attribute: "alt"
    });
}

var portfolio = {

    current_page: 1,
    current_page_count: 1,

    container: {
        width: 0,
        height: 0
    },

    init: function() {

        portfolio.container.width = $('#proyectos').width();
        portfolio.container.height = $('#proyectos').height();

        $('.hidden').css('display', 'block');

        //order all the elements appropriately in all unordered lists
        $('#proyectos ul.proyectos').each(function() {

            var cursor = {
                x: 0,
                y: 0,
                page: 0
            };

            var row_height = 0;

            //set positions for each element
            $(this).find('li').each(function() {

                //if the size of the element exceeds the space left on the row, move to next row
                if ($(this).outerWidth() > (portfolio.container.width - cursor.x)) {
                    cursor.y += row_height;
                    cursor.x = 0;

                    //and resetting the row height
                    row_height = $(this).outerHeight(true);
                }

                //determining the height of the row
                if ($(this).outerHeight(true) > row_height) {
                    row_height = $(this).outerHeight(true);
                }

                //if the height of the element exceeds the space left on the page, move to next page
                if ($(this).outerHeight() > (portfolio.container.height - cursor.y)) {
                    cursor.x = 0;
                    cursor.y = 0;
                    cursor.page += 1;
                }

                //and we can finally set the appropriate position for the element
                $(this).animate({
                    'left': (cursor.page * portfolio.container.width) + cursor.x,
                    'top': cursor.y
                });
                //and move cursor to the right
                cursor.x += $(this).outerWidth(true);
            });

            $(this).data('page_count', cursor.page + 1);

        });


        $('.hidden').hide().removeAttr('style');

        $('#proyectos').append('<div class="pagination"></div>');
        portfolio.refresh_pagination('container');

        //add the dragging feature for navigation
        $('#proyectos').mousedown(function(mdown) {
            mdown.preventDefault();
            var click_x = mdown.pageX;
            var start_left = $('#container').position();
            start_left = start_left.left;
            var delta;


            $(document).bind('mousemove', function(mmove) {
                mmove.preventDefault();
                delta = mmove.pageX - click_x;
                //$('.pagination').html(delta);
                $('#container').css('left', start_left + delta);
            });

            $(document).bind('mouseup', function() {
                $(this).unbind('mouseup');
                $(this).unbind('mousemove');

                if (delta > (portfolio.container.width / 3) && portfolio.current_page > 1) {
                    portfolio.go_to(portfolio.current_page - 1);
                } else if (delta < ((-1) * portfolio.container.width / 3) && portfolio.current_page < portfolio.current_page_count) {
                    portfolio.go_to(portfolio.current_page + 1);
                } else {
                    portfolio.go_to(portfolio.current_page);
                }
            });
        });

    },

    refresh_pagination: function(list_id) {

        //portfolio.home();
        var the_list = $('#' + list_id);
        portfolio.current_page_count = the_list.data('page_count');
        var buttons = '';
        if (portfolio.current_page_count > 1) {
            buttons = '<a class="active">Page 1</a>';

            for (i = 2; i <= portfolio.current_page_count; i++) {
                buttons = buttons + '<a>Page ' + i + '</a>';
            }
        }

        $('#proyectos .pagination').html(buttons);

        $('#proyectos .pagination a').unbind();
        $('#proyectos .pagination a').click(function() {
            $('#container').stop(true, false);
            portfolio.go_to($(this).index() + 1);
        });
    },

    go_to: function(page_number) {

        $('#proyectos .pagination a.active').removeClass('active');
        $('#proyectos .pagination a:nth-child(' + page_number + ')').addClass('active');

        $('#container').animate({
            'left': ((page_number - 1) * (-portfolio.container.width)) + 'px'
        }, 600);

        portfolio.current_page = page_number;

    },

    home: function() {
        $('#container').css('left', 0);
        portfolio.current_page = 1;
    }

};


$(document).ready(function() {


    $('.comentario').addClass('hidden');

    $('.menuportfolio a').click(function(e) {
        portfolio.home();
        var i = $('.menuportfolio a').index(this);
        e.preventDefault();
        $('#container').quicksand($('#' + dest[i] + ' li'), function() {
            imagehover();
            portfolio.refresh_pagination(dest[i]);
        });
    });

    var img = new Image();
    img.src = $('#proyectos img:last').attr('src');
    img.onload = function() {
        $('.comentario').removeClass('hidden');
    };

    var pImg = new Array();
    var nImg = $('#proyectos img').size();
    var n = 0;
    $('#proyectos img').each(function(key, value) {
        var img = $(this).attr('src');
        var portfolio = img.replace('.png', '_portfolio.jpg');
        pImg[portfolio] = new Image();
        pImg[portfolio].src = portfolio;
        pImg[portfolio].onload = function() {
            n++;
            if (n == nImg) {
                $('#portfolio_image').removeClass('hidden');
                captify();
                imagehover();
            }
        };
        //alert($(this).attr('src'));
    });



    $.each($(".menu"), function(key, value) {
        var el0 = $(this).find('a:eq(0)');
        var el1 = $(this).find('a:eq(1)');
        var el2 = $(this).find('a:eq(2)');
        var el3 = $(this).find('a:eq(3)');

        el0.click(function(e) {
            e.preventDefault();
            $.scrollTo($(".menu:first a:first"), 800, {
                axis: 'y'
            });
        });

        el1.click(function(e) {
            e.preventDefault();
            $.scrollTo($("#que_hacemos img.h"), 800, {
                axis: 'y'
            });
        });

        el2.click(function(e) {
            e.preventDefault();
            $.scrollTo($("#portfolio img.h"), 800, {
                axis: 'y'
            });
        });

        el3.click(function(e) {
            e.preventDefault();
            $.scrollTo($("#contacto img.h"), 800, {
                axis: 'y'
            });
        });

        $('#top .button').click(function(e) {
            e.preventDefault();
            $.scrollTo($("#contacto img.h"), 800, {
                axis: 'y'
            });
        });

    });

    $('#msg').html('');

    $('#fancybox').fancybox();

    $('#contok > a').click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: 'mail.php',
            data: 'nombre=' + nombre + '&telefono=' + telefono + '&email=' + email + '&direccion=' + direccion + '&comentario=' + comentario,
            success: function(data) {
                $('#msg').html('El formulario se ha enviado correctamente. Gracias.');
                setTimeout(function() {
                    $('#msg').html('');
                    $('#fancybox-close').trigger('click');
                }, 3000);
            }
        });
    });

    $('.enviar .submit').click(function(e) {
        e.preventDefault();
        nombre = $('form input[name="nombre"]').val();
        email = $('form input[name="correo"]').val();
        direccion = $('form input[name="direccion"]').val();
        telefono = $('form input[name="telefono"]').val();
        comentario = $('#comentario').val();
        error = '';
        if (nombre == '') error += '<p>Campo nombre obligatorio<p>';
        if (email == '') {
            error += '<p>Campo email obligatorio</p>';
        } else {
            if (!isValidEmail(email)) error += '<p>Email no valido</p>';
        }
        if (error != '') {
            $('#cont > ul, #cont > a').css('display', 'none');
            $('#contok').hide();
            $('#conterror').html('<h3>Necesitas completar los siguientes campos</h3>' + error).show();
            $('#fancybox').trigger('click');
            return false;
        }

        else { // datos correctos
            $('#conterror').hide();
            $('#contok').show();
            $('li.nombre').html(nombre);
            $('li.telefono').html(telefono);
            $('li.direccion').html(direccion);
            $('li.email').html(email);
            $('li.comentario').html(comentario);

            $('#cont > ul, #cont > a').css('display', 'block');
            $('#fancybox').trigger('click');
            return false;
        }

    });

    var init = new Array();
    init[0] = $('form input[name="nombre"]').val();
    init[1] = $('form input[name="correo"]').val();
    init[2] = $('form input[name="direccion"]').val();
    init[3] = $('form input[name="telefono"]').val();
    init[4] = $('#comentario').val();

    $('.enviar input').focus(function() {
        var index = $('.enviar .left input').index(this);
        if ($(this).val() == init[index]) $(this).val('');
    }).blur(function() {
        var index = $('.enviar .left input').index(this);
        if ($(this).val() == '') $(this).val(init[index]);
    });

    $('#comentario').focus(function() {
        if ($(this).val() == init[4]) $(this).val('');
    }).blur(function() {
        if ($(this).val() == '') $(this).val(init[4]);
    });

    portfolio.init();
	
	
});
