Ext.namespace( 'Builder56' );

Builder56.Icon16  = function(icon) { return "/js/Builder56/resources/icons/16x16/" + Builder56.fpng(icon) + ".png"; };
Builder56.Icon24  = function(icon) { return "/js/Builder56/resources/icons/24x24/" + Builder56.fpng(icon) + ".png"; };
Builder56.Icon32  = function(icon) { return "/js/Builder56/resources/icons/32x32/" + Builder56.fpng(icon) + ".png"; };
Builder56.Icon48  = function(icon) { return "/js/Builder56/resources/icons/48x48/" + Builder56.fpng(icon) + ".png"; };
Builder56.Icon72  = function(icon) { return "/js/Builder56/resources/icons/72x72/" + Builder56.fpng(icon) + ".png"; };
Builder56.Icon128 = function(icon) { return "/js/Builder56/resources/icons/128x128/" + Builder56.fpng(icon) + ".png"; };
Builder56.TBIcon  = function(icon) { return Builder56.Icon16(icon); };

Builder56.IconCSS  = function(icon,size) { return Ext.util.CSS.icon(Builder56,icon,size); };

Builder56.fpng = function(icon) { return icon.replace('.png',''); };

Builder56.exitHostApplication = function() { document.title = "EXT::CLOSE-CLIENT"; };


Ext.Msg.ActivityBox = function( text, boxTitle )
{
    Ext.Msg.hide();
    Ext.Msg.show({ title: (typeof boxTitle === 'undefined' ? '' : boxTitle ),
			       closable: false,
				   msg: '<img src="/js/Builder56/resources/icons/loading.gif" border="0" align="absmiddle">&#160;<span style="color:white">' + text + '</span>'
				 });       
};


Ext.Msg.NotifyBox = function( text, delay )
{
    var box = Ext.Msg.show( {icon: Ext.MessageBox.INFO, msg: '<span style="color:white">' + text + '</span>'} );   
    window.setTimeout( box.hide.createDelegate(box), ( typeof delay === 'undefined' ? 750 : delay ) );    
};				 



/**
 * extend the CSS utils with a specialized method for generating CSS required for icons
 * used in toolbuttons/etc
 *                                      
 * @param array Array of icon definitions in format { name:'cssclassname', icon:'pathtoimagefile' }
 *                 eg.  [ {name:'customers-add',icon:'customer_add.png'} ]  ->  .customers-add { background-image..... }
 */
Ext.util.CSS.addIcons = function( iconList )
{
    if ( iconList instanceof Array )
    {
        for ( var i = 0; i < iconList.length; i++ )
        {
            Ext.util.CSS.getRule('.' + iconList[i].name) || Ext.util.CSS.createStyleSheet('.' + iconList[i].name + '{background:url(' + iconList[i].icon + ') left center no-repeat ! important;}');            
        }    
    }
    else if ( typeof iconList === 'object' )
    {
        Ext.util.CSS.getRule('.' + iconList.name) || Ext.util.CSS.createStyleSheet('.' + iconList.name + '{background:url(' + iconList.icon + ') left center no-repeat ! important;}');
    }        
};

Ext.util.CSS.icon = function( NS, iconName, size )
{
    if ( typeof size === 'undefined' ) { size=16; } 
     
    var cssClass = "css56-" + iconName + "-" + size;
    Ext.util.CSS.addIcons( {name:cssClass  , icon:NS["Icon" + size](iconName)} );
    
    return cssClass;
};

/**
 * creates a "load" mask over the window with a custom message, normally done when the dialog wants to 
 * perform an activity that will take a period of time during which the user cannot interact with the window
 *
 */
Ext.Panel.prototype.showMask = function( loadingMsg )
{       
    if ( typeof this.getEl() === 'object' )
    {
        if ( typeof loadingMsg === 'undefined' ) { loadingMsg = 'Loading...'; };
        this.loadMask = new Ext.LoadMask( this.getEl(), {msg:loadingMsg} );
        this.loadMask.show();        
    }        
};
    
/**
 * hides any "load" mask that was previously created with showMask() on this window
 */
Ext.Panel.prototype.hideMask = function()
{
    if ( typeof this.loadMask === 'object' && this.loadMask !== null ) { this.loadMask.hide(); }
    this.loadMask = null;
};  



/**
 * Configure the Ext prototype to use a logical set of default that match most of our basic combo boxes
 */
Ext.form.ComboBox.prototype.triggerAction = 'all';
Ext.form.ComboBox.prototype.editable = false;
Ext.form.ComboBox.prototype.forceSelection = true;
Ext.form.ComboBox.prototype.mode = 'local';

/**
 * Configure the Ext prototype to use 'id' and 'name as the id and display fields by default
 */
Ext.form.ComboBox.prototype.valueField = 'id';
Ext.form.ComboBox.prototype.displayField = 'name';


/**
 * Configure the JSON store to assume that a data field called 'id' will be the key for this store [value in getById() lookup]
 * Also to assume root element is 'data' as produced by System.Remoting.Call  grid-client:json handler and load immediatly
 */
Ext.data.JsonStore.prototype.id = 'id';
Ext.data.JsonStore.prototype.root = 'data';
Ext.data.JsonStore.prototype.autoLoad = true;


/**
 * Configure the Ext TabPanels to always invoke the layout of lazy rendered components such as grids that
 * have been included in the items array, if this is false grids, etc  will not appear on the tabs
 */
Ext.TabPanel.prototype.layoutOnTabChange = true;



