/**
 *
 * @param selectObject - Object in which to add options
 * @param string  - String to convert into an array by splitting it using delimeter
 * @param delimeter - character/string to split the array by
 * @param delimeter2 - character/string to split each value of the array to obtain value/title
 * @param firstOption - value to place in the beginning of the list
 */
function addDelimetedStringToSelect(selectObject, string, delimeter, delimeter2, firstOption)
{
    var option = new Array();
    if(string && string != "")
    {
        if(firstOption)
            string =  "-1" + delimeter2 + firstOption + delimeter + string;
        option = option.concat(string.split(delimeter));
    }
    else
    {
        option[0] = "-1" + delimeter2 + "Not Available";
    }

    addSelectOptions(selectObject, option, delimeter2);

}

/**
 *
 * @param selectObject - Object in which to add options
 * @param arrayOptions - Array of options to add, each value can have a delimeter as a value/title pair
 * @param delimeter - Delimeter in which to split the value and the title in each option
 */
function addSelectOptions(selectObject, arrayOptions, delimeter)
{

    if(selectObject && arrayOptions && selectObject.add && arrayOptions.length > 0)
    {
        if(selectObject.length > 0)
        {
            clearSelectOptions(selectObject);
        }
        var y = null;
        var xValueString = null;
        var selected = getQueryStringValue(selectObject.name);

        for(var x in arrayOptions)
        {
            y=document.createElement('option');

            if (arrayOptions[x] && arrayOptions[x].split) {           
            
               xValueString = arrayOptions[x].split(delimeter);
               if (xValueString.length > 1) {
                  y.value = xValueString[0];
                  y.text = xValueString[1];
               }
               else {
                  y.value = xValueString;
                  y.text = xValueString;
               };
               if (selected) {
                  if (selected == y.value) {
                     y.selected = true;
                  }
                  
               }
               try {
                  selectObject.add(y, null); // standards compliant
               } 
               catch (ex) {
                  selectObject.add(y); // IE only
               }
            }
        }
    }
}

/**
 *
 * @param selectObject - Object to clear from it's options
 */
function clearSelectOptions(selectObject)
{
    var x = selectObject.options;
    var y = x.length;

    for(var i = 0; i < y; i++)
    {
        selectObject.remove(x[i]);
    }
}

/**
 *
 * @param queryName - Value of a field from the query string;
 */
function getQueryStringValue(fieldName)
{
    if(location.search && location.search.length > 0)
    {
        var queryString = location.search.substring(1).split("&");
        var arrayQueryString;

        for(var x in queryString)
        {
            if(queryString[x] && queryString[x].lastIndexOf && queryString[x].lastIndexOf(fieldName) == 0)
            {
                arrayQueryString = queryString[x].split("=");
                return arrayQueryString[1];
            }
        }
    }
    return null;
}


/**
 *
 * @param subcontent_id - Id of the SubContent div that will be displayed
 */
function showSubContent(subcontent_id)
{
    if(!subcontent_id)
        return;

    var subcontent = getObj(subcontent_id);
    var selectedlink = getObj(subcontent_id+"_link");
    var hide = null;
    var link = null;

    if(subcontent)
    {
        var y = showSubContent.arguments;
        var length = showSubContent.arguments.length;
        var z = "";

        for(var x = 0; x < length; x++)
        {
            z = y[x]+"_link";
            link = getObj(z);

            hideSubContent(y[x]);
            if(link && link.parentNode && link.parentNode.tagName == "LI")
            {
                link.parentNode.id = "";
            }
            else if( link )
            {
                var linkIds = link.id.split(" ");
                link.id = linkIds[0];
            }
        }

        if(selectedlink && selectedlink.parentNode && selectedlink.parentNode.tagName == "LI")
        {
            selectedlink.parentNode.id = "selected";
        }
        else if(selectedlink)
        {
            selectedlink.id = selectedlink.id + " selected";
        }
        if(subcontent && subcontent.style)
        {
            subcontent.style.display = "block";
        }
    }
}

/**
 *
 * @param subcontent_id - Id of the Subcontent to Hide
 */
function hideSubContent(subcontent_id)
{
    if(!subcontent_id)
        return;

    var subcontent = getObj(subcontent_id);

    if(subcontent && subcontent.style)
    {
        subcontent.style.display = "none";
    }
}

/**
 *
 * @param image_name - Image that will be replaced
 * @param new_image_path - URI Path to the image that will replace image_name.src
 */
function replaceImage(image_name, new_image_path)
{
    var image = getObj(image_name);

    if(image && image.src)
    {
        image.src = new_image_path;
    }
}

/**
 *
 */
