// ec.minamin.js
(function($) {
    var $$ = $.fn.minamin = function(defecto, settings) {
        settings = $.extend({
            nav: '.Tabs_nav',
            news: '#BoxNoticias',
            pages: '.paginador',
            overlay: '.overlay'
        },
        settings);
        var defsection = (defecto != null) ? defecto: 'ultimas';
        var $this = this;
        var $nav = $this.find(settings.nav);
        var $pages = $this.find(settings.pages);
        var $news = $this.find(settings.news);
        var $overlay = $this.find(settings.overlay);
        $nav.find('li a').each(function() {
            this._href = this.href;
            var hash = $(this).parent()[0].className.split(' ')[0];
            this.href = '#minamin_' + hash;
        }).click(function() {
            var $this = $(this);
            var d = new Date();
            var t = d.getHours() + '' + d.getMinutes() + '' + d.getSeconds();
            var href = $this[0]._href + '?time=' + t;
            if ($this.parent().is('.activo')) return false;
            cert_registerHit(18972, '/ediciononline/portada', 'certPivot');
            $overlay.show();
            $$.changeborderbottom($this.parent().attr("class"));
            $("#BoxTabs").attr("class", "nav" + $this.parent().attr("class"));
            $this.parent().siblings().removeClass('activo').end().addClass('activo');
            $news.empty().load(href,
            function() {
                $$.pages($pages, settings);
                $overlay.fadeOut('fast');
                $("#BoxNoticias .categ a").click(function() {
                    var hash = this.href.split("#")[1];
                    $$.filter(hash, settings);
                });
            });
            window.title = "El Comercio Per&uacute;";
            return false;
        });
        $overlay.hide();
        $$.changeborderbottom(defsection);
        var hash = String((document.location) ? document.location: document.location.href);
        if (hash.indexOf('#minamin_') !== -1 && hash.indexOf('#minamin_ultimas') == -1) {
            $$.hash(settings);
            var $activo = $('ul li', $nav).filter('.activo');
            var initHref = $activo.find('a')[0]._href;
            $news.load(initHref,
            function() {
                $$.pages($pages, settings);
                $overlay.fadeOut('fast');
                $news.css("display", "block");
            });
        } else {
            if (defsection != 'ultimas') {
                $$.hash(settings, defsection);
                var $activo = $('ul li', $nav).filter('.activo:not(:first-child)');
                var initHref = $activo.find('a')[0]._href;
                $news.load(initHref,
                function() {
                    $$.pages($pages, settings);
                    $overlay.fadeOut('fast');
                    $news.css("display", "block");
                });
            } else {
                $$.pages($pages, settings);
                $news.css("display", "block");
            }
        }
        $("#BoxTabs").attr("class", "nav" + $("#BoxTabs .ui-tabs-nav li.activo").attr("class").split(" ")[0]);
        $("#BoxNoticias .categ a").each(function() {}).click(function() {
            var hash = this.href.split("#")[1]; (hash == 'minamin_ee.uu.08') ? hash = 'minamin_euvote': hash = hash;
            $$.filter(hash, settings);
        });
        return this;
    };
    $$.filter = function(_hash, sett) {
        $$.changeborderbottom(_hash.split("minamin_")[1]);
        $(sett.overlay).hide();
        var hash = "#" + _hash;
        var $activo;
        $('ul li a', sett.nav).each(function() {
            if ($(this).attr("href") == hash) {
                $activo = this;
            }
        });
        var pageto = $activo._href;
        $(sett.news).load(pageto,
        function() {
            $$.pages($(sett.pages), sett);
            $(sett.overlay).fadeOut('fast');
        });
        var newactive = $($activo).parent().attr("class");
        $("li[@class=" + newactive + "]", sett.nav).siblings().removeClass('activo').end().addClass('activo');
        $("#BoxTabs").attr("class", "nav" + newactive);
        window.title = "El Comercio Per&uacute;";
    }
    $$.changeborderbottom = function(opt) {
        var borderbottomColor = '#E5E5E5';
        switch (opt) {
        case 'ultimas':
            borderbottomColor = '#C06';
            break;
        case 'deportes':
            borderbottomColor = '#6E9312';
            break;
        case 'jjoo':
            borderbottomColor = '#F00';
            break;
        default:
            borderbottomColor = '#000';
            break;
        }
        $('#BoxMinaMin').css("border-bottom", "4px solid " + borderbottomColor);
    }
    $$.pages = function($_pages, settings) {
        var mmpageout = '';
        var quant = $_pages.parent().parent().find(settings.news + ' .page').length;
        if (quant > 1) {
            mmpageout = '<ul><li class="flechas"><a href="#prev" class="pmprev"><img width="8" height="11" border="0" alt="Anterior" src="/files/image/paginador_flecha_izq.gif"/></a></li>';
            for (var i = 0; i < quant; i++) {
                var pageid = Number(i + 1);
                mmpageout += '<li ' + ((i == 0) ? 'class="active"': "") + '><a href="#page-' + pageid + '" class="mpage-' + pageid + '">' + pageid + '</a></li>';
            }
            mmpageout += '<li class="flechas"><a href="#next" class="pmnext"><img width="8" height="11" border="0" alt="Siguiente" src="/files/image/paginador_flecha_der.gif"/></a></li></ul>';
        }

        $_pages.html(mmpageout);
        $('#BoxMinaMin .paginador a').click(function() {
            var $this = $(this);
            var href = $this.attr('href').split('#')[1];
            var className = $this.attr('class');
            if ($this.is('[class^=mpage]')) {
                $this.parent().siblings().andSelf().removeClass('active').end().end().addClass('active');
                $('#BoxMinaMin .paginador a.' + className).parent().siblings().removeClass('active').end().addClass('active');
                $('#' + href).siblings().andSelf().hide().end().end().show();
            } else {
                var active = $_pages.find('.active a').attr('class');
                var i = parseInt(active.split('-')[1]);
                if ($this.is('.pmprev')) {
                    i--;
                    if (i == 0) i = quant;
                } else if ($this.is('.pmnext')) {
                    i++;
                    if (i == quant + 1) i = 1;
                }
                $('#BoxMinaMin .mpage-' + i).trigger('click');
            }
            return false;
        });
    };
    $$.hash = function(settings, def) {
        var hash = "";
        if (def == null) {
            hash = String((document.location) ? document.location: document.location.href);
            hash = hash.split('#')[1];
        } else {
            hash = "minamin_" + def;
        }
        $hash = $('#' + hash);
        $$.changeborderbottom(def);
        if ($hash.is('a[class]')) {
            var className = $hash.attr('class');
            $('.' + className, settings.nav).siblings().removeClass('activo').end().addClass('activo');
        }
    };
})(jQuery);

