/******************************************************************************
 *                Copyright (c) 2005, Bazzisoft
 ******************************************************************************
 * Utilities.js
 *
 * JavaScript class with utility functions.
 *
 *
 * $Id: Utilities.js 3 2006-10-12 14:00:31Z shay $
 *
 */

//*************************************************************************
//* Utilities
//*
//*

function Utilities()
{
}

//*************************************************************************
//* Redirect()
//*
//* Redirects the client to the specified URL.
//*

Utilities.Redirect = function(url) 
{
    window.location = url;
}

//*************************************************************************
//* ShowPopup()
//*
//* Opens a URL in another window.
//*

Utilities.ShowPopup = function(url) 
{
    window.open(url, '_blank');
    return false;
}


//*************************************************************************
//* SplitURL()
//*
//* Splits a URL into protocol, server and path.
//* Eg, http://a.com/bar/foo.php
//* Returns an array of 3 elements:
//* [0] = "http"
//* [1] = "a.com"
//* [2] = "/bar/foo.php"
//*

Utilities.SplitURL = function(url) 
{
    var ret = new Array();
    var splt;
    var slash;

    if ( url.indexOf("://") < 0 )
        return new Array("", "", url);
        
    splt = url.split("://", 2);
    ret[0] = splt[0];
    
    slash = splt[1].indexOf("/", 2);
    ret[1] = splt[1].substr(0, slash);
    ret[2] = splt[1].substr(slash);

    return ret;
}

//*************************************************************************
//* AddFormField()
//*
//* Dynamically adds a new field to a form.
//* 
//* aForm  - the form object to append to
//* aType  - the type of field (eg. 'hidden', 'text', etc)
//* aName  - the name of the field (post name)
//* aValue - the value of the field.
//*

Utilities.AddFormField = function(aForm, aType, aName, aValue) 
{
    var input = document.createElement('INPUT');
    
    input.type = aType;
    input.name = aName;
    input.value = aValue;
    
    aForm.appendChild(input);
}

//*************************************************************************
//* SetHidden()
//*
//* Set the value within the hidden field.
//*

Utilities.SetHidden = function(id, value) 
{
    var elem = Utilities.GetElem(id);
    elem.value = value;
}

//*************************************************************************
//* SubmitForm()
//*
//* Submit the form.
//*

Utilities.SubmitForm = function(id) 
{
    var elem = Utilities.GetElem(id);
    
    if ( window.global_session_counter )
        Utilities.AddFormField(elem, 'hidden', 'global_session_counter', window.global_session_counter);
    
    elem.submit();
    
    return false;
}

//*************************************************************************
//* SetHiddenAndSubmit()
//*
//* set the value within the hidden field and submit the form.
//*

Utilities.SetHiddenAndSubmit = function(form_id, hidden_id, hidden_value) 
{
    Utilities.SetHidden(hidden_id, hidden_value);
    return Utilities.SubmitForm(form_id);
}

//*************************************************************************
//* SetAction()
//*
//* Sets the form action.
//*

Utilities.SetAction = function(form_id, url) 
{
    var elem = Utilities.GetElem(form_id);
    elem.action = url;
}

//*************************************************************************
//* SetActionAndSubmit()
//*
//* Sets the form action and submits the form.
//*

Utilities.SetActionAndSubmit = function(form_id, url) 
{
    Utilities.SetAction(form_id, url);
    return Utilities.SubmitForm(form_id);
}


//*************************************************************************
//* SetFocus()
//*
//* Sets the focus on a specific element.
//*

Utilities.SetFocus = function(elem) 
{
    var elem = Utilities.GetElem(elem);
    elem.focus();
}


//*************************************************************************
//* GetCookie()
//*
//* Retrieves the cookie of the specified name.
//*

Utilities.GetCookie = function(name) 
{ 
    var endstr;
    var ck = document.cookie;
    var index = ck.indexOf(name + "=");
        
    if ( index == -1 ) 
        return null;
        
    index = ck.indexOf("=", index) + 1;
    endstr = ck.indexOf(";", index);
    
    if ( endstr == -1 ) 
        endstr = ck.length;
        
    return unescape(ck.substring(index, endstr));
}

//*************************************************************************
//* SetCookie()
//*
//* Sets a browser session cookie.
//*

Utilities.SetCookie = function(name, value) 
{ 
    if ( value != null && value != "" )
        document.cookie = name + "=" + escape(value);
}

