function DameOrigen(event)
{
	var Origen;
	if (!event)
      event = window.event;
	if (event.srcElement)
	  Origen = event.srcElement;
	else if (event.currentTarget)
	  Origen = event.currentTarget;
	return Origen;
}

function DameIDOrigen(event)
{
	var IDOrigen = '';
	
	if (event.srcElement)
	  IDOrigen = event.srcElement.id;
	else if (event.currentTarget)
	  IDOrigen = event.currentTarget.id;
	  
	return IDOrigen;
}

function Dialogo(Mensaje)
{
	$('#Dialogo').dialog('close');
	if (Mensaje)
		$('#Dialogo').html(Mensaje);
	$('#Dialogo').dialog('open');
}

function Editando()
{
    $("#BAnnadir").attr("disabled", true); 
	QuitaOnClick(".LinkEB");
}

function QuitaOnClick(Selector)
{
	$(Selector).each(function () {
		this.onclick = ""; });
}

function BeginEspere()
{
	$("#Espere").dialog('open');
	$(".ui-dialog-titlebar-close").hide();
}

function EndEspere()
{
	$("#Espere").dialog('close');
}

function ArrayToString(ElArray)
{
	var ElString = "";
	ElString = ElArray.join(",");
	return ElString;
}

function StringToArray(ElString)
{
	var ElArray = new Array()
	if (ElString.length > 0)
		ElArray = ElString.split(",");
	return ElArray;
}

function Extract(Pos, Cadena)
{
	var Result = '';
	var ElArray = new Array()
	if (Cadena.length > 0)
	{
		ElArray = Cadena.split("_");
		if (ElArray.length > Pos)
			Result = ElArray[Pos];
	}
	return Result;
}

function ExtractCol(Cadena)
{
	return Extract(3, Cadena);
}

function jQueryValToString($CajasTexto)
{
	var Resultado = "";
	var MiArray = new Array()
	$CajasTexto.each(function (i) {
		MiArray[i] = $(this).val();
	});
	return ArrayToString(MiArray);	
}

function ESDoPostBack(Boton, Parametro)
{
	$('#TAJAXUtil_Espere').dialog('open');
	__doPostBack(Boton, Parametro);	
}

function IgualaBotones($Botones)
{
    if ($Botones.length > 1)
    {
      MaxAncho = $($Botones.get(0)).outerWidth();
      for (var i = 1; i < $Botones.length; i++) 
      {
        Wn = $($Botones.get(i)).outerWidth();
        MaxAncho = Math.max(MaxAncho, Wn);
      }
      $Botones.width(MaxAncho);
    }	
}

function FixCB()
{
    $(".FixCB:checkbox").click(function()
    {
        if($.browser.msie)
        {
            $(this).fire("change").blur();
            $(this).focus();
        }
    });
}

function FixDialog(ID)
{
    if($.browser.msie)
        $("#" + ID).outerWidth($("#" + ID).outerWidth());
}

$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find(':input').not('[type=hidden]');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        return false;
    });
};

$.fn.CapturaEsc = function() {
    return this.each(function() {
		$(this).parent().unbind("keydown");
        $(this).parent().keydown(function(e) {
	        if ((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)) 
			{
				var zmax = 0;
				var DialogoTop;
				$(".Dialogo").each(function() {
			        var cur = parseInt($(this).parent().css('z-index'));
					if ($(this).parent().is(":visible"))
					{
						if (cur > zmax)
						{
					        zmax = cur;
							DialogoTop = this;
						}
					}
			    });
				$(DialogoTop).dialog("close");
		        return false;
	        }
    	});
	});
};

$.fn.IntroNextInputField = function() {
    return this.each(function() {
        $(this).keypress(function(e) {
	        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) 
			{
		        var fields = $(this).parents('form:eq(0),body').find(':button,input,textarea,select').not('[type=hidden]');
		        var index = fields.index( this );
		        if ( index > -1 && ( index + 1 ) < fields.length ) 
				{
					for (var i = index + 1; i < fields.length; i++)
					{
						if (fields.eq(i).is(':button'))
						{
				            fields.eq(i).click();
					        return false;
						}
					}
		        }
		        return false;
	        }
    	});
	});
};

$.fn.IgualaBotones = function() {
    if ($(this).length > 1)
    {
		$Botones = $(this).filter(".Boton")
	    if ($Botones.length > 1)
	    {
	      MaxAncho = $($Botones.get(0)).outerWidth();
	      for (var i = 1; i < $Botones.length; i++)
	      {
	        Wn = $($Botones.get(i)).outerWidth();
	        MaxAncho = Math.max(MaxAncho, Wn);
	      }
	      $Botones.width(MaxAncho);
	    }	
    }
	return this;	
};