// ec.puntoc
(function($) {
    var $$ = $.fn.puntoc = function(settings) {
        settings = $.extend({
            blogs: '.blog-page',
            pages: '.paginador'
        },
        settings);
        var $this = this;
        var $blogs = $this.find(settings.blogs);
        var $pages = $this.find(settings.pages);
        var rand = $$.random(3);
        $$.pages($pages, $blogs, settings);
        $blogs.hide().filter('#blog-page-' + rand).fadeIn();
        $('.blog-page-' + rand, $pages).parent().addClass('active');
        return this;
    };
    $$.pages = function($pages, $blogs, settings) {
        $pages.html(['<ul>', '<li class="flechas"><a href="#prev" class="pafter"><img width="8" height="11" border="0" alt="Anterior" src="/files/image/puntoc/navblogleft.gif" /></a></li>', '<li><a class="blog-page-1" href="#blog-page-1">1</a></li>', '<li><a class="blog-page-2" href="#blog-page-2">2</a></li>', '<li><a class="blog-page-3" href="#blog-page-3">3</a></li>', '<li><a class="blog-page-4" href="#blog-page-4">4</a></li>', '<li class="flechas"><a href="#next" class="pnext"><img width="8" height="11" border="0" alt="Siguiente" src="/files/image/puntoc/navblogright.gif" /></a></li>', '</ul>'].join('')).find('a').click(function() {
            var $this = $(this);
            var href = $this.attr('href').split('#')[1];
            var className = $this.attr('class');
            if (!$this.parent().is('.flechas')) {
                $blogs.hide().filter('#' + href).fadeIn();
                $this.parent().siblings().andSelf().removeClass('active');
                $this.parent().addClass('active');
                cert_registerHit(18972, '/ediciononline/portada/blogs', 'certPivot');
                return false;
            } else {
                var active = $pages.find('.active a').attr('class');
                var i = parseInt(active.split('-')[2]);
                if ($this.is('.pafter')) {
                    i--;
                    if (i == 0) i = 4;
                } else {
                    i++;
                    if (i == 5) i = 1;
                }
                $('.blog-page-' + i + ':first', $pages).trigger('click');
            }
            return false;
        });
    };
    $$.random = function(n) {
        return (Math.floor(Math.random() * n + 1));
    };
})(jQuery);