/**
 * given a string that is a "symbolic reference" to a function, that is, the string is the name of
 * a function in a namespace this method resolves the string into the actual function object
 * e.g.  var s = "x.y.x";   var f = Ext.resolve(s);   var myObject = new f();
 */
Ext.resolve = function( symbolicRef )
{
    if ( Ext.type(symbolicRef) != "string" || symbolicRef == "" )
    {
        throw "Ext.resolve: symbolicRef parameter must be a non-empty string";
    }
    
    // break up the namespace, if there is no namespace it will still return an array with only one element
    var nameSpace = symbolicRef.split('.');
    
    // we need to start the process, all objects can be referenced by the global window namespace
    var objectRef = window[nameSpace[0]];
    
    // lookup each additional element in the namespace to build the full object reference
    for ( var i = 1; i < nameSpace.length; i++ )
    {
        if ( typeof objectRef !== 'object' ) { throw "Ext.resolve: " + symbolicRef + " is not a valid namespace path" };
        objectRef = objectRef[nameSpace[i]];
    } 
    
    return objectRef;
};

Ext.clone = function(obj)
{
    var clone = {};
    for ( var i in obj ) 
    {
        if ( obj[i] instanceof Array )
        {
            clone[i] = [];
            for ( var n = 0; n < obj[i].length; n++ )
            {
                clone[i][n] = ( typeof obj[i][n] === 'object' ? Ext.clone(obj[i][n]) : obj[i][n] );
            }                
        }
        else
        {
            clone[i] = ( typeof obj[i] === 'object' ? Ext.clone(obj[i]) : obj[i] );
        }                
    }
    return clone;
};



Builder56.Format = 
{
    asNumeric: function( val, spacer, decimals )
    {
        // if the given value is an object, we will format
        // every property in the given numeric format
        if ( typeof val === 'object' )
        {
            for ( var n in val ) { val[n] = Builder56.Format.asNumeric(val[n],spacer,decimals); }
        }
        else
        {
            // if no spacer is given we assume commas
            if ( typeof spacer === 'undefined' ) { spacer = ','; }
            
            // if the decimal param is not given, we assume decimals are included, otherwise
            // include them only if there are 1 or more 
            var includeDecimals = ( typeof decimals === 'undefined' || decimals > 0 ); 
            
            val = parseFloat(val);
            val = val.toFixed( typeof decimals === 'undefined' ? 2 : decimals ); 
            val = val.toString().replace(/\$|\,/g,'');
            if ( isNaN(val) ) { val = "0"; }
        
            var sign = (val == (val = Math.abs(val)));
            val = Math.floor(val*100+0.50000000001);
            var cents = val%100;
            val = Math.floor(val/100).toString();
        
            for ( var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) 
            {
                val = val.substring(0, val.length - (4 * i + 3)) + spacer + val.substring(val.length - (4 * i + 3));
            }
            return (sign ? '' : '-') + val + ( includeDecimals ? '.' + (cents < 10 ? '0'+cents : cents) : '' );  
        }                  
    }       
};



Builder56.encode = function(o)
{
    return "__json__" + Ext.encode(o);
};



/// http://www.netlobo.com/url_query_string_javascript.html
Builder56.getURLParam = function( name )
{  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");               
   var regexS = "[\\?&]"+name+"=([^&#]*)";  
   var regex = new RegExp( regexS );  
   var results = regex.exec( window.location.href );  
   if( results == null ) { return ""; } else { return results[1]; }
 };

 Builder56.setCookie = function(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
};

 Builder56.getCookie = function( cookieName )
{
    if ( typeof Builder56.cookies === 'undefined' )
    {
        Builder56.cookies = {};
        var c = document.cookie + ";";
        var re = /\s?(.*?)=(.*?);/g;
    	var matches;
    	while((matches = re.exec(c)) != null)
    	{
            var name = matches[1];
            var value = matches[2];
            if ( name ) 
            {
                Builder56.cookies[name] = value;
            }
        }
    }        
    
    return Builder56.cookies[cookieName];
};

// this deletes the cookie when called
 Builder56.deleteCookie = function( name, path, domain ) {
if ( Builder56.getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
};


//  check for valid numeric strings  -- http://www.pbdr.com/vbtips/asp/JavaNumberValid.htm
String.prototype.isNumeric = function( forceInteger )
{
   var strValidChars = "0123456789" + ( typeof forceInteger === 'undefined' || forceInteger === false ? ".-" : "" );
   var strChar;
   var blnResult = true;
   var strString = this.valueOf();

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
};


/**
 * Prints the given content with the given [optional] title
 * This method can be the target of a server-side callback provived the
 * server returns its response as an object matching the specification given
 * in the object version on content param below.
 *
 * @param content {mixed} Text to print, can be a string or an object in format:
 *				{ content: [string], title: [string] }
 * @param title {string} optional Title for the document
 */
Builder56.print = function( content, title )
{
	var printContent;
	
	// if the first param is an object, then it will contain two properties,
	//   content and title, typically as a result from a server-side callback
	// we copy the fields into the local var so that we don't accidently overwrite
	// the callers object [in JS objects are always passed as a pointer]
	if ( typeof content === 'object' )
	{
		title = content.title;
		printContent = content.content;
	}
	else
	{
		printContent = content;
	}

	if ( typeof title != 'undefined' ) { title = '<title>' + title + '</title>'; } 
	var w = window.open();
	w.document.write( '<html><head>' + title + '</head><body onload="window.print();window.close();">' + printContent + '</body></html>' );
       w.document.close();
};	


Ext.BLANK_IMAGE_URL = '/js/Builder56/resources/other/s.gif';