function doNothing()
{
    return true;
}



/**
 *
 */
function Util() {

    this.timeoutFunctionCall = function(timeout, call)
    {
        var extraArguments = "";

        if(this.timeoutFunctionCall.arguments.length > 2)
        {
            for(var x = 2; x < this.timeoutFunctionCall.arguments.length; x++)
            {
                if( x > 2)
                {
                    extraArguments += ", ";
                }
                switch(typeof(this.timeoutFunctionCall.arguments[x]))
                {
                    case "number":
                    case "boolean":
                        extraArguments += this.timeoutFunctionCall.arguments[x];
                        break;

                    default:
                        extraArguments += "'" + this.timeoutFunctionCall.arguments[x] + "'";
                        break;
                }
            }
        }

        var functionCall = call + "(" + extraArguments + " ) ";

        setTimeout(functionCall, timeout);
    }

    this.setObjectStyleValue = function (obj, property, value)
    {
        if(obj && obj.style && obj.style[property])
        {
            obj.style[property] = value;
        }
    }

    this.doNothing = function () { return; }

    this.getObj = function (name)
    {
        var tmp = new Object();


        if (document.getElementById)
        {
            tmp = document.getElementById(name);
        }
        else if (document.all)
        {
            tmp = document.all[name];
        }
        else if (document.layers)
        {
            tmp.obj = this.getObjNN4(document,name);
            tmp.style = this.getObjNN4(document,name);
        }

        return tmp;
    }

    this.getObjNN4 = function (obj,name)
    {
        var layers = obj.layers;
        var foundLayer;
        for (var i = 0; i<layers.length; i++)
        {
            if (x[i].id == name)
            {
                foundLayer = x[i];
            }
            else if (x[i].layers.length)
            {
                var tmp = this.getObjNN4(x[i],name);
            }
            if (tmp) foundLayer = tmp;
        }
        return foundLayer;
    }

    this.resizeObject = function(name, width, height, delta)
    {
        var breathingroom = 0;
        var obj = this.getObj(name);
        if(obj && (typeof(obj) == "object"))
        {

            var increase = 0;

            var objWidth = parseInt(obj.offsetWidth);
            var objHeight = parseInt(obj.offsetHeight);

            var xincrement = ( objWidth < width ) ? 1 : ((objWidth == width) ? 0 : -1);
            var yincrement = ( objHeight < height ) ? 1 : ((objHeight == height) ? 0 : -1);

            var xdelta = delta * xincrement;
            var ydelta = delta * yincrement;

            var newWidth = (objWidth + xdelta);
            var newHeight = (objHeight + ydelta);

            var xpercentage = (xincrement < 0) ? .66 : .33;
            var ypercentage = (yincrement < 0) ? .66 : .33;

            if(this.resizeObject.arguments && this.resizeObject.arguments.length == 5)
            {
                increase = parseInt(this.resizeObject.arguments[4]);
                xincrease = increase * xincrement;
                yincrease = increase * yincrement;
            }


            if(height != null && height != objHeight)
            {
                obj.style["height"] = newHeight + "px";
            }
            if(width != null && width != objWidth)
            {
                obj.style["width"]  = newWidth  + "px";
            }

            if( ( height != null && ( (newHeight + (yincrement * breathingroom) ) * yincrement) < (height * yincrement) )
                 ||
                ( width  != null && ( (newWidth  + (xincrement * breathingroom) ) * xincrement) < (width  * xincrement) ) )
            {
                setTimeout("document.util.resizeObject(\"" +  name + "\" , " + width + " , " +  height + " , " + (delta+increase) + " , " + increase + " ) ", 20);

            }
            else
            {
                if(height != null)
                {
                    this.setObjectStyleValue(obj, "height",  height );
                }

                if(width != null)
                {
                    this.setObjectStyleValue(obj, "width",  width );
                }
            }
        }
    }
}


document.util = new Util();