// ec.tabs
(function($) {
    var $$ = $.fn.tabs = function(settings) {
        settings = $.extend({
            nav: 'tabs-nav',
            navAct: 'tabs-nav-active',
            cont: 'tabs-cont',
            contAct: 'tabs-cont-active'
        },
        settings);
        var $this = this;
        var $nav = $this.find('.' + settings.nav);
        var $navAct = $this.find('.' + settings.navAct);
        var $cont = $this.find('.' + settings.cont);
        var $contAct = $this.find('.' + settings.contAct);
        $nav.find('li a').click(function() {
            var $this = $(this);
            var href = $this.attr('href').split('#')[1];
            if ($this.parent().is('.' + settings.navAct)) {
                return false;
            }
            $this.parent().siblings().removeClass(settings.navAct).end().addClass(settings.navAct);
            $('#' + href).siblings().removeClass(settings.contAct).end().addClass(settings.contAct);
            return false;
        });
        $$.init($nav, settings);
        return this;
    };
    $$.init = function($nav, settings) {
        var $firstLink = $nav.find('li:first a');
        $firstLink.addClass(settings.navAct);
        var hash = $firstLink.attr('href').split('#')[1];
        $('#' + hash).addClass(settings.contAct);
    };
})(jQuery);

// ec.cine
(function($) {
    var Cine = {
        url: '/cine/json/',
        init: function(x) {
            $('select', x).each(function() {
                $(this).filter('[name=cp]').change(function() {
                    Cine.peliculas(this);
                });
                $(this).filter('[name=cc]').change(function() {
                    Cine.locales(this);
                });
            });
        },
        peliculas: function(select) {
            var url = Cine.url;
            var cine = $(select).parent().next().find('select').eq(0);
            var mid = $(select).val();
            if (parseInt(mid) > 0) {
                url += '0/' + cine.val() + '/' + mid;
                $.getJSON(url,
                function(j) {
                    Cine.populate(cine, j);
                });
            }
        },
        locales: function(select) {
            var url = Cine.url;
            var pelis = $(select).parent().prev().find('select').eq(0);
            var cid = $(select).val();
            if (parseInt(cid) > 0) {
                url += '1/' + cid + '/' + pelis.val();
                $.getJSON(url,
                function(j) {
                    Cine.populate(pelis, j);
                });
            }
        },
        populate: function(select, j) {
            select = $(select).get(0);
            var oL = select.options.length;
            for (var i = oL - 1; i >= 0; i--) {
                select.options[i] = null;
            }
            for (val in j.data) {
                var option = document.createElement("option");
                val = parseInt(val);
                option.value = val;
                option.text = j.data[val];
                if (val == parseInt(j.selected)) {
                    option.selected = true;
                }
                if ($.browser.msie) {
                    select.add(option);
                } else {
                    select.add(option, null);
                }
            };
        }
    };
    $.fn.cine = function() {
        Cine.init(this);
        return this;
    };
})(jQuery);

// ec.encuesta
(function($) {
    Encuesta = function() {
        var $encuesta = $('#encuesta');
        var $overlay = $('.overlay', $encuesta);
        var $form = $('#pool', $encuesta);
        var $results = $('#pool_results', $encuesta);
        var submit = false;
        loadajax($form, $results);
        $('.btnopt', $encuesta).find('a[href^=#]').click(function() {
            volver($form, $results);
            return false;
        });
        $form.submit(function() {
            loadajax($form, $results, true);
            return false;
        });
    };
    var loadajax = function($form, $results, submit) {
        var ajaxdata;
        if (typeof submit == 'undefined' || !submit) {
            submit = false;
            ajaxdata = $results.serialize();
        } else {
            ajaxdata = $form.serialize();
        }
        $.ajax({
            type: 'GET',
            url: $form.attr('action'),
            data: ajaxdata,
            dataType: 'xml',
            success: function(xml) {
                $('.overlay', $form.parent()).show();
                setTimeout(function() {
                    if (getCookie(xml) == true) submitted($form, $results, xml);
                    fill($form, $results, xml, submit);
                    $('.btnopt', $form.parent()).removeClass('deleted');
                    $('.overlay', $form.parent()).fadeOut();
                },
                1000);
            }
        });
    };
    var volver = function($form, $results) {
        $results.toggleClass('deleted');
        $form.toggleClass('deleted');
    };
    var fill = function($form, $results, xml, submit) {
        var $encuesta = $form.parent();
        var topresult = 0;
        var topresultId = 0;
        var totalvotes = 0;
        $('.pool_items', $encuesta).empty();
        $('.title', $encuesta).text($('TITULOENCUESTA', xml).text());
        var inicio = $('ENCUESTA', xml).attr('INICIO');
        $('OPCIONES', xml).each(function(i) {
            var $this = $(this);
            var title = $this.find('TITULOOPCION').text();
            var votes = parseInt($this.find('VOTANTES').text());
            var percent = parseInt($this.find('ANCHOIMAGEN').text());
            var value = parseInt($this.find('CODIGO').text());
            $('.pool_items', $form).append(['<p id="pool_opt1_' + (i + 1) + '">', '<span class="results"></span>', '<span class="percent">', '<input name="codepreg" type="radio" value="' + value + '" id="opt' + (i + 1) + '" />', '</span>', '<label for="opt' + (i + 1) + '">' + title + '</label></span>', '</p>'].join(''));
            $('.pool_items', $results).append(['<p id="pool_opt2_' + (i + 1) + '">', '<span class="results"><span style="width:' + percent + '%;"></span></span>', '<span class="percent">' + percent + '%</span>', title + ' <span class="votos">(' + votes + ' votos)</span>', '</p>'].join(''));
            if (percent > topresult) {
                topresult = percent;
                topresultId = i + 1;
            }
            totalvotes += votes;
        });
        $('#pool_opt2_' + topresultId, $results).addClass('topResult').find('span.percent').wrapInner('<strong>', '</strong>');
        $('form .btnopt .total-votes').text(totalvotes);
        $('#encuesta .top span').text(inicio);
        if (submit) submitted($form, $results, xml);
    };
    var submitted = function($form, $results, xml) {
        if (getCookie(xml) == false) {
            setCookie(xml);
        }
        $form.addClass('deleted');
        $results.removeClass('deleted');
        var $link = $('.btnopt a:eq(1)', $results);
        var $totalvotes = $('ENCUESTA', xml).attr('PARTICIPANTES');
        var $newlink = $link.clone();
        $link.parent().html($newlink).prepend("Votos: " + $totalvotes + " | ");
    };
    var getCookie = function(xml) {
        var cookieVal = $('ENCUESTA', xml).attr('ENCUESTA');
        var cookieName = 'codencuesta' + cookieVal;
        if ($.cookie(cookieName) !== null) return true;
        else return false;
    };
    var setCookie = function(xml) {
        var cookieVal = $('ENCUESTA', xml).attr('ENCUESTA');
        var cookieName = 'codencuesta' + cookieVal;
        $.cookie(cookieName, cookieVal, {
            expires: 1
        });
    };
})(jQuery);

