/*!
 * jQuery TPS Saved Preferences Plugin v0.0.2
 * Copyright (c) 2009 Humana Inc.
 *
 * @author Jeffrey Dang <jdang@humana.com>
 * @version 0.0.2
 * 
 * @dependency jquery
 * @dependency jquery.cookie
 */

(function($) {
    $.queryStr = function( name ) {
        // Remove the '?' if it exists
        var paramStr = document.location.search.substring(1);
        var paramArr = null;
        var value = null;
        if( paramStr == '' || name == null ) {
            return value;
        }
        paramArr = paramStr.split('&');
        for( var i = 0; i < paramArr.length; ++i ) {
            // Found the key with an assigned value
            if ( paramArr[i].substring(0, name.length + 1) == (name + '=') ) {
                value = paramArr[i].substring( name.length + 1 );
                //convert to normal and remove side white spaces
                value = $.trim(unescape(value));
                return value;
            }
        }
        // Should be null if you get to this point
        return value;
    }

     /**
      * This function retrieves, updates, and removes preferences values for
      * the given name.
      * @param  string  name    name of the preference
      * @param  string  value   value of the prefence
      * @param  object  copt    cookie parameters in object form
      */
     $.Pref = function( name, value, copt ) {
        var cookDefault = {
                            'expire'    : 7,
                            'domain'    : '',
                            'path'      : '/',
                            'secure'    : false,
                            'useCookie' : true
                          };
        // name was not provided        
        if ( name === undefined || name === null || name === '' ) {
            return null;
        }
        // extend cookie options
        copt = $.extend(cookDefault, copt);
        // Getting a value
        if ( value === undefined ) {
            //Using the cookies
            if ( copt.useCookie ) {
                return $.cookie(name);
            } else {// using Query String
                return $.queryStr(name);
            }
        } else {
            //Setting or removing a value
            if ( copt.useCookie ) { 
                return $.cookie( name, value, copt );
            }
        }
        return null;
    };// END $.fn.Pref

    /**
     * This function attaches a trigger saving function to all listed elements
     * provided within the selected element.
     * @param       object settings parameters in object form
     * @settings    String name     The preference name.
     * @settings    String trigger  The Trigger function that you want to binded
     *                              with a preference save.
     * @settings    array  elements A list of the children you want the trigger
     *                              to have binded.
     * @settings    object copt     cookie parameters in object form
     */
    $.fn.bindSavePref = function( settings ) {
        var outer = this;
        var pDefault = {
                        'name'      : '',
                        'trigger'   : 'click',
                        'elements'  : [],
                        'copt'      : {}
                       };
        settings = $.extend( pDefault, settings );
        
        // If the name is unset and this has an id, use it as the name
        if ( settings.name == '' ) {
            if( outer.id ) {
                settings.name = outer.id;
            } else {
                return outer;
            } 
        }// END IF
        // No elements were Provided so there's nothing to bind!
        if ( !(settings.elements.length > 0) ) {
            return outer;
        }
        $.each( settings.elements, function( i, val ) {
            var elem = settings.elements[i];
            $( elem, outer ).bind( settings.trigger, function() {
                $.Pref( settings.name, elem, settings.copt );
            });
        });
        return outer;
    };// END $.fn.bindSavePref

    /**
     * This function automatically binds a save preference function to each
     * to each element in values and triggers all the default ones with the
     * selected element.
     * @param string    name    name of the preference setting
     * @param array     values  list of possible values
     * @param string    trig    trigger name
     * @param object    copt    cookie parameters in object form
     */
    $.fn.autoInitPref = function ( name, values, trig, copt ) {
        var outer = this;
        var stateVal = null;
        var pstateVal = null;
        var stateIdx = -1;

        // Can't do anything without a name
        if ( name === undefined || name === null || name === '' ) {
            return null;
        }
        // Should contain at least one value
        if ( (values === undefined) || !(values.length > 0) ) {
            return null;
        }
        //Default trig value
        trig = ( trig === undefined || trig === null  ) ? 'click' : trig;

        //Bind trigger to elements
        $(outer).bindSavePref({ 'name'     : name,
                                'elements' : values,
                                'trigger'  : trig,
                                'copt'     : copt
                              });
        // Check the QueryString First
        pstateVal = $.Pref(name, undefined,{'useCookie': false});
        if( pstateVal != null ) {
            if( pstateVal.substring(0,2) == 'i_' ) {
                pstateVal = '#' + pstateVal.substring(2);
            }
            else if( pstateVal.substring(0,2) == 'c_' ) {
                pstateVal = '.' + pstateVal.substring(2);
            } else {
                pstateVal = null;
            }
            
            //Check if it's a valid value
            if ( pstateVal != null ) {
                stateIdx = $.inArray( pstateVal, values );
                if ( stateIdx != -1 ) {
                    stateVal = values[stateIdx];
                }
            }
        }
        // (Query String didn't work)
        if( stateVal == null ) {
            stateVal = $.Pref( name );
            stateIdx = Math.max( 0, $.inArray( stateVal, values ));
            stateVal = values[stateIdx];
        }
        return $( stateVal, outer ).trigger( trig );
    };// END $.fn.autoInitPref
})(jQuery);