logger = {

    logWindow : null,

    util : new Util(),

    log : false,
    scrollWindow: false,

    start : function(properties) {

        if(typeof(properties) == "object" && properties.length > 0 )
        {
            this.logWindow = window.open("", "logwindow",  properties.join(","));
            if(this.logWindow != null)
            {
                log = true;
            }
        }
        else
        {
            alert("No properties sent");
        }
    },




    info : function (message) {
         this.writeLog("LOG INFO: " + message);
    },

    writeMessage : function(message)
    {
        if(this.util && this.util.timeoutFunctionCall)
        {
            this.util.timeoutFunctionCall(100, "logger.logWindow.document.write", message);
        }
    },


    pageScroll : function () {
        if(this.scrollWindow)
        {
            this.logWindow.scrollBy(0,50); // horizontal and vertical scroll increments
            scrolldelay = setTimeout('logger.pageScroll()',1); // scrolls every 100 milliseconds
        }
    },

    writeLog : function(message) {

        if(!log)
            return;

        if (this.logWindow.innerHeight)
        {
            frameWidth = this.logWindow.innerWidth;
            frameHeight = this.logWindow.innerHeight;
        }
        else if (this.logWindow.document.documentElement && this.logWindow.document.documentElement.clientWidth)
        {
            frameWidth = this.logWindow.document.documentElement.clientWidth;
            frameHeight = this.logWindow.document.documentElement.clientHeight;
        }
        else if (this.logWindow.document.body)
        {
            frameWidth = this.logWindow.document.body.clientWidth;
            frameHeight = this.logWindow.document.body.clientHeight;
        }
        else return;


        this.writeMessage(message + " <br />");
        this.pageScroll();
    }


}

/**
 * Changes days in combo boxes to match given month.
 **/
function getDayCount( frmMonth, frmDay, frmYear )
{
  // Javascript uses 0 base months.
  month = frmMonth.value - 1;
  day   = frmDay.value;
  year  = frmYear.value;
   
  // Loop backwards from 31 till we get the same month from the object.
  fourDayArray = [ 31, 30, 29, 28 ];

  for ( ii = 0; ii < fourDayArray.length; ++ii )
  {
    // Create the date object.
    dateObj = new Date( year, month, fourDayArray[ ii ] );

    if ( month == dateObj.getMonth() )
    {
      // Found the last day.
      lastDay = fourDayArray[ ii ];

      if ( frmDay.options.length < lastDay )
      {
        addDaysToCombo( frmDay, lastDay );
        return;
      } else if ( frmDay.options.length > lastDay ) { 
        removeDaysFromCombo( frmDay, lastDay );
        return;
      } else {
        return;
      }
    }
  }
}

/**
 * Adds days to a combo box to a given last day ( last day in month ).
 **/
function addDaysToCombo( frmDay, lastDay )
{
  daysLength  = frmDay.options.length;
  addDayCount = lastDay - daysLength;

  // Add Options to day list.
  for ( ii = 0; ii < addDayCount; ++ii )
  {
     optionLocation = frmDay.options.length;

     frmDay.options[ optionLocation ] = new Option( optionLocation + 1, optionLocation );
  }
}

/**
 * Subtracts days from a combo box to a given last day.
 **/
function removeDaysFromCombo( frmDay, lastDay )
{
  daysLength = frmDay.options.length;
  removeDayCount = daysLength - lastDay;

  // Remove Options from day list.
  for ( ii = 0; ii < removeDayCount; ++ii )
  {
     optionLocation = frmDay.options.length - 1;

     frmDay.options[ optionLocation ] = null;
  }
}

/**
 * Populate user address from given select.
 **/
function populateUserAddress( select )
{
   var userInput = document.getElementById( 'addr_user' );   
   var nodes = select.childNodes;   

   for ( ii = 0; ii < nodes.length; ++ii )
   {
      node = nodes[ ii ];
      if ( node.selected == true )
      {
         userInput.value = node.value;
      }
   }
}

/**
 * Create editable combo box.
 *   Moves the text input over the combo box to fake an editable combo box.
 **/
function createEditableCombo()
{
   var input  = document.getElementById( 'addr_user' );
   var select = document.getElementById( 'userAddressSelect' ) ? document.getElementById( 'userAddressSelect' ) : false ;
      
   if ( select == false )
   {
     return;
   }

   // Get font and color settings from the input.
   var fontSize = input.style.fontSize;
   var bgColor  = "#FFFFFF";
      
   // Apply the fontSize and bgColor to the select input.
   select.style.fontSize = fontSize;
   select.style.backgroundColor = bgColor;

   // Apply the bgColor to the select input.
   input.style.backgroundColor = bgColor;

   // Absolute position for both the input and select.
   input.style.position  = "absolute";
   select.style.position = "absolute";

   // Get the width of the select box.
   clientWidth  = select.clientWidth;
   clientHeight = select.clientHeight; 

   // Browser specific styles.
   var browserName = navigator.appName;
   if ( browserName == "Microsoft Internet Explorer" )
   {
      clientWidth = clientWidth * .99;

      input.style.width  = clientWidth + "px"; // 99%.  IE doesn't see the same width.
      select.style.hieght = input.clientHeight;
      input.style.border = "2px solid #FFFFFF";
      input.style.marginTop = "3px";
      input.style.marginLeft = "2px";
   } else {
      clientWidth = clientWidth * .85; // 85% width of the select box.

      input.style.width  = clientWidth + "px";
      input.style.border = "0px";
      input.style.marginTop = "3px";
      input.style.marginLeft = "3px";
   }

   // Bring the input to the top.
   input.style.zIndex = "1000";
}
Metrosplash = {
   Util: {}
}

