var top_is_open = true;
var main_is_open = false;
var mainTopOpen = 190;
var mainTopClosed = null;
var topOpenHeight = null;
var contentOpenHeight = null;
var footerTop = null;

var here = window.location.href;

var dt = new Date();
var thisDt = dt.getFullYear()+'-'+dt.getMonth();
var today = dt.getDate();
var thisMonth = dt.getMonth();
var thisYear = dt.getFullYear();
var thisPane = null;
var thisPaneN = 0;
var nPanes = null;

var thisEvPane = null;
var thisEvPaneN = 0;
var nEvPanes = null;

var nPicsPanes = 0;
var thisPicPane = 0;

var voteWidth = 519;
var voteHeight = 568;

var thisThumbPreview = null;

var _sbloaded = false;

initsb();
function initsb() {
    if (_sbloaded == false) {
        Shadowbox.init({skipSetup: true, handleOversize: 'none'});
        _sbloaded = true;
    }
}

$(document).ready(function() {
    resizeLayout();

    $(window).resize(function(ev) {
       resizeLayout();
    });

    $('#logo').fadeIn(3000);

    $('.main-close').click(function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        if (!main_is_open) return;
        $('#intro').fadeIn();
        $('#main').animate({ top: mainTopClosed+'px'});
        $('#content_wrapper').html('');

        $('#navbar a').removeClass('selected');
        main_is_open = false;
    });
    $('.main-open').click(function(ev) {
        if (main_is_open && here == ev.target.href) {
            here = ev.target.href;
            showPage();
            return;
        }

        here = ev.target.href;

        $('#intro').fadeOut();
        $('#main').animate({ top: mainTopOpen+'px'}, {complete: showPage});
        main_is_open = true;
    });
    $('#content_wrapper').delegate('#contactenos #submit', 'click', function() {
        //alert('Working in ajax version of this form ;-)');
        
    });

    setupCalendario();
    setup1eraEdicion();
    setup2daEdicion();
    setupGaleria();
    setupContactenos();
    setupParticipa();

    // Set page on reload
    var section = getSection(here);
    if (section != false) {
        $('a[href=#'+section[1]+']').trigger('click');
    }
});

function getSection(url) {
    var toks = url.split('#');
    if (toks[1] == undefined) {
        return false;
    }
    var subtoks = toks[1].split(',');
    toks.pop();
    for(var i in subtoks) {
        toks.push(subtoks[i]);
    }

    return toks;
}

function showPage(section) {
    if (section) {
        here = section;
    }

    var sect = getSection(here);
    $('#navbar a').removeClass('selected');
    $('a[href=#'+sect[1]+']').addClass('selected');

    var url = pageUrl(here);

    $('#content_wrapper').scrollTo(0);
    $('#content_wrapper').load(url, {complete: function() {
        $('#content_wrapper').css({ height: contentOpenHeight+'px', overflow: 'auto'});
        //removeCargando('#content_wrapper');
    }});
}

function resizeLayout() {
    var docHeight = $(window).height();
    var docWidth = $(window).width();
    topOpenHeight = docHeight - $('#footer').height() - $('#navbar').height() + 21;
    contentOpenHeight = topOpenHeight - 220;
    mainTopClosed = docHeight - $('#footer').height() - $('#navbar').height();

    footerTop = docHeight - $('#footer').height();

    $('#layout').css({ width: docWidth+'px', height: docHeight+'px', top: 0 });
    $('#footer').css({ width: docWidth+'px', left: 0, top: footerTop+'px' });

    //$('#content').css({ height: contentOpenHeight+'px', width: docWidth+'px' });
    $('#main').css({ width: docWidth+'px' });
    $('#content_wrapper').css({ height: contentOpenHeight+'px', overflow: 'auto'});
    if (main_is_open) {
        $('#main').css({top: mainTopOpen+'px'});
    } else {
        $('#main').css({top: mainTopClosed+'px'});
    }
    /*
    if (top_is_open) {
        $('#header').css({ height: topOpenHeight+'px', width: docWidth+'px' });
        //$('#content').css({ height: 0, width: docWidth+'px' });
        //$('#content_wrapper').css({ height: 0 });
    } else {
        $('#header').css({ height: '250px', width: docWidth+'px' });
        //$('#content').css({ height: contentOpenHeight+'px', width: docWidth+'px' });
    }*/
}