// ec.impresa.selects
(function($) {
    $.fn.impresa = function() {
        this.click(function() {
            var select = $(this).prev()[0];
            var index = select.selectedIndex;
            var value = select.options[index].getAttribute('value') || '';
            if (value && value !== '' && value !== null) document.location.href = value;
            return false;
        });
        return this;
    };
})(jQuery);

// ec.clasificados
(function($) {
    var $$ = Clasificados = {
        init: function(x) {
            $('#clasificados_inmuebles form', x).submit(function() {
                if ($$.validateOptions(this)) {
                    var act = $(this).attr('action');
                    var rub = $$.getValue($('select[name=cmbRubro]', this)[0]);
                    var ope = $('input[name=cmbOpera]:checked', this).val();
                    var dep = $$.getValue($('select[name=cmbDepa]', this)[0]);
                    var dis = $$.getValue($('select[name=cmbDistri]', this)[0]);
                    var descRub = $('select[name=cmbRubro] option:selected', this).text();
                    var descOpe = $('input[name=cmbOpera]:checked', this).next().text();
                    var descDis = encodeURIComponent($('select[name=cmbDistri] option:selected', this).text());
                    var url = act + '?Rub=' + rub + '&Ope=' + ope + '&Dep=' + dep + '&Dis=' + dis + '&Urb=-1&Pin=-1&Pfi=-1&Ncu=-1&Fla=true&vDes=' + descRub + '&vOpe=' + descOpe + '&vDis=' + descDis + '&nHoja=1';
                    window.location.href = url;
                }
                return false;
            });
            $('#clasificados_automotores form', x).submit(function() {
                if ($$.validateOptions(this)) {
                    var act = $(this).attr('action');
                    var rub = $$.getValue($('select[name=cmbRubro]', this)[0]);
                    var ope = $('input[name=cmbOpera]:checked', this).val();
                    var mar = $$.getValue($('select[name=cmbMarca]', this)[0]);
                    var descRub = $('select[name=cmbRubro] option:selected', this).text();
                    var descMar = $('select[name=cmbMarca] option:selected', this).text();
                    var url = act + '?Rub=' + rub + '&Ope=' + ope + '&Mar=' + mar + '&Mod=-1&Pin=-1&Pfi=-1&Ain=-1&Afi=-1&Fla=true&vDes=' + descRub + '&nHoja=1';
                    window.location.href = url;
                }
                return false;
            });
            $('#clasificados_empleos form', x).submit(function() {
                if ($$.validateOptions(this)) {
                    var act = $(this).attr('action');
                    var rub = $$.getValue($('select[name=cmbRubro]', this)[0]);
                    var ope = $('input[name=cmbOpera]:checked', this).val();
                    var emp = $('input[name=txtEmpleo]', this).val();
                    var descRub = $('select[name=cmbRubro] option:selected', this).text();
                    var descEmp = encodeURIComponent(emp);
                    var url = act + '?Rub=' + rub + '&Ope=' + ope + '&Emp=' + emp + '&Fla=true&vDes=' + descRub + '&vTxt=' + descEmp + '&nHoja=1';
                    window.location.href = url;
                }
                return false;
            });
            $('#clasificados_oportunidades form', x).submit(function() {
                if ($$.validateOptions(this)) {
                    var act = $(this).attr('action');
                    var rub = $$.getValue($('select[name=cmbRubro]', this)[0]);
                    var ope = $('input[name=cmbOpera]:checked', this).val();
                    var opo = $('input[name=txtOport]', this).val();
                    var descRub = $('select[name=cmbRubro] option:selected', this).text();
                    var descOpo = encodeURIComponent(opo);
                    var url = act + '?Rub=' + rub + '&Ope=' + ope + '&Opo=' + opo + '&Fla=true&vDes=' + descRub + '&vTxt=' + descOpo + '&nHoja=1';
                    window.location.href = url;
                }
                return false;
            });
            $('select[name=cmbRubro]', x).change(function() {
                var that = this;
                $$.changeOptions(that, {
                    name: 'Marca',
                    url: 'http://clasificados.elcomercio.com.pe/macro/xmlClaseOperacion.asp?id=',
                    target: 'Modelo',
                    callback: function(xml) {
                        $$.showOperacion(that, xml);
                    }
                });
            });
            $('#automotores_tipo', x).change(function() {
                var that = this;
                $$.changeOptions(that, {
                    name: 'Marca',
                    url: 'http://clasificados.elcomercio.com.pe/macro/xmlAutomotorMarca.asp?id=',
                    target: 'Marca',
                    callback: function(xml) {
                        $$.showOptions(this.target, that, xml);
                    }
                });
            }).trigger('change');
            $('#automotores_marca', x).change(function() {
                $$.changeOptions(this, {
                    name: 'Marca',
                    url: 'http://clasificados.elcomercio.com.pe/macro/xmlAutomotorModelo.asp?id=',
                    target: 'Modelo'
                });
            });
            $('#inmuebles_tipo', x).change(function() {
                $('#inmuebles_dpto, #inmuebles_distrito', x.form).find('option').removeAttr('selected');
                $('#inmuebles_dpto option[value=1], #inmuebles_distrito option:first', x.form).attr('selected', 'selected');
                $('#inmuebles_dpto', x).trigger('change');
            });
            $('#inmuebles_dpto', x).change(function() {
                var that = this;
                $$.changeOptions(that, {
                    name: 'Marca',
                    url: 'http://clasificados.elcomercio.com.pe/macro/xmlInmobiliariaDistrito.asp?idPais=1&idDepa=',
                    target: 'Distri',
                    xmlTarget: 'Distrito',
                    callback: function(xml) {
                        $$.showDistritos(that, this, xml);
                    }
                });
            }).trigger('change');
        },
        getValue: function(x) {
            var index = x.selectedIndex;
            var value = x.options[index].getAttribute('value') || '';
            return value;
        },
        getTextValue: function(x) {
            var index = x.selectedIndex;
            var value = x.options[index].nodeValue || '';
            return value;
        },
        changeOptions: function(x, o) {
            var val = $$.getValue(x);
            if (val && val !== '0' && val !== '-1' && val !== '') {
                /*$.ajax({ 
                    type: 'GET',
                    dataType: 'xml',
                    url: o.url + val,
                    success: function(xml) {
                        if (o.callback) o.callback(xml);
                        else $$.showOptions(o.target, x, xml);
                    }
                });*/
				var $select = $('select[name=cmb' + o.name + ']', x.form);
					$select.length = 1;
					$select.append('<option value="0">-</option>');
					$select.find('option:first').attr('selected', 'selected');
            }
        },
        showOptions: function(name, x, xml) {
            var $select = $('select[name=cmb' + name + ']', x.form);
            $select[0].length = 1;
            $select.append($$.parseOptions(name, xml));
            $select.find('option:first').attr('selected', 'selected');
        },
        parseOptions: function(name, xml) {
            var options = '';
            $(name, xml).each(function(i) {
                var val = $('Id_' + name, this).text();
                var desc = $('Dsc_' + name, this).text().toLowerCase();
                options += '<option value="' + val + '">' + desc + '</option>' + "\n";
            });
            return options;
        },
        showOperacion: function(x, xml) {
            var operaciones = '';
            $('SubSeccion', xml).each(function(i) {
                var name = $(x).attr('id').split('_')[0];
                var val = $('Id_SubSeccion', this).text();
                var desc = $('Dsc_SubSeccion', this).text();
                var id = name + '_op' + (i + 1);
                operaciones += ['<p>', ' <input type="radio" id="' + id + '" value="' + val + '" name="cmbOpera" />', ' <label for="' + id + '">' + desc + '</label>', '</p>'].join("\n");
            });
            var $side2 = $('div.side2', x.form);
            $side2.find(':radio').each(function(i) {
                if ($(this).is(':checked')) checkedindex = i;
            });
            $side2.html(['<p class="operacion">Elija la operaci&oacute;n</p>', operaciones].join("\n")).find(':radio:last').attr('checked', 'checked');
        },
        showDistritos: function(x, o, xml) {
            var opciones = '';
            $(o.xmlTarget, xml).each(function(i) {
                var val = $('Id_' + o.xmlTarget, this).text();
                var desc = $('Dsc_' + o.xmlTarget, this).text().toLowerCase();
                opciones += '<option value="' + val + '">' + desc + '</option>' + "\n";
            });
            var $select = $('select[name=cmb' + o.target + ']', x.form);
            $select[0].length = 1;
            $select.append(opciones);
            $select.find('option:first').attr('selected', 'selected');
        },
        validateOptions: function(x) {
            var flag = false;
            $(x).find('select').each(function() {
                var val = $$.getValue(this);
                if (val && val !== '0' && val !== '-1' && val !== '') {
                    flag = true;
                } else {
                    flag = false;
                }
            });
            if (flag) {
                $(x).find(':text').each(function() {
                    var val = this.value;
                    if (val && val !== '0' && val !== '-1' && val !== '') {
                        flag = true;
                    } else {
                        flag = false;
                    }
                });
            }
            return flag;
        }
    };
    $.fn.clasificados = function() {
        $$.init(this);
        return this;
    };
})(jQuery);