/**
 * Calls function after a certain amount of time has passed
 * default of 20 minutes, this aggregates calls to defer/setTimeOut
 * 
 * @param {Object} callback
 */
Metrosplash.Util.timeoutCall = function(callback) {
    
     
    this.load_time = new Date();
    this.duration = this.millisFromMinutes(20);
    this.callback = callback;
    if(arguments.length > 1 && typeof(arguments[1]) == "object" )
    {
        this.args = arguments[1];        
    }
    else
    {
        this.args = {};
    } 
}

Metrosplash.Util.timeoutCall.prototype = {
    /**
     * Start's the timer, by setting load_time to new Date 
     */
    start: function() {
        this.load_time = new Date();
    },
    /**
     * Start's the timer,  and starts off the deferred call
     */
    startCallback: function() {
        this.start();
        this.deferId = this.lifeSpan.defer(this.duration, this);
    },
    /**
     * Clear's the callback timeout call but still keeps track of the original instance time
     */
    clear: function() {
        if(this.deferId)
        {
            clearTimeout(this.deferId);
        }
	    Ext.destroy(this.callback);
    },
    /**
     * Sets the duration of the callback timer
     * @param {integer} duration
     */
    setDuration: function(duration) {
        this.duration = duration;
    },
    setArgs: function(args) {
        this.args = args;
    },
    /**
     * Returns the amount of time that has passed
     */
    timeElapsed: function() {
        return new Date() - this.load_time;
    },
    /**
     * If timeElapsed is greater than the duration, call the callback
     */
    lifeSpan: function() {
        if(this.timeElapsed() >= this.duration)
        {
            this.callback(this.args);
        }
    },
    /**
     * Unfinished, if there's any activity on the loaded page, start the timer again
     */
    checkActivity: function() {
        var activity = true;
        if(activity)
        {
            this.load_time = new Date();
        }
    },
    /**
     * returns Milliseconds from passed Seconds
     * @param {integer} seconds
     */
    millisFromSeconds: function (seconds) {
        return seconds * 1000;    
    },    
    /**
     * returns Milliseconds from passed Minutes
     * @param {integer} minutes
     */
    millisFromMinutes: function (minutes) {
        return this.millisFromSeconds(minutes*60);    
    }
}

Metrosplash.Util.sendHome = function() {
	window.parent.location="/";
}

Metrosplash.Util.displayError = function(params) {
    
    if(params.callback)
    {
        params.callback();
    }
        

    config = {
       title: params.title,
       msg: params.message,
       buttons: Ext.MessageBox.OK,
       icon: Ext.MessageBox.ERROR 
    }

    if(arguments.length == 1 || arguments[1] == true)
    {
        config.fn = Metrosplash.Util.sendHome;
    }        

    Ext.MessageBox.show(config);
}

Metrosplash.Util.displayMessage = function(params) {
    
    if(params.callback)
    {
        params.callback();
    }
        
    config = {
       title: params.title,
       msg: params.message,
       buttons: Ext.MessageBox.OK,
       icon: Ext.MessageBox.INFO 
    }

    if(arguments.length == 1 || arguments[1] == true)
    {
        config.fn = Metrosplash.Util.sendHome;
    }        

    Ext.MessageBox.show(config);
}

/**
 *
 * @param textString - Object multi delimited string.
 *
 */
function parseTextString( textString )
{
  // Strings are first '|' delimited, split on it.
  var settings = textString.split( "|" );
  var properties = new Array();
    
  for ( ii = 0; ii < settings.length; ++ii )
  {
    setting = settings[ ii ];
    
    // Strings are secondly '=' delimited, split on it.
    var parts = setting.split( "=" );
    
    // Put our settings in the properties array.
    properties[ parts[ 0 ] ] = parts[ 1 ];
  }

  return properties;
}
/**
 * getQueryParams - Gives back a static object of name value pairs for the query parameters
 */
Metrosplash.Util.getQueryParams = function() {
    var return_object = {}
    var uri_split = document.location.href.split("?");
    if(uri_split.length > 1)
    {
        var query_string = uri_split[1].split("&");
        for(var x in query_string)
        {
            if(typeof query_string[x] == "string")
            {
                param = query_string[x].split("=");
                return_object[param[0]] = param[1];    
            }            
        }
    }
    return return_object;
}