(function($) {
    var fn = arguments.callee;

    if (typeof $ != 'function') {
        setTimeout(function() {
            fn(window.jQuery);
        }, 100);
        return;
    }

    var $d = $([]),
        $cbs = $([]),
        $t = $([]);

    $(function() {
        $d = $('#searchwindow');
        $cbs = $d.find('[id*="cblCategory_"]').filter(':not([id$="_0"])');
        $t = $d.find('[id$="cblCategory_0"]');

        $d.remove().appendTo('body');
        $t.click(function(e) {
            if ($t.is(':checked')) {
                $cbs.attr('disabled', 'disabled');
            }
            else {
                $cbs.removeAttr('disabled');
            }
        });
        $cbs.attr('disabled', 'disabled');
    });

    window.AbrirBusqueda = function() {
        if (!$d.length) return;

        if ($d.is(':visible')) {
            $d.hide();
        }
        else {
            var $e = $('#opensearchwindow'),
                ofs = $e.offset();

            $d.css({
                color: '#FFFFFF',
               // backgroundColor: '#86c87f',
                position: 'absolute',
                top: ofs.top + $e.height() + 5,
                display: 'block',
               // border: '1px solid #3e9234',
                zIndex: 30000,
                left: ofs.left + ($e.width() - $d.width()) / 2
            });
        }
        return false;
    }

    window.AbrirCerrarCategoriaBusqueda = function(e) {
        var $e = $(e),
            $o = $('#categoriabusqueda');

        if ($e.is(':checked')) {
            $o.show();
        }
        else {
            $o.hide();
        }
    }

    window.AbrirCerrarFechasBusqueda = function(e) {
        var $e = $(e),
            $o = $('#rangofechas');

        if ($e.is(':checked')) {
            $o.show();
        }
        else {
            $o.hide();
        }
    }

    window.ProcesarBusqueda = function() {
        var $f = $('#searchwindow'),
            error = false;

        function validarFecha(f) {
            if (!f) return false;

            if (/[^0-9\/\-\.]/.test(f)) return false;

            f = f.replace(/[\.\/]/g, '-').split('-');
            switch (f.length) {
                case 2:
                    f.push((new Date()).getFullYear());
                case 3:
                    try {
                        var tmp = new Date(),
                            y = parseInt(f.pop(), 10);

                        if (y < 100) y += y >= 80 ? 1900 : 2000;
                        tmp.setFullYear(y);
                        tmp.setMonth(parseInt(f.pop(), 10) - 1);
                        tmp.setDate(parseInt(f.pop(), 10));
                        if (!isFinite(tmp.getFullYear() + tmp.getMonth() + tmp.getDate())) return false;
                        f.push(tmp.getFullYear());
                        f.push(tmp.getMonth() < 9 ? '0' + (1 + tmp.getMonth()) : 1 + tmp.getMonth());
                        f.push(tmp.getDate() < 10 ? '0' + tmp.getDate() : tmp.getDate());
                        return f.join('-');
                    }
                    catch (x) {
                        return false;
                    }
            }
            return false;
        }

        //Caracteres invalidos
        var texto = $f.find('[name="SearchTermArt"]').val();

        texto = texto.replace(/[:\+\*\/&\.]/g, '');

        var url = [],
            u = -1;

        url[++u] = '/tabid/37/Default.aspx';
        var cat = $('#categoriabusqueda').is(':visible'),
			dates = $('#rangofechas').is(':visible');

        if (texto == '' && !cat && !dates) {
            error = 'La b\u00FAsqueda no es v\u00E1lida. Ingrese un texto a buscar, un rango de fechas y/o una categor\u00EDa.';
        }
        else {
            if (texto) {
                url[++u] = '?SearchTerm=';
                url[++u] = texto;
            }
            else {
                url[++u] = '?ShowAll=True';
            }
            if (cat) {
                var $ids = $f.find('[id*="_cblCategory_"]:checked:enabled');

                if ($ids.length) {
                    url[++u] = '&CategoryID=';
                    $ids.each(function() {
                        var c = $(this).parent().attr('class').split(' ');

                        for (var j in c) {
                            if (c[j].indexOf('id_') === 0) {
                                url[++u] = c[j].substr(3);
                                url[++u] = '-';
                            }
                        }
                    });
                    --u, url.pop();
                }
                else {
                    error = 'Debe elegir una categor\u00EDa v\u00E1lida.';
                }
            }
            if (dates) {
                var fechaDesde = $f.find('[id$="StartDate"]').val(),
                    fechaHasta = $f.find('[id$="EndDate"]').val();

                if ((fechaDesde = validarFecha(fechaDesde)) && (fechaHasta = validarFecha(fechaHasta))) {
                    url[++u] = '&StartDate=';
                    url[++u] = fechaDesde;
                    url[++u] = '&EndDate=';
                    url[++u] = fechaHasta;
                }
                else {
                    error = 'Debe ingresar un rango de fechas v\u00E1lido.';
                }
            }
        }

        if (!error) {
            window.location.href = url.join('');
        }
        else {
            alert(error);
        }
        return false;
    };
})(window.jQuery);

/* modifica variable Path de un nivel para agregarle '/index' */
function setPathToCertifica(path) {    	
	//alert(path);
    var sPath = path;
	var param = sPath.split("/");
	var i = 3;
    if (parent.location.host == 'localhost'){
        i = 4;
    }
  	if (param.length == i) 
	  {
		  //alert(param);
		  //para unificar se considera default como home por ende a default se lo setea en '//'
		  var token = param[i-2];
		  if (token.toLowerCase() == 'default') sPath = '//';
		  if (sPath != '//') sPath = sPath + 'index';
		  if (sPath == '//') sPath = "/home/index/";
	  }
	  	/* CV: 20/10/2011 - Modifica la URL, si tiene mas de 5 fragmentos la corta para el el p*/	
	    var fragmento = sPath.split("/");
  	    if (fragmento.length > 4) 
	      {
	          sPath = fragmento[1] + "/" + fragmento[2] + "/" + fragmento[3] ;
	          // CV: 20/10/2011 - Esta forma original que se pasaba hasta el titulo del articulo
		      //sPath = fragmento[1] + "/" + fragmento[2] + "/" + fragmento[3] + "/" +     fragmento[4] ;
	      }
	//alert(sPath);
	return sPath;
}