//*************************************************************************
//* GetElem()
//*
//* Retrieves the javascript element object given and object OR HTML id.
//*
//* elem        - element object or id to return
//*

Utilities.GetElem = function(elem)
{
    if ( typeof(elem) == 'string' )
        elem = document.getElementById(elem);

    return elem;    
}

//*************************************************************************
//* ShowHideById()
//*
//* Toggles the show/hide state of a specific HTML item by toggling the
//* "display" style.
//*
//* elem        - element object or id to return
//* init_show   - (optional) set to "true" if the element is initially shown
//* toggle_elem - (optional) element object/id which is the toggle button
//* show_text   - (optional) Text to place in the "innerHTML" of toggle_elem for "show element"
//* hide_text   - (optional) Text to place in the "innerHTML" of toggle_elem for "hide element"
//*

Utilities.ShowHideById = function(elem, init_show, toggle_elem, show_text, hide_text, show_title, hide_title)
{
    if ( typeof(elem) == 'string' )
        elem = document.getElementById(elem);
        
    if ( typeof(toggle_elem) == 'string' )
        toggle_elem = document.getElementById(toggle_elem);        

    if ( init_show )
    {
        if ( elem.style.display == 'none' )
        {
            if ( toggle_elem )
            {
                toggle_elem.innerHTML = hide_text;
                
                if ( hide_title )
                	toggle_elem.title = hide_title;
            }
                
            elem.style.display = 'block';
        }
        else
        {
            if ( toggle_elem )
            {
                toggle_elem.innerHTML = show_text;
			
				if ( show_title )
                	toggle_elem.title = show_title;
            }
            
            elem.style.display = 'none';
        }
    }
    else
    {
        if ( elem.style.display == 'block' )
        {
            if ( toggle_elem )
            {
                toggle_elem.innerHTML = show_text;
                
                if ( show_title )
                	toggle_elem.title = show_title;
            }
                
            elem.style.display = 'none';
        }
        else
        {
            if ( toggle_elem )
            {
                toggle_elem.innerHTML = hide_text;
                
                if ( hide_title )
                	toggle_elem.title = hide_title;
            }
                
            elem.style.display = 'block';
        }
    }
    
    return false;
}

//*************************************************************************
//* FloatToCurrencyString()
//*
//* Formats a floating point number (or integer) as a string with
//* 2 decimal places.
//*
//* num  - the amount to format
//*

Utilities.FloatToCurrencyString = function(num)
{
    var dollars;
    var cents;
    var str;
    
    num *= 100;
    num = Math.round(num);
    
    dollars = Math.floor(num / 100);
    cents = num % 100;
    
    str = dollars + "." + cents;
    return str;
}

//*************************************************************************
//* GetCurrentStyle()
//*
//* Retrieves the value of the given CSS property of the specified element.
//* Can provide the element itself or the element id.
//*
//* elem        - element object or id to get property for
//* property    - CSS property to retrieve (CSS style, with -'s)
//*

Utilities.GetCurrentStyle = function(elem, property)
{
    elem = Utilities.GetElem(elem);

    if ( elem.currentStyle )
    {  
        // IE expects style names in non-CSS format, ie font-size needs to be fontSize...
        // So remove any -'s and replace the following character with an uppercase version
      
        var i;
        var ar = property.match(/\w[^-]*/g);
        var s = ar[0];
      
        for ( i = 1; i < ar.length; i++ )		   
            s += ar[i].replace(/\w/, ar[i].charAt(0).toUpperCase());
           
        return elem.currentStyle[s];
    }
    else if ( document.defaultView.getComputedStyle )
    {
        // Mozilla/safari version

        return document.defaultView.getComputedStyle(elem, null).getPropertyValue(property);
    }
    else if ( window.getComputedStyle )
    {
        // Mozilla version

        return window.getComputedStyle(elem, null).getPropertyValue(property);
    }    
}

//*************************************************************************
//* GetPositionAndSize()
//*
//* Retrieves the x and y position and width and height of the specified 
//* element in a 4 element array.
//* Can provide the element itself or the element id.
//*
//* elem                - element object or id to get details for
//* stop_at_relative    - if true, returns position relative to the first
//*                       absolute or relative positioned parent element.
//*