$.fn.Conmuta = function(Selector) {
    if ($(Selector).length > 0)
	{
	    if ($(Selector).is(":checkbox"))
		{
			$(Selector).bind("change", {Conmutador: this}, function(event){
			    if ($(this).is(":checked"))
				{
					$(event.data.Conmutador).find(":radio").removeAttr('disabled');	
				}
				else
				{
					$(event.data.Conmutador).find(":radio").attr('disabled', 'disabled');
				}
			});
			$(Selector).change();
		}
	}
	return this;	
};

$.fn.ShowMasterValidator = function() {
    if ($(this).length = 0)
		$MVs = $(".MasterValidatorDialog")
	else
		$MVs = $(this).filter(".MasterValidatorDialog")
    if ($MVs.length > 0 && $MVs.css("visibility") != "hidden")
		Validator_Msj($MVs.text());
	return $MVs;	
};

$.fn.extend({
    fire: function(evttype){
        el = this.get(0);
        if (document.createEvent) {
            var evt = document.createEvent('HTMLEvents');
            evt.initEvent(evttype, false, false);
            el.dispatchEvent(evt);
        } else if (document.createEventObject) {
            el.fireEvent('on' + evttype);
        }
        return this;
    }
});

jQuery.fn.exists = function(){return this.length>0;} 

$.fn.DataSet = function() {
	var Datos = this.find("input, select").serializeArray();
	var ds = new Ajax.Web.DataSet();
	var dt = new Ajax.Web.DataTable();
	dt.addColumn("Nombre", "System.String");
	dt.addColumn("Valor", "System.String");
	for (var i = 0; i < Datos.length; i++) 
	{
		dt.addRow({"Nombre": Datos[i].name, "Valor": Datos[i].value});
	}
	ds.addTable(dt);
	return ds;	
};


function TimezoneDetect()
{
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    //go through each month to find the lowest offset to account for DST
    for (intMonth=0;intMonth < 12;intMonth++){
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        //To ignore daylight saving time look for the lowest offset.
        //Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

//Find start and end of DST
function DstDetect()
{
    var dtDstDetect = new Date();
    var dtDstStart = '';
    var dtDstEnd = '';
    var dtDstStartHold = ''; //Temp date hold
    var intYearDayCount = 732; //366 (include leap year) * 2 (for two years)
    var intHourOfYear = 1;
    var intDayOfYear;
    var intOffset = TimezoneDetect(); //Custom function. Make sure you include it.

    //Start from a year ago to make sure we include any previously starting DST
    dtDstDetect = new Date()
    dtDstDetect.setUTCFullYear(dtDstDetect.getUTCFullYear() - 1);
    dtDstDetect.setUTCHours(0,0,0,0);

    //Going hour by hour through the year will detect DST with shorter code but that could result in 8760
    //FOR loops and several seconds of script execution time. Longer code narrows this down a little.
    //Go one day at a time and find out approx time of DST and if there even is DST on this computer.
    //Also need to make sure we catch the most current start and end cycle.
    for(intDayOfYear = 1; intDayOfYear <= intYearDayCount; intDayOfYear++){
        dtDstDetect.setUTCDate(dtDstDetect.getUTCDate() + 1);

        if ((dtDstDetect.getTimezoneOffset() * (-1)) != intOffset && dtDstStartHold == ''){
            dtDstStartHold = new Date(dtDstDetect);
        }
        if ((dtDstDetect.getTimezoneOffset() * (-1)) == intOffset && dtDstStartHold != ''){
            dtDstStart = new Date(dtDstStartHold);
            dtDstEnd = new Date(dtDstDetect);
            dtDstStartHold = '';

            //DST is being used in this timezone. Narrow the time down to the exact hour the change happens
            //Remove 48 hours (a few extra to be on safe side) from the start/end date and find the exact change point
            //Go hour by hour until a change in the timezone offset is detected.
            dtDstStart.setUTCHours(dtDstStart.getUTCHours() - 48);
            dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() - 48);

            //First find when DST starts
            for(intHourOfYear=1; intHourOfYear <= 48; intHourOfYear++){
                dtDstStart.setUTCHours(dtDstStart.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstStart will have the correct value left in it.
                if ((dtDstStart.getTimezoneOffset() * (-1)) != intOffset){
                    break;
                }
            }

            //Now find out when DST ends
            for(intHourOfYear=1; intHourOfYear <= 48; intHourOfYear++){
                dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstEnd will have the correct value left in it.
                if ((dtDstEnd.getTimezoneOffset() * (-1)) != (intOffset + 60)){
                    break;
                }
            }

            //Check if DST is currently on for this time frame. If it is then return these values.
            //If not then keep going. The function will either return the last values collected
            //or another value that is currently in effect
            if ((new Date()).getTime() >= dtDstStart.getTime() && (new Date()).getTime() <= dtDstEnd.getTime()){
                return new Array(dtDstStart,dtDstEnd);
            }

        }
    }
    return new Array(dtDstStart,dtDstEnd);
}

