﻿
var Cookies = new function()
{
	this.Set = function( name, value, expires, path, domain, secure )
	{
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );

		/*
		if the expires variable is set, make the correct 
		expires time, the current script below will set 
		it for x number of days, to make it for hours, 
		delete * 24, for minutes, delete * 60 * 24
		*/
		if ( expires )
		{
		expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}
	
	this.Get = function( check_name )
	{
		// first we'll split this cookie up into name/value pairs
		// note: document.cookie only returns name=value, not the other components
		var a_all_cookies = document.cookie.split( ';' );
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false; // set boolean t/f default f
		
		for ( i = 0; i < a_all_cookies.length; i++ )
		{
			// now we'll split apart each name=value pair
			a_temp_cookie = a_all_cookies[i].split( '=' );
						
			// and trim left/right whitespace while we're at it
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
			// if the extracted name matches passed check_name
			if ( cookie_name == check_name )
			{
				b_cookie_found = true;
				// we need to handle case where cookie has no value but exists (no = sign, that is):
				if ( a_temp_cookie.length > 1 )
				{
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
				// note that in cases where cookie is initialized but no value, null is returned
				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if ( !b_cookie_found )
		{
			return null;
		}
	}	
}

function SetCookie( key, value )
{
	var expires = new Date();
	expires.setDate( expires + 10000000 );
		
	document.cookie = key +"="+ value +";expires:"+ expires.toGMTString() +";path=/";
}

// DELEGATE //
function Delegate()
{
	this.suscriptions = new Collection();
	
	this.Add = Suscribe;
	this.Suscribe = Suscribe; function Suscribe( instance, method )
	{
		this.suscriptions.Add( new Suscription(instance,method) );
	}
	
	this.Unsuscribe = Unsuscribe; function Unsuscribe( instance, method )
	{
		var i = 0;
		var p = -1;
		
		while( i < this.suscriptions.GetCount() && p == -1 )
		{
			suscription = this.suscriptions.Get(i);
			
			if( suscription.Instance == instance && suscription.Method == method )
				p = i;
		
			i++;
		}
		
		if( p != -1 )
			this.suscriptions.RemoveAt( p );
	}
	
	this.Raise = Raise; function Raise()
	{
		var suscription;
		
		for( var i = 0; i < this.suscriptions.GetCount(); i++ )
		{
			suscription = this.suscriptions.Get(i);
			raiseSubcription( suscription.Instance, suscription.Method, arguments );
		}
	}
	
	function raiseSubcription( instance, method, args )
	{
		var i;
		var raiseString;
		
		if( instance != null )
			Class.execInstanceMethod( instance, method, args );
		else
			Class.execMethod( method, args );
	}
	
	function Suscription( instance, method )
	{
		this.Instance = instance;
		this.Method   = method;
	}
}

var EventHandler = Delegate;

// FIN DELEGATE //
function Exception( message, innerException )
{
    this.message        = message;
    this.innerException = innerException;
}

function NoInstanciable( className )
{
	Extends( Exception, this, "No se puede instanciar la clase \""+ className +"\".", null );
}

var Class = {
	
	Extends : function( baseClass, instance )
	{
		// Copio los metodos y propiedades de la clase base
		var member;
		var baseMember;
		
		for( member in baseClass.prototype )
		{
			if( !instance[ member ] )
				instance[ member ] = baseClass.prototype[ member ];
			else
			{
				// Creo el metodo base para llamarlo a travez de this.base.method(params);
				baseMember = "_base"+ member;
				
				while( instance[ baseMember ] )
				{
					baseMember = "_"+ baseMember;
				}
				
				instance[ baseMember ] = baseClass.prototype[ member ];
				
				// Creo el objeto base.
				if( !instance.base )
					instance.base = {instance:instance,recursiveIndex:0,executeBaseMethod:Class.execBaseMethod };
				
				instance.base[ member ] = new Function("this.executeBaseMethod('"+ member +"',arguments);" );
			}	
		}
			
		// Llamo al constructor de la clase base
		var args = new Array();
		for( var i = 2; i < arguments.length; i++ )
			args.push( arguments[i] );
			
		Class.execInstanceMethod( instance, baseClass, args );
	},
	
	execInstanceMethod : function( instance, method, args )
	{
		var r;
		instance._m = method;
		
		if( args == null )
			r = instance._m();
		else
		{
			switch( args.length )
			{
				case 0:
					r = instance._m();
					break;
				case 1:
					r = instance._m( args[0] );
					break;
				case 2:
					r = instance._m( args[0], args[1] );
					break;
				case 3:
					r = instance._m( args[0], args[1], args[2] );
					break;
				default:
					throw new Exception( "No se puede ejecutar el metodo base con "+ args.length +" argumentos." );
			}
		}
		
		delete instance._m;
		
		return r;
	},
	
	execBaseMethod : function( methodName, args )
	{
		var index = this.recursiveIndex;
	
		if( index == 0 )
			method = this.instance[ "_base"+ methodName ];
		else
			method = this.instance[ pox.String.Repeat( "_", this.recursiveIndex ) +"_base"+ methodName ];
		
		this.recursiveIndex++;
		Class.execInstanceMethod( this.instance, method, args );
		
		if( index == 0 )
			this.recursiveIndex = 0;
	},
	
	execMethod : function( method, args )
	{
		switch( args.length )
		{
			case 1:
				method( args[0] ); break;
			case 2:
				method( args[0], args[1] ); break;
			case 3:
				method( args[0], args[1], args[3] ); break;
			default:
				throw( new Exception("El metodo Raise del la clase Delegate soporta hasta 3 argumentos.", null) );
		}
	}
}

var Extends = Class.Extends;

function DoNothing(){}
function ReturnFalse(){return false;}

// CALLBACK DELEGATE
var _callbacks      = new Array();
var _callbacksCount = 0;

function CallbackDelegate( target, method, execOnce )
{
	this.id     = "bck" + _callbacksCount++;
	this.target = target;
	this.method = method;
	
	if( arguments.length == 2 )
		this.execOnce = false;
	else
		this.execOnce = execOnce;
	
	_callbacks[ this.id ] = this;
	
	this.invoke = function( args )
	{
		return Class.execInstanceMethod( this.target, this.method, null );
	}
	
	this.invokeWithArgs = function( args )
	{
		return Class.execInstanceMethod( this.target, this.method, args );
	}
	
	this.CreateCallback = function()
	{
		return new Function( this.GetFunctionString() );
	}
	
	this.GetFunctionString = function()
	{
		return "return _callbacks['"+ this.id +"'].invokeWithArgs(arguments);"
	}
	
	this.getFunctionStringForTimer = function()
	{
		return "_callbacks['"+ this.id +"'].invoke();"
	}
}
// TIMER
function Timer( interval )
{
	this.OnTick    = new EventHandler();
	this.TickEvent = this.OnTick;
	this.interval  = interval;
	this.timer     = null;
	this.callback  = null;
	
	this.onTick = onTick; function onTick()
	{
		this.OnTick.Raise( this );
	}
	
	this.Start = Start; function Start()
	{
		if( this.timer )
			clearInterval( this.timer );
		
		if( this.callback == null )
		    this.callback = new CallbackDelegate( this, this.onTick ).getFunctionStringForTimer();
		
		this.timer = setInterval( this.callback, this.interval );
	}
	
	this.Stop = Stop; function Stop()
	{
		clearInterval( this.timer );
	}
}

// Devuelve un numero Randmon entre inferior y superior
function RandomInt( inferior, superior )
{
	var numPosibilidades = superior - inferior;
	var aleat = Math.random() * numPosibilidades;
	aleat = Math.round(aleat);
	return parseInt(inferior) + aleat;
}

// Esta funcion dibuja en pantalla la referencia a un archivo flash
function WriteEmbedFlash( src , width, height, version, cssClass )
{
	if( version == null )
		version = "7,0,19,0";
	
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+ version +'" width="'+ width +'" height="'+ height +'">');
	document.write('<param name="movie" value="'+ src +'" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('<embed src="'+ src +'" width="'+ width +'" height="'+ height +'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent"></embed>');
	document.write('</object>');
}

// ImageHandler
var ImageHandler = new function()
{
	this.imagesToPrelad = null;
	
	// Carga todas las imagenes pasadas por parametro.
	this.Preload = function()
	{
		if( this.imagesToPrelad == null )
		{
			this.imagesToPrelad = new Array();
			document.onload = this.preloadImages;
		}
			
		for( var i = 0; i < arguments.length; i++ )
			this.imagesToPrelad.push( arguments[i] );
	}
	
	this.preloadImages = a; function a()
	{
		var m;
		document.preloadedImages = new Array();
		
		for( var i = 0; i < ImageHandler.imagesToPreload.length; i++ )
		{
			m = new Image();
			m.src = ImageHandler.imagesToPreload[i];
			document.preloadedImages.push(m);
		}
	}
	
	this.Swap = function( overUrl )
	{
		var img    = event.srcElement;
		img.outImg = img.src;
		img.src    = overUrl;
		//SwampImageTransition( img, overUrl, duration );
	}
	
	this.Restore = function()
	{
		var img = event.srcElement;
		img.src = img.outImg;
	}
}


// String Helper
var pox = new Object()
pox.DateComparer = new function()
{
	this.IsEqual = function( valueA, valueB )
	{
		if( valueA != null && valueB != null )
			return valueA.getFullYear() == valueB.getFullYear() && valueA.getMonth() == valueB.getMonth() && valueA.getDate() == valueB.getDate();
		else
			return false;
	}
	
	this.IsGreather = function( a, b )
	{
		return a.getFullYear() > b.getFullYear() ||
			a.getFullYear() == b.getFullYear() && a.getMonth() > b.getMonth() ||
			a.getFullYear() == b.getFullYear() && a.getMonth() == b.getMonth() && a.getDate() > b.getDate();
	}
	
	this.IsGreatherEqual = function( a, b )
	{
		return this.IsEqual( a, b ) || this.IsGreather( a, b );
	}
	
	this.IsLower = function( a, b )
	{
		return a.getFullYear() < b.getFullYear() ||
			a.getFullYear() == b.getFullYear() && a.getMonth() < b.getMonth() ||
			a.getFullYear() == b.getFullYear() && a.getMonth() == b.getMonth() && a.getDate() < b.getDate();
	}
	
	this.IsLowerEqual = function( a, b )
	{
		return this.IsEqual( a, b ) || this.IsLower( a, b );
	}
	
	this.IsBetween = function( value, minValue, maxValue )
	{
		return this.IsGreatherEqual( value, minValue ) && this.IsLowerEqual( value, maxValue );
	}
}

pox.DateTime = new function()
{
	this.New = function( year, month, day )
	{
		var date = new Date();
		date.setFullYear( year );
		date.setMonth( month -1 );
		date.setDate( day );
		
		return date;
	}
	
	this.Copy = function( date )
	{
		return this.New( date.getFullYear(), date.getMonth() + 1, date.getDate() );
	}
}

// Esto reemplaza la funcionalidad de CallbackDelegate
pox.delegateKey = 0;
pox.delegates   = new Array();
pox.Delegate    = function( instance, method )
{
	this.instance    = instance;
	this.method      = method;
	this.delegateKey = null;
	
	this.Invoke = function()
	{
		return Class.execInstanceMethod( this.instance, this.method, arguments );
	}
	
	this.invoke = function( args )
	{
		return Class.execInstanceMethod( this.instance, this.method, args );
	}
	
	this.CreateFunction = function()
	{
		this.delegateKey = "del"+ pox.delegateKey++;
		var fn = new Function("return pox.delegates['"+ this.delegateKey +"'].invoke( arguments )");
		
		pox.delegates[ this.delegateKey ] = this;
		
		return fn;
	}
	
	this.Dispose = function()
	{
		if( this.delegateKey != null )
		{
			delete pox.delegates[ this.delegateKey ];
			this.delegateKey = null;
		}
	}
}

pox.String = new function()
{
    this.PadLeft = function( val, ch, num )
    {
        var re  = new RegExp(".{" + num + "}$");
        var pad = "";
        
        if(!ch)
            ch = " ";
        do
        {
            pad += ch;
        }while(pad.length < num);
        
        return re.exec(pad + val);
    }
    
    this.PadRight = function( val, ch, num )
    {
        var re = new RegExp("^.{" + num + "}");
        var pad = "";
        
        if (!ch)
            ch = " ";
        
        do
        {
            pad += ch;
        }
        while (pad.length < num);

        return re.exec(val + pad);
    }
    
    this.Trim = function( s )
    {
		s = s.replace(/\s+/gi, ' '); //sacar espacios repetidos dejando solo uno
		s = s.replace(/^\s+|\s+$/gi,''); //sacar espacios blanco principio y final

		return s;
	}
	
	this.Repeat = function( s, index )
	{
		var r = "";
		
		for( var i = 0; i < index; i++ )
			r += s;
			
		return r;
	}
}

pox.KeyBoard = new function()
{
	this.Keys = {"Backspace":8,"Tab":9,"Enter":13,"Shift":16,"Ctrl":17,"Alt":18,"Escape":27,"PageUp":33,"PageDown":34,"End":35,"Home":36,
	"LeftArroy":37,"UpArrow":38,"RightArrow":39,"DownArrow":40,"Insert":45,"Delete":46};

	this.IsNumber = function( keyCode )
	{
		return keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 105;
	}
	
	this.GetCharFromKeyCode = function( keyCode )
	{
		if( keyCode >= 96 && keyCode <= 105 )
			return String.fromCharCode( keyCode - 48 );
		else
			return String.fromCharCode( keyCode );
	}
}

//--------------------------------------------------------------------------------------------------------------------------------
// NameSpace Pox.Drawing
//--------------------------------------------------------------------------------------------------------------------------------
pox.Drawing = new function()
{
	// Clase Rectangle
	this.Rectangle = function( top, left, width, height )
	{
		this.Top    = top;
		this.Left   = left;
		this.Width  = width;
		this.Height = height;
		this.Bottom = top + height;
		this.Right  = left + width;
	}
	
	// Clase Estatica Aligning
	this.Aligning = new function()
	{
		// Devuelve la diferencia de B para estar centrada sobre A
		this.AlignCenter = function( a, b )
		{
			return Math.floor( (a - b) / 2 );
		}
	    
		this.AlignRight = function( a, b )
		{
			  return a - b;
		}
	}
}

//--------------------------------------------------------------------------------------------------------------------------------
// CONTROLHANDLER
//--------------------------------------------------------------------------------------------------------------------------------
var ControlHandler = new function()
{
	this.controlOnFocus       = null;
	this.serializableControls = new Array();
	
	this.GetControlByElement = function( element )
	{
		var control = null;
		
		while( element && control == null )
		{
			if( element.control )
				control = element.control;
			
			element = element.parentNode;
		}
		
		return control;
	}
	
	// Esta funcion es llamada desde el formulario antes de ejecutar onsubmit
	this.serializeControls = function( formId )
	{
		var form = document.getElementById( formId );
		
		for( i = 0; i < this.serializableControls.length; i++ )
			this.serializableControls[i].serialize( form );
		
		return true;
	}
	
	// Este metodo es llamado por la clase Control para que asigne en foco el control.
	this.setOnFocus = function( control )
	{
		if( this.controlOnFocus != null && control != this.controlOnFocus )
			this.controlOnFocus.Blur( control );
		
		this.controlOnFocus = control;
	}
	
	this.IsOnFocus = function( control )
	{
		return control == this.controlOnFocus;
	}
	
	this.RegisterSerialization = function( control )
	{
		this.serializableControls.push( control );
	}
	
	this.GetByElementId = function( elementId )
	{
		var element = browser.GetElementById( elementId );
		
		if( element )
			return element.control;
		else
			return null;
	}
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();