/*!*******************************************************************************
|	$Revision: 3 $
|	$Date: 2009-10-22 09:55:22 +0200 (Thu, 22 Oct 2009) $
|
********************************************************************************/

/* Application base
----------------------------------------------------------------------------*/

if( ( typeof CP == 'undefined' ) || ( null == CP ) )
    var CP = {};

// Default/fallback defines
CP.DEBUG = 0;
CP.BASE_HREF = '';

/*
	TODO: 	normalizalni az extendezo methodok neveit. most van extend es set is.
			meg kell kulonboztetnia statikus es dinamikus classok eseten
*/

$.extend( CP, {
	extend: function( namespace, keys )
	{
		var _ns = {};

		// javascript "classes" will be overwritten, only objects/static classes gets merged
        if ( typeof keys === 'function' )
		{
			var path = namespace.split( '.' ),
				current = ( typeof path === 'string' ) ? path : path.pop(),
				_keys = {};

			_keys[current] = keys;
			_ns = this.namespace( path.join( '.' ) );			
			$.extend( _ns, _keys );
        }
		else
		{
			_ns = this.namespace( namespace );
			$.extend( _ns, keys );
        }		

		return _ns;
	}	
	,set: function( namespace, keys )
	{
		var _root = this;
		
		function klass()
		{
			var instanceId = null;
			this._ns = _root.namespace( namespace );
			
			// Singleton
			if( this._ns.singleton === true )
			{
				instanceId = 0;
				
				this.initialize.apply( this, arguments );
			}
			else
			{
				if( this.uid && this._ns.instanceClass === null )
					throw namespace + '.instanceClass has to be set!';
					
				this.initialize.apply( this, arguments );						

				if( this.uid )
					instanceId = this.uid;
			}

			if( instanceId !== null )
			{
				this._ns.pushInstance( instanceId, this );		
				_log( 'CP.' + namespace + ' instance #' + instanceId );				
			}
				
			return this;
		}
		
		klass.instances = {};
		klass.instanceClass = null;
		klass.singleton = false;
		klass.pushInstance = function( uid, instance )
		{
			this.instances[uid] = instance;
		}
		klass.getInstance = function( uid )
		{
			if( this.singleton )
				uid = 0;
			return ( this.instances[uid] || null );
		}
		klass.findInstance = function( dom )
		{
			var uid = $( dom ).parents( '.' + this.instanceClass ).attr( 'id' );
			return this.getInstance( uid || null );
		}
		klass.extend = function( ns, keys )
		{
			_root.set( ns, $.extend( {}, this.prototype, keys ) );
		}

		for ( key in keys )
			klass.prototype[key] = keys[key];

		if ( !klass.prototype.initialize )
			klass.prototype.initialize = new Function();

		klass.prototype.constructor = klass;

		return this.extend( namespace, klass );
	}
	,_namespace: function( namespace, create )
	{
		var _n = ( namespace ) ? namespace.split( '.' ) : [],
			obj = this,
			def = create ? {} : false;

        for ( j = ( _n[0] == 'CP' ) ? 1 : 0; j < _n.length; j++ )
		{  
            obj[_n[j]] = obj[_n[j]] || def; 
            obj = obj[_n[j]];  

			if( !obj )
				return false;
        }

		return obj;
	}
	,namespace: function( namespace )
	{
		return this._namespace( namespace, true );
	}
	,isClass: function( namespace )
	{
		return this._namespace( namespace, false );		
	}
});

// Config

CP.Config = CP.Config || {
	_config: {
		debug: 1
	}
};

$.extend( CP.Config, {
	set: function( key, value )
	{
		return this._config[key] = value;
	}
	,get: function( key )
	{
		return this._config[key] || null;
	}
});

/* Utilities
----------------------------------------------------------------------------*/

// Global Functions

function object( o )
{
    var F = new Function();
    F.prototype = o;
    return new F();
}

function isUndefined( variable )
{
	return typeof variable == 'undefined';
}

function isObject( variable )
{
	return typeof variable == 'object';
}

function isArray( obj )
{
   if ( obj.constructor.toString().indexOf("Array") == -1 )
      return false;
   else
      return true;
}

function urlDecode( str )
{
    str=str.replace( new RegExp( '\\+', 'g' ),' ' );
    return unescape( str );
}

function urlEncode( str )
{
    str = escape( str );
    str = str.replace( new RegExp( '\\+', 'g' ), '%2B' );
    return str.replace( new RegExp( '%20', 'g' ), '+' );
}

function setConfirmUnload( a )
{
	window.onbeforeunload = a ? function(){ return a } : null
}

$.bind = function( object, method )
{
    var args = Array.prototype.slice.call( arguments, 2 );
    return function() {
        var args2 = [this].concat( args, $.makeArray( arguments ) );
        return method.apply( object, args2 );
    };
};

$.keys = function( object )
{
    var keys = [];
    for ( var property in object )
      keys.push( property );
    return keys;
}

$.fn.onEnter = function( cb ){
	$( this ).keydown( function( e ){
		if( e.which == 13 ){
			if( $.isFunction( cb ) )
				cb.call( this, e );
		};
	});

	return this;
}

/* @projectDescription jQuery Serialize Anything - Serialize anything (and not just forms!)
 * @author Bramus! (Bram Van Damme)
 * @version 1.0
 * @website: http://www.bram.us/
 * @license : CC 3.0 BY-SA
*/
$.fn.serializeAnything = function()
{
	var toReturn = [];
	var els	= $( this ).find(':input').get();
	if (!els.length) els = $( this ).filter(':input').get();

	$.each(els, function() {
		if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
			var val = $( this ).val();
			toReturn.push( encodeURIComponent( this.name ) + "=" + encodeURIComponent( val ) );
		}
	});
	return toReturn.join( "&" ).replace( /%20/g, "+" );
}

$.serializeObject = function( obj )
{
	var toReturn = [];

	$.each( obj, function( key, val ) {
		toReturn.push( encodeURIComponent( key ) + "=" + encodeURIComponent( val ) );
	});
	return toReturn.join( "&" ).replace( /%20/g, "+" );
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value' );
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value' );
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie' );
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('' );
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';' );
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// i18n functions

function __( string, substitutes )
{
	if( CP.i18n && CP.i18n.messages )
	{
		if( CP.i18n.messages[string] )
		{
			string = CP.i18n.messages[string];
		}
	}
	
	if( typeof( substitutes ) == 'object' )
	{
		$.each( substitutes, function( key, value ){
			string = string.replace( '%' + key + '%', value );
		});
	}	
	
	return string;
}

var alertBox = {
	alert: function( a ){
		_log( a );
	}
}

/* Console
----------------------------------------------------------------------------*/

// if( isUndefined( window.console ) )
// {
// 	var methods = [	'assert', 'count', 'debug', 'dir', 'dirxml', 'error',
// 					'group', 'groupEnd', 'info', 'log', 'profile', 'profileEnd',
// 					'time', 'timeEnd', 'trace', 'warn'];
// 
// 	window.console = {};
// 	
// 	for ( var method in methods )
// 		window.console[method] = new Function();	
// }
// 
// function _log( obj )
// {
// 	window.console.log( obj );
// }

function _log( m )
{
	if ( window.console && typeof( console.log ) == "function" ) console.log( m ); // firebug, safari
	else if ( window.opera && typeof( opera.postError ) == "function" ) opera.postError( m );
}