function pageUrl(url) {
    var sect = getSection(url);
    return sect[0] + 'site/' + sect[1];
}

function setupParticipa() {
    $('#content_wrapper').ajaxComplete(function(e, xhr, settings) {
        if (settings.url.search('/participa') > 0) {
            $('#content_wrapper .link a').live('click', function(ev) {
                ev.preventDefault();
                ev.stopPropagation();
                return false;
            })
        }
    });
}

function setupCalendario() {
    $('#content_wrapper').ajaxComplete(function(e, xhr, settings) {
        if (settings.url.search('/calendario')) {
            nPanes = $('#month_selector .cal_panes').length;
            thisPane = $('#month_selector .cal_panes')[0];
            thisPaneN = 0;

            nEvPanes = $('#months_btns .event_lnk').length;
            thisEvPane = $('#months_btns .event_lnk')[0];
            thisEvPaneN = 0;
        }
    });

    $('#content_wrapper #date_select').live('change', function(ev) {
        var pane = $('#m'+$(ev.target).val());

        var thisPanePos = $(thisPane).position();
        var nextPanePos = $(pane).position();
        var dt = $(ev.target).val().split('-');
        $('#month_selector .clip').animate({left: -nextPanePos.left+'px'});

        var evPane = $('#months_btns .m'+dt[1]+'.y'+dt[0])[0];
        if (evPane != undefined) {
            $('#months_btns .clip').animate({left: -$(evPane).position().left+'px'});
            thisEvPane = evPane;
        }
        thisPane = pane;
    });
    $('#content_wrapper #cal_prev').live('click', function(ev) {
        ev.stopPropagation();
        ev.preventDefault();

        if (thisEvPaneN <= 0) {
            thisEvPaneN = nEvPanes; //-2;
        }

        var pane = $('#months_btns .event_lnk')[--thisEvPaneN];
        $('#months_btns .clip').animate({left: -$(pane).position().left+'px'});
        thisEvPane = pane;
    });
    $('#content_wrapper #cal_next').live('click', function(ev) {
        ev.stopPropagation();
        ev.preventDefault();

        //if (thisEvPaneN >= (nEvPanes-3)) {
        if (thisEvPaneN >= (nEvPanes-1)) {
            thisEvPaneN = -1;
        }

        var pane = $('#months_btns .event_lnk')[++thisEvPaneN];
        $('#months_btns .clip').animate({left: -$(pane).position().left+'px'});
        thisEvPane = pane;
    });
    $('#content_wrapper .day.event').live('click', function(ev) {
        var id = $(ev.currentTarget).attr('id');
        var date = {y:id.substr(1,4), m:id.substr(5,2), d:id.substr(8,2)};

        var pane = $('#e'+id.substr(1));
        $('#months_btns .clip').animate({left: -$(pane).position().left+'px'});
        pane.trigger('click');
        thisEvPane = pane;
    });
    $('#content_wrapper .event_lnk').live('click', function(ev) {
        $('.months_link').find('.info').hide();
        $(ev.currentTarget).find('.info').fadeIn('slow');
    });
}

function setup1eraEdicion() {
    $('#content_wrapper').ajaxComplete(function(e, xhr, settings) {
        if (settings.url.search('/primera_edicion') > 0) {
            thisPicPane = 0;
            nPicsPanes = $('#galeria .picpane').length;

            voteHeight = 500;

            var sect = getSection(window.location.href);
            if (typeof sect[2] === 'string') {
                openVoteForm(sect[0]+'site/galeria_1era_edicion/'+sect[2]);
            }
        }
    });
}

function setup2daEdicion() {
    $('#content_wrapper').ajaxComplete(function(e, xhr, settings) {
        if (settings.url.search('/segunda_edicion') > 0) {
            thisPicPane = 0;
            nPicsPanes = $('#galeria .picpane').length;

            voteHeight = 500;

            var sect = getSection(window.location.href);
            if (typeof sect[2] === 'string') {
                openVoteForm(sect[0]+'site/galeria_2da_edicion/'+sect[2]);
            }
        }
    });
}


