var popup;
$(document).ready(function(){
    if(isIE6()){
        IE6Aviso();
        return false;
    }
    $('body').addClass('js');    
    activarCufon();
    slideHome();
    slideArticleList_T01($('#blkObras'));
    // Creo los popups    
    popup = new Popup();
    // Activo galerías.
    $('.gallery').each(function(i){
        var gal = new Gallery($(this),5,140,10,i+1,false);
    });
    // Links externos.
    $('a[rel=external]').attr('target','_blank');
    fontSize();
    // Muestro el mensaje de bienvenida.
    showMensajeBienvenida();
});


function fontSize(){
    var div = $('.fontSize');    
    var divText = div.closest('div.text');
    var btnMore = $('<span class="btnMore" title="Aumenta el tamaño de texto"></span>');
    var btnLess = $('<span class="btnLess" title="Disminuye el tamaño de texto"></span>');
    var currentSize = 12;  
    var maxSize = 18;
    var minSize = 11;
    var setFontSize = function(size){
        if(minSize<=size&&size<=maxSize){
            currentSize = size;
            divText.css('font-size',currentSize+'px');
        }
    };    
    btnMore.click(function(){
        setFontSize(currentSize+1);
    });
    btnLess.click(function(){
        setFontSize(currentSize-1);
    });    
    div.append(btnLess).append(btnMore);
}