// archive
(function($) {
    ArchiveCalendar = {
        selectedDay: 0,
        selectedMonth: 0,
        selectedYear: 0,
        prevText: '<img src="/files/image/paginador_flecha_izq.gif" width="8" height="11" alt="Anterior" />',
        nextText: '<img src="/files/image/paginador_flecha_der.gif" width="8" height="11" alt="Siguiente" />',
        currentText: 'Hoy',
        appendText: '',
        dayNames: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
        monthNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
        dateFormat: 'DMY/',
        yearRange: '-10:+10',
        changeMonth: true,
        changeYear: true,
        firstDay: 0,
        showOtherMonths: false,
        minDate: null,
        maxDate: null,
        archiveDate: new Date(2009,0,29),
        closeAtTop: true,
        hideIfNoPrevNext: true,
        customEvent: false,
        targetDayURL: "http://www.elcomercio.com.pe/impresa/edicion/",
        targetArchiveURL: "http://www.elcomercio.com.pe/edicionimpresa/html/",
        init: function(target) {
            this.selectingMonthYear = false;
            this.calendarDiv = $('<div id="archivos-cal"></div>');
            $(target).append(this.calendarDiv);
            ArchiveCalendar.showCalendar();
            ArchiveCalendar.gotoToday();
        },
        showFor: function(target) {
            var input = (target.nodeName && target.nodeName.toLowerCase() == 'input' ? target: this);
            ArchiveCalendar.input = $(input);
            ArchiveCalendar.showCalendar();
        },
        showCalendar: function() {
            $("#archivos-cal").empty();
            this.popUpShowing = true;
            var today = new Date();
            today = new Date(today.getFullYear(), today.getMonth(), today.getDate());
            var html = '<div id="calendar_links"><div class="calendar_controls">' + (this.canAdjustMonth( - 1) ? '<a id="calendar_prev" onclick="ArchiveCalendar.adjustDate(-1, \'M\');">' + this.prevText + '</a>': (this.hideIfNoPrevNext ? '': '<label id="calendar_prev">' + this.prevText + '</label>')) + '<div class="calendar_actmonth">' + this.monthNames[this.selectedMonth] + '</div>' + (this.canAdjustMonth( + 1) ? '<a id="calendar_next" onclick="ArchiveCalendar.adjustDate(+1, \'M\');">' + this.nextText + '</a>': (this.hideIfNoPrevNext ? '': '<label id="calendar_next">' + this.nextText + '</label>')) + '</div>';
            if (!this.changeYear) {
                html += this.selectedYear;
            } else {
                var years = this.yearRange.split(':');
                var year = 0;
                var endYear = 0;
                if (years.length != 2) {
                    year = this.selectedYear - 10;
                    endYear = this.selectedYear + 10;
                }
                else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
                    year = this.selectedYear + parseInt(years[0]);
                    endYear = this.selectedYear + parseInt(years[1]);
                }
                else {
                    year = parseInt(years[0]);
                    endYear = parseInt(years[1]);
                }
                year = (this.minDate ? Math.max(year, this.minDate.getFullYear()) : year);
                endYear = (this.maxDate ? Math.min(endYear, this.maxDate.getFullYear()) : endYear);
                html += '<select id="calendar_newYear" onchange="ArchiveCalendar.selectMonthYear(this, \'Y\');" ' + '>';
                for (; year <= endYear; year++) {
                    html += '<option value="' + year + '"' + (year == this.selectedYear ? ' selected="selected"': '') + '>' + year + '</option>';
                }
                html += '</select>';
            }
            html += '</div>';
            html += '<table id="calendar" cellpadding="0" cellspacing="0"><thead>' + '<tr class="calendar_titleRow">';
            for (var dow = 0; dow < 7; dow++) {
                sund_ = (this.dayNames[(dow + this.firstDay)] == "D") ? ' class="domingo"': '';
                html += '<td' + sund_ + '>' + this.dayNames[(dow + this.firstDay) % 7] + '</td>';
            }
            html += '</tr></thead><tbody>';
            var daysInMonth = this.getDaysInMonth(this.selectedYear, this.selectedMonth);
            this.selectedDay = Math.min(this.selectedDay, daysInMonth);
            var leadDays = (this.getFirstDayOfMonth(this.selectedYear, this.selectedMonth) - this.firstDay + 7) % 7;
            var currentDate = new Date(this.currentYear, this.currentMonth, this.currentDay);
            var selectedDate = new Date(this.selectedYear, this.selectedMonth, this.selectedDay);
            var printDate = new Date(this.selectedYear, this.selectedMonth, 1 - leadDays);
            var numRows = Math.ceil((leadDays + daysInMonth) / 7);
            for (var row = 0; row < numRows; row++) {
                html += '<tr class="calendar_daysRow">';
                for (var dow = 0; dow < 7; dow++) {
                    var customSettings = (this.customDate ? this.customDate(printDate) : [true, '']);
                    var otherMonth = (printDate.getMonth() != this.selectedMonth);
                    var unselectable = otherMonth || !customSettings[0] || (this.minDate && printDate < this.minDate) || (this.maxDate && printDate > this.maxDate);
		    if (this.isInArchive(printDate)){ 
                    html += '<td class="calendar_daysCell' + ((dow + this.firstDay + 6) % 7 >= 6 ? ' calendar_weekEndCell': '') + (otherMonth ? ' calendar_otherMonth': '') + (printDate.getTime() == selectedDate.getTime() ? ' calendar_daysCellOver': '') + (!otherMonth || this.showOtherMonths ? ' ' + customSettings[1] : '') + '"' + (printDate.getTime() == currentDate.getTime() ? ' id="calendar_currentDay"': (printDate.getTime() == today.getTime() ? ' id="calendar_today"': '')) + '>' + (otherMonth ? (this.showOtherMonths ? printDate.getDate() : '&nbsp;') : (unselectable ? printDate.getDate() : '<a href="' + this.targetArchiveURL + ArchiveCalendar.getDashedDate(printDate) + '/ImpresaIndex.html">' + printDate.getDate() + '</a>')) + '</td>';
		    }
		    else {
                    html += '<td class="calendar_daysCell' + ((dow + this.firstDay + 6) % 7 >= 6 ? ' calendar_weekEndCell': '') + (otherMonth ? ' calendar_otherMonth': '') + (printDate.getTime() == selectedDate.getTime() ? ' calendar_daysCellOver': '') + (!otherMonth || this.showOtherMonths ? ' ' + customSettings[1] : '') + '"' + (printDate.getTime() == currentDate.getTime() ? ' id="calendar_currentDay"': (printDate.getTime() == today.getTime() ? ' id="calendar_today"': '')) + '>' + (otherMonth ? (this.showOtherMonths ? printDate.getDate() : '&nbsp;') : (unselectable ? printDate.getDate() : '<a href="' + this.targetDayURL + ArchiveCalendar.getDashedDate(printDate) + '">' + printDate.getDate() + '</a>')) + '</td>';
		    }
                    printDate.setDate(printDate.getDate() + 1);
                }
                html += '</tr>';
            }
            html += '</tbody></table>' + (this.closeAtTop || this.inline ? '': controls);
            this.calendarDiv.append(html).show("fast");
        },
        gotoToday: function() {
            var date = new Date();
            ArchiveCalendar.selectedDay = date.getDate();
            ArchiveCalendar.selectedMonth = date.getMonth();
            ArchiveCalendar.selectedYear = date.getFullYear();
            ArchiveCalendar.adjustDate();
        },
        selectMonthYear: function(select, period) {
            ArchiveCalendar.selectingMonthYear = false;
            ArchiveCalendar[period == 'M' ? 'selectedMonth': 'selectedYear'] = select.options[select.selectedIndex].value - 0;
            ArchiveCalendar.adjustDate();
        },
        noWeekends: function(date) {
            var day = date.getDay();
            return [(day > 0 && day < 6), ''];
        },
        formatDate: function(day, month, year) {
            month++;
            var dateString = '';
            for (var i = 0; i < 3; i++) {
                dateString += this.dateFormat.charAt(3) + (this.dateFormat.charAt(i) == 'D' ? (day < 10 ? '0': '') + day: (this.dateFormat.charAt(i) == 'M' ? (month < 10 ? '0': '') + month: (this.dateFormat.charAt(i) == 'Y' ? year: '?')));
            }
            return dateString.substring(this.dateFormat.charAt(3) ? 1 : 0);
        },
        getDaysInMonth: function(year, month) {
            return 32 - new Date(year, month, 32).getDate();
        },
        getFirstDayOfMonth: function(year, month) {
            return new Date(year, month, 1).getDay();
        },
        canAdjustMonth: function(offset) {
            var date = new Date(this.selectedYear, this.selectedMonth + offset, 1);
            if (offset < 0) {
                date.setDate(this.getDaysInMonth(date.getFullYear(), date.getMonth()));
            }
            return this.isInRange(date);
        },
        isInRange: function(date) {
            return ((!this.minDate || date >= this.minDate) && (!this.maxDate || date <= this.maxDate));
        },
        isInArchive: function(date) {
            return (date <= this.archiveDate);
        },
        adjustDate: function(offset, period, dontShow) {
            var date = new Date(this.selectedYear + (period == 'Y' ? offset: 0), this.selectedMonth + (period == 'M' ? offset: 0), this.selectedDay + (period == 'D' ? offset: 0));
            date = (this.minDate && date < this.minDate ? this.minDate: date);
            date = (this.maxDate && date > this.maxDate ? this.maxDate: date);
            this.selectedDay = date.getDate();
            this.selectedMonth = date.getMonth();
            this.selectedYear = date.getFullYear();
            this.showCalendar();
        },
        getDashedDate: function(date) {
            var _today = (date.getDate() < 10) ? '0' + date.getDate() : date.getDate();
            var _month = (date.getMonth() < 9) ? '0' + Number(date.getMonth() + 1) : Number(date.getMonth() + 1);
            var _year = date.getFullYear();
            var str_date = _year + "-" + _month + "-" + _today;
            return str_date;
        }
    };
})(jQuery);