function setupGaleria() {
    $('#content_wrapper').ajaxComplete(function(e, xhr, settings) {
        if (settings.url.search('/galeria') > 0) {
            thisPicPane = 0;
            nPicsPanes = $('#galeria .picpane').length;
            voteHeight = 568;

            var sect = getSection(window.location.href);

            if (typeof sect[3] === 'string') {
                openVoteForm(sect[0]+'site/galeria_foto/'+sect[3]+'/'+sect[2]);
            }
        }
    });

    $('#content_wrapper .pics .title').live('click', clickOpenVoteForm);
    $('#content_wrapper .thumbs a').live('click', clickOpenVoteForm);
    $('#content_wrapper .toolbar .go_fotos').live('click', function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        var toks = $(ev.currentTarget).get(0).href.split('_');
        if (toks[1] == undefined)
            return;
        var pos = $('#pane'+toks[1]).position();
        $('#galeria .wrapper').animate({left: -pos.left+'px'});
        thisPicPane = toks[1];
    });
    $('#content_wrapper .toolbar #prev_fotos').live('click', function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        if (thisPicPane < 1) {
            return;
        }
        thisPicPane--;
        var pos = $('#pane'+thisPicPane).position();
        if (pos) {
            $('#galeria .wrapper').animate({left: -pos.left+'px'});
        }
    });
    $('#content_wrapper .toolbar #next_fotos').live('click', function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        if (thisPicPane >= nPicsPanes) {
            return;
        }
        thisPicPane++;
        var pos = $('#pane'+thisPicPane).position();
        if (pos) {
            $('#galeria .wrapper').animate({left: -pos.left+'px'});
        }
    });

    $('#content_wrapper .thumbs a').live('mouseenter', function(ev) {

        $('#thumb_preview').remove();
        var a = ev.currentTarget;
        thisThumbPreview = $(ev.currentTarget).parent();
       // pos.top = $(ev.currentTarget).position().top;
        $('#layout').after('<div id="thumb_preview"></div>');
        $(a).next('a').clone(true).appendTo('#thumb_preview').show();
        //$('#thumb_preview').hide();
        //$('#__previmg').load(function(ev) {setPreviewPos(); $('#thumb_preview').show();}).attr('src',$(a).parent().attr('data-preview'));

        setPreviewPos();
    });
    $('#content_wrapper .thumbs a').live('mousemove', function(ev) {
        setPreviewPos();
    });
    $('#default #thumb_preview').live('mouseleave', function(ev) {
        thisThumbPreview = null;
        $(ev.currentTarget).remove();
    });
    $('#default .preview_link').live('click', function(ev) {
        thisThumbPreview = null;
        $('#thumb_preview').remove();
        clickOpenVoteForm(ev);
    });

}

function setPreviewPos() {
    if (!thisThumbPreview) return;
    var pos = $(thisThumbPreview).parent().find('.info').offset();

    var top = pos.top-$('#thumb_preview').height()-10;
    var left = pos.left-($('#thumb_preview').width()/3);
    if (left < 0) {
        left = 10;
    }

    $('#thumb_preview').css({left: left+'px', top: top+'px'});
}

function setupContactenos() {
    $('#content_wrapper').ajaxComplete(function(e, xhr, settings) {
        if (settings.url.search('/contactenos') > 0) {
        }
    });

    $('#content_wrapper #contactenos #submit').live('click', function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        $('#contactenos #submit').attr({
            disabled: 'true'
        }).html('Enviando...');
        var url = $('#contactenos form').attr('action');
        var d = $('#contactenos form').serialize();

        $.post(url, d, function(res) {
            var data = jQuery.parseJSON(res); 

            $('#ajaxMsg').html(data.msg);
            $('#contactenos #submit').html('Enviar').removeAttr('disabled');
            $('#content_wrapper').scrollTo(0);

            if (data.status == 1) {
                clear_form('#contactenos form');
            }
        });

    });
}

function clickOpenVoteForm(ev) {
    ev.preventDefault();
    ev.stopPropagation();

    openVoteForm($(ev.currentTarget).get(0).href);
}

function openVoteForm(url) {
    initsb();
    Shadowbox.open({
        content: url,
        player: 'iframe',
        title: null,
        width: voteWidth,
        height: voteHeight
    });
}

function showCargando(clss) {
    return '<div class="loader '+clss+'">Cargando</div>';
}

function removeCargando(container) {
    $(container).find('.loader').remove();
}

function clear_form(ele) {

    $(ele).find(':input').each(function() {
        switch(this.type) {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });

}