function createCookie(name,value,days){
    if(days){
        var date=new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = ";expires="+date.toGMTString();
    }else {
        var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


                            



























function Gallery(div,itemsPerPag,itemWidth,sepWidth,galleryCount,preloadImg){    
    if(itemsPerPag==undefined||itemWidth==undefined||sepWidth==undefined||galleryCount==undefined){
        return false;
    }
    
    if(preloadImg==undefined){
        preloadImg=true;
    }

    var ul = $('ul',div);
    var aItems = [];    
    var tot = $('li a',ul).length;
    var itemsIds = [],itemsById = {};
    var currentImage = 0;
    var currentPage = -1;    
    var totPag = Math.ceil(tot/itemsPerPag);
    var showing = false;
    
    // Agrego elementos html galería.
    var divBtns = $('<div class="btns"><span> | </span></div>'),
    btnPrevPage = $('<a href="" class="btnPrev">Anteriores</a>'),
    btnNextPage = $('<a href="" class="btnNext">Siguientes</a>');
    var divPag = $('<div class="pagInfo"><span> | '+tot+' Total</span></div>'),
    counterPages = $('<strong></strong>');        
    // Agrego elementos   
    if(1<totPag){
        divBtns.prepend(btnPrevPage).prepend(btnNextPage).prependTo(div);
    }
    divPag.prepend(counterPages).prependTo(div);    
    
    // Creo controles imagen ampliada.
    var divImageControls = $('<div></div>'),
    btnPrevImage = $('<a class="btnPrev" href="">Anterior</a>'),
    btnNextImage = $('<a class="btnNext" href="">Siguiente</a>'),
    counterImages= $('<strong></strong>'),
    divCounterImages= $('<div class="imagesPagination"><span> | '+tot+' Total</span></div>'),
    btnClose = $('<a class="btnClose" href="">Cerrar</a>'); 
    // Agrego elementos.
    divImageControls.append(btnPrevImage).append(btnNextImage).append(btnClose).append(divCounterImages);
    divCounterImages.prepend(counterImages);
    

    /*  Funciones paginado */
    var disablePageBtns = function(pag){
        if(pag==totPag){
            btnNextPage.addClass('disable');
        }else{
            btnNextPage.removeClass('disable');            
        }
        if(pag==1){
            btnPrevPage.addClass('disable');
        }else{
            btnPrevPage.removeClass('disable');            
        }        
    };
    var showPageInfo = function(pag){
        var firstItem = ((pag-1)*itemsPerPag);
        counterPages.text(1+firstItem+' - '+Math.min(tot,firstItem+itemsPerPag));        
    };
    var goPage = function(pag){
        if(pag<1){
            pag = 1;
        }else if(totPag<pag){
            pag = totPag;
        }
        if(currentPage != pag){
            var xPos = (pag-1)*itemsPerPag*(itemWidth+sepWidth);
            ul.animate({
                'left':-xPos+'px'
            });
            disablePageBtns(pag);
            showPageInfo(pag);
            currentPage = pag;
        }
    };    
    var prevPage = function(){
        goPage(currentPage-1);        
    };    
    var nextPage = function(){
        goPage(currentPage+1);
    };
    //  Activo botones.
    btnPrevPage.click(function(){
        prevPage();
        return false;
    });
    btnNextPage.click(function(){
        nextPage();
        return false;
    });
    
    /*  Ampliar imagen  */
    var setCurrentIndex = function(i){
        currentImage = i;  
        var page = Math.ceil((1+i)/itemsPerPag);        
        if(page!=currentPage){
            // Agrego delay para evitar que se mueva la galería mientras esta el fade.
            setTimeout(function(){
                goPage(page)
            },600);  
        }
        counterImages.text('Imagen '+(i+1));
    }  
    var showImageById = function(id){
        showing = true;
        var i = 0;
        while(i<itemsIds.length&&itemsIds[i]!=id){
            i++;
        }
        setCurrentIndex(i);
        var item= itemsById[id].html;
        if(itemsById[id].loaded==true){
            popup.show(id,true);
            // Agrego el menu navegacion en la imagen.
            setTimeout(function(){
                itemsById[id].html.append(divImageControls);
                Cufon.replace(
                    'div.galleryImg a',
                    {
                        fontFamily: 'cambria',
                        hover:true
                    });   
            },200);
        }else{
            popup.show('galImage_'+galleryCount+'_loading',true);
            if(!preloadImg){
                var href= aItems[i].attr('href');
                var imgObj = new Image();
                imgObj.onload = function(){
                    item.width(this.width);
                    item.prepend(this);
                    // Indico que se cargo la imagen.
                    itemsById[id].loaded = true;
                    // Si se estaba mostrando la imagen.
                    if(showing&&itemsIds[currentImage]==id){
                        showImageById(id);
                    }
                };
                setTimeout(function(){
                    imgObj.src = href;
                },1000);
                
            }
        }
    };
    var hideImage = function(){
        showing = false;
        popup.close();        
    };
    var showImage = function(i){
        if(i<0){
            i = itemsIds.length-1;
        }else if(itemsIds.length<=i){
            i=0;
        }
        var id = itemsIds[i];
        showImageById(id);
    };
    var prevImage = function(){
        showImage(currentImage-1);
    };
    var nextImage = function(){
        showImage(currentImage+1);        
    };    
    btnPrevImage.click(function(){
        prevImage();
        return false;
    });    
    btnNextImage.click(function(){
        nextImage();
        return false;
    });   
    btnClose.click(function(){
        hideImage();
        return false;
    });
    
    // Agrego popup loading.
    popup.add('galImage_'+galleryCount+'_loading',$('<div class="galleryImgLoading"></div>'), false, true);
    
    // Genero los popups para ampliar las imágenes.
    $('li a',ul).each(function(i){
        var a = $(this);
        aItems.push(a);
        var id = 'galImage_'+galleryCount+'_'+i;
        var item = $('<div class="galleryImg"></div>');
        if(preloadImg){
            var imgObj = new Image();
            imgObj.onload = function(){
                item.width(this.width);
                item.prepend(this);
                // Indico que se cargo la imagen.
                itemsById[id].loaded = true;
                // Si se estaba mostrando la imagen.
                if(showing&&itemsIds[currentImage]==id){                
                    showImageById(id);
                }
            };
            imgObj.src = a.attr('href');
        }
        var desc = $('<em></em>');
        desc.text($('img',a).attr('alt')); 
        desc.appendTo(item);  
        // Guardo en la colección.
        itemsIds.push(id);
        itemsById[id] = {
            'loaded':false,
            'html':item
        };        
        // Agrego popup.
        popup.add(id,item, false, true);
        a.click(function(){
            showImageById(id);
            return false;            
        });
    });
    
    // Inicializo en la primer página.
    goPage(1);    
    
    // Completo con con recuadro gris las imágenes faltantes.
    var totEmptyItems = itemsPerPag-(tot%itemsPerPag);
    for(i=0;i<totEmptyItems;i++){
        ul.append('<li><div class="relleno"><div></div></div></li>');        
    }
}
function slideArticleList_T01(blk){
    var div = $('.articleList.t01',blk);
    if(div.length==1){
        var items = [];
        var currentIndex = 0;
        var articles = $('.article',div);
        var tot = articles.length;
        var divBtns = $('<div class="btns"></div>'),
        pagination = $('<span class="pag"></span>'),
        counter = $('<strong>1</strong>');
        btnNext = $('<span class="btnNext"></span>'),
        btnPrev = $('<span class="btnPrev"></span>');
        var timer;
        var itemWidth=620,itemSep=20;
        var intervalo = 4000,direction=1;   
        
        // Agrego contenedor.
        div.wrap('<div class="slide"></div>');
        div.width(tot*(itemWidth+itemSep)+100);        
        pagination.text(' / '+tot).prepend(counter);
        
        // Muestra el item seleccionado.        
        var mostrarItem = function(i){
            if(timer!=undefined){
                clearTimeout(timer);
            }  
            if(tot-1<i){
                i=0;
            }else if(i<0){
                i = tot-1;
            }       
            if(i==0){                
                direction = 1;
            }else if(i==tot-1){     
                direction = -1;                
            }
            
            div.animate({
                left:-(i*(itemWidth+itemSep))+'px'
            },function(){
                currentIndex = i;
            });
            counter.text(i+1);
        };   
        
        // Muestra el item siguiente.
        var mostrarSiguiente = function(){                    
            mostrarItem(currentIndex+direction);  
            timer = setTimeout(function(){
                mostrarSiguiente();
            },intervalo);        
        };

        
        articles.each(function(i){
            var item = $(this);
            var div = $('<div style="width:'+itemWidth+'px;margin-right:'+itemSep+'px;float:left;"></div>');
            item.wrap(div);
            items.push(item);
        });       
        
        // Activo botones.
        btnPrev.click(function(){          
            mostrarItem(currentIndex-1);  
        });
        btnNext.click(function(){          
            mostrarItem(currentIndex+1);  
        });
  
        //  Agrego contenedor navegación.
        divBtns.append(btnPrev).append(btnNext).append(pagination).insertAfter(div);
       
        // Inicializo.
        timer = setTimeout(function(){
            mostrarSiguiente();
        },intervalo+2000);        
        
        div.mouseover(function(){
            if(timer!=undefined){
                clearTimeout(timer);
            }
        }).mouseleave(function(){
            if(timer!=undefined){
                clearTimeout(timer);
            }
            timer = setTimeout(function(){
                mostrarSiguiente();
            },intervalo);
        });
    }
}
function slideHome(){
    var div = $('#pgHome div#heading');
    if(div.length==1){        
        var items = [];
        var imgs = [];
        var currentIndex = 0;
        var articles = $('.article',div);
        var tot = articles.length;
        var divBtns = $('<div class="btns"></div>');
        var btn;
        var timer;
        var intervalo = 4000;        

        var mostrarItem = function(i){
            if(tot-1<i){
                i=0;                
            }       
            // Marco botón.
            $('span.selected',divBtns).removeClass('selected');
            $('span._'+i,divBtns).addClass('selected');            
            if(currentIndex<i){
                items[currentIndex].fadeOut('normal');
                items[i].fadeIn('slow'); 
                imgs[i].fadeIn(function(){
                    imgs[currentIndex].hide();             
                    currentIndex = i;
                }); 
            }else if(i<currentIndex){
                items[currentIndex].fadeOut();
                items[i].fadeIn(); 
                imgs[i].css({
                    'display':'block'
                });                
                imgs[currentIndex].fadeOut(function(){    
                    currentIndex = i;
                }); 
            }            
        };        
        var mostrarSiguiente = function(i){           
            mostrarItem(currentIndex+1);           
            timer = setTimeout(function(){
                mostrarSiguiente();
            },intervalo);             
        };
        //  Elimino clase que se utiliza para dar estilos si no hay js.
        $('div.articleList',div).removeClass('t02');        
        articles.each(function(i){
            var item = $(this);
            item.css({
                'z-index':i,
                display:'none'
            });
            items.push(item);
            var img = $('a.img',item);
            img.css({
                'z-index':i,
                display:'none'
            });
            imgs.push(img);
            img.appendTo(div);
            var tit = $('.tit',item);
            var a = $('a',tit);
            var textoTit = a.text();
            tit.html('').text(textoTit);
            a.text('Ampliar información').addClass('btn t02').appendTo(item);
        });
        // Muestro el primer banner.
        items[0].show(); 
        imgs[0].show();         
        //  Agrego botones "paginado".
        divBtns.appendTo(div);
        for(var i=0;i<tot;i++){
            btn = $('<span class="_'+i+(i==0?' selected':'')+'">'+i+'</span>');
            btn.click(function(){
                var index = parseInt($(this).text());
                mostrarItem(index);
            }).appendTo(divBtns);
            // Centro los botones en base al primero.
            if(i==0){
                btn.css({
                    'margin-left':(300-(20*tot))/2+'px'
                });                
            }            
        }        
        timer = setTimeout(function(){
            mostrarSiguiente();
        },intervalo);        
        
        div.mouseover(function(){
            if(timer!=undefined){
                clearTimeout(timer);
            }
        }).mouseleave(function(){
            if(timer!=undefined){
                clearTimeout(timer);
            }
            timer = setTimeout(function(){
                mostrarSiguiente();
            },intervalo);
        });
    }
}
function activarCufon(){
    // Cufon para títulos.
    Cufon.replace(
        '#header .info strong'+
        ',#main h1'+
        ',.articleList.t01 .article > .tit'+
        ',.articleList.t02 .article > .tit'+
        ',.articleList.t03 .article > .tit'+
        ',.articleList.t03 .article > .date'+
        ',.articleList.t04 .article > .tit'+
        ',.articleList.t04 .article > .date'+
        ',#footer ul.menu strong'+
        ',#secondaryMenu a'+
        ',#sideMenu > ul > li > a'+
        ',#sideMenu > ul > li > strong'+
        ',ul.menu > li > a'+
        ',ul.menu > li > strong'+
        ',#blkIntendente .tit'+
        ',.btn.t01'+
        ',.btn.t02'+
        ',.btn.t03'+
        ',#blkInfoHorarios strong'+
        ',#pgHome #heading .tit'+
        ',.block.t01 > .hdr .tit'+
        ',.block.t02 > .hdr .tit'+
        ',.block.t03 > .hdr .tit'+
        ',dl.autoridades dt',
        {
            fontFamily: 'cambria',
            hover:true
        }
        );

    /*  Agrego strong y span para hover del menu. El hover solo da problemas */
    $('#mainMenu > li > a').each(function(){
        var a=$(this),text=a.text();
        a.html('<strong>'+text+'</strong>').append('<span>'+text+'</span>');
    });
    // Cufon en main menu.
    Cufon.replace(
        '#mainMenu>li>a',
        {
            fontFamily: 'cambria'
        });
}



if(typeof(isIE)!='function')
    function isIE(){
        return ($.browser.msie);
    }
if(typeof(isIE6)!='function')
    function isIE6(){
        if(isIE()&&parseInt($.browser.version)==6)return true;
        return false;
    }
if(typeof(isIE7)!='function')
    function isIE7(){
        if(isIE()&&parseInt($.browser.version)==7)return true;
        return false;
    }
    
function IE6Aviso(){
    $('html').css({
        background:'#fff'
    });
    $('body').css({
        background:'#fff'
    }).html('<div style="clear: both; height: 59px; width:820px;margin:200px auto; position: relative;"><a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode"><img src="http://ie6countdown.blob.core.windows.net/assets/100/images/banners/warning_bar_0012_spanish_LATAM.jpg" border="0" height="42" width="820" alt="Actualizar la versión de Internet Explorer." /></a></div>');        
}