// ep.youtube.js
(function($) {
    cambiarVideo = function(ytid) {
        $('#youtube-viewer').empty();
        $('#youtube-viewer').flash({
            src: 'http://www.youtube.com/v/' + ytid+'&hl=es&fs=1&showinfo=0',
            width: 640,
            height: 400,
            flashvars: {
                wmode: 'transparent'
            }
        },
        {
            version: 8
        });
        return false;
    };
    createYouTubeList = function() {
        $("#ytube ul a:first").toggleClass("selected");
        $("#ytube ul a").each(function(i) {
            $(this).bind("click",
            function() {
                $("#ytube ul a").removeClass("selected");
                $(this).toggleClass("selected");
                var getYouTubeId = $(this).attr("href").split("watch?v=");
                cambiarVideo(getYouTubeId[1]);
                return false;
            });
        });
    };
    setYouTube = function() {
        var firstVideo = $("#ytube ul a").attr("href").split("watch?v=");
        cambiarVideo(firstVideo[1]);
        createYouTubeList();
    };
})(jQuery);

// google-maps
function getCamapanaGoogleMapsHTML(title, map_url, goto_url) {
    var titleHtml = title + " <span>(ampliar)</span>";
    var mapDefUrl_str = map_url;
    var iframeHtml_a = ['<a href="/maps/', '"><img src="', '" border="0"/></a>'];
    var iframeHtml_str = iframeHtml_a[0] + goto_url + iframeHtml_a[1] + mapDefUrl_str + iframeHtml_a[2];
    var outPut_a = [titleHtml, iframeHtml_str];
    return outPut_a;
}
function setCampanaGoogleMaps() {
    var headArea_obj = $("#portada-mapas .header");
    var contentArea_obj = $("#portada-mapas .content");
    var defOption_obj = headArea_obj.find("form select option").eq(1);
    var defOptionValue_a = defOption_obj.attr("value").split("|--|");
    var defMapsHTML = getCamapanaGoogleMapsHTML(defOption_obj.text(), defOptionValue_a[0], defOptionValue_a[1]);
    headArea_obj.find("h4 a").empty().html(defMapsHTML[0]).attr("href", "/maps/" + defOptionValue_a[1]);
    contentArea_obj.empty().html(defMapsHTML[1]);
    headArea_obj.find("form select").change(function() {
        if (this.selectedIndex > 0) {
            var option_obj = headArea_obj.find("form select option").eq(this.selectedIndex);
            var optionValue_a = option_obj.attr("value").split("|--|");
            var mapsHTML = getCamapanaGoogleMapsHTML(option_obj.text(), optionValue_a[0], optionValue_a[1]);
            headArea_obj.find("h4 a").empty().html(mapsHTML[0]).attr("href", "/maps/" + optionValue_a[1]);
            contentArea_obj.empty().html(mapsHTML[1]);
        }
    });
}

function getMercados() {
    $("#financiero .content").empty().html("<p>Cargando...</p>").empty().load("/f/html/mercados.htm");
}

