
DEBUG=1;
LANG='pt';


$(document).ready(function(){
  mainApp.init();
})


var mainApp = {

  backDiv       : $('#back'),
  langDiv       : $('#lang'),
  footerDiv     : $('#footer'),
  contentDiv    : $('#content'),
  loadingDiv    : $('#loading'),
  menuDiv       : $('#menu'),
  logoDiv       : $('#logo'),

  blnBackLoaded : false,

    init : function() {
        
        mainApp.initLang();
        mainApp.adjust();
        mainApp.initAjax();
        mainApp.initSubMenus();

        $(window).resize(mainApp.adjust);
    },


    initAjax : function() {
        $.address.externalChange(function(event) {
            //$('a.ajax').address();

        //}).change(function(event) {
            var page = event.value;
            if (page=='/' || page=='/#' || page=='/!#' || page=='') {
                page = '/'+LANG+'/intro';
            }

            if (page.indexOf('home_manuel_alcino_pratas')!=-1) page = page.replace(/home_manuel_alcino_pratas/,'home');

            $('#menu a').removeClass('cur');
            $('#menu a[href*='+page+']').addClass('cur');

            var ajax = function() {
                
                if (page!='/'+LANG+'/intro' && !mainApp.blnBackLoaded) {
                    $('#back,#logo,#lang,#footer,#menu').fadeIn('normal',function(){
                        mainApp.blnBackLoaded = true;
                    });
                } else {
                    mainApp.blnBackLoaded = false;
                }
                $.ajax({
                    url: page,
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        //for (i in XMLHttpRequest) console.log(i+' '+XMLHttpRequest[i]);
                        //console.log(XMLHttpRequest.responseBody);
                        //console.log(page);
                    },
                    success: function(data, textStatus, XMLHttpRequest) {
                        //console.log(data);
                        //$('#content,#back').fadeTo(0,1);
                        $('.loading').remove();
                        $('#content').html(data);
                        $.address.title(ajaxContent.title + ' | Alcino Ourives');

                        
                        if (typeof ajaxContent.background != 'undefined') {
                            mainApp.setBackground(ajaxContent.background,ajaxContent.callbackIn);
                        } else {
                            ajaxContent.callbackIn();
                        }
                    }
                });
            };

            $('.subMenu:visible').animate({height:0},{duration:500});
            $('<div class="loading"></div>').appendTo('body');

            setTimeout(
                function(){
                    if (typeof ajaxContent != 'undefined') {
                        ajaxContent.callbackOut(ajax);
                    } else {
                        ajax();
                    }
                },
                500
            );
        });
    },


    getBackground : function(){
        return $(mainApp.backDiv).find('img').attr('src');
    },


    setBackground : function(src,callback) {
        var argLength = arguments.length;
        if (src==mainApp.getBackground()) {
            if (argLength==2) callback();
            return false;
        }
        $(mainApp.backDiv).fadeOut(500,function(){
            var img = new Image();

            img.onload = function(){
                $(mainApp.backDiv).find('img').attr('src',src);
                $(mainApp.backDiv).fadeIn(500,function(){
                    if (argLength==2) callback();
                })
            }
            img.src = src;
        });
        return false;
    },


    initScrollers : function(el){
        if (!el) el=$('.scroll-pane');
        $(el).jScrollPane({dragMaxHeight:20,scrollbarMargin:30});
    },


    adjust : function() {

        // redimendionar imagem de fundo
        var w=Math.ceil($(window).width());
        var h=Math.ceil($(window).height());

        var bodyOverflow = 'hidden';
        if (w<980 || h<590) {
            bodyOverflow = 'auto';
        }
        $('body').css({'overflow':bodyOverflow});
  
        var ratio=953/1600;

        if ((h/w) > ratio){
            $(mainApp.backDiv).height(h);
            $(mainApp.backDiv).width(h / ratio);
            $(mainApp.backDiv).children().height(h);
            $(mainApp.backDiv).children().width(h / ratio);
        } else {
            $(mainApp.backDiv).width(w);
            $(mainApp.backDiv).height(w * ratio);
            $(mainApp.backDiv).children().width(w);
            $(mainApp.backDiv).children().height(w * ratio);
        }

        var l0=Math.ceil($(window).width()/2-$(mainApp.backDiv).width()/2);
        var t0=Math.ceil($(window).height()/2-$(mainApp.backDiv).height()/2);

        var l1=Math.max(0,Math.ceil($(window).width()/2-$(mainApp.contentDiv).width()/2));
        var t1=Math.max(0,Math.ceil($(window).height()/2-$(mainApp.contentDiv).height()/2));

        // reposicionar imagem de fundo
        $(mainApp.backDiv).css({
            'left':l0+'px',
            //'top':t0+'px'
            'top':'0px'
        })

        // reposicionar conteúdo
        $(mainApp.contentDiv).css({
            'left':l1+'px',
            'top':t1+'px'
        })
        $(mainApp.loadingDiv).css({
            'left':l1+'px',
            'top':t1+'px'
        })
        $(mainApp.menuDiv).css({
            'left':l1+'px',
            'top':t1+$(mainApp.contentDiv).height()+'px'
        })

        // reposionar logo
        $(mainApp.logoDiv).css({
            'left':l1+'px',
            'top':t1-60+'px'
        })
        // reposionar línguas
        var l2=l1+$(mainApp.contentDiv).width()-$(mainApp.langDiv).width();
        $(mainApp.langDiv).css({
            'left':l2+'px'
        })
        // reposionar footer
        var l3=l1+$(mainApp.contentDiv).width()-$(mainApp.footerDiv).width();
        $(mainApp.footerDiv).css({
            'left':l3+'px'
        })
        // submenus
        b1=$(window).height()-$(mainApp.contentDiv).height()-$(mainApp.contentDiv).position().top;
        $('.subMenu').css({
            'left':l1+'px',
            'bottom':b1+'px'
        })
    },

    initLang : function() {
        $(mainApp.langDiv).hover(
            function(){
                $(mainApp.langDiv).addClass('open');
            },
            function(){
                $(mainApp.langDiv).removeClass('open');
            }
        );

        $('#lang #lang_'+LANG).hide();
			
			/*
        $(mainApp.langDiv).find('a').click(function(){
          $(this).blur();
          $(mainApp.langDiv).removeClass('open').find('li:first').html($(this).text());
          LANG=$(this).text().toLowerCase();
          $('#lang li').show();
          $('#lang li#lang_'+LANG).hide();

          return false;
        })
        */
    },

    initSubMenus : function() {        
        $('a[href=#empresa]').live('click',function(){
            //$('#content,#back').fadeTo('normal', 0.5);
            $('.sectionMenu').animate(
                {height:0},
                {
                    duration:500,
                    complete:function(){
                        h='150px';
                        if ($('#empresaSubMenu').height()!=0) h=0;
                        $('#empresaSubMenu').animate({height:h},500);
                        $('.sectionMenu').hide();
                    }
                }
            )
            return false;
        })
        $('a[href=#catalogo]').live('click',function(){
            //$('#content,#back').fadeTo('normal', 0.5);
            $('.sectionMenu').animate(
                {height:0},
                {
                    duration:500,
                    complete:function(){
                        h='358px';
                        if ($('#catalogoSubMenu').height()!=0) h=0;
                        $('#catalogoSubMenu').animate({height:h},500);
                        $('.sectionMenu').hide();
                    }
                }
            )
            return false;
        })
        
    }
}


function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function nl2br (str, is_xhtml) {
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
}