Utilities.GetPositionAndSize = function(elem, stop_at_relative)
{
    var x = 0;
    var y = 0;
    var css;
    var pelem;
    var parent_relative;
    var ret = new Array(4);
    var first = true;
    
    elem = Utilities.GetElem(elem);
    ret[2] = elem.offsetWidth;
    ret[3] = elem.offsetHeight;

    while ( elem  )
    {
        // Check if we want the position relative to the first
        // position:absolute or position:relative element
        // If so, stop looping there
        
        if ( !first && stop_at_relative )
        {
            css = Utilities.GetCurrentStyle(elem, 'position');
        
            if ( css == 'absolute' || css == 'relative' )
                break;
        }
        
        // Add offset of current element from parent

        x += elem.offsetLeft - elem.scrollLeft;
        y += elem.offsetTop - elem.scrollTop;
                
        // Get parent element to continue adding offsets
                
        pelem = elem.parentNode;
        elem = elem.offsetParent;

        // If we need to stop at a relative/absolute parent, check all parents in 
        // between elem and the new offsetParent
        
        parent_relative = false;
    
        while ( pelem != elem && pelem.tagName != 'HTML' )
        {
            x -= pelem.scrollLeft;
            y -= pelem.scrollTop;
            
            css = Utilities.GetCurrentStyle(pelem, 'position'); 
            if ( css == 'absolute' || css == 'relative' )
            {
                parent_relative = true;
                break;
            }
            
            pelem = pelem.parentNode;                
        }
        
        if ( stop_at_relative && parent_relative )
            break;
            
        first = false;
    }
    
    ret[0] = x;
    ret[1] = y;

    return ret;
}

//*************************************************************************
//* CenterElementOnScreen()
//*
//* Centers the given element on screen using absolute positioning styles.
//*
//* elem                - element object or id to get details for
//*

Utilities.CenterElementOnScreen = function(elem)
{
    var elem = Utilities.GetElem(elem);
    
    var screenW = ( window.innerWidth ? window.innerWidth : document.documentElement.clientWidth );
    var screenH = ( window.innerHeight ? window.innerHeight : document.documentElement.clientHeight );
    var elemW = elem.offsetWidth;
    var elemH = elem.offsetHeight;
    
    elem.style.left = (Math.floor((screenW - elemW) / 2) + document.documentElement.scrollLeft) + 'px';
    elem.style.top = (Math.floor((screenH - elemH) / 2) + document.documentElement.scrollTop) + 'px';
}

//*************************************************************************
//* FixOverflowWidth()
//*
//* IE has a problem with DIV and oveflow:auto elements. If you include
//* a width:100% element inside, it adds a hscroll because the scrollbar
//* is counted as part of the width, but the 100% is calculated without
//* taking the scrollbar into account.
//*
//* To use this function define two div's... the outer one with
//* overflow:auto and the inner one with width:100% or nothing at all.
//* Then, call this function at OnLoad with the id's of both div's, and
//* it will calculate and assign the appropriate width to the inner div.
//*
//* outer_elem   - element object or id of the outer div
//* inner_elem   - element object or id of the outer div
//*

Utilities.FixOverflowWidth = function(outer_elem, inner_elem)
{
    outer_elem = Utilities.GetElem(outer_elem);
    inner_elem = Utilities.GetElem(inner_elem);
      
    inner_elem.style.width = outer_elem.clientWidth;
}

//*************************************************************************
//* GetEvent()
//*
//* Returns an object with the following attributes:
//*   type      - the tyoe of event (mouseover, etc)
//*   element   - the element that triggered the event
//*
//* You must pass to this function the 1st parameter of the event
//* handler.
//*

Utilities.GetEvent = function(evt)
{
    function UtilitiesEvent() 
    {
        this.type = null;
        this.element = null;
    }
    
    if ( !evt )
        evt = event;
        
    var e = new UtilitiesEvent;
    e.type = evt.type;
    
    if ( evt.srcElement )
        e.element = evt.srcElement;
    else
        e.element = evt.target;
        
    return e;
}

//*************************************************************************
//* StopEventPropagationHandler()
//*
//* Event handler function that merely stops any event propagation.
//* Assign as handler like so: .onclick = Utilities.StopEventPropagationHandler
//*

Utilities.StopEventPropagationHandler = function(evt)
{
    if ( !evt )
        evt = event;
        
    if ( evt.stopPropagation )
        evt.stopPropagation();
    else
        evt.cancelBubble = true;
}
